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

openmc-dev / openmc / 26783873914

01 Jun 2026 09:43PM UTC coverage: 81.362% (+0.03%) from 81.333%
26783873914

Pull #3948

github

web-flow
Merge 6314ea576 into 111eb7706
Pull Request #3948: Fix get_index_in_direction for regular meshes

18027 of 26121 branches covered (69.01%)

Branch coverage included in aggregate %.

43 of 45 new or added lines in 9 files covered. (95.56%)

443 existing lines in 12 files now uncovered.

59175 of 68766 relevant lines covered (86.05%)

48551677.44 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,575✔
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,575✔
126
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
127

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

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

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

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

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

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

187
inline void atomic_max_double(double* ptr, double value)
19,233,792✔
188
{
189
  atomic_update_double(ptr, value, false);
6,411,264✔
190
}
6,411,264✔
191

192
inline void atomic_min_double(double* ptr, double value)
19,233,792✔
193
{
194
  atomic_update_double(ptr, value, true);
6,411,264✔
195
}
196

197
namespace detail {
198

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

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

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

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

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

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,575!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,575✔
242
      bool claimed_slot =
1,575✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,575✔
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,575!
248
#pragma omp atomic
872✔
249
        this->volumes(index_elem, slot) += volume;
1,575✔
250
        if (bbox) {
1,575✔
251
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
175✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
175✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
175✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
175✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
175✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
175✔
257
        }
258
        return;
1,575✔
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,225✔
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,225✔
338
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
2,342✔
339
  } else if (mesh_type == RectilinearMesh::mesh_type) {
883✔
340
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
111✔
341
  } else if (mesh_type == CylindricalMesh::mesh_type) {
772✔
342
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
389✔
343
  } else if (mesh_type == SphericalMesh::mesh_type) {
383✔
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 &&
25!
352
             mesh_library == LibMesh::mesh_lib_type) {
25!
353
    model::meshes.push_back(make_unique<LibMesh>(dataset));
25✔
354
#endif
355
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
356
    fatal_error("Unstructured mesh support is not enabled or the mesh "
×
357
                "library is invalid.");
358
  } else {
359
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
360
  }
361

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

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

368
Mesh::Mesh(pugi::xml_node node)
3,291✔
369
{
370
  // Read mesh id
371
  id_ = std::stoi(get_node_value(node, "id"));
6,582✔
372
  if (check_for_node(node, "name"))
3,291✔
373
    name_ = get_node_value(node, "name");
15✔
374
}
3,291✔
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
287✔
424
{
425
  vector<double> volumes(n_bins());
287✔
426
  for (int i = 0; i < n_bins(); i++) {
1,122,895✔
427
    volumes[i] = this->volume(i);
1,122,608✔
428
  }
429
  return volumes;
287✔
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,
209✔
439
  int32_t* materials, double* volumes, double* bboxes) const
440
{
441
  if (mpi::master) {
209!
442
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
209✔
443
  }
444
  write_message(7, "Number of mesh elements = {}", n_bins());
209✔
445
  write_message(7, "Number of rays (x) = {}", nx);
209✔
446
  write_message(7, "Number of rays (y) = {}", ny);
209✔
447
  write_message(7, "Number of rays (z) = {}", nz);
209✔
448
  int64_t n_total = static_cast<int64_t>(nx) * ny +
209✔
449
                    static_cast<int64_t>(ny) * nz +
209✔
450
                    static_cast<int64_t>(nx) * nz;
209✔
451
  write_message(7, "Total number of rays = {}", n_total);
209✔
452
  write_message(7, "Table size per mesh element = {}", table_size);
209✔
453

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

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

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

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

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

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

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

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

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

493
      // Determine width of rays and number of rays in other directions
494
      int ax1 = (axis + 1) % 3;
285✔
495
      int ax2 = (axis + 2) % 3;
285✔
496
      double min1 = bbox.min[ax1];
285✔
497
      double min2 = bbox.min[ax2];
285✔
498
      double d1 = width[ax1];
285✔
499
      double d2 = width[ax2];
285✔
500
      int n1 = n_rays[ax1];
285✔
501
      int n2 = n_rays[ax2];
285✔
502
      if (n1 == 0 || n2 == 0) {
285✔
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;
225✔
509
      int remainder = n1 % mpi::n_procs;
225✔
510
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
225!
511
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
225!
512
      int i1_end = i1_start + n1_local;
225✔
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) {
17,600✔
517
        for (int i2 = 0; i2 < n2; ++i2) {
3,080,220✔
518
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,062,845✔
519
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,062,845✔
520

521
          p.from_source(&site);
3,062,845✔
522

523
          // Determine particle's location
524
          if (!exhaustive_find_cell(p)) {
3,062,845✔
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)
3,022,915!
531
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
532

533
          // Initialize last cells from current cell
534
          for (int j = 0; j < p.n_coord(); ++j) {
6,045,830✔
535
            p.cell_last(j) = p.coord(j).cell();
3,022,915✔
536
          }
537
          p.n_coord_last() = p.n_coord();
3,022,915✔
538

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

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

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

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

556
            // Add volumes to any mesh elements that were crossed
557
            int i_material = p.material();
3,899,715✔
558
            if (i_material != C_NONE) {
3,899,715✔
559
              i_material = model::materials[i_material]->id();
1,234,005✔
560
            }
561
            double cumulative_frac = 0.0;
3,899,715✔
562
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
8,018,080✔
563
              int mesh_index = bins[i_bin];
4,118,365✔
564
              double length = distance * length_fractions[i_bin];
4,118,365✔
565
              double volume = length * d1 * d2;
4,118,365✔
566

567
              if (compute_bboxes) {
4,118,365✔
568
                double axis_start = r0[axis] + distance * cumulative_frac;
2,912,280✔
569
                double axis_end = axis_start + length;
2,912,280✔
570
                cumulative_frac += length_fractions[i_bin];
2,912,280✔
571

572
                Position contrib_min = site.r;
2,912,280✔
573
                Position contrib_max = site.r;
2,912,280✔
574

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

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

585
                result.add_volume(
2,912,280✔
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,899,715✔
594
              break;
595

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

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

606
            if (boundary.lattice_translation()[0] != 0 ||
876,800!
607
                boundary.lattice_translation()[1] != 0 ||
876,800!
608
                boundary.lattice_translation()[2] != 0) {
876,800!
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()};
876,800✔
614
              p.cross_surface(*surf);
876,800✔
615
            }
616
          }
876,800✔
617
        }
618
      }
619
    }
620
  }
95✔
621

622
  // Check for errors
