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

openmc-dev / openmc / 23919098363

02 Apr 2026 07:53PM UTC coverage: 81.336% (+0.01%) from 81.324%
23919098363

Pull #3734

github

web-flow
Merge 5ddfca290 into d9b30bbbd
Pull Request #3734: Specify temperature from a field (structured mesh only)

17720 of 25601 branches covered (69.22%)

Branch coverage included in aggregate %.

183 of 204 new or added lines in 15 files covered. (89.71%)

69 existing lines in 3 files now uncovered.

58284 of 67843 relevant lines covered (85.91%)

44754406.4 hits per line

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

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

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

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

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

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

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

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

58
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,521✔
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,521✔
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)
37,089,450✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
33,884✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
37,089,408✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
37,089,408✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
37,089,408✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
37,089,408✔
155
  double current = bit_cast_value<double>(current_bits);
37,089,408✔
156
  while (is_min ? (value < current) : (value > current)) {
37,089,450✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
33,884✔
158
    uint64_t expected_bits = current_bits;
33,884✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
33,884✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
37,089,408✔
162
    }
163
    current_bits = expected_bits;
42✔
164
    current = bit_cast_value<double>(current_bits);
42✔
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)
18,544,704✔
188
{
189
  atomic_update_double(ptr, value, false);
6,181,568✔
190
}
6,181,568✔
191

192
inline void atomic_min_double(double* ptr, double value)
18,544,704✔
193
{
194
  atomic_update_double(ptr, value, true);
6,181,568✔
195
}
196

197
namespace detail {
198

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

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

220
    // Non-atomic read of current material
221
    int32_t current_val = *slot_ptr;
8,834,955✔
222

223
    // Found the desired material; accumulate volume and bbox
224
    if (current_val == index_material) {
8,834,955✔
225
#pragma omp atomic
4,859,250✔
226
      this->volumes(index_elem, slot) += volume;
8,833,434✔
227
      if (bbox) {
8,833,434✔
228
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,181,443✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,181,443✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,181,443✔
231
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,181,443✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,181,443✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,181,443✔
234
      }
235
      return;
8,833,434✔
236
    }
237

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,521!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,521✔
242
      bool claimed_slot =
1,521✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,521✔
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,521!
248
#pragma omp atomic
839✔
249
        this->volumes(index_elem, slot) += volume;
1,521✔
250
        if (bbox) {
1,521✔
251
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
125✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
125✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
125✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
125✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
125✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
125✔
257
        }
258
        return;
1,521✔
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,044✔
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,044✔
338
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
2,163✔
339
  } else if (mesh_type == RectilinearMesh::mesh_type) {
881✔
340
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
111✔
341
  } else if (mesh_type == CylindricalMesh::mesh_type) {
770✔
342
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
389✔
343
  } else if (mesh_type == SphericalMesh::mesh_type) {
381✔
344
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
334✔
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 &&
23!
352
             mesh_library == LibMesh::mesh_lib_type) {
23!
353
    model::meshes.push_back(make_unique<LibMesh>(dataset));
23✔
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,044✔
364

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

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

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

381
  // Read mesh name
382
  if (object_exists(group, "name")) {
44!
383
    read_dataset(group, "name", name_);
×
384
  }
385
}
44✔
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
246✔
424
{
425
  vector<double> volumes(n_bins());
246✔
426
  for (int i = 0; i < n_bins(); i++) {
1,111,189✔
427
    volumes[i] = this->volume(i);
1,110,943✔
428
  }
429
  return volumes;
246✔
430
}
×
431

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

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

454
  Timer timer;
187✔
455
  timer.start();
187✔
456

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

461
  // Determine bounding box
462
  auto bbox = this->bounding_box();
187✔
463

464
  std::array<int, 3> n_rays = {nx, ny, nz};
187✔
465

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

472
  // Set flag for mesh being contained within model
473
  bool out_of_model = false;
187✔
474

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

482
    SourceSite site;
85✔
483
    site.E = 1.0;
85✔
484
    site.particle = ParticleType::neutron();
85✔
485

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

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

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

514
      // Loop over rays on face of bounding box
515
#pragma omp for collapse(2)
516
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
15,800✔
517
        for (int i2 = 0; i2 < n2; ++i2) {
2,978,340✔
518
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
2,962,735✔
519
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
2,962,735✔
520

521
          p.from_source(&site);
2,962,735✔
522

523
          // Determine particle's location
524
          if (!exhaustive_find_cell(p)) {
2,962,735✔
525
            out_of_model = true;
39,930✔
526
            continue;
39,930✔
527
          }
528

529
          // Set birth cell attribute
530
          if (p.cell_born() == C_NONE)
2,922,805!
531
            p.cell_born() = p.lowest_coord().cell();
2,922,805✔
532

533
          // Initialize last cells from current cell
534
          for (int j = 0; j < p.n_coord(); ++j) {
5,845,610✔
535
            p.cell_last(j) = p.coord(j).cell();
2,922,805✔
536
          }
537
          p.n_coord_last() = p.n_coord();
2,922,805✔
538

539
          while (true) {
4,646,241✔
540
            // Ray trace from r_start to r_end
541
            Position r0 = p.r();
3,784,523✔
542
            double max_distance = bbox.max[axis] - r0[axis];
3,784,523✔
543

544
            // Find the distance to the nearest boundary
545
            BoundaryInfo boundary = distance_to_boundary(p);
3,784,523✔
546

547
            // Advance particle forward
548
            double distance = std::min(boundary.distance(), max_distance);
3,784,523✔
549
            p.move_distance(distance);
3,784,523✔
550

551
            // Determine what mesh elements were crossed by particle
552
            bins.clear();
3,784,523✔
553
            length_fractions.clear();
3,784,523✔
554
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
3,784,523✔
555

556
            // Add volumes to any mesh elements that were crossed
557
            int i_material = p.material();
3,784,523✔
558
            if (i_material != C_NONE) {
3,784,523✔
559
              i_material = model::materials[i_material]->id();
1,113,929✔
560
            }
561
            double cumulative_frac = 0.0;
3,784,523✔
562
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
7,787,696✔
563
              int mesh_index = bins[i_bin];
4,003,173✔
564
              double length = distance * length_fractions[i_bin];
4,003,173✔
565
              double volume = length * d1 * d2;
4,003,173✔
566

567
              if (compute_bboxes) {
4,003,173✔
568
                double axis_start = r0[axis] + distance * cumulative_frac;
2,797,088✔
569
                double axis_end = axis_start + length;
2,797,088✔
570
                cumulative_frac += length_fractions[i_bin];
2,797,088✔
571

572
                Position contrib_min = site.r;
2,797,088✔
573
                Position contrib_max = site.r;
2,797,088✔
574

575
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,797,088✔
576
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,797,088✔
577
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,797,088✔
578
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,797,088✔
579
                contrib_min[axis] = std::min(axis_start, axis_end);
2,797,088!
580
                contrib_max[axis] = std::max(axis_start, axis_end);
5,594,176!
581

582
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,797,088✔
583
                contrib_bbox &= bbox;
2,797,088✔
584

585
                result.add_volume(
2,797,088✔
586
                  mesh_index, i_material, volume, &contrib_bbox);
587
              } else {
588
                // Add volume to result
589
                result.add_volume(mesh_index, i_material, volume);
1,206,085✔
590
              }
591
            }
592

593
            if (distance == max_distance)
3,784,523✔
594
              break;
595

596
            // cross next geometric surface
597
            for (int j = 0; j < p.n_coord(); ++j) {
1,723,436✔
598
              p.cell_last(j) = p.coord(j).cell();
861,718✔
599
            }
600
            p.n_coord_last() = p.n_coord();
861,718✔
601

602
            // Set surface that particle is on and adjust coordinate levels
603
            p.surface() = boundary.surface();
861,718✔
604
            p.n_coord() = boundary.coord_level();
861,718✔
605

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

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

630
  // Compute time for raytracing
631
  double t_raytrace = timer.elapsed();
176✔
632

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

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

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

691
  // Report time for MPI communication
692
  double t_mpi = timer.elapsed() - t_raytrace;
64✔
693
#else
694
  double t_mpi = 0.0;
96✔
695
#endif
696

697
  // Normalize based on known volumes of elements
698
  for (int i = 0; i < this->n_bins(); ++i) {
1,067✔
699
    // Estimated total volume in element i
700
    double volume = 0.0;
701
    for (int j = 0; j < table_size; ++j) {
8,151✔
702
      volume += result.volumes(i, j);
7,260✔
703
    }
704
    // Renormalize volumes based on known volume of element i
705
    double norm = this->volume(i) / volume;
891✔
706
    for (int j = 0; j < table_size; ++j) {
8,151✔
707
      result.volumes(i, j) *= norm;
7,260✔
708
    }
709
  }
710

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

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

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

737
  // Write mesh type
738
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,938✔
739

740
  // Write mesh ID
741
  write_attribute(mesh_group, "id", id_);
2,938✔
742

743
  // Write mesh name
744
  write_dataset(mesh_group, "name", name_);
2,938✔
745

746
  // Write mesh data
747
  this->to_hdf5_inner(mesh_group);
2,938✔
748

749
  // Close group
750
  close_group(mesh_group);
2,938✔
751
}
2,938✔
752