623
  if (out_of_model) {
209✔
624
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
625
  } else if (result.table_full()) {
198!
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();
198✔
632

633
#ifdef OPENMC_MPI
634
  // Combine results from multiple MPI processes
635
  if (mpi::n_procs > 1) {
72!
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;
72✔
693
#else
694
  double t_mpi = 0.0;
108✔
695
#endif
696

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

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

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

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

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

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

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

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

749
  // Close group
750
  close_group(mesh_group);
3,160✔
751
}
3,160✔
752

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

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

761
  if (n_dimension_ > 2) {
5,160,280✔
762
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,144,341✔
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,763✔
771
{
772
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,763✔
773
}
774

775
Position StructuredMesh::sample_element(
1,434,199✔
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,434,199✔
780
  double x_max = positive_grid_boundary(ijk, 0);
1,434,199✔
781

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

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

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

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

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

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

808
  // check if a length unit multiplier was specified
809
  if (check_for_node(node, "length_multiplier")) {
49!
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")) {
49!
815
    filename_ = get_node_value(node, "filename");
49!
816
    if (!file_exists(filename_)) {
49!
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")) {
49!
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")) {
49!
831
    output_ = get_node_value_bool(node, "output");
×
832
  }
833
}
49✔
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

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

897
Position UnstructuredMesh::sample_tet(
601,230✔
898
  std::array<Position, 4> coords, uint64_t* seed) const
899
{
900
  // Uniform distribution
901
  double s = prn(seed);
601,230✔
902
  double t = prn(seed);
601,230✔
903
  double u = prn(seed);
601,230✔
904

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

927
const std::string UnstructuredMesh::mesh_type = "unstructured";
928

929
std::string UnstructuredMesh::get_mesh_type() const
34✔
930
{
931
  return mesh_type;
34✔
932
}
933

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

940
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
941
{
942
  return fmt::format("Mesh Index ({})", bin);
207,736✔
943
};
944

945
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
946
{
947
  write_dataset(mesh_group, "filename", filename_);
34!
948
  write_dataset(mesh_group, "library", this->library());
34!
949
  if (!options_.empty()) {
34✔
950
    write_attribute(mesh_group, "options", options_);
8✔
951
  }
952

953
  if (length_multiplier_ > 0.0)
34!
954
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
955

956
  // write vertex coordinates
957
  tensor::Tensor<double> vertices(
34✔
958
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
34✔
959
  for (int i = 0; i < this->n_vertices(); i++) {
72,939!
960
    auto v = this->vertex(i);
72,905!
961
    vertices.slice(i) = {v.x, v.y, v.z};
145,810!
962
  }
963
  write_dataset(mesh_group, "vertices", vertices);
34!
964

965
  int num_elem_skipped = 0;
34✔
966

967
  // write element types and connectivity
968
  vector<double> volumes;
34!
969
  tensor::Tensor<int> connectivity(
34✔
970
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
971
  tensor::Tensor<int> elem_types(
34✔
972
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
973
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
974
    auto conn = this->connectivity(i);
351,736!
975

976
    volumes.emplace_back(this->volume(i));
351,736!
977

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

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

1003
  write_dataset(mesh_group, "volumes", volumes);
34!
1004
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1005
  write_dataset(mesh_group, "element_types", elem_types);
34!
1006
}
102✔
1007

1008
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
25✔
1009
{
1010
  length_multiplier_ = length_multiplier;
25✔
1011
}
25✔
1012

1013
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1014
{
1015
  auto conn = connectivity(bin);
120,000✔
1016

1017
  if (conn.size() == 4)
120,000!
1018
    return ElementType::LINEAR_TET;
1019
  else if (conn.size() == 8)
×
1020
    return ElementType::LINEAR_HEX;
1021
  else
1022
    return ElementType::UNSUPPORTED;
×
1023
}
120,000✔
1024

1025
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,584,342,848✔
1026
  Position r, Direction u, bool& in_mesh) const
1027
{
1028
  MeshIndex ijk;
1,584,342,848✔
1029
  in_mesh = true;
1,584,342,848✔
1030
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1031
    ijk[i] = get_index_in_direction(r[i], u[i], i);
2,147,483,647✔
1032

1033
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1034
      in_mesh = false;
105,112,662✔
1035
  }
1036
  return ijk;
1,584,342,848✔
1037
}
1038

1039
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1040
{
1041
  switch (n_dimension_) {
2,147,483,647!
1042
  case 1:
880,605✔
1043
    return ijk[0] - 1;
880,605✔
1044
  case 2:
136,375,228✔
1045
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
136,375,228✔
1046
  case 3:
2,045,931,690✔
1047
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,045,931,690✔
1048
  default:
×
1049
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1050
  }
1051
}
1052

1053
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,808,420✔
1054
{
1055
  MeshIndex ijk;
7,808,420✔
1056
  if (n_dimension_ == 1) {
7,808,420✔
1057
    ijk[0] = bin + 1;
275✔
1058
  } else if (n_dimension_ == 2) {
7,808,145✔
1059
    ijk[0] = bin % shape_[0] + 1;
15,664✔
1060
    ijk[1] = bin / shape_[0] + 1;
15,664✔
1061
  } else if (n_dimension_ == 3) {
7,792,481!
1062
    ijk[0] = bin % shape_[0] + 1;
7,792,481✔
1063
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,792,481✔
1064
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,792,481✔
1065
  }
1066
  return ijk;
7,808,420✔
1067
}
1068

1069
int StructuredMesh::get_bin(Position r, Direction u) const
408,881,142✔
1070
{
1071
  // Determine indices
1072
  bool in_mesh;
408,881,142✔
1073
  MeshIndex ijk = get_indices(r, u, in_mesh);
408,881,142✔
1074
  if (!in_mesh)
408,881,142✔
1075
    return -1;
1076

1077
  // Convert indices to bin
1078
  return get_bin_from_indices(ijk);
387,861,045✔
1079
}
1080

1081
int StructuredMesh::n_bins() const
1,137,913✔
1082
{
1083
  return std::accumulate(
2,275,826✔
1084
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,137,913✔
1085
}
1086

1087
int StructuredMesh::n_surface_bins() const
370✔
1088
{
1089
  return 4 * n_dimension_ * n_bins();
370✔
1090
}
1091

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

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

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

1106
    // determine scoring bin for entropy mesh
NEW
1107
    int mesh_bin = get_bin(site.r, site.u);
×
1108

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

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

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

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

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

1138
  return counts;
×
1139
}
×
1140

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

1154
  // Compute the length of the entire track.
1155
  double total_distance = (r1 - r0).norm();
1,212,263,716✔
1156
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,212,263,716✔
1157
    return;
1158

1159
  // keep a copy of the original global position to pass to get_indices,
1160
  // which performs its own transformation to local coordinates
1161
  Position global_r = r0;
1,168,197,306✔
1162
  Position local_r = local_coords(r0);
1,168,197,306✔
1163

1164
  const int n = n_dimension_;
1,168,197,306✔
1165

1166
  // Flag if position is inside the mesh
1167
  bool in_mesh;
1168

1169
  // Position is r = r0 + u * traveled_distance, start at r0
1170
  double traveled_distance {0.0};
1,168,197,306✔
1171

1172
  // Calculate index of current cell. Offset the position a tiny bit in
1173
  // direction of flight
1174
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, u, in_mesh);
1,168,197,306✔
1175

1176
  // if track is very short, assume that it is completely inside one cell.
1177
  // Only the current cell will score and no surfaces
1178
  if (total_distance < 2 * TINY_BIT) {
1,168,197,306✔
1179
    if (in_mesh) {
361,844✔
1180
      tally.track(ijk, 1.0);
361,360✔
1181
    }
1182
    return;
361,844✔
1183
  }
1184

1185
  // Calculate initial distances to next surfaces in all three dimensions
1186
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1187
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1188
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1189
  }
1190

1191
  // Loop until r = r1 is eventually reached
1192
  while (true) {
1193

1194
    if (in_mesh) {
1,965,767,479✔
1195

1196
      // find surface with minimal distance to current position
1197
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,876,850,493✔
1198
                     distances.begin();
1,876,850,493✔
1199

1200
      // Tally track length delta since last step
1201
      tally.track(ijk,
1,876,850,493✔
1202
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1203
          total_distance);
1204

1205
      // update position and leave, if we have reached end position
1206
      traveled_distance = distances[k].distance;
1,876,850,493✔
1207
      if (traveled_distance >= total_distance)
1,876,850,493✔
1208
        return;
1209

1210
      // If we have not reached r1, we have hit a surface. Tally outward
1211
      // current
1212
      tally.surface(ijk, k, distances[k].max_surface, false);
790,667,617✔
1213

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

1220
      // Check if we have left the interior of the mesh
1221
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
797,574,473✔
1222

1223
      // If we are still inside the mesh, tally inward current for the next
1224
      // cell
1225
      if (in_mesh)
29,576,899✔
1226
        tally.surface(ijk, k, !distances[k].max_surface, true);
796,515,800✔
1227

1228
    } else { // not inside mesh
1229

1230
      // For all directions outside the mesh, find the distance that we need
1231
      // to travel to reach the next surface. Use the largest distance, as
1232
      // only this will cross all outer surfaces.
1233
      int k_max {-1};
1234
      for (int k = 0; k < n; ++k) {
354,223,578✔
1235
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
265,306,592✔
1236
            (distances[k].distance > traveled_distance)) {
96,924,901✔
1237
          traveled_distance = distances[k].distance;
1238
          k_max = k;
1239
        }
1240
      }
1241
      // Assure some distance is traveled
1242
      if (k_max == -1) {
88,916,986✔
1243
        traveled_distance += TINY_BIT;
110✔
1244
      }
1245

1246
      // If r1 is not inside the mesh, exit here
1247
      if (traveled_distance >= total_distance)
88,916,986✔
1248
        return;
1249

1250
      // Calculate the new cell index and update all distances to next
1251
      // surfaces.
1252
      ijk =
1253
        get_indices(global_r + (traveled_distance + TINY_BIT) * u, u, in_mesh);
7,264,400✔
1254
      for (int k = 0; k < n; ++k) {
28,849,062✔
1255
        distances[k] =
21,584,662✔
1256
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,584,662✔
1257
      }
1258

1259
      // If inside the mesh, Tally inward current
1260
      if (in_mesh && k_max >= 0)
7,264,400!
1261
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
768,332,150✔
1262
    }
1263
  }
1264
}
1265

1266
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,100,136,151✔
1267
  vector<int>& bins, vector<double>& lengths) const
1268
{
1269

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

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

1290
  // Perform the mesh raytrace with the helper class.
1291
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,100,136,151✔
1292
}
1,100,136,151✔
1293

1294
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1295
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1296
{
1297

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

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

1321
  // Perform the mesh raytrace with the helper class.
1322
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1323
}
112,127,565✔
1324

1325
//==============================================================================
1326
// RegularMesh implementation
1327
//==============================================================================
1328

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

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

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

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

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

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

1364
  } else if (upper_right_.size() > 0) {
2,329!
1365

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

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

1381
    // Set width
1382
    width_ = (upper_right_ - lower_left_) / shape;
6,987✔
1383
  }
1384

1385
  // Set material volumes
1386
  volume_frac_ = 1.0 / shape.prod();
2,375✔
1387

1388
  element_volume_ = 1.0;
2,375✔
1389
  for (int i = 0; i < n_dimension_; i++) {
8,953✔
1390
    element_volume_ *= width_[i];
6,578✔
1391
  }
1392
  return 0;
1393
}
2,375✔
1394

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

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

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

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

1423
    width_ = get_node_tensor<double>(node, "width");
92✔
1424

1425
  } else if (check_for_node(node, "upper_right")) {
2,318!
1426

1427
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,636✔
1428

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

1433
  if (int err = set_grid()) {
2,364!
1434
    fatal_error(openmc_err_msg);
×
1435
  }
1436
}
2,364✔
1437

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

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

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

1461
  if (object_exists(group, "upper_right")) {
11!
1462

1463
    read_dataset(group, "upper_right", upper_right_);
11✔
1464

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

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

1474
int RegularMesh::get_index_in_direction(double r, double u, int i) const
2,147,483,647✔
1475
{
1476
  int idx = std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1477

1478
  // If on upper boundary with positive direction, use next index
1479
  if (r == lower_left_[i] + width_[i] * idx) {
2,147,483,647✔
1480
    if (u > 0.0) {
278,876✔
1481
      idx++;
146,527✔
1482
    }
1483
  }
1484

1485
  return idx;
2,147,483,647✔
1486
}
1487

1488
const std::string RegularMesh::mesh_type = "regular";
1489

1490
std::string RegularMesh::get_mesh_type() const
3,478✔
1491
{
1492
  return mesh_type;
3,478✔
1493
}
1494

1495
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,864,496,375✔
1496
{
1497
  return lower_left_[i] + ijk[i] * width_[i];
1,864,496,375✔
1498
}
1499

1500
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,795,424,928✔
1501
{
1502
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,795,424,928✔
1503
}
1504

1505
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1506
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1507
  double l) const
1508
{
1509
  MeshDistance d;
2,147,483,647✔
1510
  d.next_index = ijk[i];
2,147,483,647✔
1511
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1512
    return d;
15,248,952✔
1513

1514
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1515
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1516
    d.next_index++;
1,860,193,778✔
1517
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,860,193,778✔
1518
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,814,113,844✔
1519
    d.next_index--;
1,791,122,331✔
1520
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,791,122,331✔
1521
  }
1522

1523
  return d;
2,147,483,647✔
1524
}
1525

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

1548
  // Get the coordinates of the mesh lines along both of the axes.
1549
  array<vector<double>, 2> axis_lines;
1550
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1551
    int axis = axes[i_ax];
44!
1552
    if (axis == -1)
44!
1553
      continue;
×
1554
    auto& lines {axis_lines[i_ax]};
44✔
1555

1556
    double coord = lower_left_[axis];
44✔
1557
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1558
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1559
        lines.push_back(coord);
242✔
1560
      coord += width_[axis];
242✔
1561
    }
1562
  }
1563

1564
  return {axis_lines[0], axis_lines[1]};
44✔
1565
}
1566

1567
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,323✔
1568
{
1569
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,323✔
1570
  write_dataset(mesh_group, "lower_left", lower_left_);
2,323✔
1571
  write_dataset(mesh_group, "upper_right", upper_right_);
2,323✔
1572
  write_dataset(mesh_group, "width", width_);
2,323✔
1573
}
2,323✔
1574

1575
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1576
  const SourceSite* bank, int64_t length, bool* outside) const
1577
{
1578
  // Determine shape of array for counts
1579
  std::size_t m = this->n_bins();
7,820✔
1580
  vector<std::size_t> shape = {m};
7,820✔
1581

1582
  // Create array of zeros
1583
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1584
  bool outside_ = false;
2,892✔
1585

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

1589
    // determine scoring bin for entropy mesh
1590
    int mesh_bin = get_bin(site.r, site.u);
7,667,451✔
1591

1592
    // if outside mesh, skip particle
1593
    if (mesh_bin < 0) {
7,667,451!
1594
      outside_ = true;
×
1595
      continue;
×
1596
    }
1597

1598
    // Add to appropriate bin
1599
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1600
  }
1601

1602
  // Create reduced count data
1603
  auto counts = tensor::zeros<double>(shape);
7,820✔
1604
  int total = cnt.size();
7,820✔
1605

1606
#ifdef OPENMC_MPI
1607
  // collect values from all processors
1608
  MPI_Reduce(
2,892✔
1609
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1610

1611
  // Check if there were sites outside the mesh for any processor
1612
  if (outside) {
2,892!
1613
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1614
  }
1615
#else
1616
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1617
  if (outside)
4,928!
1618
    *outside = outside_;
4,928✔
1619
#endif
1620

1621
  return counts;
7,820✔
1622
}
7,820✔
1623

1624
double RegularMesh::volume(const MeshIndex& ijk) const
1,123,862✔
1625
{
1626
  return element_volume_;
1,123,862✔
1627
}
1628

1629
//==============================================================================
1630
// RectilinearMesh implementation
1631
//==============================================================================
1632

1633
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1634
{
1635
  n_dimension_ = 3;
133✔
1636

1637
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1638
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1639
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1640

1641
  if (int err = set_grid()) {
133!
1642
    fatal_error(openmc_err_msg);
×
1643
  }
1644
}
133✔
1645

1646
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1647
{
1648
  n_dimension_ = 3;
11✔
1649

1650
  read_dataset(group, "x_grid", grid_[0]);
11✔
1651
  read_dataset(group, "y_grid", grid_[1]);
11✔
1652
  read_dataset(group, "z_grid", grid_[2]);
11✔
1653

1654
  if (int err = set_grid()) {
11!
1655
    fatal_error(openmc_err_msg);
×
1656
  }
1657
}
11✔
1658

1659
const std::string RectilinearMesh::mesh_type = "rectilinear";
1660

1661
std::string RectilinearMesh::get_mesh_type() const
275✔
1662
{
1663
  return mesh_type;
275✔
1664
}
1665

1666
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1667
  const MeshIndex& ijk, int i) const
1668
{
1669
  return grid_[i][ijk[i]];
26,505,963✔
1670
}
1671

1672
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1673
  const MeshIndex& ijk, int i) const
1674
{
1675
  return grid_[i][ijk[i] - 1];
25,739,406✔
1676
}
1677

1678
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087✔
1679
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1680
  double l) const
1681
{
1682
  MeshDistance d;
53,602,087✔
1683
  d.next_index = ijk[i];
53,602,087✔
1684
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087✔
1685
    return d;
571,824✔
1686

1687
  d.max_surface = (u[i] > 0);
53,030,263✔
1688
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263✔
1689
    d.next_index++;
26,505,963✔
1690
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963✔
1691
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300✔
1692
    d.next_index--;
25,739,406✔
1693
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1694
  }
1695
  return d;
53,030,263✔
1696
}
1697

1698
int RectilinearMesh::set_grid()
188✔
1699
{
1700
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1701
    static_cast<int>(grid_[1].size()) - 1,
188✔
1702
    static_cast<int>(grid_[2].size()) - 1};
188✔
1703

1704
  for (const auto& g : grid_) {
752✔
1705
    if (g.size() < 2) {
564!
1706
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1707
                 "must each have at least 2 points");
1708
      return OPENMC_E_INVALID_ARGUMENT;
×
1709
    }
1710
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
564!
1711
        g.end()) {
564!
1712
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1713
                 "rectilinear meshes must be sorted and unique.");
1714
      return OPENMC_E_INVALID_ARGUMENT;
×
1715
    }
1716
  }
1717

1718
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1719
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1720

1721
  return 0;
188✔
1722
}
1723

1724
int RectilinearMesh::get_index_in_direction(double r, double u, int i) const
74,109,046✔
1725
{
1726
  int idx = lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,109,046✔
1727

1728
  // If on lower boundary with negative direction, use previous index
1729
  if (r == grid_[i][idx - 1]) {
74,109,046✔
1730
    if (u < 0) {
22✔
1731
      idx--;
11✔
1732
    }
1733
  }
1734

1735
  // If on upper boundary with positive direction, use next index
1736
  if (r == grid_[i][idx]) {
74,109,046✔
1737
    if (u > 0) {
6,809✔
1738
      idx++;
22✔
1739
    }
1740
  }
1741

1742
  return idx;
74,109,046✔
1743
}
1744

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

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

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

1772
  return {axis_lines[0], axis_lines[1]};
22✔
1773
}
1774

1775
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1776
{
1777
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1778
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1779
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1780
}
110✔
1781

1782
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1783
{
1784
  double vol {1.0};
132✔
1785

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

1792
//==============================================================================
1793
// CylindricalMesh implementation
1794
//==============================================================================
1795

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

1805
  if (int err = set_grid()) {
400!
1806
    fatal_error(openmc_err_msg);
×
1807
  }
1808
}
400✔
1809

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

1818
  if (int err = set_grid()) {
11!
1819
    fatal_error(openmc_err_msg);
×
1820
  }
1821
}
11✔
1822

1823
const std::string CylindricalMesh::mesh_type = "cylindrical";
1824

1825
std::string CylindricalMesh::get_mesh_type() const
484✔
1826
{
1827
  return mesh_type;
484✔
1828
}
1829

1830
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1831
  Position r, Direction u, bool& in_mesh) const
1832
{
1833
  r = local_coords(r);
47,732,091✔
1834

1835
  Position mapped_r;
47,732,091✔
1836
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1837
  mapped_r[2] = r[2];
47,732,091✔
1838

1839
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1840
    mapped_r[1] = 0.0;
1841
  } else {
1842
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1843
    if (mapped_r[1] < 0)
47,732,091✔
1844
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1845
  }
1846

1847
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, u, in_mesh);
47,732,091✔
1848

1849
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1850

1851
  return idx;
47,732,091✔
1852
}
1853

1854
Position CylindricalMesh::sample_element(
88,110✔
1855
  const MeshIndex& ijk, uint64_t* seed) const
1856
{
1857
  double r_min = this->r(ijk[0] - 1);
88,110✔
1858
  double r_max = this->r(ijk[0]);
88,110✔
1859

1860
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1861
  double phi_max = this->phi(ijk[1]);
88,110✔
1862

1863
  double z_min = this->z(ijk[2] - 1);
88,110✔
1864
  double z_max = this->z(ijk[2]);
88,110✔
1865

1866
  double r_min_sq = r_min * r_min;
88,110✔
1867
  double r_max_sq = r_max * r_max;
88,110✔
1868
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1869
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1870
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1871

1872
  double x = r * std::cos(phi);
88,110✔
1873
  double y = r * std::sin(phi);
88,110✔
1874

1875
  return origin_ + Position(x, y, z);
88,110✔
1876
}
1877

1878
double CylindricalMesh::find_r_crossing(
142,588,486✔
1879
  const Position& r, const Direction& u, double l, int shell) const
1880
{
1881

1882
  if ((shell < 0) || (shell > shape_[0]))
142,588,486!
1883
    return INFTY;
1884

1885
  // solve r.x^2 + r.y^2 == r0^2
1886
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1887
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1888

1889
  const double r0 = grid_[0][shell];
124,674,511✔
1890
  if (r0 == 0.0)
124,674,511✔
1891
    return INFTY;
1892

1893
  const double denominator = u.x * u.x + u.y * u.y;
117,538,437✔
1894

1895
  // Direction of flight is in z-direction. Will never intersect r.
1896
  if (std::abs(denominator) < FP_PRECISION)
117,538,437✔
1897
    return INFTY;
1898

1899
  // inverse of dominator to help the compiler to speed things up
1900
  const double inv_denominator = 1.0 / denominator;
117,479,477✔
1901

1902
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,479,477✔
1903
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,479,477✔
1904
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,479,477✔
1905

1906
  if (D < 0.0)
117,479,477✔
1907
    return INFTY;
1908

1909
  D = std::sqrt(D);
107,743,355✔
1910

1911
  // Particle is already on the shell surface; avoid spurious crossing
1912
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,743,355✔
1913
    return INFTY;
1914

1915
  // Check -p - D first because it is always smaller as -p + D
1916
  if (-p - D > l)
101,109,981✔
1917
    return -p - D;
1918
  if (-p + D > l)
80,902,376✔
1919
    return -p + D;
50,078,497✔
1920

1921
  return INFTY;
1922
}
1923

1924
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1925
  const Position& r, const Direction& u, double l, int shell) const
1926
{
1927
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1928
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1929
    return INFTY;
1930

1931
  shell = sanitize_phi(shell);
43,970,718✔
1932

1933
  const double p0 = grid_[1][shell];
43,970,718✔
1934

1935
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1936
  // => x(s) * cos(p0) = y(s) * sin(p0)
1937
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1938
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1939

1940
  const double c0 = std::cos(p0);
43,970,718✔
1941
  const double s0 = std::sin(p0);
43,970,718✔
1942

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

1945
  // Check if direction of flight is not parallel to phi surface
1946
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1947
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1948
    // Check if solution is in positive direction of flight and crosses the
1949
    // correct phi surface (not -phi)
1950
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1951
      return s;
20,219,859✔
1952
  }
1953

1954
  return INFTY;
1955
}
1956

1957
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1958
  const Position& r, const Direction& u, double l, int shell) const
1959
{
1960
  MeshDistance d;
36,695,747✔
1961
  d.next_index = shell;
36,695,747✔
1962

1963
  // Direction of flight is within xy-plane. Will never intersect z.
1964
  if (std::abs(u.z) < FP_PRECISION)
36,695,747✔
1965
    return d;
1,118,216✔
1966

1967
  d.max_surface = (u.z > 0.0);
35,577,531✔
1968
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1969
    d.next_index += 1;
16,875,892✔
1970
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1971
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1972
    d.next_index -= 1;
16,846,225✔
1973
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1974
  }
1975
  return d;
35,577,531✔
1976
}
1977

1978
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,192✔
1979
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1980
  double l) const
1981
{
1982
  if (i == 0) {
145,218,192✔
1983

1984
    return std::min(
142,588,486✔
1985
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,243✔
1986
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,486✔
1987

1988
  } else if (i == 1) {
73,923,949✔
1989

1990
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1991
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1992
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1993
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1994

1995
  } else {
1996
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1997
  }
1998
}
1999

2000
int CylindricalMesh::set_grid()
433✔
2001
{
2002
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
2003
    static_cast<int>(grid_[1].size()) - 1,
433✔
2004
    static_cast<int>(grid_[2].size()) - 1};
433✔
2005

2006
  for (const auto& g : grid_) {
1,732✔
2007
    if (g.size() < 2) {
1,299!
2008
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2009
                 "must each have at least 2 points");
2010
      return OPENMC_E_INVALID_ARGUMENT;
×
2011
    }
2012
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,299!
2013
        g.end()) {
1,299!
2014
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2015
                 "cylindrical meshes must be sorted and unique.");
2016
      return OPENMC_E_INVALID_ARGUMENT;
×
2017
    }
2018
  }
2019
  if (grid_[0].front() < 0.0) {
433!
2020
    set_errmsg("r-grid for "
×
2021
               "cylindrical meshes must start at r >= 0.");
2022
    return OPENMC_E_INVALID_ARGUMENT;
×
2023
  }
2024
  if (grid_[1].front() < 0.0) {
433!
2025
    set_errmsg("phi-grid for "
×
2026
               "cylindrical meshes must start at phi >= 0.");
2027
    return OPENMC_E_INVALID_ARGUMENT;
×
2028
  }