753
//==============================================================================
754
// Structured Mesh implementation
755
//==============================================================================
756

757
std::string StructuredMesh::bin_label(int bin) const
5,134,881✔
758
{
759
  MeshIndex ijk = get_indices_from_bin(bin);
5,134,881✔
760

761
  if (n_dimension_ > 2) {
5,134,881✔
762
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,118,942✔
763
  } else if (n_dimension_ > 1) {
15,939✔
764
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
15,664✔
765
  } else {
766
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
767
  }
768
}
769

770
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,543✔
771
{
772
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,543✔
773
}
774

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

782
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,444,927!
783
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,444,927!
784

785
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,444,927!
786
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,444,927!
787

788
  return {x_min + (x_max - x_min) * prn(seed),
1,444,927✔
789
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,444,927✔
790
}
791

792
//==============================================================================
793
// Unstructured Mesh implementation
794
//==============================================================================
795

796
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
47!
797
{
798
  n_dimension_ = 3;
47✔
799

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

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

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

824
  if (check_for_node(node, "options")) {
47!
825
    options_ = get_node_value(node, "options");
16!
826
  }
827

828
  // check if mesh tally data should be written with
829
  // statepoint files
830
  if (check_for_node(node, "output")) {
47!
831
    output_ = get_node_value_bool(node, "output");
×
832
  }
833
}
47✔
834