2029
  if (grid_[1].back() > 2.0 * PI) {
433!
2030
    set_errmsg("phi-grids for "
×
2031
               "cylindrical meshes must end with theta <= 2*pi.");
2032

2033
    return OPENMC_E_INVALID_ARGUMENT;
×
2034
  }
2035

2036
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
433!
2037

2038
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2039
    origin_[2] + grid_[2].front()};
433✔
2040
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2041
    origin_[2] + grid_[2].back()};
433✔
2042

2043
  return 0;
433✔
2044
}
2045

2046
int CylindricalMesh::get_index_in_direction(double r, double u, int i) const
143,196,273✔
2047
{
2048
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2049
}
2050

2051
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2052
  Position plot_ll, Position plot_ur) const
2053
{
2054
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2055

2056
  // Figure out which axes lie in the plane of the plot.
2057
  array<vector<double>, 2> axis_lines;
2058
  return {axis_lines[0], axis_lines[1]};
2059
}
2060

2061
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2062
{
2063
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2064
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2065
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2066
  write_dataset(mesh_group, "origin", origin_);
374✔
2067
}
374✔
2068

2069
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2070
{
2071
  double r_i = grid_[0][ijk[0] - 1];
792✔
2072
  double r_o = grid_[0][ijk[0]];
792✔
2073

2074
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2075
  double phi_o = grid_[1][ijk[1]];
792✔
2076

2077
  double z_i = grid_[2][ijk[2] - 1];
792✔
2078
  double z_o = grid_[2][ijk[2]];
792✔
2079

2080
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2081
}
2082

2083
//==============================================================================
2084
// SphericalMesh implementation
2085
//==============================================================================
2086

2087
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2088
  : PeriodicStructuredMesh {node}
345✔
2089
{
2090
  n_dimension_ = 3;
345✔
2091

2092
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2093
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2094
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2095
  origin_ = get_node_position(node, "origin");
345✔
2096

2097
  if (int err = set_grid()) {
345!
2098
    fatal_error(openmc_err_msg);
×
2099
  }
2100
}
345✔
2101

2102
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2103
{
2104
  n_dimension_ = 3;
11✔
2105

2106
  read_dataset(group, "r_grid", grid_[0]);
11✔
2107
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2108
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2109
  read_dataset(group, "origin", origin_);
11✔
2110

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

2116
const std::string SphericalMesh::mesh_type = "spherical";
2117

2118
std::string SphericalMesh::get_mesh_type() const
385✔
2119
{
2120
  return mesh_type;
385✔
2121
}
2122

2123
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2124
  Position r, Direction u, bool& in_mesh) const
2125
{
2126
  r = local_coords(r);
68,592,128✔
2127

2128
  Position mapped_r;
68,592,128✔
2129
  mapped_r[0] = r.norm();
68,592,128✔
2130

2131
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2132
    mapped_r[1] = 0.0;
2133
    mapped_r[2] = 0.0;
2134
  } else {
2135
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2136
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2137
    if (mapped_r[2] < 0)
68,592,128✔
2138
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2139
  }
2140

2141
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, u, in_mesh);
68,592,128✔
2142

2143
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2144
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2145

2146
  return idx;
68,592,128✔
2147
}
2148

2149
Position SphericalMesh::sample_element(
110✔
2150
  const MeshIndex& ijk, uint64_t* seed) const
2151
{
2152
  double r_min = this->r(ijk[0] - 1);
110✔
2153
  double r_max = this->r(ijk[0]);
110✔
2154

2155
  double theta_min = this->theta(ijk[1] - 1);
110✔
2156
  double theta_max = this->theta(ijk[1]);
110✔
2157

2158
  double phi_min = this->phi(ijk[2] - 1);
110✔
2159
  double phi_max = this->phi(ijk[2]);
110✔
2160

2161
  double cos_theta =
110✔
2162
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2163
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2164
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2165
  double r_min_cub = std::pow(r_min, 3);
110✔
2166
  double r_max_cub = std::pow(r_max, 3);
110✔
2167
  // might be faster to do rejection here?
2168
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2169

2170
  double x = r * std::cos(phi) * sin_theta;
110✔
2171
  double y = r * std::sin(phi) * sin_theta;
110✔
2172
  double z = r * cos_theta;
110✔
2173

2174
  return origin_ + Position(x, y, z);
110✔
2175
}
2176

2177
double SphericalMesh::find_r_crossing(
443,981,868✔
2178
  const Position& r, const Direction& u, double l, int shell) const
2179
{
2180
  if ((shell < 0) || (shell > shape_[0]))
443,981,868✔
2181
    return INFTY;
2182

2183
  // solve |r+s*u| = r0
2184
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2185
  const double r0 = grid_[0][shell];
404,360,781✔
2186
  if (r0 == 0.0)
404,360,781✔
2187
    return INFTY;
2188
  const double p = r.dot(u);
396,682,264✔
2189
  double R = r.norm();
396,682,264✔
2190
  double D = p * p - (R - r0) * (R + r0);
396,682,264✔
2191

2192
  // Particle is already on the shell surface; avoid spurious crossing
2193
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,682,264✔
2194
    return INFTY;
2195

2196
  if (D >= 0.0) {
385,973,610✔
2197
    D = std::sqrt(D);
358,096,662✔
2198
    // Check -p - D first because it is always smaller as -p + D
2199
    if (-p - D > l)
358,096,662✔
2200
      return -p - D;
2201
    if (-p + D > l)
293,782,962✔
2202
      return -p + D;
177,242,120✔
2203
  }
2204

2205
  return INFTY;
2206
}
2207

2208
double SphericalMesh::find_theta_crossing(
110,161,348✔
2209
  const Position& r, const Direction& u, double l, int shell) const
2210
{
2211
  // Theta grid is [0, π], thus there is no real surface to cross
2212
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2213
    return INFTY;
2214

2215
  shell = sanitize_theta(shell);
38,358,540✔
2216

2217
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2218
  // yields
2219
  // a*s^2 + 2*b*s + c == 0 with
2220
  // a = cos(theta)^2 - u.z * u.z
2221
  // b = r*u * cos(theta)^2 - u.z * r.z
2222
  // c = r*r * cos(theta)^2 - r.z^2
2223

2224
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2225
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2226
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2227

2228
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2229
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2230
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2231

2232
  // if factor of s^2 is zero, direction of flight is parallel to theta
2233
  // surface
2234
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2235
    // if b vanishes, direction of flight is within theta surface and crossing
2236
    // is not possible
2237
    if (std::abs(b) < FP_PRECISION)
482,548!
2238
      return INFTY;
2239

2240
    const double s = -0.5 * c / b;
×
2241
    // Check if solution is in positive direction of flight and has correct
2242
    // sign
2243
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2244
      return s;
×
2245

2246
    // no crossing is possible
2247
    return INFTY;
2248
  }
2249

2250
  const double p = b / a;
37,875,992✔
2251
  double D = p * p - c / a;
37,875,992✔
2252

2253
  if (D < 0.0)
37,875,992✔
2254
    return INFTY;
2255

2256
  D = std::sqrt(D);
26,921,004✔
2257

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

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

2269
  return INFTY;
2270
}
2271

2272
double SphericalMesh::find_phi_crossing(
111,750,826✔
2273
  const Position& r, const Direction& u, double l, int shell) const
2274
{
2275
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2276
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2277
    return INFTY;
2278

2279
  shell = sanitize_phi(shell);
39,948,018✔
2280

2281
  const double p0 = grid_[2][shell];
39,948,018✔
2282

2283
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2284
  // => x(s) * cos(p0) = y(s) * sin(p0)
2285
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2286
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2287

2288
  const double c0 = std::cos(p0);
39,948,018✔
2289
  const double s0 = std::sin(p0);
39,948,018✔
2290

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

2293
  // Check if direction of flight is not parallel to phi surface
2294
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2295
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2296
    // Check if solution is in positive direction of flight and crosses the
2297
    // correct phi surface (not -phi)
2298
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2299
      return s;
17,579,452✔
2300
  }
2301

2302
  return INFTY;
2303
}
2304

2305
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,947,021✔
2306
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2307
  double l) const
2308
{
2309

2310
  if (i == 0) {
332,947,021✔
2311
    return std::min(
443,981,868✔
2312
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,990,934✔
2313
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,981,868✔
2314

2315
  } else if (i == 1) {
110,956,087✔
2316
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2317
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2318
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2319
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2320

2321
  } else {
2322
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2323
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2324
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2325
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2326
  }
2327
}
2328

2329
int SphericalMesh::set_grid()
378✔
2330
{
2331
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2332
    static_cast<int>(grid_[1].size()) - 1,
378✔
2333
    static_cast<int>(grid_[2].size()) - 1};
378✔
2334

2335
  for (const auto& g : grid_) {
1,512✔
2336
    if (g.size() < 2) {
1,134!
2337
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2338
                 "must each have at least 2 points");
2339
      return OPENMC_E_INVALID_ARGUMENT;
×
2340
    }
2341
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2342
        g.end()) {
1,134!
2343
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2344
                 "spherical meshes must be sorted and unique.");
2345
      return OPENMC_E_INVALID_ARGUMENT;
×
2346
    }
2347
    if (g.front() < 0.0) {
1,134!
2348
      set_errmsg("r-, theta-, and phi- grids for "
×
2349
                 "spherical meshes must start at v >= 0.");
2350
      return OPENMC_E_INVALID_ARGUMENT;
×
2351
    }
2352
  }
2353
  if (grid_[1].back() > PI) {
378!
2354
    set_errmsg("theta-grids for "
×
2355
               "spherical meshes must end with theta <= pi.");
2356

2357
    return OPENMC_E_INVALID_ARGUMENT;
×
2358
  }
2359
  if (grid_[2].back() > 2 * PI) {
378!
2360
    set_errmsg("phi-grids for "
×
2361
               "spherical meshes must end with phi <= 2*pi.");
2362
    return OPENMC_E_INVALID_ARGUMENT;
×
2363
  }
2364

2365
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2366
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2367

2368
  double r = grid_[0].back();
378✔
2369
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2370
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2371

2372
  return 0;
378✔
2373
}
2374

2375
int SphericalMesh::get_index_in_direction(double r, double u, int i) const
205,776,384✔
2376
{
2377
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2378
}
2379

2380
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2381
  Position plot_ll, Position plot_ur) const
2382
{
2383
  fatal_error("Plot of spherical Mesh not implemented");
×
2384

2385
  // Figure out which axes lie in the plane of the plot.
2386
  array<vector<double>, 2> axis_lines;
2387
  return {axis_lines[0], axis_lines[1]};
2388
}
2389

2390
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2391
{
2392
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2393
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2394
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2395
  write_dataset(mesh_group, "origin", origin_);
319✔
2396
}
319✔
2397

2398
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2399
{
2400
  double r_i = grid_[0][ijk[0] - 1];
935✔
2401
  double r_o = grid_[0][ijk[0]];
935✔
2402

2403
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2404
  double theta_o = grid_[1][ijk[1]];
935✔
2405

2406
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2407
  double phi_o = grid_[2][ijk[2]];
935✔
2408

2409
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2410
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2411
}
2412

2413
//==============================================================================
2414
// Helper functions for the C API
2415
//==============================================================================
2416

2417
int check_mesh(int32_t index)
6,490✔
2418
{
2419
  if (index < 0 || index >= model::meshes.size()) {
6,490!
2420
    set_errmsg("Index in meshes array is out of bounds.");
×
2421
    return OPENMC_E_OUT_OF_BOUNDS;
×
2422
  }
2423
  return 0;
2424
}
2425

2426
template<class T>
2427
int check_mesh_type(int32_t index)
1,100✔
2428
{
2429
  if (int err = check_mesh(index))
1,100!
2430
    return err;
2431

2432
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2433
  if (!mesh) {
1,100!
2434
    set_errmsg("This function is not valid for input mesh.");
×
2435
    return OPENMC_E_INVALID_TYPE;
×
2436
  }
2437
  return 0;
2438
}
2439

2440
template<class T>
2441
bool is_mesh_type(int32_t index)
2442
{
2443
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2444
  return mesh;
2445
}
2446

2447
//==============================================================================
2448
// C API functions
2449
//==============================================================================
2450

2451
// Return the type of mesh as a C string
2452
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2453
{
2454
  if (int err = check_mesh(index))
1,496!
2455
    return err;
2456

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

2459
  return 0;
1,496✔
2460
}
2461

2462
//! Extend the meshes array by n elements
2463
extern "C" int openmc_extend_meshes(
253✔
2464
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2465
{
2466
  if (index_start)
253!
2467
    *index_start = model::meshes.size();
253✔
2468
  std::string mesh_type;
253✔
2469

2470
  for (int i = 0; i < n; ++i) {
506✔
2471
    if (RegularMesh::mesh_type == type) {
253✔
2472
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2473
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2474
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2475
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2476
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2477
    } else if (SphericalMesh::mesh_type == type) {
22!
2478
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2479
    } else {
2480
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2481
    }
2482
  }
2483
  if (index_end)
253!
2484
    *index_end = model::meshes.size() - 1;
×
2485

2486
  return 0;
253✔
2487
}
253✔
2488

2489
//! Adds a new unstructured mesh to OpenMC
2490
extern "C" int openmc_add_unstructured_mesh(
×
2491
  const char filename[], const char library[], int* id)
2492
{
2493
  std::string lib_name(library);
×
2494
  std::string mesh_file(filename);
×
2495
  bool valid_lib = false;
×
2496

2497
#ifdef OPENMC_DAGMC_ENABLED
2498
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2499
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2500
    valid_lib = true;
2501
  }
2502
#endif
2503

2504
#ifdef OPENMC_LIBMESH_ENABLED
2505
  if (lib_name == LibMesh::mesh_lib_type) {
×
2506
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2507
    valid_lib = true;
2508
  }
2509
#endif
2510

2511
  if (!valid_lib) {
×
2512
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2513
                           "by this build of OpenMC",
2514
      lib_name));
2515
    return OPENMC_E_INVALID_ARGUMENT;
×
2516
  }
2517

2518
  // auto-assign new ID
2519
  model::meshes.back()->set_id(-1);
×
2520
  *id = model::meshes.back()->id_;
2521

2522
  return 0;
2523
}
×
2524

2525
//! Return the index in the meshes array of a mesh with a given ID
2526
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2527
{
2528
  auto pair = model::mesh_map.find(id);
429!
2529
  if (pair == model::mesh_map.end()) {
429!
2530
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2531
    return OPENMC_E_INVALID_ID;
×
2532
  }
2533
  *index = pair->second;
429✔
2534
  return 0;
429✔
2535
}
2536

2537
//! Return the ID of a mesh
2538
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,827✔
2539
{
2540
  if (int err = check_mesh(index))
2,827!
2541
    return err;
2542
  *id = model::meshes[index]->id_;
2,827✔
2543
  return 0;
2,827✔
2544
}
2545

2546
//! Set the ID of a mesh
2547
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2548
{
2549
  if (int err = check_mesh(index))
253!
2550
    return err;
2551
  model::meshes[index]->id_ = id;
253✔
2552
  model::mesh_map[id] = index;
253✔
2553
  return 0;
253✔
2554
}
2555

2556
//! Get the number of elements in a mesh
2557
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2558
{
2559
  if (int err = check_mesh(index))
297!
2560
    return err;
2561
  *n = model::meshes[index]->n_bins();
297✔
2562
  return 0;
297✔
2563
}
2564

2565
//! Get the volume of each element in the mesh
2566
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2567
{
2568
  if (int err = check_mesh(index))
88!
2569
    return err;
2570
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2571
    volumes[i] = model::meshes[index]->volume(i);
880✔
2572
  }
2573
  return 0;
2574
}
2575

2576
//! Get the bounding box of a mesh
2577
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2578
{
2579
  if (int err = check_mesh(index))
176!
2580
    return err;
2581

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

2584
  // set lower left corner values
2585
  ll[0] = bbox.min.x;
176✔
2586
  ll[1] = bbox.min.y;
176✔
2587
  ll[2] = bbox.min.z;
176✔
2588

2589
  // set upper right corner values
2590
  ur[0] = bbox.max.x;
176✔
2591
  ur[1] = bbox.max.y;
176✔
2592
  ur[2] = bbox.max.z;
176✔
2593
  return 0;
176✔
2594
}
2595

2596
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2597
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2598
{
2599
  if (int err = check_mesh(index))
209!
2600
    return err;
2601

2602
  try {
209✔
2603
    model::meshes[index]->material_volumes(
209✔
2604
      nx, ny, nz, table_size, materials, volumes, bboxes);
2605
  } catch (const std::exception& e) {
11!
2606
    set_errmsg(e.what());
11✔
2607
    if (starts_with(e.what(), "Mesh")) {
11!
2608
      return OPENMC_E_GEOMETRY;
11✔
2609
    } else {
2610
      return OPENMC_E_ALLOCATE;
×
2611
    }
2612
  }
11✔
2613

2614
  return 0;
2615
}
2616

2617
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2618
  Position width, int basis, int* pixels, int32_t* data)
2619
{
2620
  if (int err = check_mesh(index))
44!
2621
    return err;
2622
  const auto& mesh = model::meshes[index].get();
44!
2623

2624
  int pixel_width = pixels[0];
44✔
2625
  int pixel_height = pixels[1];
44✔
2626

2627
  // get pixel size
2628
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2629
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2630

2631
  // setup basis indices and initial position centered on pixel
2632
  int in_i, out_i;
44✔
2633
  Position xyz = origin;
44✔
2634
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2635
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2636
  switch (basis_enum) {
44!
2637
  case PlotBasis::xy:
2638
    in_i = 0;
2639
    out_i = 1;
2640
    break;
2641
  case PlotBasis::xz:
2642
    in_i = 0;
2643
    out_i = 2;
2644
    break;
2645
  case PlotBasis::yz:
2646
    in_i = 1;
2647
    out_i = 2;
2648
    break;
2649
  default:
×
2650
    UNREACHABLE();
×
2651
  }
2652

2653
  // set initial position
2654
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2655
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2656

2657
#pragma omp parallel
24✔
2658
  {
20✔
2659
    Position r = xyz;
20✔
2660
    Direction placeholder_u = Direction(1.0, 0.0, 0.0);
20✔
2661

2662
#pragma omp for
2663
    for (int y = 0; y < pixel_height; y++) {
420✔
2664
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2665
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2666
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2667
        data[pixel_width * y + x] = mesh->get_bin(r, placeholder_u);
8,000✔
2668
      }
2669
    }
2670
  }
2671

2672
  return 0;
44✔
2673
}
2674

2675
//! Get the dimension of a regular mesh
2676
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2677
  int32_t index, int** dims, int* n)
2678
{
2679
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2680
    return err;
2681
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2682
  *dims = mesh->shape_.data();
11✔
2683
  *n = mesh->n_dimension_;
11✔
2684
  return 0;
11✔
2685
}
2686

2687
//! Set the dimension of a regular mesh
2688
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2689
  int32_t index, int n, const int* dims)
2690
{
2691
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2692
    return err;
2693
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2694

2695
  // Copy dimension
2696
  mesh->n_dimension_ = n;
187✔
2697
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2698
  return 0;
187✔
2699
}
2700

2701
//! Get the regular mesh parameters
2702
extern "C" int openmc_regular_mesh_get_params(
209✔
2703
  int32_t index, double** ll, double** ur, double** width, int* n)
2704
{
2705
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2706
    return err;
2707
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2708

2709
  if (m->lower_left_.empty()) {
209!
2710
    set_errmsg("Mesh parameters have not been set.");
×
2711
    return OPENMC_E_ALLOCATE;
×
2712
  }
2713

2714
  *ll = m->lower_left_.data();
209✔
2715
  *ur = m->upper_right_.data();
209✔
2716
  *width = m->width_.data();
209✔
2717
  *n = m->n_dimension_;
209✔
2718
  return 0;
209✔
2719
}
2720

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

2729
  if (m->n_dimension_ == -1) {
220!
2730
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2731
    return OPENMC_E_UNASSIGNED;
×
2732
  }
2733

2734
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2735
  if (ll && ur) {
220✔
2736
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2737
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2738
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2739
  } else if (ll && width) {
22✔
2740
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2741
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2742
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2743
  } else if (ur && width) {
11!
2744
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2745
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2746
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2747
  } else {
2748
    set_errmsg("At least two parameters must be specified.");
×
2749
    return OPENMC_E_INVALID_ARGUMENT;
×
2750
  }
2751

2752
  // Set material volumes
2753

2754
  // TODO: incorporate this into method in RegularMesh that can be called from
2755
  // here and from constructor
2756
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2757
  m->element_volume_ = 1.0;
220✔
2758
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2759
    m->element_volume_ *= m->width_[i];
660✔
2760
  }
2761

2762
  return 0;
2763
}
220✔
2764

2765
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2766
template<class C>
2767
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2768
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2769
  const int nz)
2770
{
2771
  if (int err = check_mesh_type<C>(index))
88!
2772
    return err;
2773

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

2776
  m->n_dimension_ = 3;
88✔
2777

2778
  m->grid_[0].reserve(nx);
88✔
2779
  m->grid_[1].reserve(ny);
88✔
2780
  m->grid_[2].reserve(nz);
88✔
2781

2782
  for (int i = 0; i < nx; i++) {
572✔
2783
    m->grid_[0].push_back(grid_x[i]);
484✔
2784
  }
2785
  for (int i = 0; i < ny; i++) {
341✔
2786
    m->grid_[1].push_back(grid_y[i]);
253✔
2787
  }
2788
  for (int i = 0; i < nz; i++) {
319✔
2789
    m->grid_[2].push_back(grid_z[i]);
231✔
2790
  }
2791

2792
  int err = m->set_grid();
88✔
2793
  return err;
88✔
2794
}
2795