835
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
836
{
837
  n_dimension_ = 3;
×
838

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

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

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

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

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

NEW
875
double UnstructuredMesh::distance_to_next_boundary(
×
876
  Position r, Direction u) const
877
{
NEW
878
  fatal_error("Not implemented");
×
879
  return -1.0;
880
}
881

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

904
Position UnstructuredMesh::sample_tet(
601,230✔
905
  std::array<Position, 4> coords, uint64_t* seed) const
906
{
907
  // Uniform distribution
908
  double s = prn(seed);
601,230✔
909
  double t = prn(seed);
601,230✔
910
  double u = prn(seed);
601,230✔
911

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

934
const std::string UnstructuredMesh::mesh_type = "unstructured";
935

936
std::string UnstructuredMesh::get_mesh_type() const
32✔
937
{
938
  return mesh_type;
32✔
939
}
940

941
void UnstructuredMesh::surface_bins_crossed(
×
942
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
943
{
944
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
945
}
946

947
std::string UnstructuredMesh::bin_label(int bin) const
205,736✔
948
{
949
  return fmt::format("Mesh Index ({})", bin);
205,736✔
950
};
951

952
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
32✔
953
{
954
  write_dataset(mesh_group, "filename", filename_);
32!
955
  write_dataset(mesh_group, "library", this->library());
32!
956
  if (!options_.empty()) {
32✔
957
    write_attribute(mesh_group, "options", options_);
8✔
958
  }
959

960
  if (length_multiplier_ > 0.0)
32!
961
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
962

963
  // write vertex coordinates
964
  tensor::Tensor<double> vertices(
32✔
965
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
32✔
966
  for (int i = 0; i < this->n_vertices(); i++) {
70,275!
967
    auto v = this->vertex(i);
70,243!
968
    vertices.slice(i) = {v.x, v.y, v.z};
140,486!
969
  }
970
  write_dataset(mesh_group, "vertices", vertices);
32!
971

972
  int num_elem_skipped = 0;
32✔
973

974
  // write element types and connectivity
975
  vector<double> volumes;
32!
976
  tensor::Tensor<int> connectivity(
32✔
977
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
32!
978
  tensor::Tensor<int> elem_types(
32✔
979
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
32!
980
  for (int i = 0; i < this->n_bins(); i++) {
349,768!
981
    auto conn = this->connectivity(i);
349,736!
982

983
    volumes.emplace_back(this->volume(i));
349,736!
984

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

1002
  // warn users that some elements were skipped
1003
  if (num_elem_skipped > 0) {
32!
1004
    warning(fmt::format("The connectivity of {} elements "
×
1005
                        "on mesh {} were not written "
1006
                        "because they are not of type linear tet/hex.",
1007
      num_elem_skipped, this->id_));
×
1008
  }
1009

1010
  write_dataset(mesh_group, "volumes", volumes);
32!
1011
  write_dataset(mesh_group, "connectivity", connectivity);
32!
1012
  write_dataset(mesh_group, "element_types", elem_types);
32!
1013
}
96✔
1014

1015
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
1016
{
1017
  length_multiplier_ = length_multiplier;
23✔
1018
}
23✔
1019

1020
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1021
{
1022
  auto conn = connectivity(bin);
120,000✔
1023

1024
  if (conn.size() == 4)
120,000!
1025
    return ElementType::LINEAR_TET;
1026
  else if (conn.size() == 8)
×
1027
    return ElementType::LINEAR_HEX;
1028
  else
1029
    return ElementType::UNSUPPORTED;
×
1030
}
120,000✔
1031

1032
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,193,152,523✔
1033
  Position r, bool& in_mesh) const
1034
{
1035
  MeshIndex ijk;
1,193,152,523✔
1036
  in_mesh = true;
1,193,152,523✔
1037
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1038
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1039

1040
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1041
      in_mesh = false;
102,653,558✔
1042
  }
1043
  return ijk;
1,193,152,523✔
1044
}
1045

1046
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,754,669,474✔
1047
{
1048
  switch (n_dimension_) {
1,754,669,474!
1049
  case 1:
880,605✔
1050
    return ijk[0] - 1;
880,605✔
1051
  case 2:
136,375,228✔
1052
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
136,375,228✔
1053
  case 3:
1,617,413,641✔
1054
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,617,413,641✔
1055
  default:
×
1056
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1057
  }
1058
}
1059

1060
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,782,062✔
1061
{
1062
  MeshIndex ijk;
7,782,062✔
1063
  if (n_dimension_ == 1) {
7,782,062✔
1064
    ijk[0] = bin + 1;
275✔
1065
  } else if (n_dimension_ == 2) {
7,781,787✔
1066
    ijk[0] = bin % shape_[0] + 1;
15,664✔
1067
    ijk[1] = bin / shape_[0] + 1;
15,664✔
1068
  } else if (n_dimension_ == 3) {
7,766,123!
1069
    ijk[0] = bin % shape_[0] + 1;
7,766,123✔
1070
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,766,123✔
1071
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,766,123✔
1072
  }
1073
  return ijk;
7,782,062✔
1074
}
1075

1076
int StructuredMesh::get_bin(Position r) const
256,274,794✔
1077
{
1078
  // Determine indices
1079
  bool in_mesh;
256,274,794✔
1080
  MeshIndex ijk = get_indices(r, in_mesh);
256,274,794✔
1081
  if (!in_mesh)
256,274,794✔
1082
    return -1;
1083

1084
  // Convert indices to bin
1085
  return get_bin_from_indices(ijk);
235,228,946✔
1086
}
1087

1088
int StructuredMesh::n_bins() const
1,125,627✔
1089
{
1090
  return std::accumulate(
2,251,254✔
1091
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,125,627✔
1092
}
1093

1094
int StructuredMesh::n_surface_bins() const
370✔
1095
{
1096
  return 4 * n_dimension_ * n_bins();
370✔
1097
}
1098

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

1106
  // Create array of zeros
1107
  auto cnt = tensor::zeros<double>(shape);
×
1108
  bool outside_ = false;
1109

1110
  for (int64_t i = 0; i < length; i++) {
×
1111
    const auto& site = bank[i];
×
1112

1113
    // determine scoring bin for entropy mesh
1114
    int mesh_bin = get_bin(site.r);
×
1115

1116
    // if outside mesh, skip particle
1117
    if (mesh_bin < 0) {
×
1118
      outside_ = true;
×
1119
      continue;
×
1120
    }
1121

1122
    // Add to appropriate bin
1123
    cnt(mesh_bin) += site.wgt;
×
1124
  }
1125

1126
  // Create reduced count data
1127
  auto counts = tensor::zeros<double>(shape);
×
1128
  int total = cnt.size();
×
1129

1130
#ifdef OPENMC_MPI
1131
  // collect values from all processors
1132
  MPI_Reduce(
×
1133
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1134

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

1145
  return counts;
×
1146
}
×
1147

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

1161
  // Compute the length of the entire track.
1162
  double total_distance = (r1 - r0).norm();
940,438,214✔
1163
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
940,438,214✔
1164
    return;
1165

1166
  // keep a copy of the original global position to pass to get_indices,
1167
  // which performs its own transformation to local coordinates
1168
  Position global_r = r0;
928,343,302✔
1169
  Position local_r = local_coords(r0);
928,343,302✔
1170

1171
  const int n = n_dimension_;
928,343,302✔
1172

1173
  // Flag if position is inside the mesh
1174
  bool in_mesh;
1175

1176
  // Position is r = r0 + u * traveled_distance, start at r0
1177
  double traveled_distance {0.0};
928,343,302✔
1178

1179
  // Calculate index of current cell. Offset the position a tiny bit in
1180
  // direction of flight
1181
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
928,343,302✔
1182

1183
  // if track is very short, assume that it is completely inside one cell.
1184
  // Only the current cell will score and no surfaces
1185
  if (total_distance < 2 * TINY_BIT) {
928,343,302✔
1186
    if (in_mesh) {
331,637✔
1187
      tally.track(ijk, 1.0);
331,153✔
1188
    }
1189
    return;
331,637✔
1190
  }
1191

1192
  // Calculate initial distances to next surfaces in all three dimensions
1193
  std::array<MeshDistance, 3> distances;
1,856,023,330✔
1194
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1195
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1196
  }
1197

1198
  // Loop until r = r1 is eventually reached
1199
  while (true) {
1200

1201
    if (in_mesh) {
1,687,265,389✔
1202

1203
      // find surface with minimal distance to current position
1204
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,600,994,750✔
1205
                     distances.begin();
1,600,994,750✔
1206

1207
      // Tally track length delta since last step
1208
      tally.track(ijk,
1,600,994,750✔
1209
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1210
          total_distance);
1211

1212
      // update position and leave, if we have reached end position
1213
      traveled_distance = distances[k].distance;
1,600,994,750✔
1214
      if (traveled_distance >= total_distance)
1,600,994,750✔
1215
        return;
1216

1217
      // If we have not reached r1, we have hit a surface. Tally outward
1218
      // current
1219
      tally.surface(ijk, k, distances[k].max_surface, false);
752,083,506✔
1220

1221
      // Update cell and calculate distance to next surface in k-direction.
1222
      // The two other directions are still valid!
1223
      ijk[k] = distances[k].next_index;
752,083,506✔
1224
      distances[k] =
752,083,506✔
1225
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
752,083,506✔
1226

1227
      // Check if we have left the interior of the mesh
1228
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
758,917,641✔
1229

1230
      // If we are still inside the mesh, tally inward current for the next
1231
      // cell
1232
      if (in_mesh)
29,576,899✔
1233
        tally.surface(ijk, k, !distances[k].max_surface, true);
757,837,507✔
1234

1235
    } else { // not inside mesh
1236

1237
      // For all directions outside the mesh, find the distance that we need
1238
      // to travel to reach the next surface. Use the largest distance, as
1239
      // only this will cross all outer surfaces.
1240
      int k_max {-1};
1241
      for (int k = 0; k < n; ++k) {
343,638,190✔
1242
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,367,551✔
1243
            (distances[k].distance > traveled_distance)) {
94,278,554✔
1244
          traveled_distance = distances[k].distance;
1245
          k_max = k;
1246
        }
1247
      }
1248
      // Assure some distance is traveled
1249
      if (k_max == -1) {
86,270,639✔
1250
        traveled_distance += TINY_BIT;
110✔
1251
      }
1252

1253
      // If r1 is not inside the mesh, exit here
1254
      if (traveled_distance >= total_distance)
86,270,639✔
1255
        return;
1256

1257
      // Calculate the new cell index and update all distances to next
1258
      // surfaces.
1259
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,170,218✔
1260
      for (int k = 0; k < n; ++k) {
28,472,334✔
1261
        distances[k] =
21,302,116✔
1262
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,302,116✔
1263
      }
1264

1265
      // If inside the mesh, Tally inward current
1266
      if (in_mesh && k_max >= 0)
7,170,218!
1267
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
729,653,857✔
1268
    }
1269
  }
1270
}
1271

1272
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
828,310,649✔
1273
  vector<int>& bins, vector<double>& lengths) const
1274
{
1275

1276
  // Helper tally class.
1277
  // stores a pointer to the mesh class and references to bins and lengths
1278
  // parameters. Performs the actual tally through the track method.
1279
  struct TrackAggregator {
828,310,649✔
1280
    TrackAggregator(
828,310,649✔
1281
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1282
      : mesh(_mesh), bins(_bins), lengths(_lengths)
828,310,649✔
1283
    {}
1284
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1285
    void track(const MeshIndex& ijk, double l) const
1,461,281,339✔
1286
    {
1287
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,461,281,339✔
1288
      lengths.push_back(l);
1,461,281,339✔
1289
    }
1,461,281,339✔
1290

1291
    const StructuredMesh* mesh;
1292
    vector<int>& bins;
1293
    vector<double>& lengths;
1294
  };
1295

1296
  // Perform the mesh raytrace with the helper class.
1297
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
828,310,649✔
1298
}
828,310,649✔
1299

1300
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1301
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1302
{
1303

1304
  // Helper tally class.
1305
  // stores a pointer to the mesh class and a reference to the bins parameter.
1306
  // Performs the actual tally through the surface method.
1307
  struct SurfaceAggregator {
112,127,565✔
1308
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,565✔
1309
      : mesh(_mesh), bins(_bins)
112,127,565✔
1310
    {}
1311
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,189✔
1312
    {
1313
      int i_bin =
58,159,189✔
1314
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,189✔
1315
      if (max)
58,159,189✔
1316
        i_bin += 2;
29,051,440✔
1317
      if (inward)
58,159,189✔
1318
        i_bin += 1;
28,582,290✔
1319
      bins.push_back(i_bin);
58,159,189✔
1320
    }
58,159,189✔
1321
    void track(const MeshIndex& idx, double l) const {}
1322

1323
    const StructuredMesh* mesh;
1324
    vector<int>& bins;
1325
  };
1326

1327
  // Perform the mesh raytrace with the helper class.
1328
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1329
}
112,127,565✔
1330

1331
double StructuredMesh::distance_to_next_boundary(Position r, Direction u) const
1,364,209✔
1332
{
1333
  Position global_r = r;
1,364,209✔
1334
  Position local_r = local_coords(r);
1,364,209✔
1335

1336
  double distance = 0.0;
1,364,209✔
1337
  const int n = n_dimension_;
1,364,209✔
1338
  bool in_mesh;
1,364,209✔
1339

1340
  StructuredMesh::MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,364,209✔
1341

1342
  // Calculate initial distances to next surfaces in all three dimensions
1343
  std::array<StructuredMesh::MeshDistance, 3> distances;
2,728,418✔
1344
  for (int k = 0; k < n; ++k) {
5,456,836✔
1345
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
4,092,627✔
1346
  }
1347

1348
  if (in_mesh) {
1,364,209✔
1349

1350
    // Find surface with minimal distance to current position
1351
    const auto k =
1352
      std::min_element(distances.begin(), distances.end()) - distances.begin();
1,364,099✔
1353

1354
    distance = distances[k].distance;
1,364,099✔
1355

1356
  } else { // not inside mesh
1357

1358
    // For all directions outside the mesh, find the distance that we need
1359
    // to travel to reach the next surface. Use the largest distance, as
1360
    // only this will cross all outer surfaces.
1361
    int k_max {-1};
1362
    for (int k = 0; k < n; ++k) {
440✔
1363
      if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
330!
1364
          (distances[k].distance > distance)) {
110!
1365
        distance = distances[k].distance;
1366
        k_max = k;
1367
      }
1368
    }
1369
  }
1370

1371
  return distance;
1,364,209✔
1372
}
1373

1374
//==============================================================================
1375
// RegularMesh implementation
1376
//==============================================================================
1377

1378
int RegularMesh::set_grid()
2,207✔
1379
{
1380
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,207✔
1381

1382
  // Check that dimensions are all greater than zero
1383
  if ((shape <= 0).any()) {
6,621!
1384
    set_errmsg("All entries for a regular mesh dimensions "
×
1385
               "must be positive.");
1386
    return OPENMC_E_INVALID_ARGUMENT;
×
1387
  }
1388

1389
  // Make sure lower_left and dimension match
1390
  if (lower_left_.size() != n_dimension_) {
2,207!
1391
    set_errmsg("Number of entries in lower_left must be the same "
×
1392
               "as the regular mesh dimensions.");
1393
    return OPENMC_E_INVALID_ARGUMENT;
×
1394
  }
1395
  if (width_.size() > 0) {
2,207✔
1396

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

1404
    // Check for negative widths
1405
    if ((width_ < 0.0).any()) {
138!
1406
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1407
      return OPENMC_E_INVALID_ARGUMENT;
×
1408
    }
1409

1410
    // Set width and upper right coordinate
1411
    upper_right_ = lower_left_ + shape * width_;
138✔
1412

1413
  } else if (upper_right_.size() > 0) {
2,161!
1414

1415
    // Check to ensure upper_right_ has same dimensions
1416
    if (upper_right_.size() != n_dimension_) {
2,161!
1417
      set_errmsg("Number of entries on upper_right must be the "
×
1418
                 "same as the regular mesh dimensions.");
1419
      return OPENMC_E_INVALID_ARGUMENT;
×
1420
    }
1421

1422
    // Check that upper-right is above lower-left
1423
    if ((upper_right_ < lower_left_).any()) {
6,483!
1424
      set_errmsg(
×
1425
        "The upper_right coordinates of a regular mesh must be greater than "
1426
        "the lower_left coordinates.");
1427
      return OPENMC_E_INVALID_ARGUMENT;
×
1428
    }
1429

1430
    // Set width
1431
    width_ = (upper_right_ - lower_left_) / shape;
6,483✔
1432
  }
1433

1434
  // Set material volumes
1435
  volume_frac_ = 1.0 / shape.prod();
2,207✔
1436

1437
  element_volume_ = 1.0;
2,207✔
1438
  for (int i = 0; i < n_dimension_; i++) {
8,281✔
1439
    element_volume_ *= width_[i];
6,074✔
1440
  }
1441
  return 0;
1442
}
2,207✔
1443

1444
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,196✔
1445
{
1446
  // Determine number of dimensions for mesh
1447
  if (!check_for_node(node, "dimension")) {
2,196!
1448
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1449
  }
1450

1451
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,196✔
1452
  int n = n_dimension_ = shape.size();
2,196!
1453
  if (n != 1 && n != 2 && n != 3) {
2,196!
1454
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1455
  }
1456
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,196✔
1457

1458
  // Check for lower-left coordinates
1459
  if (check_for_node(node, "lower_left")) {
2,196!
1460
    // Read mesh lower-left corner location
1461
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,196✔
1462
  } else {
1463
    fatal_error("Must specify <lower_left> on a mesh.");
×
1464
  }
1465

1466
  if (check_for_node(node, "width")) {
2,196✔
1467
    // Make sure one of upper-right or width were specified
1468
    if (check_for_node(node, "upper_right")) {
46!
1469
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1470
    }
1471

1472
    width_ = get_node_tensor<double>(node, "width");
92✔
1473

1474
  } else if (check_for_node(node, "upper_right")) {
2,150!
1475

1476
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,300✔
1477

1478
  } else {
1479
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1480
  }
1481

1482
  if (int err = set_grid()) {
2,196!
1483
    fatal_error(openmc_err_msg);
×
1484
  }
1485
}
2,196✔
1486

1487
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
11✔
1488
{
1489
  // Determine number of dimensions for mesh
1490
  if (!object_exists(group, "dimension")) {
11!
1491
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1492
  }
1493

1494
  tensor::Tensor<int> shape;
11✔
1495
  read_dataset(group, "dimension", shape);
11✔
1496
  int n = n_dimension_ = shape.size();
11!
1497
  if (n != 1 && n != 2 && n != 3) {
11!
1498
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1499
  }
1500
  std::copy(shape.begin(), shape.end(), shape_.begin());
11✔
1501

1502
  // Check for lower-left coordinates
1503
  if (object_exists(group, "lower_left")) {
11!
1504
    // Read mesh lower-left corner location
1505
    read_dataset(group, "lower_left", lower_left_);
11✔
1506
  } else {
1507
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1508
  }
1509

1510
  if (object_exists(group, "upper_right")) {
11!
1511

1512
    read_dataset(group, "upper_right", upper_right_);
11✔
1513

1514
  } else {
1515
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1516
  }
1517

1518
  if (int err = set_grid()) {
11!
1519
    fatal_error(openmc_err_msg);
×
1520
  }
1521
}
11✔
1522

1523
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1524
{
1525
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1526
}
1527

1528
const std::string RegularMesh::mesh_type = "regular";
1529

1530
std::string RegularMesh::get_mesh_type() const
3,236✔
1531
{
1532
  return mesh_type;
3,236✔
1533
}
1534

1535
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,488,473,268✔
1536
{
1537
  return lower_left_[i] + ijk[i] * width_[i];
1,488,473,268✔
1538
}
1539

1540
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,419,274,701✔
1541
{
1542
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,419,274,701✔
1543
}
1544

1545
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1546
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1547
  double l) const
1548
{
1549
  MeshDistance d;
2,147,483,647✔
1550
  d.next_index = ijk[i];
2,147,483,647✔
1551
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1552
    return d;
14,784,126✔
1553

1554
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1555
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1556
    d.next_index++;
1,484,138,487✔
1557
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,484,138,487✔
1558
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,436,388,243✔
1559
    d.next_index--;
1,414,939,920✔
1560
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,414,939,920✔
1561
  }
1562

1563
  return d;
2,147,483,647✔
1564
}
1565