2796
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2797
template<class C>
2798
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2799
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2800
{
2801
  if (int err = check_mesh_type<C>(index))
385!
2802
    return err;
2803
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2804

2805
  if (m->lower_left_.empty()) {
385!
2806
    set_errmsg("Mesh parameters have not been set.");
×
2807
    return OPENMC_E_ALLOCATE;
×
2808
  }
2809

2810
  *grid_x = m->grid_[0].data();
385✔
2811
  *nx = m->grid_[0].size();
385✔
2812
  *grid_y = m->grid_[1].data();
385✔
2813
  *ny = m->grid_[1].size();
385✔
2814
  *grid_z = m->grid_[2].data();
385✔
2815
  *nz = m->grid_[2].size();
385✔
2816

2817
  return 0;
385✔
2818
}
2819

2820
//! Get the rectilinear mesh grid
2821
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2822
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2823
{
2824
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2825
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2826
}
2827

2828
//! Set the rectilienar mesh parameters
2829
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2830
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2831
  const double* grid_z, const int nz)
2832
{
2833
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2834
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2835
}
2836

2837
//! Get the cylindrical mesh grid
2838
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2839
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2840
{
2841
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2842
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2843
}
2844

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

2854
//! Get the spherical mesh grid
2855
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2856
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2857
{
2858

2859
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2860
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2861
  ;
121✔
2862
}
2863

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

2873
#ifdef OPENMC_DAGMC_ENABLED
2874

2875
const std::string MOABMesh::mesh_lib_type = "moab";
2876

2877
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2878
{
2879
  initialize();
24✔
2880
}
24!
2881

2882
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2883
{
2884
  initialize();
×
2885
}
×
2886

2887
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2888
  : UnstructuredMesh()
×
2889
{
2890
  n_dimension_ = 3;
2891
  filename_ = filename;
×
2892
  set_length_multiplier(length_multiplier);
×
2893
  initialize();
×
2894
}
×
2895

2896
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2897
{
2898
  mbi_ = external_mbi;
1✔
2899
  filename_ = "unknown (external file)";
1✔
2900
  this->initialize();
1✔
2901
}
1!
2902

2903
void MOABMesh::initialize()
25✔
2904
{
2905

2906
  // Create the MOAB interface and load data from file
2907
  this->create_interface();
25✔
2908

2909
  // Initialise MOAB error code
2910
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2911

2912
  // Set the dimension
2913
  n_dimension_ = 3;
25✔
2914

2915
  // set member range of tetrahedral entities
2916
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2917
  if (rval != moab::MB_SUCCESS) {
25!
2918
    fatal_error("Failed to get all tetrahedral elements");
2919
  }
2920

2921
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2922
    warning("Non-tetrahedral elements found in unstructured "
×
2923
            "mesh file: " +
2924
            filename_);
2925
  }
2926

2927
  // set member range of vertices
2928
  int vertex_dim = 0;
25✔
2929
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2930
  if (rval != moab::MB_SUCCESS) {
25!
2931
    fatal_error("Failed to get all vertex handles");
2932
  }
2933

2934
  // make an entity set for all tetrahedra
2935
  // this is used for convenience later in output
2936
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2937
  if (rval != moab::MB_SUCCESS) {
25!
2938
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2939
  }
2940

2941
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2942
  if (rval != moab::MB_SUCCESS) {
25!
2943
    fatal_error("Failed to add tetrahedra to an entity set.");
2944
  }
2945

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

2974
  // Determine bounds of mesh
2975
  this->determine_bounds();
25✔
2976
}
25✔
2977

2978
void MOABMesh::prepare_for_point_location()
21✔
2979
{
2980
  // if the KDTree has already been constructed, do nothing
2981
  if (kdtree_)
21!
2982
    return;
2983

2984
  // build acceleration data structures
2985
  compute_barycentric_data(ehs_);
21✔
2986
  build_kdtree(ehs_);
21✔
2987
}
2988

2989
void MOABMesh::create_interface()
25✔
2990
{
2991
  // Do not create a MOAB instance if one is already in memory
2992
  if (mbi_)
25✔
2993
    return;
2994

2995
  // create MOAB instance
2996
  mbi_ = std::make_shared<moab::Core>();
24!
2997

2998
  // load unstructured mesh file
2999
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
3000
  if (rval != moab::MB_SUCCESS) {
24!
3001
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3002
  }
3003
}
3004

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

3016
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3017
    warning("Non-triangle elements found in tet adjacencies in "
×
3018
            "unstructured mesh file: " +
3019
            filename_);
×
3020
  }
3021

3022
  // combine into one range
3023
  moab::Range all_tets_and_tris;
21✔
3024
  all_tets_and_tris.merge(all_tets);
21✔
3025
  all_tets_and_tris.merge(all_tris);
21✔
3026

3027
  // create a kd-tree instance
3028
  write_message(
21✔
3029
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3030
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3031

3032
  // Determine what options to use
3033
  std::ostringstream options_stream;
21✔
3034
  if (options_.empty()) {
21✔
3035
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3036
  } else {
3037
    options_stream << options_;
16✔
3038
  }
3039
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3040

3041
  // Build the k-d tree
3042
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3043
  if (rval != moab::MB_SUCCESS) {
21!
3044
    fatal_error("Failed to construct KDTree for the "
3045
                "unstructured mesh file: " +
3046
                filename_);
×
3047
  }
3048
}
21✔
3049

3050
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3051
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3052
{
3053
  hits.clear();
1,543,584!
3054

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

3067
  // remove duplicate intersection distances
3068
  std::unique(hits.begin(), hits.end());
1,543,584✔
3069

3070
  // sorts by first component of std::pair by default
3071
  std::sort(hits.begin(), hits.end());
1,543,584✔
3072
}
1,543,584✔
3073

3074
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3075
  vector<int>& bins, vector<double>& lengths) const
3076
{
3077
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3078
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3079
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3080
  dir.normalize();
1,543,584✔
3081

3082
  double track_len = (end - start).length();
1,543,584✔
3083
  if (track_len == 0.0)
1,543,584!
3084
    return;
721,692✔
3085

3086
  start -= TINY_BIT * dir;
1,543,584✔
3087
  end += TINY_BIT * dir;
1,543,584✔
3088

3089
  vector<double> hits;
1,543,584✔
3090
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3091

3092
  bins.clear();
1,543,584!
3093
  lengths.clear();
1,543,584!
3094

3095
  // if there are no intersections the track may lie entirely
3096
  // within a single tet. If this is the case, apply entire
3097
  // score to that tet and return.
3098
  if (hits.size() == 0) {
1,543,584✔
3099
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3100
    int bin = this->get_bin(midpoint, u);
721,692✔
3101
    if (bin != -1) {
721,692✔
3102
      bins.push_back(bin);
242,866✔
3103
      lengths.push_back(1.0);
242,866✔
3104
    }
3105
    return;
721,692✔
3106
  }
3107

3108
  // for each segment in the set of tracks, try to look up a tet
3109
  // at the midpoint of the segment
3110
  Position current = r0;
3111
  double last_dist = 0.0;
3112
  for (const auto& hit : hits) {
5,516,161✔
3113
    // get the segment length
3114
    double segment_length = hit - last_dist;
4,694,269✔
3115
    last_dist = hit;
4,694,269✔
3116
    // find the midpoint of this segment
3117
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3118
    // try to find a tet for this position
3119
    int bin = this->get_bin(midpoint, u);
4,694,269✔
3120

3121
    // determine the start point for this segment
3122
    current = r0 + u * hit;
4,694,269✔
3123

3124
    if (bin == -1) {
4,694,269✔
3125
      continue;
20,522✔
3126
    }
3127

3128
    bins.push_back(bin);
4,673,747✔
3129
    lengths.push_back(segment_length / track_len);
4,673,747✔
3130
  }
3131

3132
  // tally remaining portion of track after last hit if
3133
  // the last segment of the track is in the mesh but doesn't
3134
  // reach the other side of the tet
3135
  if (hits.back() < track_len) {
821,892!
3136
    Position segment_start = r0 + u * hits.back();
821,892✔
3137
    double segment_length = track_len - hits.back();
821,892✔
3138
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3139
    int bin = this->get_bin(midpoint, u);
821,892✔
3140
    if (bin != -1) {
821,892✔
3141
      bins.push_back(bin);
766,509✔
3142
      lengths.push_back(segment_length / track_len);
766,509✔
3143
    }
3144
  }
3145
};
1,543,584✔
3146

3147
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3148
{
3149
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3150
  // find the leaf of the kd-tree for this position
3151
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3152
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3153
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3154
    return 0;
3155
  }
3156

3157
  // retrieve the tet elements of this leaf
3158
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3159
  moab::Range tets;
6,305,335✔
3160
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3161
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3162
    warning("MOAB error finding tets.");
×
3163
  }
3164

3165
  // loop over the tets in this leaf, returning the containing tet if found
3166
  for (const auto& tet : tets) {
260,211,273✔
3167
    if (point_in_tet(pos, tet)) {
260,208,426✔
3168
      return tet;
6,302,488✔
3169
    }
3170
  }
3171

3172
  // if no tet is found, return an invalid handle
3173
  return 0;
2,847✔
3174
}
14,634,464✔
3175

3176
double MOABMesh::volume(int bin) const
167,880✔
3177
{
3178
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3179
}
3180

3181
std::string MOABMesh::library() const
34✔
3182
{
3183
  return mesh_lib_type;
34✔
3184
}
3185

3186
// Sample position within a tet for MOAB type tets
3187
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3188
{
3189

3190
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3191

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

3207
  std::array<Position, 4> tet_verts;
200,410✔
3208
  for (int i = 0; i < 4; i++) {
1,002,050✔
3209
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3210
  }
3211
  // Samples position within tet using Barycentric stuff
3212
  return this->sample_tet(tet_verts, seed);
200,410✔
3213
}
3214

3215
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3216
{
3217
  vector<moab::EntityHandle> conn;
167,880✔
3218
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3219
  if (rval != moab::MB_SUCCESS) {
167,880!
3220
    fatal_error("Failed to get tet connectivity");
3221
  }
3222

3223
  moab::CartVect p[4];
167,880✔
3224
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3225
  if (rval != moab::MB_SUCCESS) {
167,880!
3226
    fatal_error("Failed to get tet coords");
3227
  }
3228

3229
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3230
}
167,880✔
3231

3232
int MOABMesh::get_bin(Position r, Direction u) const
7,317,232✔
3233
{
3234
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3235
  if (tet == 0) {
7,317,232✔
3236
    return -1;
3237
  } else {
3238
    return get_bin_from_ent_handle(tet);
6,302,488✔
3239
  }
3240
}
3241

3242
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3243
{
3244
  moab::ErrorCode rval;
21✔
3245

3246
  baryc_data_.clear();
21!
3247
  baryc_data_.resize(tets.size());
21✔
3248

3249
  // compute the barycentric data for each tet element
3250
  // and store it as a 3x3 matrix
3251
  for (auto& tet : tets) {
239,757✔
3252
    vector<moab::EntityHandle> verts;
239,736✔
3253
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3254
    if (rval != moab::MB_SUCCESS) {
239,736!
3255
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3256
    }
3257

3258
    moab::CartVect p[4];
239,736✔
3259
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3260
    if (rval != moab::MB_SUCCESS) {
239,736!
3261
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3262
    }
3263

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

3266
    // invert now to avoid this cost later
3267
    a = a.transpose().inverse();
239,736✔
3268
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3269
  }
239,736✔
3270
}
21✔
3271