1566
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1567
  Position plot_ll, Position plot_ur) const
1568
{
1569
  // Figure out which axes lie in the plane of the plot.
1570
  array<int, 2> axes {-1, -1};
22✔
1571
  if (plot_ur.z == plot_ll.z) {
22!
1572
    axes[0] = 0;
22!
1573
    if (n_dimension_ > 1)
22!
1574
      axes[1] = 1;
22✔
1575
  } else if (plot_ur.y == plot_ll.y) {
×
1576
    axes[0] = 0;
×
1577
    if (n_dimension_ > 2)
×
1578
      axes[1] = 2;
×
1579
  } else if (plot_ur.x == plot_ll.x) {
×
1580
    if (n_dimension_ > 1)
×
1581
      axes[0] = 1;
×
1582
    if (n_dimension_ > 2)
×
1583
      axes[1] = 2;
×
1584
  } else {
1585
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1586
  }
1587

1588
  // Get the coordinates of the mesh lines along both of the axes.
1589
  array<vector<double>, 2> axis_lines;
1590
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1591
    int axis = axes[i_ax];
44!
1592
    if (axis == -1)
44!
1593
      continue;
×
1594
    auto& lines {axis_lines[i_ax]};
44✔
1595

1596
    double coord = lower_left_[axis];
44✔
1597
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1598
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1599
        lines.push_back(coord);
242✔
1600
      coord += width_[axis];
242✔
1601
    }
1602
  }
1603

1604
  return {axis_lines[0], axis_lines[1]};
44✔
1605
}
1606

1607
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,103✔
1608
{
1609
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,103✔
1610
  write_dataset(mesh_group, "lower_left", lower_left_);
2,103✔
1611
  write_dataset(mesh_group, "upper_right", upper_right_);
2,103✔
1612
  write_dataset(mesh_group, "width", width_);
2,103✔
1613
}
2,103✔
1614