3272
bool MOABMesh::point_in_tet(
260,208,426✔
3273
  const moab::CartVect& r, moab::EntityHandle tet) const
3274
{
3275

3276
  moab::ErrorCode rval;
260,208,426✔
3277

3278
  // get tet vertices
3279
  vector<moab::EntityHandle> verts;
260,208,426✔
3280
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3281
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3282
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3283
    return false;
3284
  }
3285

3286
  // first vertex is used as a reference point for the barycentric data -
3287
  // retrieve its coordinates
3288
  moab::CartVect p_zero;
260,208,426✔
3289
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3290
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3291
    warning("Failed to get coordinates of a vertex in "
×
3292
            "unstructured mesh: " +
3293
            filename_);
×
3294
    return false;
3295
  }
3296

3297
  // look up barycentric data
3298
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3299
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3300

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

3303
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3304
          bary_coords[2] >= 0.0 &&
318,957,185✔
3305
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3306
}
260,208,426✔
3307

3308
int MOABMesh::get_bin_from_index(int idx) const
3309
{
3310
  if (idx >= n_bins()) {
×
3311
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3312
  }
3313
  return ehs_[idx] - ehs_[0];
3314
}
3315

3316
int MOABMesh::get_index(
3317
  const Position& r, const Direction& u, bool* in_mesh) const
3318
{
3319
  int bin = get_bin(r, u);
3320
  *in_mesh = bin != -1;
3321
  return bin;
3322
}
3323

3324
int MOABMesh::get_index_from_bin(int bin) const
3325
{
3326
  return bin;
3327
}
3328

3329
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3330
  Position plot_ll, Position plot_ur) const
3331
{
3332
  // TODO: Implement mesh lines
3333
  return {};
3334
}
3335

3336
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3337
{
3338
  int idx = vert - verts_[0];
815,520✔
3339
  if (idx >= n_vertices()) {
815,520!
3340
    fatal_error(
3341
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3342
  }
3343
  return idx;
815,520✔
3344
}
3345

3346
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3347
{
3348
  int bin = eh - ehs_[0];
266,750,650✔
3349
  if (bin >= n_bins()) {
266,750,650!
3350
    fatal_error(fmt::format("Invalid bin: {}", bin));
3351
  }
3352
  return bin;
266,750,650✔
3353
}
3354

3355
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3356
{
3357
  if (bin >= n_bins()) {
572,170!
3358
    fatal_error(fmt::format("Invalid bin index: ", bin));
3359
  }
3360
  return ehs_[0] + bin;
572,170✔
3361
}
3362

3363
int MOABMesh::n_bins() const
267,526,773✔
3364
{
3365
  return ehs_.size();
267,526,773✔
3366
}
3367

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

3381
Position MOABMesh::centroid(int bin) const
3382
{
3383
  moab::ErrorCode rval;
3384

3385
  auto tet = this->get_ent_handle_from_bin(bin);
3386

3387
  // look up the tet connectivity
3388
  vector<moab::EntityHandle> conn;
×
3389
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3390
  if (rval != moab::MB_SUCCESS) {
×
3391
    warning("Failed to get connectivity of a mesh element.");
×
3392
    return {};
3393
  }
3394

3395
  // get the coordinates
3396
  vector<moab::CartVect> coords(conn.size());
×
3397
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3398
  if (rval != moab::MB_SUCCESS) {
×
3399
    warning("Failed to get the coordinates of a mesh element.");
×
3400
    return {};
3401
  }
3402

3403
  // compute the centroid of the element vertices
3404
  moab::CartVect centroid(0.0, 0.0, 0.0);
3405
  for (const auto& coord : coords) {
×
3406
    centroid += coord;
3407
  }
3408
  centroid /= double(coords.size());
3409

3410
  return {centroid[0], centroid[1], centroid[2]};
3411
}
3412

3413
int MOABMesh::n_vertices() const
845,874✔
3414
{
3415
  return verts_.size();
845,874✔
3416
}
3417

3418
Position MOABMesh::vertex(int id) const
86,227✔
3419
{
3420

3421
  moab::ErrorCode rval;
86,227✔
3422

3423
  moab::EntityHandle vert = verts_[id];
86,227✔
3424

3425
  moab::CartVect coords;
86,227✔
3426
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3427
  if (rval != moab::MB_SUCCESS) {
86,227!
3428
    fatal_error("Failed to get the coordinates of a vertex.");
3429
  }
3430

3431
  return {coords[0], coords[1], coords[2]};
86,227✔
3432
}
3433

3434
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3435
{
3436
  moab::ErrorCode rval;
203,880✔
3437

3438
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3439

3440
  // look up the tet connectivity
3441
  vector<moab::EntityHandle> conn;
203,880✔
3442
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3443
  if (rval != moab::MB_SUCCESS) {
203,880!
3444
    fatal_error("Failed to get connectivity of a mesh element.");
3445
    return {};
3446
  }
3447

3448
  std::vector<int> verts(4);
203,880✔
3449
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3450
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3451
  }
3452

3453
  return verts;
203,880✔
3454
}
203,880✔
3455

3456
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3457
  std::string score) const
3458
{
3459
  moab::ErrorCode rval;
3460
  // add a tag to the mesh
3461
  // all scores are treated as a single value
3462
  // with an uncertainty
3463
  moab::Tag value_tag;
3464

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

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

3491
  // return the populated tag handles
3492
  return {value_tag, error_tag};
3493
}
3494

3495
void MOABMesh::add_score(const std::string& score)
3496
{
3497
  auto score_tags = get_score_tags(score);
×
3498
  tag_names_.push_back(score);
3499
}
3500

3501
void MOABMesh::remove_scores()
3502
{
3503
  for (const auto& name : tag_names_) {
×
3504
    auto value_name = name + "_mean";
3505
    moab::Tag tag;
3506
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3507
    if (rval != moab::MB_SUCCESS)
×
3508
      return;
3509

3510
    rval = mbi_->tag_delete(tag);
×
3511
    if (rval != moab::MB_SUCCESS) {
×
3512
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3513
                             " on unstructured mesh {}",
3514
        name, id_);
×
3515
      fatal_error(msg);
3516
    }
3517

3518
    auto std_dev_name = name + "_std_dev";
×
3519
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3520
    if (rval != moab::MB_SUCCESS) {
×
3521
      auto msg =
3522
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3523
                    " on unstructured mesh {}",
3524
          name, id_);
×
3525
    }
3526

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

3538
void MOABMesh::set_score_data(const std::string& score,
3539
  const vector<double>& values, const vector<double>& std_dev)
3540
{
3541
  auto score_tags = this->get_score_tags(score);
×
3542

3543
  moab::ErrorCode rval;
3544
  // set the score value
3545
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3546
  if (rval != moab::MB_SUCCESS) {
×
3547
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3548
                           "on unstructured mesh {}",
3549
      score, id_);
3550
    warning(msg);
×
3551
  }
3552

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

3563
void MOABMesh::write(const std::string& base_filename) const
3564
{
3565
  // add extension to the base name
3566
  auto filename = base_filename + ".vtk";
3567
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3568
  filename = settings::path_output + filename;
×
3569

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

3581
#endif
3582

3583
#ifdef OPENMC_LIBMESH_ENABLED
3584

3585
const std::string LibMesh::mesh_lib_type = "libmesh";
3586

3587
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3588
{
3589
  // filename_ and length_multiplier_ will already be set by the
3590
  // UnstructuredMesh constructor
3591
  set_mesh_pointer_from_filename(filename_);
25✔
3592
  set_length_multiplier(length_multiplier_);
25✔
3593
  initialize();
25✔
3594
}
25✔
3595

3596
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3597
{
3598
  // filename_ and length_multiplier_ will already be set by the
3599
  // UnstructuredMesh constructor
3600
  set_mesh_pointer_from_filename(filename_);
×
3601
  set_length_multiplier(length_multiplier_);
×
3602
  initialize();
×
3603
}
3604

3605
// create the mesh from a pointer to a libMesh Mesh
3606
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3607
{
3608
  if (!input_mesh.is_replicated()) {
×
3609
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3610
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3611
  }
3612

3613
  m_ = &input_mesh;
3614
  set_length_multiplier(length_multiplier);
×
3615
  initialize();
×
3616
}
3617

3618
// create the mesh from an input file
3619
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3620
{
3621
  n_dimension_ = 3;
3622
  set_mesh_pointer_from_filename(filename);
×
3623
  set_length_multiplier(length_multiplier);
×
3624
  initialize();
×
3625
}
3626

3627
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3628
{
3629
  filename_ = filename;
25✔
3630
  unique_m_ =
25✔
3631
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3632
  m_ = unique_m_.get();
25✔
3633
  m_->read(filename_);
25✔
3634
}
25✔
3635

3636
// build a libMesh equation system for storing values
3637
void LibMesh::build_eqn_sys()
17✔
3638
{
3639
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3640
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3641
  libMesh::ExplicitSystem& eq_sys =
17✔
3642
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3643
}
17✔
3644

3645
// intialize from mesh file
3646
void LibMesh::initialize()
25✔
3647
{
3648
  if (!settings::libmesh_comm) {
25!
3649
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3650
                "communicator.");
3651
  }
3652

3653
  // assuming that unstructured meshes used in OpenMC are 3D
3654
  n_dimension_ = 3;
25✔
3655

3656
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3657
  // Otherwise assume that it is prepared by its owning application
3658
  if (unique_m_) {
25!
3659
    m_->prepare_for_use();
25✔
3660
  }
3661

3662
  // ensure that the loaded mesh is 3 dimensional
3663
  if (m_->mesh_dimension() != n_dimension_) {
25!
3664
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3665
                            "mesh is not a 3D mesh.",
3666
      filename_));
3667
  }
3668

3669
  for (int i = 0; i < num_threads(); i++) {
75✔
3670
    pl_.emplace_back(m_->sub_point_locator());
50✔
3671
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
50✔
3672
    pl_.back()->enable_out_of_mesh_mode();
50✔
3673
  }
3674

3675
  // store first element in the mesh to use as an offset for bin indices
3676
  auto first_elem = *m_->elements_begin();
50✔
3677
  first_element_id_ = first_elem->id();
25✔
3678

3679
  // bounding box for the mesh for quick rejection checks
3680
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3681
  libMesh::Point ll = bbox_.min();
25!
3682
  libMesh::Point ur = bbox_.max();
25!
3683
  if (length_multiplier_ > 0.0) {
25!
3684
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3685
      length_multiplier_ * ll(2)};
3686
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3687
      length_multiplier_ * ur(2)};
3688
  } else {
3689
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3690
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3691
  }
3692
}
25✔
3693

3694
// Sample position within a tet for LibMesh type tets
3695
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3696
{
3697
  const auto& elem = get_element_from_bin(bin);
400,820✔
3698
  // Get tet vertex coordinates from LibMesh
3699
  std::array<Position, 4> tet_verts;
400,820✔
3700
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3701
    auto node_ref = elem.node_ref(i);
1,603,280✔
3702
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3703
  }
1,603,280✔
3704
  // Samples position within tet using Barycentric coordinates