1615
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1616
  const SourceSite* bank, int64_t length, bool* outside) const
1617
{
1618
  // Determine shape of array for counts
1619
  std::size_t m = this->n_bins();
7,820✔
1620
  vector<std::size_t> shape = {m};
7,820✔
1621

1622
  // Create array of zeros
1623
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1624
  bool outside_ = false;
2,892✔
1625

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

1629
    // determine scoring bin for entropy mesh
1630
    int mesh_bin = get_bin(site.r);
7,667,451✔
1631

1632
    // if outside mesh, skip particle
1633
    if (mesh_bin < 0) {
7,667,451!
1634
      outside_ = true;
×
1635
      continue;
×
1636
    }
1637

1638
    // Add to appropriate bin
1639
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1640
  }
1641

1642
  // Create reduced count data
1643
  auto counts = tensor::zeros<double>(shape);
7,820✔
1644
  int total = cnt.size();
7,820✔
1645

1646
#ifdef OPENMC_MPI
1647
  // collect values from all processors
1648
  MPI_Reduce(
2,892✔
1649
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1650

1651
  // Check if there were sites outside the mesh for any processor
1652
  if (outside) {
2,892!
1653
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1654
  }
1655
#else
1656
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1657
  if (outside)
4,928!
1658
    *outside = outside_;
4,928✔
1659
#endif
1660

1661
  return counts;
7,820✔
1662
}
7,820✔
1663

1664
double RegularMesh::volume(const MeshIndex& ijk) const
1,112,175✔
1665
{
1666
  return element_volume_;
1,112,175✔
1667
}
1668

1669
//==============================================================================
1670
// RectilinearMesh implementation
1671
//==============================================================================
1672

1673
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1674
{
1675
  n_dimension_ = 3;
133✔
1676

1677
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1678
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1679
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1680

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

1686
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1687
{
1688
  n_dimension_ = 3;
11✔
1689

1690
  read_dataset(group, "x_grid", grid_[0]);
11✔
1691
  read_dataset(group, "y_grid", grid_[1]);
11✔
1692
  read_dataset(group, "z_grid", grid_[2]);
11✔
1693

1694
  if (int err = set_grid()) {
11!
1695
    fatal_error(openmc_err_msg);
×
1696
  }
1697
}
11✔
1698

1699
const std::string RectilinearMesh::mesh_type = "rectilinear";
1700

1701
std::string RectilinearMesh::get_mesh_type() const
275✔
1702
{
1703
  return mesh_type;
275✔
1704
}
1705

1706
double RectilinearMesh::positive_grid_boundary(
26,505,985✔
1707
  const MeshIndex& ijk, int i) const
1708
{
1709
  return grid_[i][ijk[i]];
26,505,985✔
1710
}
1711

1712
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1713
  const MeshIndex& ijk, int i) const
1714
{
1715
  return grid_[i][ijk[i] - 1];
25,739,406✔
1716
}
1717

1718
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,186✔
1719
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1720
  double l) const
1721
{
1722
  MeshDistance d;
53,602,186✔
1723
  d.next_index = ijk[i];
53,602,186✔
1724
  if (std::abs(u[i]) < FP_PRECISION)
53,602,186✔
1725
    return d;
571,890✔
1726

1727
  d.max_surface = (u[i] > 0);
53,030,296✔
1728
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,296✔
1729
    d.next_index++;
26,505,985✔
1730
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,985✔
1731
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,311✔
1732
    d.next_index--;
25,739,406✔
1733
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1734
  }
1735
  return d;
53,030,296✔
1736
}
1737

1738
int RectilinearMesh::set_grid()
188✔
1739
{
1740
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1741
    static_cast<int>(grid_[1].size()) - 1,
188✔
1742
    static_cast<int>(grid_[2].size()) - 1};
188✔
1743

1744
  for (const auto& g : grid_) {
752✔
1745
    if (g.size() < 2) {
564!
1746
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1747
                 "must each have at least 2 points");
1748
      return OPENMC_E_INVALID_ARGUMENT;
×
1749
    }
1750
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
564!
1751
        g.end()) {
564!
1752
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1753
                 "rectilinear meshes must be sorted and unique.");
1754
      return OPENMC_E_INVALID_ARGUMENT;
×
1755
    }
1756
  }
1757

1758
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1759
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1760

1761
  return 0;
188✔
1762
}
1763

1764
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,991✔
1765
{
1766
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,991✔
1767
}
1768

1769
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1770
  Position plot_ll, Position plot_ur) const
1771
{
1772
  // Figure out which axes lie in the plane of the plot.
1773
  array<int, 2> axes {-1, -1};
11✔
1774
  if (plot_ur.z == plot_ll.z) {
11!
1775
    axes = {0, 1};
×
1776
  } else if (plot_ur.y == plot_ll.y) {
11!
1777
    axes = {0, 2};
11✔
1778
  } else if (plot_ur.x == plot_ll.x) {
×
1779
    axes = {1, 2};
×
1780
  } else {
1781
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1782
  }
1783

1784
  // Get the coordinates of the mesh lines along both of the axes.
1785
  array<vector<double>, 2> axis_lines;
1786
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1787
    int axis = axes[i_ax];
22✔
1788
    vector<double>& lines {axis_lines[i_ax]};
22✔
1789

1790
    for (auto coord : grid_[axis]) {
110✔
1791
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1792
        lines.push_back(coord);
88✔
1793
    }
1794
  }
1795

1796
  return {axis_lines[0], axis_lines[1]};
22✔
1797
}
1798

1799
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1800
{
1801
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1802
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1803
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1804
}
110✔
1805

1806
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1807
{
1808
  double vol {1.0};
132✔
1809

1810
  for (int i = 0; i < n_dimension_; i++) {
528✔
1811
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1812
  }
1813
  return vol;
132✔
1814
}
1815

1816
//==============================================================================
1817
// CylindricalMesh implementation
1818
//==============================================================================
1819

1820
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
411✔
1821
  : PeriodicStructuredMesh {node}
411✔
1822
{
1823
  n_dimension_ = 3;
411✔
1824
  grid_[0] = get_node_array<double>(node, "r_grid");
411✔
1825
  grid_[1] = get_node_array<double>(node, "phi_grid");
411✔
1826
  grid_[2] = get_node_array<double>(node, "z_grid");
411✔
1827
  origin_ = get_node_position(node, "origin");
411✔
1828

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

1834
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1835
{
1836
  n_dimension_ = 3;
11✔
1837
  read_dataset(group, "r_grid", grid_[0]);
11✔
1838
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1839
  read_dataset(group, "z_grid", grid_[2]);
11✔
1840
  read_dataset(group, "origin", origin_);
11✔
1841

1842
  if (int err = set_grid()) {
11!
1843
    fatal_error(openmc_err_msg);
×
1844
  }
1845
}
11✔
1846

1847
const std::string CylindricalMesh::mesh_type = "cylindrical";
1848

1849
std::string CylindricalMesh::get_mesh_type() const
484✔
1850
{
1851
  return mesh_type;
484✔
1852
}
1853

1854
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,124✔
1855
  Position r, bool& in_mesh) const
1856
{
1857
  r = local_coords(r);
47,732,124✔
1858

1859
  Position mapped_r;
47,732,124✔
1860
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,124✔
1861
  mapped_r[2] = r[2];
47,732,124✔
1862

1863
  if (mapped_r[0] < FP_PRECISION) {
47,732,124!
1864
    mapped_r[1] = 0.0;
1865
  } else {
1866
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,124✔
1867
    if (mapped_r[1] < 0)
47,732,124✔
1868
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1869
  }
1870

1871
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,124✔
1872

1873
  idx[1] = sanitize_phi(idx[1]);
47,732,124✔
1874

1875
  return idx;
47,732,124✔
1876
}
1877

1878
Position CylindricalMesh::sample_element(
88,110✔
1879
  const MeshIndex& ijk, uint64_t* seed) const
1880
{
1881
  double r_min = this->r(ijk[0] - 1);
88,110✔
1882
  double r_max = this->r(ijk[0]);
88,110✔
1883

1884
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1885
  double phi_max = this->phi(ijk[1]);
88,110✔
1886

1887
  double z_min = this->z(ijk[2] - 1);
88,110✔
1888
  double z_max = this->z(ijk[2]);
88,110✔
1889

1890
  double r_min_sq = r_min * r_min;
88,110✔
1891
  double r_max_sq = r_max * r_max;
88,110✔
1892
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1893
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1894
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1895

1896
  double x = r * std::cos(phi);
88,110✔
1897
  double y = r * std::sin(phi);
88,110✔
1898

1899
  return origin_ + Position(x, y, z);
88,110✔
1900
}
1901

1902
double CylindricalMesh::find_r_crossing(
142,588,552✔
1903
  const Position& r, const Direction& u, double l, int shell) const
1904
{
1905

1906
  if ((shell < 0) || (shell > shape_[0]))
142,588,552✔
1907
    return INFTY;
1908

1909
  // solve r.x^2 + r.y^2 == r0^2
1910
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1911
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1912

1913
  const double r0 = grid_[0][shell];
124,674,544✔
1914
  if (r0 == 0.0)
124,674,544✔
1915
    return INFTY;
1916

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

1919
  // Direction of flight is in z-direction. Will never intersect r.
1920
  if (std::abs(denominator) < FP_PRECISION)
117,538,470✔
1921
    return INFTY;
1922

1923
  // inverse of dominator to help the compiler to speed things up
1924
  const double inv_denominator = 1.0 / denominator;
117,479,510✔
1925

1926
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,479,510✔
1927
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,479,510✔
1928
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,479,510✔
1929

1930
  if (D < 0.0)
117,479,510✔
1931
    return INFTY;
1932

1933
  D = std::sqrt(D);
107,743,388✔
1934

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

1939
  // Check -p - D first because it is always smaller as -p + D
1940
  if (-p - D > l)
101,110,014✔
1941
    return -p - D;
1942
  if (-p + D > l)
80,902,398✔
1943
    return -p + D;
50,078,508✔
1944

1945
  return INFTY;
1946
}
1947

1948
double CylindricalMesh::find_phi_crossing(
74,456,470✔
1949
  const Position& r, const Direction& u, double l, int shell) const
1950
{
1951
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1952
  if (full_phi_ && (shape_[1] == 1))
74,456,470✔
1953
    return INFTY;
1954

1955
  shell = sanitize_phi(shell);
43,970,718✔
1956

1957
  const double p0 = grid_[1][shell];
43,970,718✔
1958

1959
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1960
  // => x(s) * cos(p0) = y(s) * sin(p0)
1961
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1962
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1963

1964
  const double c0 = std::cos(p0);
43,970,718✔
1965
  const double s0 = std::sin(p0);
43,970,718✔
1966

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

1969
  // Check if direction of flight is not parallel to phi surface
1970
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1971
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1972
    // Check if solution is in positive direction of flight and crosses the
1973
    // correct phi surface (not -phi)
1974
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1975
      return s;
20,219,859✔
1976
  }
1977

1978
  return INFTY;
1979
}
1980

1981
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,780✔
1982
  const Position& r, const Direction& u, double l, int shell) const
1983
{
1984
  MeshDistance d;
36,695,780✔
1985
  d.next_index = shell;
36,695,780✔
1986

1987
  // Direction of flight is within xy-plane. Will never intersect z.
1988
  if (std::abs(u.z) < FP_PRECISION)
36,695,780✔
1989
    return d;
1,118,249✔
1990

1991
  d.max_surface = (u.z > 0.0);
35,577,531✔
1992
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1993
    d.next_index += 1;
16,875,892✔
1994
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1995
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1996
    d.next_index -= 1;
16,846,225✔
1997
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1998
  }
1999
  return d;
35,577,531✔
2000
}
2001

2002
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,291✔
2003
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2004
  double l) const
2005
{
2006
  if (i == 0) {
145,218,291✔
2007

2008
    return std::min(
142,588,552✔
2009
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,276✔
2010
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,552✔
2011

2012
  } else if (i == 1) {
73,924,015✔
2013

2014
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,235✔
2015
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,235✔
2016
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,235✔
2017
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,470✔
2018

2019
  } else {
2020
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,780✔
2021
  }
2022
}
2023

2024
int CylindricalMesh::set_grid()
444✔
2025
{
2026
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
444✔
2027
    static_cast<int>(grid_[1].size()) - 1,
444✔
2028
    static_cast<int>(grid_[2].size()) - 1};
444✔
2029

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

2057
    return OPENMC_E_INVALID_ARGUMENT;
×
2058
  }
2059

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

2062
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
444✔
2063
    origin_[2] + grid_[2].front()};
444✔
2064
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
444✔
2065
    origin_[2] + grid_[2].back()};
444✔
2066

2067
  return 0;
444✔
2068
}
2069

2070
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,372✔
2071
{
2072
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,372✔
2073
}
2074

2075
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2076
  Position plot_ll, Position plot_ur) const
2077
{
2078
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2079

2080
  // Figure out which axes lie in the plane of the plot.
2081
  array<vector<double>, 2> axis_lines;
2082
  return {axis_lines[0], axis_lines[1]};
2083
}
2084

2085
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2086
{
2087
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2088
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2089
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2090
  write_dataset(mesh_group, "origin", origin_);
374✔
2091
}
374✔
2092

2093
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2094
{
2095
  double r_i = grid_[0][ijk[0] - 1];
792✔
2096
  double r_o = grid_[0][ijk[0]];
792✔
2097

2098
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2099
  double phi_o = grid_[1][ijk[1]];
792✔
2100

2101
  double z_i = grid_[2][ijk[2] - 1];
792✔
2102
  double z_o = grid_[2][ijk[2]];
792✔
2103

2104
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2105
}
2106

2107
//==============================================================================
2108
// SphericalMesh implementation
2109
//==============================================================================
2110

2111
SphericalMesh::SphericalMesh(pugi::xml_node node)
356✔
2112
  : PeriodicStructuredMesh {node}
356✔
2113
{
2114
  n_dimension_ = 3;
356✔
2115

2116
  grid_[0] = get_node_array<double>(node, "r_grid");
356✔
2117
  grid_[1] = get_node_array<double>(node, "theta_grid");
356✔
2118
  grid_[2] = get_node_array<double>(node, "phi_grid");
356✔
2119
  origin_ = get_node_position(node, "origin");
356✔
2120

2121
  if (int err = set_grid()) {
356!
2122
    fatal_error(openmc_err_msg);
×
2123
  }
2124
}
356✔
2125

2126
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2127
{
2128
  n_dimension_ = 3;
11✔
2129

2130
  read_dataset(group, "r_grid", grid_[0]);
11✔
2131
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2132
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2133
  read_dataset(group, "origin", origin_);
11✔
2134

2135
  if (int err = set_grid()) {
11!
2136
    fatal_error(openmc_err_msg);
×
2137
  }
2138
}
11✔
2139

2140
const std::string SphericalMesh::mesh_type = "spherical";
2141

2142
std::string SphericalMesh::get_mesh_type() const
385✔
2143
{
2144
  return mesh_type;
385✔
2145
}
2146

2147
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,161✔
2148
  Position r, bool& in_mesh) const
2149
{
2150
  r = local_coords(r);
68,592,161✔
2151

2152
  Position mapped_r;
68,592,161✔
2153
  mapped_r[0] = r.norm();
68,592,161✔
2154

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

2165
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,161✔
2166

2167
  idx[1] = sanitize_theta(idx[1]);
68,592,161✔
2168
  idx[2] = sanitize_phi(idx[2]);
68,592,161✔
2169

2170
  return idx;
68,592,161✔
2171
}
2172

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

2179
  double theta_min = this->theta(ijk[1] - 1);
110✔
2180
  double theta_max = this->theta(ijk[1]);
110✔
2181

2182
  double phi_min = this->phi(ijk[2] - 1);
110✔
2183
  double phi_max = this->phi(ijk[2]);
110✔
2184

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

2194
  double x = r * std::cos(phi) * sin_theta;
110✔
2195
  double y = r * std::sin(phi) * sin_theta;
110✔
2196
  double z = r * cos_theta;
110✔
2197

2198
  return origin_ + Position(x, y, z);
110✔
2199
}
2200

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

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

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