3705
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3706
  if (length_multiplier_ > 0.0) {
400,820!
3707
    return length_multiplier_ * sampled_position;
3708
  } else {
3709
    return sampled_position;
400,820✔
3710
  }
3711
}
3712

3713
Position LibMesh::centroid(int bin) const
3714
{
3715
  const auto& elem = this->get_element_from_bin(bin);
3716
  auto centroid = elem.vertex_average();
3717
  if (length_multiplier_ > 0.0) {
×
3718
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3719
  } else {
3720
    return {centroid(0), centroid(1), centroid(2)};
3721
  }
3722
}
3723

3724
int LibMesh::n_vertices() const
42,644✔
3725
{
3726
  return m_->n_nodes();
42,644✔
3727
}
3728

3729
Position LibMesh::vertex(int vertex_id) const
42,604✔
3730
{
3731
  const auto node_ref = m_->node_ref(vertex_id);
42,604✔
3732
  if (length_multiplier_ > 0.0) {
42,604!
3733
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3734
  } else {
3735
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3736
  }
3737
}
42,604✔
3738

3739
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3740
{
3741
  std::vector<int> conn;
267,856✔
3742
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3743
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3744
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3745
  }
3746
  return conn;
267,856✔
3747
}
3748

3749
std::string LibMesh::library() const
37✔
3750
{
3751
  return mesh_lib_type;
37✔
3752
}
3753

3754
int LibMesh::n_bins() const
1,788,419✔
3755
{
3756
  return m_->n_elem();
1,788,419✔
3757
}
3758

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

3777
void LibMesh::add_score(const std::string& var_name)
17✔
3778
{
3779
  if (!equation_systems_) {
17!
3780
    build_eqn_sys();
17✔
3781
  }
3782

3783
  // check if this is a new variable
3784
  std::string value_name = var_name + "_mean";
17✔
3785
  if (!variable_map_.count(value_name)) {
17✔
3786
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3787
    auto var_num =
17✔
3788
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3789
    variable_map_[value_name] = var_num;
17✔
3790
  }
3791

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

3802
void LibMesh::remove_scores()
17✔
3803
{
3804
  if (equation_systems_) {
17!
3805
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3806
    eqn_sys.clear();
17✔
3807
    variable_map_.clear();
17✔
3808
  }
3809
}
17✔
3810

3811
void LibMesh::set_score_data(const std::string& var_name,
17✔
3812
  const vector<double>& values, const vector<double>& std_dev)
3813
{
3814
  if (!equation_systems_) {
17!
3815
    build_eqn_sys();
3816
  }
3817

3818
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3819

3820
  if (!eqn_sys.is_initialized()) {
17!
3821
    equation_systems_->init();
17✔
3822
  }
3823

3824
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3825

3826
  // look up the value variable
3827
  std::string value_name = var_name + "_mean";
17✔
3828
  unsigned int value_num = variable_map_.at(value_name);
17✔
3829
  // look up the std dev variable
3830
  std::string std_dev_name = var_name + "_std_dev";
17✔
3831
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3832

3833
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3834
       it++) {
3835
    if (!(*it)->active()) {
99,856!
3836
      continue;
3837
    }
3838

3839
    auto bin = get_bin_from_element(*it);
99,856✔
3840

3841
    // set value
3842
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3843
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3844
    assert(value_dof_indices.size() == 1);
99,856✔
3845
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3846

3847
    // set std dev
3848
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3849
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3850
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3851
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3852
  }
99,873✔
3853
}
17✔
3854

3855
void LibMesh::write(const std::string& filename) const
17✔
3856
{
3857
  write_message(fmt::format(
17✔
3858
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3859
  libMesh::ExodusII_IO exo(*m_);
17✔
3860
  std::set<std::string> systems_out = {eq_system_name_};
34!
3861
  exo.write_discontinuous_exodusII(
17✔
3862
    filename + ".e", *equation_systems_, &systems_out);
34✔
3863
}
17✔
3864

3865
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3866
  vector<int>& bins, vector<double>& lengths) const
3867
{
3868
  // TODO: Implement triangle crossings here
3869
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3870
}
3871

3872
int LibMesh::get_bin(Position r, Direction u) const
2,340,604✔
3873
{
3874
  // look-up a tet using the point locator
3875
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3876

3877
  if (length_multiplier_ > 0.0) {
2,340,604!
3878
    // Scale the point down
3879
    p /= length_multiplier_;
2,340,604✔
3880
  }
3881

3882
  // quick rejection check
3883
  if (!bbox_.contains_point(p)) {
2,340,604✔
3884
    return -1;
3885
  }
3886

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

3889
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3890
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3891
}
2,340,604✔
3892

3893
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3894
{
3895
  int bin = elem->id() - first_element_id_;
1,520,434✔
3896
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3897
    fatal_error(fmt::format("Invalid bin: {}", bin));
3898
  }
3899
  return bin;
1,520,434✔
3900
}
3901

3902
std::pair<vector<double>, vector<double>> LibMesh::plot(
3903
  Position plot_ll, Position plot_ur) const
3904
{
3905
  return {};
3906
}
3907

3908
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3909
{
3910
  return m_->elem_ref(bin);
769,460✔
3911
}
3912

3913
double LibMesh::volume(int bin) const
368,640✔
3914
{
3915
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3916
         length_multiplier_ * length_multiplier_;
368,640✔
3917
}
3918

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

3946
int AdaptiveLibMesh::n_bins() const
3947
{
3948
  return num_active_;
3949
}
3950

3951
void AdaptiveLibMesh::add_score(const std::string& var_name)
3952
{
3953
  warning(fmt::format(
×
3954
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3955
    this->id_));
3956
}
3957

3958
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3959
  const vector<double>& values, const vector<double>& std_dev)
3960
{
3961
  warning(fmt::format(
×
3962
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3963
    this->id_));
3964
}
3965

3966
void AdaptiveLibMesh::write(const std::string& filename) const
3967
{
3968
  warning(fmt::format(
×
3969
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3970
    this->id_));
3971
}
3972

3973
int AdaptiveLibMesh::get_bin(Position r, Direction u) const
3974
{
3975
  // look-up a tet using the point locator
3976
  libMesh::Point p(r.x, r.y, r.z);
×
3977

3978
  if (length_multiplier_ > 0.0) {
×
3979
    // Scale the point down
3980
    p /= length_multiplier_;
3981
  }
3982

3983
  // quick rejection check
3984
  if (!bbox_.contains_point(p)) {
×
3985
    return -1;
3986
  }
3987

3988
  const auto& point_locator = pl_.at(thread_num());
×
3989

3990
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3991
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3992
}
3993

3994
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3995
{
3996
  int bin = elem_to_bin_map_[elem->id()];
3997
  if (bin >= n_bins() || bin < 0) {
×
3998
    fatal_error(fmt::format("Invalid bin: {}", bin));
3999
  }
4000
  return bin;
4001
}
4002

4003
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4004
{
4005
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4006
}
4007

4008
#endif // OPENMC_LIBMESH_ENABLED
4009

4010
//==============================================================================
4011
// Non-member functions
4012
//==============================================================================
4013

4014
void read_meshes(pugi::xml_node root)
13,394✔
4015
{
4016
  std::unordered_set<int> mesh_ids;
13,394✔
4017

4018
  for (auto node : root.children("mesh")) {
16,619✔
4019
    // Check to make sure multiple meshes in the same file don't share IDs
4020
    int id = std::stoi(get_node_value(node, "id"));
6,450✔
4021
    if (contains(mesh_ids, id)) {
6,450!
4022
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4023
                              "'{}' in the same input file",
4024
        id));
4025
    }
4026
    mesh_ids.insert(id);
3,225✔
4027

4028
    // If we've already read a mesh with the same ID in a *different* file,
4029
    // assume it is the same here
4030
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,225!
4031
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4032
      continue;
×
4033
    }
4034

4035
    std::string mesh_type;
3,225✔
4036
    if (check_for_node(node, "type")) {
3,225✔
4037
      mesh_type = get_node_value(node, "type", true, true);
950✔
4038
    } else {
4039
      mesh_type = "regular";
2,275✔
4040
    }
4041

4042
    // determine the mesh library to use
4043
    std::string mesh_lib;
3,225✔
4044
    if (check_for_node(node, "library")) {
3,225✔
4045
      mesh_lib = get_node_value(node, "library", true, true);
49!
4046
    }
4047

4048
    Mesh::create(node, mesh_type, mesh_lib);
3,225✔
4049
  }
3,225✔
4050
}
13,394✔
4051

4052
void read_meshes(hid_t group)
22✔
4053
{
4054
  std::unordered_set<int> mesh_ids;
22✔
4055

4056
  std::vector<int> ids;
22✔
4057
  read_attribute(group, "ids", ids);
22✔
4058

4059
  for (auto id : ids) {
55✔
4060

4061
    // Check to make sure multiple meshes in the same file don't share IDs
4062
    if (contains(mesh_ids, id)) {
66!
4063
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4064
                              "'{}' in the same HDF5 input file",
4065
        id));
4066
    }
4067
    mesh_ids.insert(id);
33✔
4068

4069
    // If we've already read a mesh with the same ID in a *different* file,
4070
    // assume it is the same here
4071
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
4072
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4073
      continue;
33✔
4074
    }
4075

4076
    std::string name = fmt::format("mesh {}", id);
×
4077
    hid_t mesh_group = open_group(group, name.c_str());
×
4078

4079
    std::string mesh_type;
×
4080
    if (object_exists(mesh_group, "type")) {
×
4081
      read_dataset(mesh_group, "type", mesh_type);
×
4082
    } else {
4083
      mesh_type = "regular";
×
4084
    }
4085

4086
    // determine the mesh library to use
4087
    std::string mesh_lib;
×
4088
    if (object_exists(mesh_group, "library")) {
×
4089
      read_dataset(mesh_group, "library", mesh_lib);
×
4090
    }
4091

4092
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4093
  }
×
4094
}
44✔
4095

4096
void meshes_to_hdf5(hid_t group)
7,624✔
4097
{
4098
  // Write number of meshes
4099
  hid_t meshes_group = create_group(group, "meshes");
7,624✔
4100
  int32_t n_meshes = model::meshes.size();
7,624✔
4101
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,624✔
4102

4103
  if (n_meshes > 0) {
7,624✔
4104
    // Write IDs of meshes
4105
    vector<int> ids;
2,304✔
4106
    for (const auto& m : model::meshes) {
5,253✔
4107
      m->to_hdf5(meshes_group);
2,949✔
4108
      ids.push_back(m->id_);
2,949✔
4109
    }
4110
    write_attribute(meshes_group, "ids", ids);
2,304✔
4111
  }
2,304✔
4112

4113
  close_group(meshes_group);
7,624✔
4114
}
7,624✔
4115

4116
void free_memory_mesh()
8,721✔
4117
{
4118
  model::meshes.clear();
8,721✔
4119
  model::mesh_map.clear();
8,721✔
4120
}
8,721✔
4121

4122
extern "C" int n_meshes()
308✔
4123
{
4124
  return model::meshes.size();
308✔
4125
}
4126

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