2220
  if (D >= 0.0) {
385,973,643✔
2221
    D = std::sqrt(D);
358,096,695✔
2222
    // Check -p - D first because it is always smaller as -p + D
2223
    if (-p - D > l)
358,096,695✔
2224
      return -p - D;
2225
    if (-p + D > l)
293,782,984✔
2226
      return -p + D;
177,242,131✔
2227
  }
2228

2229
  return INFTY;
2230
}
2231

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

2239
  shell = sanitize_theta(shell);
38,358,540✔
2240

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

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

2252
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2253
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2254
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2255

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

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

2270
    // no crossing is possible
2271
    return INFTY;
2272
  }
2273

2274
  const double p = b / a;
37,875,992✔
2275
  double D = p * p - c / a;
37,875,992✔
2276

2277
  if (D < 0.0)
37,875,992✔
2278
    return INFTY;
2279

2280
  D = std::sqrt(D);
26,921,004✔
2281

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

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

2293
  return INFTY;
2294
}
2295

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

2303
  shell = sanitize_phi(shell);
39,948,018✔
2304

2305
  const double p0 = grid_[2][shell];
39,948,018✔
2306

2307
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2308
  // => x(s) * cos(p0) = y(s) * sin(p0)
2309
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2310
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2311

2312
  const double c0 = std::cos(p0);
39,948,018✔
2313
  const double s0 = std::sin(p0);
39,948,018✔
2314

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

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

2326
  return INFTY;
2327
}
2328

2329
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,947,120✔
2330
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2331
  double l) const
2332
{
2333

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

2339
  } else if (i == 1) {
110,956,153✔
2340
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,707✔
2341
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,707✔
2342
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,707✔
2343
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,414✔
2344

2345
  } else {
2346
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,446✔
2347
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,446✔
2348
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,446✔
2349
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,892✔
2350
  }
2351
}
2352

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

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

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

2389
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
389!
2390
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
389✔
2391

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

2396
  return 0;
389✔
2397
}
2398

2399
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,483✔
2400
{
2401
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,483✔
2402
}
2403

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

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

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

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

2427
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2428
  double theta_o = grid_[1][ijk[1]];
935✔
2429

2430
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2431
  double phi_o = grid_[2][ijk[2]];
935✔
2432

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

2437
//==============================================================================
2438
// Helper functions for the C API
2439
//==============================================================================
2440

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

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

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

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

2471
//==============================================================================
2472
// C API functions
2473
//==============================================================================
2474

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

2481
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,474✔
2482

2483
  return 0;
1,474✔
2484
}
2485

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

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

2510
  return 0;
253✔
2511
}
253✔
2512

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

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

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

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

2542
  // auto-assign new ID
2543
  model::meshes.back()->set_id(-1);
×
2544
  *id = model::meshes.back()->id_;
2545

2546
  return 0;
2547
}
×
2548

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

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

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

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

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

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

2606
  BoundingBox bbox = model::meshes[index]->bounding_box();
154✔
2607

2608
  // set lower left corner values
2609
  ll[0] = bbox.min.x;
154✔
2610
  ll[1] = bbox.min.y;
154✔
2611
  ll[2] = bbox.min.z;
154✔
2612

2613
  // set upper right corner values
2614
  ur[0] = bbox.max.x;
154✔
2615
  ur[1] = bbox.max.y;
154✔
2616
  ur[2] = bbox.max.z;
154✔
2617
  return 0;
154✔
2618
}
2619

2620
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
187✔
2621
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2622
{
2623
  if (int err = check_mesh(index))
187!
2624
    return err;
2625

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

2638
  return 0;
2639
}
2640

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

2648
  int pixel_width = pixels[0];
44✔
2649
  int pixel_height = pixels[1];
44✔
2650

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

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

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

2681
#pragma omp parallel
24✔
2682
  {
20✔
2683
    Position r = xyz;
20✔
2684

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

2695
  return 0;
44✔
2696
}
2697

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

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

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

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

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

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

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

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

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

2775
  // Set material volumes
2776

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

2785
  return 0;
2786
}
220✔
2787

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

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

2799
  m->n_dimension_ = 3;
88✔
2800

2801
  m->grid_[0].reserve(nx);
88✔
2802
  m->grid_[1].reserve(ny);
88✔
2803
  m->grid_[2].reserve(nz);
88✔
2804

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

2815
  int err = m->set_grid();
88✔
2816
  return err;
88✔
2817
}
2818

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

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

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

2840
  return 0;
385✔
2841
}
2842

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

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

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

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

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

2882
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2883
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2884
  ;
121✔
2885
}
2886

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

2896
#ifdef OPENMC_DAGMC_ENABLED
2897

2898
const std::string MOABMesh::mesh_lib_type = "moab";
2899

2900
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2901
{
2902
  initialize();
24✔
2903
}
24!
2904

2905
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2906
{
2907
  initialize();
×
2908
}
×
2909

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

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

2926
void MOABMesh::initialize()
25✔
2927
{
2928

2929
  // Create the MOAB interface and load data from file
2930
  this->create_interface();
25✔
2931

2932
  // Initialise MOAB error code
2933
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2934

2935
  // Set the dimension
2936
  n_dimension_ = 3;
25✔
2937

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

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

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

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

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

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

2997
  // Determine bounds of mesh
2998
  this->determine_bounds();
25✔
2999
}
25✔
3000

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

3007
  // build acceleration data structures
3008
  compute_barycentric_data(ehs_);
21✔
3009
  build_kdtree(ehs_);
21✔
3010
}
3011

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

3018
  // create MOAB instance
3019
  mbi_ = std::make_shared<moab::Core>();
24!
3020

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

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

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

3045
  // combine into one range
3046
  moab::Range all_tets_and_tris;
21✔
3047
  all_tets_and_tris.merge(all_tets);
21✔
3048
  all_tets_and_tris.merge(all_tris);
21✔
3049

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

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

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

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

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

3090
  // remove duplicate intersection distances
3091
  std::unique(hits.begin(), hits.end());
1,543,584✔
3092

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

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

3105
  double track_len = (end - start).length();
1,543,584✔
3106
  if (track_len == 0.0)
1,543,584!
3107
    return;
721,692✔
3108

3109
  start -= TINY_BIT * dir;
1,543,584✔
3110
  end += TINY_BIT * dir;
1,543,584✔
3111

3112
  vector<double> hits;
1,543,584✔
3113
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3114

3115
  bins.clear();
1,543,584!
3116
  lengths.clear();
1,543,584!
3117

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

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

3144
    // determine the start point for this segment
3145
    current = r0 + u * hit;
4,694,269✔
3146

3147
    if (bin == -1) {
4,694,269✔
3148
      continue;
20,522✔
3149
    }
3150

3151
    bins.push_back(bin);
4,673,747✔
3152
    lengths.push_back(segment_length / track_len);
4,673,747✔
3153
  }
3154

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

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

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

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

3195
  // if no tet is found, return an invalid handle
3196
  return 0;
2,847✔
3197
}
14,634,464✔
3198

3199
double MOABMesh::volume(int bin) const
167,880✔
3200
{
3201
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3202
}
3203

3204
std::string MOABMesh::library() const
34✔
3205
{
3206
  return mesh_lib_type;
34✔
3207
}
3208

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

3213
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3214

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

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

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

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

3252
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3253
}
167,880✔
3254

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

3265
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3266
{
3267
  moab::ErrorCode rval;
21✔
3268

3269
  baryc_data_.clear();
21!
3270
  baryc_data_.resize(tets.size());
21✔
3271

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

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

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

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

3295
bool MOABMesh::point_in_tet(
260,208,426✔
3296
  const moab::CartVect& r, moab::EntityHandle tet) const
3297
{
3298

3299
  moab::ErrorCode rval;
260,208,426✔
3300

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

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

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

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

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

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

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

3346
int MOABMesh::get_index_from_bin(int bin) const
3347
{
3348
  return bin;
3349
}
3350

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

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

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

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

3385
int MOABMesh::n_bins() const
267,526,773✔
3386
{
3387
  return ehs_.size();
267,526,773✔
3388
}
3389

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

3403
Position MOABMesh::centroid(int bin) const
3404
{
3405
  moab::ErrorCode rval;
3406

3407
  auto tet = this->get_ent_handle_from_bin(bin);
3408

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

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

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

3432
  return {centroid[0], centroid[1], centroid[2]};
3433
}
3434

3435
int MOABMesh::n_vertices() const
845,874✔
3436
{
3437
  return verts_.size();
845,874✔
3438
}
3439

3440
Position MOABMesh::vertex(int id) const
86,227✔
3441
{
3442

3443
  moab::ErrorCode rval;
86,227✔
3444

3445
  moab::EntityHandle vert = verts_[id];
86,227✔
3446

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

3453
  return {coords[0], coords[1], coords[2]};
86,227✔
3454
}
3455

3456
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3457
{
3458
  moab::ErrorCode rval;
203,880✔
3459

3460
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3461

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

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

3475
  return verts;
203,880✔
3476
}
203,880✔
3477

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

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

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

3513
  // return the populated tag handles
3514
  return {value_tag, error_tag};
3515
}
3516

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

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

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

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

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

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

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

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

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

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

3603
#endif
3604

3605
#ifdef OPENMC_LIBMESH_ENABLED
3606

3607
const std::string LibMesh::mesh_lib_type = "libmesh";
3608

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

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

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

3635
  m_ = &input_mesh;
3636
  set_length_multiplier(length_multiplier);
×
3637
  initialize();
×
3638
}
3639

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

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

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

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

3675
  // assuming that unstructured meshes used in OpenMC are 3D
3676
  n_dimension_ = 3;
23✔
3677

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

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

3691
  for (int i = 0; i < num_threads(); i++) {
69✔
3692
    pl_.emplace_back(m_->sub_point_locator());
46✔
3693
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3694
    pl_.back()->enable_out_of_mesh_mode();
46✔
3695
  }
3696

3697
  // store first element in the mesh to use as an offset for bin indices
3698
  auto first_elem = *m_->elements_begin();
46✔
3699
  first_element_id_ = first_elem->id();
23✔
3700

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

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

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

3746
int LibMesh::n_vertices() const
39,978✔
3747
{
3748
  return m_->n_nodes();
39,978✔
3749
}
3750

3751
Position LibMesh::vertex(int vertex_id) const
39,942✔
3752
{
3753
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3754
  if (length_multiplier_ > 0.0) {
39,942!
3755
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3756
  } else {
3757
    return {node_ref(0), node_ref(1), node_ref(2)};
39,942✔
3758
  }
3759
}
39,942✔
3760

3761
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
3762
{
3763
  std::vector<int> conn;
265,856✔
3764
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
3765
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
3766
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
3767
  }
3768
  return conn;
265,856✔
3769
}
3770

3771
std::string LibMesh::library() const
33✔
3772
{
3773
  return mesh_lib_type;
33✔
3774
}
3775

3776
int LibMesh::n_bins() const
1,784,407✔
3777
{
3778
  return m_->n_elem();
1,784,407✔
3779
}
3780

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

3799
void LibMesh::add_score(const std::string& var_name)
15✔
3800
{
3801
  if (!equation_systems_) {
15!
3802
    build_eqn_sys();
15✔
3803
  }
3804

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

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

3824
void LibMesh::remove_scores()
15✔
3825
{
3826
  if (equation_systems_) {
15!
3827
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3828
    eqn_sys.clear();
15✔
3829
    variable_map_.clear();
15✔
3830
  }
3831
}
15✔
3832

3833
void LibMesh::set_score_data(const std::string& var_name,
15✔
3834
  const vector<double>& values, const vector<double>& std_dev)
3835
{
3836
  if (!equation_systems_) {
15!
3837
    build_eqn_sys();
3838
  }
3839

3840
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3841

3842
  if (!eqn_sys.is_initialized()) {
15!
3843
    equation_systems_->init();
15✔
3844
  }
3845

3846
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3847

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

3855
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
195,757✔
3856
       it++) {
3857
    if (!(*it)->active()) {
97,856!
3858
      continue;
3859
    }
3860

3861
    auto bin = get_bin_from_element(*it);
97,856✔
3862

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

3869
    // set std dev
3870
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
3871
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
3872
    assert(std_dev_dof_indices.size() == 1);
97,856✔
3873
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
3874
  }
97,871✔
3875
}
15✔
3876

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

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

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

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

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

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

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

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

3924
std::pair<vector<double>, vector<double>> LibMesh::plot(
3925
  Position plot_ll, Position plot_ur) const
3926
{
3927
  return {};
3928
}
3929

3930
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3931
{
3932
  return m_->elem_ref(bin);
765,460✔
3933
}
3934

3935
double LibMesh::volume(int bin) const
364,640✔
3936
{
3937
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
364,640✔
3938
         length_multiplier_ * length_multiplier_;
364,640✔
3939
}
3940

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

3968
int AdaptiveLibMesh::n_bins() const
3969
{
3970
  return num_active_;
3971
}
3972

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

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

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

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

4000
  if (length_multiplier_ > 0.0) {
×
4001
    // Scale the point down
4002
    p /= length_multiplier_;
4003
  }
4004

4005
  // quick rejection check
4006
  if (!bbox_.contains_point(p)) {
×
4007
    return -1;
4008
  }
4009

4010
  const auto& point_locator = pl_.at(thread_num());
×
4011

4012
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4013
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4014
}
4015

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

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

4030
#endif // OPENMC_LIBMESH_ENABLED
4031

4032
//==============================================================================
4033
// Non-member functions
4034
//==============================================================================
4035

4036
void read_meshes(pugi::xml_node root)
12,742✔
4037
{
4038
  std::unordered_set<int> mesh_ids;
12,742✔
4039

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

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

4057
    std::string mesh_type;
3,044✔
4058
    if (check_for_node(node, "type")) {
3,044✔
4059
      mesh_type = get_node_value(node, "type", true, true);
948✔
4060
    } else {
4061
      mesh_type = "regular";
2,096✔
4062
    }
4063

4064
    // determine the mesh library to use
4065
    std::string mesh_lib;
3,044✔
4066
    if (check_for_node(node, "library")) {
3,044✔
4067
      mesh_lib = get_node_value(node, "library", true, true);
47!
4068
    }
4069

4070
    Mesh::create(node, mesh_type, mesh_lib);
3,044✔
4071
  }
3,044✔
4072
}
12,742✔
4073

4074
void read_meshes(hid_t group)
22✔
4075
{
4076
  std::unordered_set<int> mesh_ids;
22✔
4077

4078
  std::vector<int> ids;
22✔
4079
  read_attribute(group, "ids", ids);
22✔
4080

4081
  for (auto id : ids) {
55✔
4082

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

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

4098
    std::string name = fmt::format("mesh {}", id);
×
4099
    hid_t mesh_group = open_group(group, name.c_str());
×
4100

4101
    std::string mesh_type;
×
4102
    if (object_exists(mesh_group, "type")) {
×
4103
      read_dataset(mesh_group, "type", mesh_type);
×
4104
    } else {
4105
      mesh_type = "regular";
×
4106
    }
4107

4108
    // determine the mesh library to use
4109
    std::string mesh_lib;
×
4110
    if (object_exists(mesh_group, "library")) {
×
4111
      read_dataset(mesh_group, "library", mesh_lib);
×
4112
    }
4113

4114
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4115
  }
×
4116
}
44✔
4117

4118
void meshes_to_hdf5(hid_t group)
7,071✔
4119
{
4120
  // Write number of meshes
4121
  hid_t meshes_group = create_group(group, "meshes");
7,071✔
4122
  int32_t n_meshes = model::meshes.size();
7,071✔
4123
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,071✔
4124

4125
  if (n_meshes > 0) {
7,071✔
4126
    // Write IDs of meshes
4127
    vector<int> ids;
2,181✔
4128
    for (const auto& m : model::meshes) {
4,941✔
4129
      m->to_hdf5(meshes_group);
2,760✔
4130
      ids.push_back(m->id_);
2,760✔
4131
    }
4132
    write_attribute(meshes_group, "ids", ids);
2,181✔
4133
  }
2,181✔
4134

4135
  close_group(meshes_group);
7,071✔
4136
}
7,071✔
4137

4138
void free_memory_mesh()
8,379✔
4139
{
4140
  model::meshes.clear();
8,379✔
4141
  model::mesh_map.clear();
8,379✔
4142
}
8,379✔
4143

4144
extern "C" int n_meshes()
308✔
4145
{
4146
  return model::meshes.size();
308✔
4147
}
4148

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

© 2026 Coveralls, Inc