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

openmc-dev / openmc / 26644777111

29 May 2026 03:01PM UTC coverage: 81.333%. Remained the same
26644777111

Pull #3948

github

web-flow
Merge 67690798f into dfb6c5699
Pull Request #3948: Fix get_index_in_direction for regular meshes

17993 of 26085 branches covered (68.98%)

Branch coverage included in aggregate %.

31 of 37 new or added lines in 9 files covered. (83.78%)

1 existing line in 1 file now uncovered.

59109 of 68713 relevant lines covered (86.02%)

48550063.61 hits per line

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

70.19
/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,338,414✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
35,879✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
38,338,272✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
38,338,272✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
38,338,272✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
38,338,272✔
155
  double current = bit_cast_value<double>(current_bits);
38,338,272✔
156
  while (is_min ? (value < current) : (value > current)) {
38,338,414✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
35,879✔
158
    uint64_t expected_bits = current_bits;
35,879✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
35,879✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
38,338,272✔
162
    }
163
    current_bits = expected_bits;
142✔
164
    current = bit_cast_value<double>(current_bits);
142✔
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,169,136✔
188
{
189
  atomic_update_double(ptr, value, false);
6,389,712✔
190
}
6,389,712✔
191

192
inline void atomic_min_double(double* ptr, double value)
19,169,136✔
193
{
194
  atomic_update_double(ptr, value, true);
6,389,712✔
195
}
196

197
namespace detail {
198

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

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

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

223
    // Found the desired material; accumulate volume and bbox
224
    if (current_val == index_material) {
9,043,099✔
225
#pragma omp atomic
5,239,166✔
226
      this->volumes(index_elem, slot) += volume;
9,041,524✔
227
      if (bbox) {
9,041,524✔
228
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,389,538✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,389,538✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,389,538✔
231
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,389,538✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,389,538✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,389,538✔
234
      }
235
      return;
9,041,524✔
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
874✔
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);
174✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
174✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
174✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
174✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
174✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
174✔
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,678,259✔
540
            // Ray trace from r_start to r_end
541
            Position r0 = p.r();
3,850,587✔
542
            double max_distance = bbox.max[axis] - r0[axis];
3,850,587✔
543

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

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

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

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

567
              if (compute_bboxes) {
4,069,237✔
568
                double axis_start = r0[axis] + distance * cumulative_frac;
2,863,152✔
569
                double axis_end = axis_start + length;
2,863,152✔
570
                cumulative_frac += length_fractions[i_bin];
2,863,152✔
571

572
                Position contrib_min = site.r;
2,863,152✔
573
                Position contrib_max = site.r;
2,863,152✔
574

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

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

585
                result.add_volume(
2,863,152✔
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,850,587✔
594
              break;
595

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

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

606
            if (boundary.lattice_translation()[0] != 0 ||
827,672!
607
                boundary.lattice_translation()[1] != 0 ||
827,672!
608
                boundary.lattice_translation()[2] != 0) {
827,672!
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()};
827,672✔
614
              p.cross_surface(*surf);
827,672✔
615
            }
616
          }
827,672✔
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,442,495✔
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,442,495✔
780
  double x_max = positive_grid_boundary(ijk, 0);
1,442,495✔
781

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

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

788
  return {x_min + (x_max - x_min) * prn(seed),
1,442,495✔
789
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,442,495✔
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;
299,979✔
910
    t = 1.0 - t;
299,979✔
911
  }
912
  if (s + t + u > 1) {
601,230✔
913
    if (t + u > 1) {
400,824✔
914
      double old_t = t;
200,992✔
915
      t = 1.0 - u;
200,992✔
916
      u = 1.0 - s - old_t;
200,992✔
917
    } else if (t + u <= 1) {
199,832!
918
      double old_s = s;
199,832✔
919
      s = 1.0 - t - u;
199,832✔
920
      u = old_s + t + u - 1;
199,832✔
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,595,796,089✔
1026
  Position r, bool& in_mesh) const
1027
{
1028
  MeshIndex ijk;
1,595,796,089✔
1029
  in_mesh = true;
1,595,796,089✔
1030
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1031
    ijk[i] = get_index_in_direction(r[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,544✔
1035
  }
1036
  return ijk;
1,595,796,089✔
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,057,818,350✔
1047
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,057,818,350✔
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,816,716✔
1054
{
1055
  MeshIndex ijk;
7,816,716✔
1056
  if (n_dimension_ == 1) {
7,816,716✔
1057
    ijk[0] = bin + 1;
275✔
1058
  } else if (n_dimension_ == 2) {
7,816,441✔
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,800,777!
1062
    ijk[0] = bin % shape_[0] + 1;
7,800,777✔
1063
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,800,777✔
1064
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,800,777✔
1065
  }
1066
  return ijk;
7,816,716✔
1067
}
1068

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

1077
  // Convert indices to bin
1078
  return get_bin_from_indices(ijk);
393,600,552✔
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);
×
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,217,984,326✔
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,217,984,326✔
1156
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,217,984,326✔
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,173,911,158✔
1162
  Position local_r = local_coords(r0);
1,173,911,158✔
1163

1164
  const int n = n_dimension_;
1,173,911,158✔
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,173,911,158✔
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, in_mesh);
1,173,911,158✔
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,173,911,158✔
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,971,914,632✔
1195

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

1200
      // Tally track length delta since last step
1201
      tally.track(ijk,
1,882,997,646✔
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,882,997,646✔
1207
      if (traveled_distance >= total_distance)
1,882,997,646✔
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);
791,100,918✔
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;
791,100,918✔
1217
      distances[k] =
791,100,918✔
1218
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
791,100,918✔
1219

1220
      // Check if we have left the interior of the mesh
1221
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
798,007,774✔
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,949,101✔
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 = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,264,400✔
1253
      for (int k = 0; k < n; ++k) {
28,849,062✔
1254
        distances[k] =
21,584,662✔
1255
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,584,662✔
1256
      }
1257

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

1265
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,105,856,761✔
1266
  vector<int>& bins, vector<double>& lengths) const
1267
{
1268

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

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

1289
  // Perform the mesh raytrace with the helper class.
1290
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,105,856,761✔
1291
}
1,105,856,761✔
1292

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

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

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

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

1324
//==============================================================================
1325
// RegularMesh implementation
1326
//==============================================================================
1327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1473
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1474
{
1475
  if (r == lower_left_[i]) {
2,147,483,647✔
1476
    return 1;
1477
  } else {
1478
    return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1479
  }
1480
}
1481

1482
const std::string RegularMesh::mesh_type = "regular";
1483

1484
std::string RegularMesh::get_mesh_type() const
3,478✔
1485
{
1486
  return mesh_type;
3,478✔
1487
}
1488

1489
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,873,289,280✔
1490
{
1491
  return lower_left_[i] + ijk[i] * width_[i];
1,873,289,280✔
1492
}
1493

1494
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,804,299,760✔
1495
{
1496
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,804,299,760✔
1497
}
1498

1499
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1500
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1501
  double l) const
1502
{
1503
  MeshDistance d;
2,147,483,647✔
1504
  d.next_index = ijk[i];
2,147,483,647✔
1505
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1506
    return d;
15,205,848✔
1507

1508
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1509
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1510
    d.next_index++;
1,868,961,795✔
1511
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,868,961,795✔
1512
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,822,963,788✔
1513
    d.next_index--;
1,799,972,275✔
1514
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,799,972,275✔
1515
  }
1516

1517
  return d;
2,147,483,647✔
1518
}
1519

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

1542
  // Get the coordinates of the mesh lines along both of the axes.
1543
  array<vector<double>, 2> axis_lines;
1544
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1545
    int axis = axes[i_ax];
44!
1546
    if (axis == -1)
44!
1547
      continue;
×
1548
    auto& lines {axis_lines[i_ax]};
44✔
1549

1550
    double coord = lower_left_[axis];
44✔
1551
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1552
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1553
        lines.push_back(coord);
242✔
1554
      coord += width_[axis];
242✔
1555
    }
1556
  }
1557

1558
  return {axis_lines[0], axis_lines[1]};
44✔
1559
}
1560

1561
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,323✔
1562
{
1563
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,323✔
1564
  write_dataset(mesh_group, "lower_left", lower_left_);
2,323✔
1565
  write_dataset(mesh_group, "upper_right", upper_right_);
2,323✔
1566
  write_dataset(mesh_group, "width", width_);
2,323✔
1567
}
2,323✔
1568

1569
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1570
  const SourceSite* bank, int64_t length, bool* outside) const
1571
{
1572
  // Determine shape of array for counts
1573
  std::size_t m = this->n_bins();
7,820✔
1574
  vector<std::size_t> shape = {m};
7,820✔
1575

1576
  // Create array of zeros
1577
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1578
  bool outside_ = false;
2,892✔
1579

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

1583
    // determine scoring bin for entropy mesh
1584
    int mesh_bin = get_bin(site.r);
7,667,451✔
1585

1586
    // if outside mesh, skip particle
1587
    if (mesh_bin < 0) {
7,667,451!
1588
      outside_ = true;
×
1589
      continue;
×
1590
    }
1591

1592
    // Add to appropriate bin
1593
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1594
  }
1595

1596
  // Create reduced count data
1597
  auto counts = tensor::zeros<double>(shape);
7,820✔
1598
  int total = cnt.size();
7,820✔
1599

1600
#ifdef OPENMC_MPI
1601
  // collect values from all processors
1602
  MPI_Reduce(
2,892✔
1603
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1604

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

1615
  return counts;
7,820✔
1616
}
7,820✔
1617

1618
double RegularMesh::volume(const MeshIndex& ijk) const
1,123,862✔
1619
{
1620
  return element_volume_;
1,123,862✔
1621
}
1622

1623
//==============================================================================
1624
// RectilinearMesh implementation
1625
//==============================================================================
1626

1627
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1628
{
1629
  n_dimension_ = 3;
133✔
1630

1631
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1632
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1633
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1634

1635
  if (int err = set_grid()) {
133!
1636
    fatal_error(openmc_err_msg);
×
1637
  }
1638
}
133✔
1639

1640
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1641
{
1642
  n_dimension_ = 3;
11✔
1643

1644
  read_dataset(group, "x_grid", grid_[0]);
11✔
1645
  read_dataset(group, "y_grid", grid_[1]);
11✔
1646
  read_dataset(group, "z_grid", grid_[2]);
11✔
1647

1648
  if (int err = set_grid()) {
11!
1649
    fatal_error(openmc_err_msg);
×
1650
  }
1651
}
11✔
1652

1653
const std::string RectilinearMesh::mesh_type = "rectilinear";
1654

1655
std::string RectilinearMesh::get_mesh_type() const
275✔
1656
{
1657
  return mesh_type;
275✔
1658
}
1659

1660
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1661
  const MeshIndex& ijk, int i) const
1662
{
1663
  return grid_[i][ijk[i]];
26,505,963✔
1664
}
1665

1666
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1667
  const MeshIndex& ijk, int i) const
1668
{
1669
  return grid_[i][ijk[i] - 1];
25,739,406✔
1670
}
1671

1672
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087✔
1673
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1674
  double l) const
1675
{
1676
  MeshDistance d;
53,602,087✔
1677
  d.next_index = ijk[i];
53,602,087✔
1678
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087✔
1679
    return d;
571,824✔
1680

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

1692
int RectilinearMesh::set_grid()
188✔
1693
{
1694
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1695
    static_cast<int>(grid_[1].size()) - 1,
188✔
1696
    static_cast<int>(grid_[2].size()) - 1};
188✔
1697

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

1712
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1713
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1714

1715
  return 0;
188✔
1716
}
1717

1718
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,914✔
1719
{
1720
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,914✔
1721
}
1722

1723
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1724
  Position plot_ll, Position plot_ur) const
1725
{
1726
  // Figure out which axes lie in the plane of the plot.
1727
  array<int, 2> axes {-1, -1};
11✔
1728
  if (plot_ur.z == plot_ll.z) {
11!
NEW
1729
    axes = {0, 1};
×
1730
  } else if (plot_ur.y == plot_ll.y) {
11!
1731
    axes = {0, 2};
11✔
NEW
1732
  } else if (plot_ur.x == plot_ll.x) {
×
NEW
1733
    axes = {1, 2};
×
1734
  } else {
NEW
1735
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1736
  }
1737

1738
  // Get the coordinates of the mesh lines along both of the axes.
1739
  array<vector<double>, 2> axis_lines;
1740
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1741
    int axis = axes[i_ax];
22✔
1742
    vector<double>& lines {axis_lines[i_ax]};
22✔
1743

1744
    for (auto coord : grid_[axis]) {
110✔
1745
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1746
        lines.push_back(coord);
88✔
1747
    }
1748
  }
1749

1750
  return {axis_lines[0], axis_lines[1]};
22✔
1751
}
1752

1753
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1754
{
1755
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1756
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1757
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1758
}
110✔
1759

1760
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1761
{
1762
  double vol {1.0};
132✔
1763

1764
  for (int i = 0; i < n_dimension_; i++) {
528✔
1765
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1766
  }
1767
  return vol;
132✔
1768
}
1769

1770
//==============================================================================
1771
// CylindricalMesh implementation
1772
//==============================================================================
1773

1774
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
400✔
1775
  : PeriodicStructuredMesh {node}
400✔
1776
{
1777
  n_dimension_ = 3;
400✔
1778
  grid_[0] = get_node_array<double>(node, "r_grid");
400✔
1779
  grid_[1] = get_node_array<double>(node, "phi_grid");
400✔
1780
  grid_[2] = get_node_array<double>(node, "z_grid");
400✔
1781
  origin_ = get_node_position(node, "origin");
400✔
1782

1783
  if (int err = set_grid()) {
400!
1784
    fatal_error(openmc_err_msg);
×
1785
  }
1786
}
400✔
1787

1788
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1789
{
1790
  n_dimension_ = 3;
11✔
1791
  read_dataset(group, "r_grid", grid_[0]);
11✔
1792
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1793
  read_dataset(group, "z_grid", grid_[2]);
11✔
1794
  read_dataset(group, "origin", origin_);
11✔
1795

1796
  if (int err = set_grid()) {
11!
1797
    fatal_error(openmc_err_msg);
×
1798
  }
1799
}
11✔
1800

1801
const std::string CylindricalMesh::mesh_type = "cylindrical";
1802

1803
std::string CylindricalMesh::get_mesh_type() const
484✔
1804
{
1805
  return mesh_type;
484✔
1806
}
1807

1808
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1809
  Position r, bool& in_mesh) const
1810
{
1811
  r = local_coords(r);
47,732,091✔
1812

1813
  Position mapped_r;
47,732,091✔
1814
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1815
  mapped_r[2] = r[2];
47,732,091✔
1816

1817
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1818
    mapped_r[1] = 0.0;
1819
  } else {
1820
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1821
    if (mapped_r[1] < 0)
47,732,091✔
1822
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1823
  }
1824

1825
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,091✔
1826

1827
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1828

1829
  return idx;
47,732,091✔
1830
}
1831

1832
Position CylindricalMesh::sample_element(
88,110✔
1833
  const MeshIndex& ijk, uint64_t* seed) const
1834
{
1835
  double r_min = this->r(ijk[0] - 1);
88,110✔
1836
  double r_max = this->r(ijk[0]);
88,110✔
1837

1838
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1839
  double phi_max = this->phi(ijk[1]);
88,110✔
1840

1841
  double z_min = this->z(ijk[2] - 1);
88,110✔
1842
  double z_max = this->z(ijk[2]);
88,110✔
1843

1844
  double r_min_sq = r_min * r_min;
88,110✔
1845
  double r_max_sq = r_max * r_max;
88,110✔
1846
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1847
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1848
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1849

1850
  double x = r * std::cos(phi);
88,110✔
1851
  double y = r * std::sin(phi);
88,110✔
1852

1853
  return origin_ + Position(x, y, z);
88,110✔
1854
}
1855

1856
double CylindricalMesh::find_r_crossing(
142,588,486✔
1857
  const Position& r, const Direction& u, double l, int shell) const
1858
{
1859

1860
  if ((shell < 0) || (shell > shape_[0]))
142,588,486!
1861
    return INFTY;
1862

1863
  // solve r.x^2 + r.y^2 == r0^2
1864
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1865
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1866

1867
  const double r0 = grid_[0][shell];
124,674,511✔
1868
  if (r0 == 0.0)
124,674,511✔
1869
    return INFTY;
1870

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

1873
  // Direction of flight is in z-direction. Will never intersect r.
1874
  if (std::abs(denominator) < FP_PRECISION)
117,538,437✔
1875
    return INFTY;
1876

1877
  // inverse of dominator to help the compiler to speed things up
1878
  const double inv_denominator = 1.0 / denominator;
117,479,477✔
1879

1880
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,479,477✔
1881
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,479,477✔
1882
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,479,477✔
1883

1884
  if (D < 0.0)
117,479,477✔
1885
    return INFTY;
1886

1887
  D = std::sqrt(D);
107,743,355✔
1888

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

1893
  // Check -p - D first because it is always smaller as -p + D
1894
  if (-p - D > l)
101,109,981✔
1895
    return -p - D;
1896
  if (-p + D > l)
80,902,376✔
1897
    return -p + D;
50,078,497✔
1898

1899
  return INFTY;
1900
}
1901

1902
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1903
  const Position& r, const Direction& u, double l, int shell) const
1904
{
1905
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1906
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1907
    return INFTY;
1908

1909
  shell = sanitize_phi(shell);
43,970,718✔
1910

1911
  const double p0 = grid_[1][shell];
43,970,718✔
1912

1913
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1914
  // => x(s) * cos(p0) = y(s) * sin(p0)
1915
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1916
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1917

1918
  const double c0 = std::cos(p0);
43,970,718✔
1919
  const double s0 = std::sin(p0);
43,970,718✔
1920

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

1923
  // Check if direction of flight is not parallel to phi surface
1924
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1925
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1926
    // Check if solution is in positive direction of flight and crosses the
1927
    // correct phi surface (not -phi)
1928
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1929
      return s;
20,219,859✔
1930
  }
1931

1932
  return INFTY;
1933
}
1934

1935
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1936
  const Position& r, const Direction& u, double l, int shell) const
1937
{
1938
  MeshDistance d;
36,695,747✔
1939
  d.next_index = shell;
36,695,747✔
1940

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

1945
  d.max_surface = (u.z > 0.0);
35,577,531✔
1946
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1947
    d.next_index += 1;
16,875,892✔
1948
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1949
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1950
    d.next_index -= 1;
16,846,225✔
1951
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1952
  }
1953
  return d;
35,577,531✔
1954
}
1955

1956
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,192✔
1957
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1958
  double l) const
1959
{
1960
  if (i == 0) {
145,218,192✔
1961

1962
    return std::min(
142,588,486✔
1963
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,243✔
1964
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,486✔
1965

1966
  } else if (i == 1) {
73,923,949✔
1967

1968
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1969
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1970
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1971
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1972

1973
  } else {
1974
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1975
  }
1976
}
1977

1978
int CylindricalMesh::set_grid()
433✔
1979
{
1980
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
1981
    static_cast<int>(grid_[1].size()) - 1,
433✔
1982
    static_cast<int>(grid_[2].size()) - 1};
433✔
1983

1984
  for (const auto& g : grid_) {
1,732✔
1985
    if (g.size() < 2) {
1,299!
1986
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
1987
                 "must each have at least 2 points");
1988
      return OPENMC_E_INVALID_ARGUMENT;
×
1989
    }
1990
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,299!
1991
        g.end()) {
1,299!
1992
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
1993
                 "cylindrical meshes must be sorted and unique.");
1994
      return OPENMC_E_INVALID_ARGUMENT;
×
1995
    }
1996
  }
1997
  if (grid_[0].front() < 0.0) {
433!
1998
    set_errmsg("r-grid for "
×
1999
               "cylindrical meshes must start at r >= 0.");
2000
    return OPENMC_E_INVALID_ARGUMENT;
×
2001
  }
2002
  if (grid_[1].front() < 0.0) {
433!
2003
    set_errmsg("phi-grid for "
×
2004
               "cylindrical meshes must start at phi >= 0.");
2005
    return OPENMC_E_INVALID_ARGUMENT;
×
2006
  }
2007
  if (grid_[1].back() > 2.0 * PI) {
433!
2008
    set_errmsg("phi-grids for "
×
2009
               "cylindrical meshes must end with theta <= 2*pi.");
2010

2011
    return OPENMC_E_INVALID_ARGUMENT;
×
2012
  }
2013

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

2016
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2017
    origin_[2] + grid_[2].front()};
433✔
2018
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2019
    origin_[2] + grid_[2].back()};
433✔
2020

2021
  return 0;
433✔
2022
}
2023

2024
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2025
{
2026
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2027
}
2028

2029
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2030
  Position plot_ll, Position plot_ur) const
2031
{
2032
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2033

2034
  // Figure out which axes lie in the plane of the plot.
2035
  array<vector<double>, 2> axis_lines;
2036
  return {axis_lines[0], axis_lines[1]};
2037
}
2038

2039
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2040
{
2041
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2042
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2043
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2044
  write_dataset(mesh_group, "origin", origin_);
374✔
2045
}
374✔
2046

2047
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2048
{
2049
  double r_i = grid_[0][ijk[0] - 1];
792✔
2050
  double r_o = grid_[0][ijk[0]];
792✔
2051

2052
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2053
  double phi_o = grid_[1][ijk[1]];
792✔
2054

2055
  double z_i = grid_[2][ijk[2] - 1];
792✔
2056
  double z_o = grid_[2][ijk[2]];
792✔
2057

2058
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2059
}
2060

2061
//==============================================================================
2062
// SphericalMesh implementation
2063
//==============================================================================
2064

2065
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2066
  : PeriodicStructuredMesh {node}
345✔
2067
{
2068
  n_dimension_ = 3;
345✔
2069

2070
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2071
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2072
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2073
  origin_ = get_node_position(node, "origin");
345✔
2074

2075
  if (int err = set_grid()) {
345!
2076
    fatal_error(openmc_err_msg);
×
2077
  }
2078
}
345✔
2079

2080
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2081
{
2082
  n_dimension_ = 3;
11✔
2083

2084
  read_dataset(group, "r_grid", grid_[0]);
11✔
2085
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2086
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2087
  read_dataset(group, "origin", origin_);
11✔
2088

2089
  if (int err = set_grid()) {
11!
2090
    fatal_error(openmc_err_msg);
×
2091
  }
2092
}
11✔
2093

2094
const std::string SphericalMesh::mesh_type = "spherical";
2095

2096
std::string SphericalMesh::get_mesh_type() const
385✔
2097
{
2098
  return mesh_type;
385✔
2099
}
2100

2101
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2102
  Position r, bool& in_mesh) const
2103
{
2104
  r = local_coords(r);
68,592,128✔
2105

2106
  Position mapped_r;
68,592,128✔
2107
  mapped_r[0] = r.norm();
68,592,128✔
2108

2109
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2110
    mapped_r[1] = 0.0;
2111
    mapped_r[2] = 0.0;
2112
  } else {
2113
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2114
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2115
    if (mapped_r[2] < 0)
68,592,128✔
2116
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2117
  }
2118

2119
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,128✔
2120

2121
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2122
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2123

2124
  return idx;
68,592,128✔
2125
}
2126

2127
Position SphericalMesh::sample_element(
110✔
2128
  const MeshIndex& ijk, uint64_t* seed) const
2129
{
2130
  double r_min = this->r(ijk[0] - 1);
110✔
2131
  double r_max = this->r(ijk[0]);
110✔
2132

2133
  double theta_min = this->theta(ijk[1] - 1);
110✔
2134
  double theta_max = this->theta(ijk[1]);
110✔
2135

2136
  double phi_min = this->phi(ijk[2] - 1);
110✔
2137
  double phi_max = this->phi(ijk[2]);
110✔
2138

2139
  double cos_theta =
110✔
2140
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2141
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2142
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2143
  double r_min_cub = std::pow(r_min, 3);
110✔
2144
  double r_max_cub = std::pow(r_max, 3);
110✔
2145
  // might be faster to do rejection here?
2146
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2147

2148
  double x = r * std::cos(phi) * sin_theta;
110✔
2149
  double y = r * std::sin(phi) * sin_theta;
110✔
2150
  double z = r * cos_theta;
110✔
2151

2152
  return origin_ + Position(x, y, z);
110✔
2153
}
2154

2155
double SphericalMesh::find_r_crossing(
443,981,868✔
2156
  const Position& r, const Direction& u, double l, int shell) const
2157
{
2158
  if ((shell < 0) || (shell > shape_[0]))
443,981,868✔
2159
    return INFTY;
2160

2161
  // solve |r+s*u| = r0
2162
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2163
  const double r0 = grid_[0][shell];
404,360,781✔
2164
  if (r0 == 0.0)
404,360,781✔
2165
    return INFTY;
2166
  const double p = r.dot(u);
396,682,264✔
2167
  double R = r.norm();
396,682,264✔
2168
  double D = p * p - (R - r0) * (R + r0);
396,682,264✔
2169

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

2174
  if (D >= 0.0) {
385,973,610✔
2175
    D = std::sqrt(D);
358,096,662✔
2176
    // Check -p - D first because it is always smaller as -p + D
2177
    if (-p - D > l)
358,096,662✔
2178
      return -p - D;
2179
    if (-p + D > l)
293,782,962✔
2180
      return -p + D;
177,242,120✔
2181
  }
2182

2183
  return INFTY;
2184
}
2185

2186
double SphericalMesh::find_theta_crossing(
110,161,348✔
2187
  const Position& r, const Direction& u, double l, int shell) const
2188
{
2189
  // Theta grid is [0, π], thus there is no real surface to cross
2190
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2191
    return INFTY;
2192

2193
  shell = sanitize_theta(shell);
38,358,540✔
2194

2195
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2196
  // yields
2197
  // a*s^2 + 2*b*s + c == 0 with
2198
  // a = cos(theta)^2 - u.z * u.z
2199
  // b = r*u * cos(theta)^2 - u.z * r.z
2200
  // c = r*r * cos(theta)^2 - r.z^2
2201

2202
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2203
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2204
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2205

2206
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2207
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2208
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2209

2210
  // if factor of s^2 is zero, direction of flight is parallel to theta
2211
  // surface
2212
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2213
    // if b vanishes, direction of flight is within theta surface and crossing
2214
    // is not possible
2215
    if (std::abs(b) < FP_PRECISION)
482,548!
2216
      return INFTY;
2217

2218
    const double s = -0.5 * c / b;
×
2219
    // Check if solution is in positive direction of flight and has correct
2220
    // sign
2221
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2222
      return s;
×
2223

2224
    // no crossing is possible
2225
    return INFTY;
2226
  }
2227

2228
  const double p = b / a;
37,875,992✔
2229
  double D = p * p - c / a;
37,875,992✔
2230

2231
  if (D < 0.0)
37,875,992✔
2232
    return INFTY;
2233

2234
  D = std::sqrt(D);
26,921,004✔
2235

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

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

2247
  return INFTY;
2248
}
2249

2250
double SphericalMesh::find_phi_crossing(
111,750,826✔
2251
  const Position& r, const Direction& u, double l, int shell) const
2252
{
2253
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2254
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2255
    return INFTY;
2256

2257
  shell = sanitize_phi(shell);
39,948,018✔
2258

2259
  const double p0 = grid_[2][shell];
39,948,018✔
2260

2261
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2262
  // => x(s) * cos(p0) = y(s) * sin(p0)
2263
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2264
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2265

2266
  const double c0 = std::cos(p0);
39,948,018✔
2267
  const double s0 = std::sin(p0);
39,948,018✔
2268

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

2271
  // Check if direction of flight is not parallel to phi surface
2272
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2273
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2274
    // Check if solution is in positive direction of flight and crosses the
2275
    // correct phi surface (not -phi)
2276
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2277
      return s;
17,579,452✔
2278
  }
2279

2280
  return INFTY;
2281
}
2282

2283
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,947,021✔
2284
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2285
  double l) const
2286
{
2287

2288
  if (i == 0) {
332,947,021✔
2289
    return std::min(
443,981,868✔
2290
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,990,934✔
2291
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,981,868✔
2292

2293
  } else if (i == 1) {
110,956,087✔
2294
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2295
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2296
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2297
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2298

2299
  } else {
2300
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2301
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2302
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2303
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2304
  }
2305
}
2306

2307
int SphericalMesh::set_grid()
378✔
2308
{
2309
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2310
    static_cast<int>(grid_[1].size()) - 1,
378✔
2311
    static_cast<int>(grid_[2].size()) - 1};
378✔
2312

2313
  for (const auto& g : grid_) {
1,512✔
2314
    if (g.size() < 2) {
1,134!
2315
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2316
                 "must each have at least 2 points");
2317
      return OPENMC_E_INVALID_ARGUMENT;
×
2318
    }
2319
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2320
        g.end()) {
1,134!
2321
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2322
                 "spherical meshes must be sorted and unique.");
2323
      return OPENMC_E_INVALID_ARGUMENT;
×
2324
    }
2325
    if (g.front() < 0.0) {
1,134!
2326
      set_errmsg("r-, theta-, and phi- grids for "
×
2327
                 "spherical meshes must start at v >= 0.");
2328
      return OPENMC_E_INVALID_ARGUMENT;
×
2329
    }
2330
  }
2331
  if (grid_[1].back() > PI) {
378!
2332
    set_errmsg("theta-grids for "
×
2333
               "spherical meshes must end with theta <= pi.");
2334

2335
    return OPENMC_E_INVALID_ARGUMENT;
×
2336
  }
2337
  if (grid_[2].back() > 2 * PI) {
378!
2338
    set_errmsg("phi-grids for "
×
2339
               "spherical meshes must end with phi <= 2*pi.");
2340
    return OPENMC_E_INVALID_ARGUMENT;
×
2341
  }
2342

2343
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2344
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2345

2346
  double r = grid_[0].back();
378✔
2347
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2348
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2349

2350
  return 0;
378✔
2351
}
2352

2353
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2354
{
2355
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2356
}
2357

2358
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2359
  Position plot_ll, Position plot_ur) const
2360
{
2361
  fatal_error("Plot of spherical Mesh not implemented");
×
2362

2363
  // Figure out which axes lie in the plane of the plot.
2364
  array<vector<double>, 2> axis_lines;
2365
  return {axis_lines[0], axis_lines[1]};
2366
}
2367

2368
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2369
{
2370
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2371
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2372
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2373
  write_dataset(mesh_group, "origin", origin_);
319✔
2374
}
319✔
2375

2376
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2377
{
2378
  double r_i = grid_[0][ijk[0] - 1];
935✔
2379
  double r_o = grid_[0][ijk[0]];
935✔
2380

2381
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2382
  double theta_o = grid_[1][ijk[1]];
935✔
2383

2384
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2385
  double phi_o = grid_[2][ijk[2]];
935✔
2386

2387
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2388
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2389
}
2390

2391
//==============================================================================
2392
// Helper functions for the C API
2393
//==============================================================================
2394

2395
int check_mesh(int32_t index)
6,490✔
2396
{
2397
  if (index < 0 || index >= model::meshes.size()) {
6,490!
2398
    set_errmsg("Index in meshes array is out of bounds.");
×
2399
    return OPENMC_E_OUT_OF_BOUNDS;
×
2400
  }
2401
  return 0;
2402
}
2403

2404
template<class T>
2405
int check_mesh_type(int32_t index)
1,100✔
2406
{
2407
  if (int err = check_mesh(index))
1,100!
2408
    return err;
2409

2410
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2411
  if (!mesh) {
1,100!
2412
    set_errmsg("This function is not valid for input mesh.");
×
2413
    return OPENMC_E_INVALID_TYPE;
×
2414
  }
2415
  return 0;
2416
}
2417

2418
template<class T>
2419
bool is_mesh_type(int32_t index)
2420
{
2421
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2422
  return mesh;
2423
}
2424

2425
//==============================================================================
2426
// C API functions
2427
//==============================================================================
2428

2429
// Return the type of mesh as a C string
2430
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2431
{
2432
  if (int err = check_mesh(index))
1,496!
2433
    return err;
2434

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

2437
  return 0;
1,496✔
2438
}
2439

2440
//! Extend the meshes array by n elements
2441
extern "C" int openmc_extend_meshes(
253✔
2442
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2443
{
2444
  if (index_start)
253!
2445
    *index_start = model::meshes.size();
253✔
2446
  std::string mesh_type;
253✔
2447

2448
  for (int i = 0; i < n; ++i) {
506✔
2449
    if (RegularMesh::mesh_type == type) {
253✔
2450
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2451
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2452
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2453
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2454
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2455
    } else if (SphericalMesh::mesh_type == type) {
22!
2456
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2457
    } else {
2458
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2459
    }
2460
  }
2461
  if (index_end)
253!
2462
    *index_end = model::meshes.size() - 1;
×
2463

2464
  return 0;
253✔
2465
}
253✔
2466

2467
//! Adds a new unstructured mesh to OpenMC
2468
extern "C" int openmc_add_unstructured_mesh(
×
2469
  const char filename[], const char library[], int* id)
2470
{
2471
  std::string lib_name(library);
×
2472
  std::string mesh_file(filename);
×
2473
  bool valid_lib = false;
×
2474

2475
#ifdef OPENMC_DAGMC_ENABLED
2476
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2477
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2478
    valid_lib = true;
2479
  }
2480
#endif
2481

2482
#ifdef OPENMC_LIBMESH_ENABLED
2483
  if (lib_name == LibMesh::mesh_lib_type) {
×
2484
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2485
    valid_lib = true;
2486
  }
2487
#endif
2488

2489
  if (!valid_lib) {
×
2490
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2491
                           "by this build of OpenMC",
2492
      lib_name));
2493
    return OPENMC_E_INVALID_ARGUMENT;
×
2494
  }
2495

2496
  // auto-assign new ID
2497
  model::meshes.back()->set_id(-1);
×
2498
  *id = model::meshes.back()->id_;
2499

2500
  return 0;
2501
}
×
2502

2503
//! Return the index in the meshes array of a mesh with a given ID
2504
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2505
{
2506
  auto pair = model::mesh_map.find(id);
429!
2507
  if (pair == model::mesh_map.end()) {
429!
2508
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2509
    return OPENMC_E_INVALID_ID;
×
2510
  }
2511
  *index = pair->second;
429✔
2512
  return 0;
429✔
2513
}
2514

2515
//! Return the ID of a mesh
2516
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,827✔
2517
{
2518
  if (int err = check_mesh(index))
2,827!
2519
    return err;
2520
  *id = model::meshes[index]->id_;
2,827✔
2521
  return 0;
2,827✔
2522
}
2523

2524
//! Set the ID of a mesh
2525
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2526
{
2527
  if (int err = check_mesh(index))
253!
2528
    return err;
2529
  model::meshes[index]->id_ = id;
253✔
2530
  model::mesh_map[id] = index;
253✔
2531
  return 0;
253✔
2532
}
2533

2534
//! Get the number of elements in a mesh
2535
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2536
{
2537
  if (int err = check_mesh(index))
297!
2538
    return err;
2539
  *n = model::meshes[index]->n_bins();
297✔
2540
  return 0;
297✔
2541
}
2542

2543
//! Get the volume of each element in the mesh
2544
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2545
{
2546
  if (int err = check_mesh(index))
88!
2547
    return err;
2548
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2549
    volumes[i] = model::meshes[index]->volume(i);
880✔
2550
  }
2551
  return 0;
2552
}
2553

2554
//! Get the bounding box of a mesh
2555
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2556
{
2557
  if (int err = check_mesh(index))
176!
2558
    return err;
2559

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

2562
  // set lower left corner values
2563
  ll[0] = bbox.min.x;
176✔
2564
  ll[1] = bbox.min.y;
176✔
2565
  ll[2] = bbox.min.z;
176✔
2566

2567
  // set upper right corner values
2568
  ur[0] = bbox.max.x;
176✔
2569
  ur[1] = bbox.max.y;
176✔
2570
  ur[2] = bbox.max.z;
176✔
2571
  return 0;
176✔
2572
}
2573

2574
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2575
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2576
{
2577
  if (int err = check_mesh(index))
209!
2578
    return err;
2579

2580
  try {
209✔
2581
    model::meshes[index]->material_volumes(
209✔
2582
      nx, ny, nz, table_size, materials, volumes, bboxes);
2583
  } catch (const std::exception& e) {
11!
2584
    set_errmsg(e.what());
11✔
2585
    if (starts_with(e.what(), "Mesh")) {
11!
2586
      return OPENMC_E_GEOMETRY;
11✔
2587
    } else {
2588
      return OPENMC_E_ALLOCATE;
×
2589
    }
2590
  }
11✔
2591

2592
  return 0;
2593
}
2594

2595
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2596
  Position width, int basis, int* pixels, int32_t* data)
2597
{
2598
  if (int err = check_mesh(index))
44!
2599
    return err;
2600
  const auto& mesh = model::meshes[index].get();
44!
2601

2602
  int pixel_width = pixels[0];
44✔
2603
  int pixel_height = pixels[1];
44✔
2604

2605
  // get pixel size
2606
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2607
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2608

2609
  // setup basis indices and initial position centered on pixel
2610
  int in_i, out_i;
44✔
2611
  Position xyz = origin;
44✔
2612
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2613
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2614
  switch (basis_enum) {
44!
2615
  case PlotBasis::xy:
2616
    in_i = 0;
2617
    out_i = 1;
2618
    break;
2619
  case PlotBasis::xz:
2620
    in_i = 0;
2621
    out_i = 2;
2622
    break;
2623
  case PlotBasis::yz:
2624
    in_i = 1;
2625
    out_i = 2;
2626
    break;
2627
  default:
×
2628
    UNREACHABLE();
×
2629
  }
2630

2631
  // set initial position
2632
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2633
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2634

2635
#pragma omp parallel
24✔
2636
  {
20✔
2637
    Position r = xyz;
20✔
2638

2639
#pragma omp for
2640
    for (int y = 0; y < pixel_height; y++) {
420✔
2641
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2642
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2643
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2644
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2645
      }
2646
    }
2647
  }
2648

2649
  return 0;
44✔
2650
}
2651

2652
//! Get the dimension of a regular mesh
2653
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2654
  int32_t index, int** dims, int* n)
2655
{
2656
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2657
    return err;
2658
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2659
  *dims = mesh->shape_.data();
11✔
2660
  *n = mesh->n_dimension_;
11✔
2661
  return 0;
11✔
2662
}
2663

2664
//! Set the dimension of a regular mesh
2665
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2666
  int32_t index, int n, const int* dims)
2667
{
2668
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2669
    return err;
2670
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2671

2672
  // Copy dimension
2673
  mesh->n_dimension_ = n;
187✔
2674
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2675
  return 0;
187✔
2676
}
2677

2678
//! Get the regular mesh parameters
2679
extern "C" int openmc_regular_mesh_get_params(
209✔
2680
  int32_t index, double** ll, double** ur, double** width, int* n)
2681
{
2682
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2683
    return err;
2684
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2685

2686
  if (m->lower_left_.empty()) {
209!
2687
    set_errmsg("Mesh parameters have not been set.");
×
2688
    return OPENMC_E_ALLOCATE;
×
2689
  }
2690

2691
  *ll = m->lower_left_.data();
209✔
2692
  *ur = m->upper_right_.data();
209✔
2693
  *width = m->width_.data();
209✔
2694
  *n = m->n_dimension_;
209✔
2695
  return 0;
209✔
2696
}
2697

2698
//! Set the regular mesh parameters
2699
extern "C" int openmc_regular_mesh_set_params(
220✔
2700
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2701
{
2702
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2703
    return err;
2704
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2705

2706
  if (m->n_dimension_ == -1) {
220!
2707
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2708
    return OPENMC_E_UNASSIGNED;
×
2709
  }
2710

2711
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2712
  if (ll && ur) {
220✔
2713
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2714
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2715
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2716
  } else if (ll && width) {
22✔
2717
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2718
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2719
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2720
  } else if (ur && width) {
11!
2721
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2722
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2723
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2724
  } else {
2725
    set_errmsg("At least two parameters must be specified.");
×
2726
    return OPENMC_E_INVALID_ARGUMENT;
×
2727
  }
2728

2729
  // Set material volumes
2730

2731
  // TODO: incorporate this into method in RegularMesh that can be called from
2732
  // here and from constructor
2733
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2734
  m->element_volume_ = 1.0;
220✔
2735
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2736
    m->element_volume_ *= m->width_[i];
660✔
2737
  }
2738

2739
  return 0;
2740
}
220✔
2741

2742
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2743
template<class C>
2744
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2745
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2746
  const int nz)
2747
{
2748
  if (int err = check_mesh_type<C>(index))
88!
2749
    return err;
2750

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

2753
  m->n_dimension_ = 3;
88✔
2754

2755
  m->grid_[0].reserve(nx);
88✔
2756
  m->grid_[1].reserve(ny);
88✔
2757
  m->grid_[2].reserve(nz);
88✔
2758

2759
  for (int i = 0; i < nx; i++) {
572✔
2760
    m->grid_[0].push_back(grid_x[i]);
484✔
2761
  }
2762
  for (int i = 0; i < ny; i++) {
341✔
2763
    m->grid_[1].push_back(grid_y[i]);
253✔
2764
  }
2765
  for (int i = 0; i < nz; i++) {
319✔
2766
    m->grid_[2].push_back(grid_z[i]);
231✔
2767
  }
2768

2769
  int err = m->set_grid();
88✔
2770
  return err;
88✔
2771
}
2772

2773
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2774
template<class C>
2775
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2776
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2777
{
2778
  if (int err = check_mesh_type<C>(index))
385!
2779
    return err;
2780
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2781

2782
  if (m->lower_left_.empty()) {
385!
2783
    set_errmsg("Mesh parameters have not been set.");
×
2784
    return OPENMC_E_ALLOCATE;
×
2785
  }
2786

2787
  *grid_x = m->grid_[0].data();
385✔
2788
  *nx = m->grid_[0].size();
385✔
2789
  *grid_y = m->grid_[1].data();
385✔
2790
  *ny = m->grid_[1].size();
385✔
2791
  *grid_z = m->grid_[2].data();
385✔
2792
  *nz = m->grid_[2].size();
385✔
2793

2794
  return 0;
385✔
2795
}
2796

2797
//! Get the rectilinear mesh grid
2798
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2799
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2800
{
2801
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2802
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2803
}
2804

2805
//! Set the rectilienar mesh parameters
2806
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2807
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2808
  const double* grid_z, const int nz)
2809
{
2810
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2811
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2812
}
2813

2814
//! Get the cylindrical mesh grid
2815
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2816
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2817
{
2818
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2819
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2820
}
2821

2822
//! Set the cylindrical mesh parameters
2823
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2824
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2825
  const double* grid_z, const int nz)
2826
{
2827
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2828
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2829
}
2830

2831
//! Get the spherical mesh grid
2832
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2833
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2834
{
2835

2836
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2837
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2838
  ;
121✔
2839
}
2840

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

2850
#ifdef OPENMC_DAGMC_ENABLED
2851

2852
const std::string MOABMesh::mesh_lib_type = "moab";
2853

2854
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2855
{
2856
  initialize();
24✔
2857
}
24!
2858

2859
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2860
{
2861
  initialize();
×
2862
}
×
2863

2864
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2865
  : UnstructuredMesh()
×
2866
{
2867
  n_dimension_ = 3;
2868
  filename_ = filename;
×
2869
  set_length_multiplier(length_multiplier);
×
2870
  initialize();
×
2871
}
×
2872

2873
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2874
{
2875
  mbi_ = external_mbi;
1✔
2876
  filename_ = "unknown (external file)";
1✔
2877
  this->initialize();
1✔
2878
}
1!
2879

2880
void MOABMesh::initialize()
25✔
2881
{
2882

2883
  // Create the MOAB interface and load data from file
2884
  this->create_interface();
25✔
2885

2886
  // Initialise MOAB error code
2887
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2888

2889
  // Set the dimension
2890
  n_dimension_ = 3;
25✔
2891

2892
  // set member range of tetrahedral entities
2893
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2894
  if (rval != moab::MB_SUCCESS) {
25!
2895
    fatal_error("Failed to get all tetrahedral elements");
2896
  }
2897

2898
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2899
    warning("Non-tetrahedral elements found in unstructured "
×
2900
            "mesh file: " +
2901
            filename_);
2902
  }
2903

2904
  // set member range of vertices
2905
  int vertex_dim = 0;
25✔
2906
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2907
  if (rval != moab::MB_SUCCESS) {
25!
2908
    fatal_error("Failed to get all vertex handles");
2909
  }
2910

2911
  // make an entity set for all tetrahedra
2912
  // this is used for convenience later in output
2913
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2914
  if (rval != moab::MB_SUCCESS) {
25!
2915
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2916
  }
2917

2918
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2919
  if (rval != moab::MB_SUCCESS) {
25!
2920
    fatal_error("Failed to add tetrahedra to an entity set.");
2921
  }
2922

2923
  if (length_multiplier_ > 0.0) {
25!
2924
    // get the connectivity of all tets
2925
    moab::Range adj;
×
2926
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2927
    if (rval != moab::MB_SUCCESS) {
×
2928
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2929
    }
2930
    // scale all vertex coords by multiplier (done individually so not all
2931
    // coordinates are in memory twice at once)
2932
    for (auto vert : adj) {
×
2933
      // retrieve coords
2934
      std::array<double, 3> coord;
2935
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2936
      if (rval != moab::MB_SUCCESS) {
×
2937
        fatal_error("Could not get coordinates of vertex.");
2938
      }
2939
      // scale coords
2940
      for (auto& c : coord) {
×
2941
        c *= length_multiplier_;
2942
      }
2943
      // set new coords
2944
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2945
      if (rval != moab::MB_SUCCESS) {
×
2946
        fatal_error("Failed to set new vertex coordinates");
2947
      }
2948
    }
2949
  }
2950

2951
  // Determine bounds of mesh
2952
  this->determine_bounds();
25✔
2953
}
25✔
2954

2955
void MOABMesh::prepare_for_point_location()
21✔
2956
{
2957
  // if the KDTree has already been constructed, do nothing
2958
  if (kdtree_)
21!
2959
    return;
2960

2961
  // build acceleration data structures
2962
  compute_barycentric_data(ehs_);
21✔
2963
  build_kdtree(ehs_);
21✔
2964
}
2965

2966
void MOABMesh::create_interface()
25✔
2967
{
2968
  // Do not create a MOAB instance if one is already in memory
2969
  if (mbi_)
25✔
2970
    return;
2971

2972
  // create MOAB instance
2973
  mbi_ = std::make_shared<moab::Core>();
24!
2974

2975
  // load unstructured mesh file
2976
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2977
  if (rval != moab::MB_SUCCESS) {
24!
2978
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2979
  }
2980
}
2981

2982
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
2983
{
2984
  moab::Range all_tris;
21✔
2985
  int adj_dim = 2;
21✔
2986
  write_message("Getting tet adjacencies...", 7);
21✔
2987
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
2988
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2989
  if (rval != moab::MB_SUCCESS) {
21!
2990
    fatal_error("Failed to get adjacent triangles for tets");
2991
  }
2992

2993
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
2994
    warning("Non-triangle elements found in tet adjacencies in "
×
2995
            "unstructured mesh file: " +
2996
            filename_);
×
2997
  }
2998

2999
  // combine into one range
3000
  moab::Range all_tets_and_tris;
21✔
3001
  all_tets_and_tris.merge(all_tets);
21✔
3002
  all_tets_and_tris.merge(all_tris);
21✔
3003

3004
  // create a kd-tree instance
3005
  write_message(
21✔
3006
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3007
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3008

3009
  // Determine what options to use
3010
  std::ostringstream options_stream;
21✔
3011
  if (options_.empty()) {
21✔
3012
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3013
  } else {
3014
    options_stream << options_;
16✔
3015
  }
3016
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3017

3018
  // Build the k-d tree
3019
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3020
  if (rval != moab::MB_SUCCESS) {
21!
3021
    fatal_error("Failed to construct KDTree for the "
3022
                "unstructured mesh file: " +
3023
                filename_);
×
3024
  }
3025
}
21✔
3026

3027
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3028
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3029
{
3030
  hits.clear();
1,543,584!
3031

3032
  moab::ErrorCode rval;
1,543,584✔
3033
  vector<moab::EntityHandle> tris;
1,543,584✔
3034
  // get all intersections with triangles in the tet mesh
3035
  // (distances are relative to the start point, not the previous
3036
  // intersection)
3037
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3038
    dir.array(), start.array(), tris, hits, 0, track_len);
3039
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3040
    fatal_error(
3041
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3042
  }
3043

3044
  // remove duplicate intersection distances
3045
  std::unique(hits.begin(), hits.end());
1,543,584✔
3046

3047
  // sorts by first component of std::pair by default
3048
  std::sort(hits.begin(), hits.end());
1,543,584✔
3049
}
1,543,584✔
3050

3051
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3052
  vector<int>& bins, vector<double>& lengths) const
3053
{
3054
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3055
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3056
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3057
  dir.normalize();
1,543,584✔
3058

3059
  double track_len = (end - start).length();
1,543,584✔
3060
  if (track_len == 0.0)
1,543,584!
3061
    return;
721,692✔
3062

3063
  start -= TINY_BIT * dir;
1,543,584✔
3064
  end += TINY_BIT * dir;
1,543,584✔
3065

3066
  vector<double> hits;
1,543,584✔
3067
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3068

3069
  bins.clear();
1,543,584!
3070
  lengths.clear();
1,543,584!
3071

3072
  // if there are no intersections the track may lie entirely
3073
  // within a single tet. If this is the case, apply entire
3074
  // score to that tet and return.
3075
  if (hits.size() == 0) {
1,543,584✔
3076
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3077
    int bin = this->get_bin(midpoint);
721,692✔
3078
    if (bin != -1) {
721,692✔
3079
      bins.push_back(bin);
242,866✔
3080
      lengths.push_back(1.0);
242,866✔
3081
    }
3082
    return;
721,692✔
3083
  }
3084

3085
  // for each segment in the set of tracks, try to look up a tet
3086
  // at the midpoint of the segment
3087
  Position current = r0;
3088
  double last_dist = 0.0;
3089
  for (const auto& hit : hits) {
5,516,161✔
3090
    // get the segment length
3091
    double segment_length = hit - last_dist;
4,694,269✔
3092
    last_dist = hit;
4,694,269✔
3093
    // find the midpoint of this segment
3094
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3095
    // try to find a tet for this position
3096
    int bin = this->get_bin(midpoint);
4,694,269✔
3097

3098
    // determine the start point for this segment
3099
    current = r0 + u * hit;
4,694,269✔
3100

3101
    if (bin == -1) {
4,694,269✔
3102
      continue;
20,522✔
3103
    }
3104

3105
    bins.push_back(bin);
4,673,747✔
3106
    lengths.push_back(segment_length / track_len);
4,673,747✔
3107
  }
3108

3109
  // tally remaining portion of track after last hit if
3110
  // the last segment of the track is in the mesh but doesn't
3111
  // reach the other side of the tet
3112
  if (hits.back() < track_len) {
821,892!
3113
    Position segment_start = r0 + u * hits.back();
821,892✔
3114
    double segment_length = track_len - hits.back();
821,892✔
3115
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3116
    int bin = this->get_bin(midpoint);
821,892✔
3117
    if (bin != -1) {
821,892✔
3118
      bins.push_back(bin);
766,509✔
3119
      lengths.push_back(segment_length / track_len);
766,509✔
3120
    }
3121
  }
3122
};
1,543,584✔
3123

3124
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3125
{
3126
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3127
  // find the leaf of the kd-tree for this position
3128
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3129
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3130
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3131
    return 0;
3132
  }
3133

3134
  // retrieve the tet elements of this leaf
3135
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3136
  moab::Range tets;
6,305,335✔
3137
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3138
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3139
    warning("MOAB error finding tets.");
×
3140
  }
3141

3142
  // loop over the tets in this leaf, returning the containing tet if found
3143
  for (const auto& tet : tets) {
260,211,273✔
3144
    if (point_in_tet(pos, tet)) {
260,208,426✔
3145
      return tet;
6,302,488✔
3146
    }
3147
  }
3148

3149
  // if no tet is found, return an invalid handle
3150
  return 0;
2,847✔
3151
}
14,634,464✔
3152

3153
double MOABMesh::volume(int bin) const
167,880✔
3154
{
3155
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3156
}
3157

3158
std::string MOABMesh::library() const
34✔
3159
{
3160
  return mesh_lib_type;
34✔
3161
}
3162

3163
// Sample position within a tet for MOAB type tets
3164
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3165
{
3166

3167
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3168

3169
  // Get vertex coordinates for MOAB tet
3170
  const moab::EntityHandle* conn1;
200,410✔
3171
  int conn1_size;
200,410✔
3172
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3173
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3174
    fatal_error(fmt::format(
3175
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3176
      conn1_size));
3177
  }
3178
  moab::CartVect p[4];
200,410✔
3179
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3180
  if (rval != moab::MB_SUCCESS) {
200,410!
3181
    fatal_error("Failed to get tet coords");
3182
  }
3183

3184
  std::array<Position, 4> tet_verts;
200,410✔
3185
  for (int i = 0; i < 4; i++) {
1,002,050✔
3186
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3187
  }
3188
  // Samples position within tet using Barycentric stuff
3189
  return this->sample_tet(tet_verts, seed);
200,410✔
3190
}
3191

3192
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3193
{
3194
  vector<moab::EntityHandle> conn;
167,880✔
3195
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3196
  if (rval != moab::MB_SUCCESS) {
167,880!
3197
    fatal_error("Failed to get tet connectivity");
3198
  }
3199

3200
  moab::CartVect p[4];
167,880✔
3201
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3202
  if (rval != moab::MB_SUCCESS) {
167,880!
3203
    fatal_error("Failed to get tet coords");
3204
  }
3205

3206
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3207
}
167,880✔
3208

3209
int MOABMesh::get_bin(Position r) const
7,317,232✔
3210
{
3211
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3212
  if (tet == 0) {
7,317,232✔
3213
    return -1;
3214
  } else {
3215
    return get_bin_from_ent_handle(tet);
6,302,488✔
3216
  }
3217
}
3218

3219
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3220
{
3221
  moab::ErrorCode rval;
21✔
3222

3223
  baryc_data_.clear();
21!
3224
  baryc_data_.resize(tets.size());
21✔
3225

3226
  // compute the barycentric data for each tet element
3227
  // and store it as a 3x3 matrix
3228
  for (auto& tet : tets) {
239,757✔
3229
    vector<moab::EntityHandle> verts;
239,736✔
3230
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3231
    if (rval != moab::MB_SUCCESS) {
239,736!
3232
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3233
    }
3234

3235
    moab::CartVect p[4];
239,736✔
3236
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3237
    if (rval != moab::MB_SUCCESS) {
239,736!
3238
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3239
    }
3240

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

3243
    // invert now to avoid this cost later
3244
    a = a.transpose().inverse();
239,736✔
3245
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3246
  }
239,736✔
3247
}
21✔
3248

3249
bool MOABMesh::point_in_tet(
260,208,426✔
3250
  const moab::CartVect& r, moab::EntityHandle tet) const
3251
{
3252

3253
  moab::ErrorCode rval;
260,208,426✔
3254

3255
  // get tet vertices
3256
  vector<moab::EntityHandle> verts;
260,208,426✔
3257
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3258
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3259
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3260
    return false;
3261
  }
3262

3263
  // first vertex is used as a reference point for the barycentric data -
3264
  // retrieve its coordinates
3265
  moab::CartVect p_zero;
260,208,426✔
3266
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3267
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3268
    warning("Failed to get coordinates of a vertex in "
×
3269
            "unstructured mesh: " +
3270
            filename_);
×
3271
    return false;
3272
  }
3273

3274
  // look up barycentric data
3275
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3276
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3277

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

3280
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3281
          bary_coords[2] >= 0.0 &&
318,957,185✔
3282
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3283
}
260,208,426✔
3284

3285
int MOABMesh::get_bin_from_index(int idx) const
3286
{
3287
  if (idx >= n_bins()) {
×
3288
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3289
  }
3290
  return ehs_[idx] - ehs_[0];
3291
}
3292

3293
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3294
{
3295
  int bin = get_bin(r);
3296
  *in_mesh = bin != -1;
3297
  return bin;
3298
}
3299

3300
int MOABMesh::get_index_from_bin(int bin) const
3301
{
3302
  return bin;
3303
}
3304

3305
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3306
  Position plot_ll, Position plot_ur) const
3307
{
3308
  // TODO: Implement mesh lines
3309
  return {};
3310
}
3311

3312
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3313
{
3314
  int idx = vert - verts_[0];
815,520✔
3315
  if (idx >= n_vertices()) {
815,520!
3316
    fatal_error(
3317
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3318
  }
3319
  return idx;
815,520✔
3320
}
3321

3322
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3323
{
3324
  int bin = eh - ehs_[0];
266,750,650✔
3325
  if (bin >= n_bins()) {
266,750,650!
3326
    fatal_error(fmt::format("Invalid bin: {}", bin));
3327
  }
3328
  return bin;
266,750,650✔
3329
}
3330

3331
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3332
{
3333
  if (bin >= n_bins()) {
572,170!
3334
    fatal_error(fmt::format("Invalid bin index: ", bin));
3335
  }
3336
  return ehs_[0] + bin;
572,170✔
3337
}
3338

3339
int MOABMesh::n_bins() const
267,526,773✔
3340
{
3341
  return ehs_.size();
267,526,773✔
3342
}
3343

3344
int MOABMesh::n_surface_bins() const
3345
{
3346
  // collect all triangles in the set of tets for this mesh
3347
  moab::Range tris;
×
3348
  moab::ErrorCode rval;
3349
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3350
  if (rval != moab::MB_SUCCESS) {
×
3351
    warning("Failed to get all triangles in the mesh instance");
×
3352
    return -1;
3353
  }
3354
  return 2 * tris.size();
×
3355
}
3356

3357
Position MOABMesh::centroid(int bin) const
3358
{
3359
  moab::ErrorCode rval;
3360

3361
  auto tet = this->get_ent_handle_from_bin(bin);
3362

3363
  // look up the tet connectivity
3364
  vector<moab::EntityHandle> conn;
×
3365
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3366
  if (rval != moab::MB_SUCCESS) {
×
3367
    warning("Failed to get connectivity of a mesh element.");
×
3368
    return {};
3369
  }
3370

3371
  // get the coordinates
3372
  vector<moab::CartVect> coords(conn.size());
×
3373
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3374
  if (rval != moab::MB_SUCCESS) {
×
3375
    warning("Failed to get the coordinates of a mesh element.");
×
3376
    return {};
3377
  }
3378

3379
  // compute the centroid of the element vertices
3380
  moab::CartVect centroid(0.0, 0.0, 0.0);
3381
  for (const auto& coord : coords) {
×
3382
    centroid += coord;
3383
  }
3384
  centroid /= double(coords.size());
3385

3386
  return {centroid[0], centroid[1], centroid[2]};
3387
}
3388

3389
int MOABMesh::n_vertices() const
845,874✔
3390
{
3391
  return verts_.size();
845,874✔
3392
}
3393

3394
Position MOABMesh::vertex(int id) const
86,227✔
3395
{
3396

3397
  moab::ErrorCode rval;
86,227✔
3398

3399
  moab::EntityHandle vert = verts_[id];
86,227✔
3400

3401
  moab::CartVect coords;
86,227✔
3402
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3403
  if (rval != moab::MB_SUCCESS) {
86,227!
3404
    fatal_error("Failed to get the coordinates of a vertex.");
3405
  }
3406

3407
  return {coords[0], coords[1], coords[2]};
86,227✔
3408
}
3409

3410
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3411
{
3412
  moab::ErrorCode rval;
203,880✔
3413

3414
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3415

3416
  // look up the tet connectivity
3417
  vector<moab::EntityHandle> conn;
203,880✔
3418
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3419
  if (rval != moab::MB_SUCCESS) {
203,880!
3420
    fatal_error("Failed to get connectivity of a mesh element.");
3421
    return {};
3422
  }
3423

3424
  std::vector<int> verts(4);
203,880✔
3425
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3426
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3427
  }
3428

3429
  return verts;
203,880✔
3430
}
203,880✔
3431

3432
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3433
  std::string score) const
3434
{
3435
  moab::ErrorCode rval;
3436
  // add a tag to the mesh
3437
  // all scores are treated as a single value
3438
  // with an uncertainty
3439
  moab::Tag value_tag;
3440

3441
  // create the value tag if not present and get handle
3442
  double default_val = 0.0;
3443
  auto val_string = score + "_mean";
3444
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3445
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3446
  if (rval != moab::MB_SUCCESS) {
×
3447
    auto msg =
3448
      fmt::format("Could not create or retrieve the value tag for the score {}"
3449
                  " on unstructured mesh {}",
3450
        score, id_);
×
3451
    fatal_error(msg);
3452
  }
3453

3454
  // create the std dev tag if not present and get handle
3455
  moab::Tag error_tag;
3456
  std::string err_string = score + "_std_dev";
×
3457
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3458
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3459
  if (rval != moab::MB_SUCCESS) {
×
3460
    auto msg =
3461
      fmt::format("Could not create or retrieve the error tag for the score {}"
3462
                  " on unstructured mesh {}",
3463
        score, id_);
×
3464
    fatal_error(msg);
3465
  }
3466

3467
  // return the populated tag handles
3468
  return {value_tag, error_tag};
3469
}
3470

3471
void MOABMesh::add_score(const std::string& score)
3472
{
3473
  auto score_tags = get_score_tags(score);
×
3474
  tag_names_.push_back(score);
3475
}
3476

3477
void MOABMesh::remove_scores()
3478
{
3479
  for (const auto& name : tag_names_) {
×
3480
    auto value_name = name + "_mean";
3481
    moab::Tag tag;
3482
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3483
    if (rval != moab::MB_SUCCESS)
×
3484
      return;
3485

3486
    rval = mbi_->tag_delete(tag);
×
3487
    if (rval != moab::MB_SUCCESS) {
×
3488
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3489
                             " on unstructured mesh {}",
3490
        name, id_);
×
3491
      fatal_error(msg);
3492
    }
3493

3494
    auto std_dev_name = name + "_std_dev";
×
3495
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3496
    if (rval != moab::MB_SUCCESS) {
×
3497
      auto msg =
3498
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3499
                    " on unstructured mesh {}",
3500
          name, id_);
×
3501
    }
3502

3503
    rval = mbi_->tag_delete(tag);
×
3504
    if (rval != moab::MB_SUCCESS) {
×
3505
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3506
                             " on unstructured mesh {}",
3507
        name, id_);
×
3508
      fatal_error(msg);
3509
    }
3510
  }
3511
  tag_names_.clear();
3512
}
3513

3514
void MOABMesh::set_score_data(const std::string& score,
3515
  const vector<double>& values, const vector<double>& std_dev)
3516
{
3517
  auto score_tags = this->get_score_tags(score);
×
3518

3519
  moab::ErrorCode rval;
3520
  // set the score value
3521
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3522
  if (rval != moab::MB_SUCCESS) {
×
3523
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3524
                           "on unstructured mesh {}",
3525
      score, id_);
3526
    warning(msg);
×
3527
  }
3528

3529
  // set the error value
3530
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3531
  if (rval != moab::MB_SUCCESS) {
×
3532
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3533
                           "on unstructured mesh {}",
3534
      score, id_);
3535
    warning(msg);
×
3536
  }
3537
}
3538

3539
void MOABMesh::write(const std::string& base_filename) const
3540
{
3541
  // add extension to the base name
3542
  auto filename = base_filename + ".vtk";
3543
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3544
  filename = settings::path_output + filename;
×
3545

3546
  // write the tetrahedral elements of the mesh only
3547
  // to avoid clutter from zero-value data on other
3548
  // elements during visualization
3549
  moab::ErrorCode rval;
3550
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3551
  if (rval != moab::MB_SUCCESS) {
×
3552
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3553
    warning(msg);
×
3554
  }
3555
}
3556

3557
#endif
3558

3559
#ifdef OPENMC_LIBMESH_ENABLED
3560

3561
const std::string LibMesh::mesh_lib_type = "libmesh";
3562

3563
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3564
{
3565
  // filename_ and length_multiplier_ will already be set by the
3566
  // UnstructuredMesh constructor
3567
  set_mesh_pointer_from_filename(filename_);
25✔
3568
  set_length_multiplier(length_multiplier_);
25✔
3569
  initialize();
25✔
3570
}
25✔
3571

3572
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3573
{
3574
  // filename_ and length_multiplier_ will already be set by the
3575
  // UnstructuredMesh constructor
3576
  set_mesh_pointer_from_filename(filename_);
×
3577
  set_length_multiplier(length_multiplier_);
×
3578
  initialize();
×
3579
}
3580

3581
// create the mesh from a pointer to a libMesh Mesh
3582
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3583
{
3584
  if (!input_mesh.is_replicated()) {
×
3585
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3586
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3587
  }
3588

3589
  m_ = &input_mesh;
3590
  set_length_multiplier(length_multiplier);
×
3591
  initialize();
×
3592
}
3593

3594
// create the mesh from an input file
3595
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3596
{
3597
  n_dimension_ = 3;
3598
  set_mesh_pointer_from_filename(filename);
×
3599
  set_length_multiplier(length_multiplier);
×
3600
  initialize();
×
3601
}
3602

3603
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3604
{
3605
  filename_ = filename;
25✔
3606
  unique_m_ =
25✔
3607
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3608
  m_ = unique_m_.get();
25✔
3609
  m_->read(filename_);
25✔
3610
}
25✔
3611

3612
// build a libMesh equation system for storing values
3613
void LibMesh::build_eqn_sys()
17✔
3614
{
3615
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3616
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3617
  libMesh::ExplicitSystem& eq_sys =
17✔
3618
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3619
}
17✔
3620

3621
// intialize from mesh file
3622
void LibMesh::initialize()
25✔
3623
{
3624
  if (!settings::libmesh_comm) {
25!
3625
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3626
                "communicator.");
3627
  }
3628

3629
  // assuming that unstructured meshes used in OpenMC are 3D
3630
  n_dimension_ = 3;
25✔
3631

3632
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3633
  // Otherwise assume that it is prepared by its owning application
3634
  if (unique_m_) {
25!
3635
    m_->prepare_for_use();
25✔
3636
  }
3637

3638
  // ensure that the loaded mesh is 3 dimensional
3639
  if (m_->mesh_dimension() != n_dimension_) {
25!
3640
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3641
                            "mesh is not a 3D mesh.",
3642
      filename_));
3643
  }
3644

3645
  for (int i = 0; i < num_threads(); i++) {
75✔
3646
    pl_.emplace_back(m_->sub_point_locator());
50✔
3647
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
50✔
3648
    pl_.back()->enable_out_of_mesh_mode();
50✔
3649
  }
3650

3651
  // store first element in the mesh to use as an offset for bin indices
3652
  auto first_elem = *m_->elements_begin();
50✔
3653
  first_element_id_ = first_elem->id();
25✔
3654

3655
  // bounding box for the mesh for quick rejection checks
3656
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3657
  libMesh::Point ll = bbox_.min();
25!
3658
  libMesh::Point ur = bbox_.max();
25!
3659
  if (length_multiplier_ > 0.0) {
25!
3660
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3661
      length_multiplier_ * ll(2)};
3662
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3663
      length_multiplier_ * ur(2)};
3664
  } else {
3665
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3666
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3667
  }
3668
}
25✔
3669

3670
// Sample position within a tet for LibMesh type tets
3671
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3672
{
3673
  const auto& elem = get_element_from_bin(bin);
400,820✔
3674
  // Get tet vertex coordinates from LibMesh
3675
  std::array<Position, 4> tet_verts;
400,820✔
3676
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3677
    auto node_ref = elem.node_ref(i);
1,603,280✔
3678
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3679
  }
1,603,280✔
3680
  // Samples position within tet using Barycentric coordinates
3681
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3682
  if (length_multiplier_ > 0.0) {
400,820!
3683
    return length_multiplier_ * sampled_position;
3684
  } else {
3685
    return sampled_position;
400,820✔
3686
  }
3687
}
3688

3689
Position LibMesh::centroid(int bin) const
3690
{
3691
  const auto& elem = this->get_element_from_bin(bin);
3692
  auto centroid = elem.vertex_average();
3693
  if (length_multiplier_ > 0.0) {
×
3694
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3695
  } else {
3696
    return {centroid(0), centroid(1), centroid(2)};
3697
  }
3698
}
3699

3700
int LibMesh::n_vertices() const
42,644✔
3701
{
3702
  return m_->n_nodes();
42,644✔
3703
}
3704

3705
Position LibMesh::vertex(int vertex_id) const
42,604✔
3706
{
3707
  const auto node_ref = m_->node_ref(vertex_id);
42,604✔
3708
  if (length_multiplier_ > 0.0) {
42,604!
3709
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3710
  } else {
3711
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3712
  }
3713
}
42,604✔
3714

3715
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3716
{
3717
  std::vector<int> conn;
267,856✔
3718
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3719
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3720
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3721
  }
3722
  return conn;
267,856✔
3723
}
3724

3725
std::string LibMesh::library() const
37✔
3726
{
3727
  return mesh_lib_type;
37✔
3728
}
3729

3730
int LibMesh::n_bins() const
1,788,419✔
3731
{
3732
  return m_->n_elem();
1,788,419✔
3733
}
3734

3735
int LibMesh::n_surface_bins() const
3736
{
3737
  int n_bins = 0;
3738
  for (int i = 0; i < this->n_bins(); i++) {
×
3739
    const libMesh::Elem& e = get_element_from_bin(i);
3740
    n_bins += e.n_faces();
3741
    // if this is a boundary element, it will only be visited once,
3742
    // the number of surface bins is incremented to
3743
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3744
      // null neighbor pointer indicates a boundary face
3745
      if (!neighbor_ptr) {
×
3746
        n_bins++;
3747
      }
3748
    }
3749
  }
3750
  return n_bins;
3751
}
3752

3753
void LibMesh::add_score(const std::string& var_name)
17✔
3754
{
3755
  if (!equation_systems_) {
17!
3756
    build_eqn_sys();
17✔
3757
  }
3758

3759
  // check if this is a new variable
3760
  std::string value_name = var_name + "_mean";
17✔
3761
  if (!variable_map_.count(value_name)) {
17✔
3762
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3763
    auto var_num =
17✔
3764
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3765
    variable_map_[value_name] = var_num;
17✔
3766
  }
3767

3768
  std::string std_dev_name = var_name + "_std_dev";
17✔
3769
  // check if this is a new variable
3770
  if (!variable_map_.count(std_dev_name)) {
17✔
3771
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3772
    auto var_num =
17✔
3773
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3774
    variable_map_[std_dev_name] = var_num;
17✔
3775
  }
3776
}
17✔
3777

3778
void LibMesh::remove_scores()
17✔
3779
{
3780
  if (equation_systems_) {
17!
3781
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3782
    eqn_sys.clear();
17✔
3783
    variable_map_.clear();
17✔
3784
  }
3785
}
17✔
3786

3787
void LibMesh::set_score_data(const std::string& var_name,
17✔
3788
  const vector<double>& values, const vector<double>& std_dev)
3789
{
3790
  if (!equation_systems_) {
17!
3791
    build_eqn_sys();
3792
  }
3793

3794
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3795

3796
  if (!eqn_sys.is_initialized()) {
17!
3797
    equation_systems_->init();
17✔
3798
  }
3799

3800
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3801

3802
  // look up the value variable
3803
  std::string value_name = var_name + "_mean";
17✔
3804
  unsigned int value_num = variable_map_.at(value_name);
17✔
3805
  // look up the std dev variable
3806
  std::string std_dev_name = var_name + "_std_dev";
17✔
3807
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3808

3809
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3810
       it++) {
3811
    if (!(*it)->active()) {
99,856!
3812
      continue;
3813
    }
3814

3815
    auto bin = get_bin_from_element(*it);
99,856✔
3816

3817
    // set value
3818
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3819
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3820
    assert(value_dof_indices.size() == 1);
99,856✔
3821
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3822

3823
    // set std dev
3824
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3825
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3826
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3827
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3828
  }
99,873✔
3829
}
17✔
3830

3831
void LibMesh::write(const std::string& filename) const
17✔
3832
{
3833
  write_message(fmt::format(
17✔
3834
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3835
  libMesh::ExodusII_IO exo(*m_);
17✔
3836
  std::set<std::string> systems_out = {eq_system_name_};
34!
3837
  exo.write_discontinuous_exodusII(
17✔
3838
    filename + ".e", *equation_systems_, &systems_out);
34✔
3839
}
17✔
3840

3841
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3842
  vector<int>& bins, vector<double>& lengths) const
3843
{
3844
  // TODO: Implement triangle crossings here
3845
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3846
}
3847

3848
int LibMesh::get_bin(Position r) const
2,340,604✔
3849
{
3850
  // look-up a tet using the point locator
3851
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3852

3853
  if (length_multiplier_ > 0.0) {
2,340,604!
3854
    // Scale the point down
3855
    p /= length_multiplier_;
2,340,604✔
3856
  }
3857

3858
  // quick rejection check
3859
  if (!bbox_.contains_point(p)) {
2,340,604✔
3860
    return -1;
3861
  }
3862

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

3865
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3866
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3867
}
2,340,604✔
3868

3869
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3870
{
3871
  int bin = elem->id() - first_element_id_;
1,520,434✔
3872
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3873
    fatal_error(fmt::format("Invalid bin: {}", bin));
3874
  }
3875
  return bin;
1,520,434✔
3876
}
3877

3878
std::pair<vector<double>, vector<double>> LibMesh::plot(
3879
  Position plot_ll, Position plot_ur) const
3880
{
3881
  return {};
3882
}
3883

3884
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3885
{
3886
  return m_->elem_ref(bin);
769,460✔
3887
}
3888

3889
double LibMesh::volume(int bin) const
368,640✔
3890
{
3891
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3892
         length_multiplier_ * length_multiplier_;
368,640✔
3893
}
3894

3895
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3896
  double length_multiplier,
3897
  const std::set<libMesh::subdomain_id_type>& block_ids)
3898
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3899
    block_restrict_(!block_ids_.empty()),
×
3900
    num_active_(
×
3901
      block_restrict_
3902
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
3903
            m_->active_subdomain_set_elements_end(block_ids_))
×
3904
        : m_->n_active_elem())
×
3905
{
3906
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3907
  // contiguous in ID space, so we need to map from bin indices (defined over
3908
  // active elements) to global dof ids
3909
  bin_to_elem_map_.reserve(num_active_);
×
3910
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3911
  auto begin = block_restrict_
3912
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
3913
                 : m_->active_elements_begin();
×
3914
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
3915
                             : m_->active_elements_end();
×
3916
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
3917
    bin_to_elem_map_.push_back(elem->id());
×
3918
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3919
  }
3920
}
3921

3922
int AdaptiveLibMesh::n_bins() const
3923
{
3924
  return num_active_;
3925
}
3926

3927
void AdaptiveLibMesh::add_score(const std::string& var_name)
3928
{
3929
  warning(fmt::format(
×
3930
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3931
    this->id_));
3932
}
3933

3934
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3935
  const vector<double>& values, const vector<double>& std_dev)
3936
{
3937
  warning(fmt::format(
×
3938
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3939
    this->id_));
3940
}
3941

3942
void AdaptiveLibMesh::write(const std::string& filename) const
3943
{
3944
  warning(fmt::format(
×
3945
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3946
    this->id_));
3947
}
3948

3949
int AdaptiveLibMesh::get_bin(Position r) const
3950
{
3951
  // look-up a tet using the point locator
3952
  libMesh::Point p(r.x, r.y, r.z);
×
3953

3954
  if (length_multiplier_ > 0.0) {
×
3955
    // Scale the point down
3956
    p /= length_multiplier_;
3957
  }
3958

3959
  // quick rejection check
3960
  if (!bbox_.contains_point(p)) {
×
3961
    return -1;
3962
  }
3963

3964
  const auto& point_locator = pl_.at(thread_num());
×
3965

3966
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3967
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3968
}
3969

3970
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3971
{
3972
  int bin = elem_to_bin_map_[elem->id()];
3973
  if (bin >= n_bins() || bin < 0) {
×
3974
    fatal_error(fmt::format("Invalid bin: {}", bin));
3975
  }
3976
  return bin;
3977
}
3978

3979
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3980
{
3981
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3982
}
3983

3984
#endif // OPENMC_LIBMESH_ENABLED
3985

3986
//==============================================================================
3987
// Non-member functions
3988
//==============================================================================
3989

3990
void read_meshes(pugi::xml_node root)
13,267✔
3991
{
3992
  std::unordered_set<int> mesh_ids;
13,267✔
3993

3994
  for (auto node : root.children("mesh")) {
16,492✔
3995
    // Check to make sure multiple meshes in the same file don't share IDs
3996
    int id = std::stoi(get_node_value(node, "id"));
6,450✔
3997
    if (contains(mesh_ids, id)) {
6,450!
3998
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
3999
                              "'{}' in the same input file",
4000
        id));
4001
    }
4002
    mesh_ids.insert(id);
3,225✔
4003

4004
    // If we've already read a mesh with the same ID in a *different* file,
4005
    // assume it is the same here
4006
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,225!
4007
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4008
      continue;
×
4009
    }
4010

4011
    std::string mesh_type;
3,225✔
4012
    if (check_for_node(node, "type")) {
3,225✔
4013
      mesh_type = get_node_value(node, "type", true, true);
950✔
4014
    } else {
4015
      mesh_type = "regular";
2,275✔
4016
    }
4017

4018
    // determine the mesh library to use
4019
    std::string mesh_lib;
3,225✔
4020
    if (check_for_node(node, "library")) {
3,225✔
4021
      mesh_lib = get_node_value(node, "library", true, true);
49!
4022
    }
4023

4024
    Mesh::create(node, mesh_type, mesh_lib);
3,225✔
4025
  }
3,225✔
4026
}
13,267✔
4027

4028
void read_meshes(hid_t group)
22✔
4029
{
4030
  std::unordered_set<int> mesh_ids;
22✔
4031

4032
  std::vector<int> ids;
22✔
4033
  read_attribute(group, "ids", ids);
22✔
4034

4035
  for (auto id : ids) {
55✔
4036

4037
    // Check to make sure multiple meshes in the same file don't share IDs
4038
    if (contains(mesh_ids, id)) {
66!
4039
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4040
                              "'{}' in the same HDF5 input file",
4041
        id));
4042
    }
4043
    mesh_ids.insert(id);
33✔
4044

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

4052
    std::string name = fmt::format("mesh {}", id);
×
4053
    hid_t mesh_group = open_group(group, name.c_str());
×
4054

4055
    std::string mesh_type;
×
4056
    if (object_exists(mesh_group, "type")) {
×
4057
      read_dataset(mesh_group, "type", mesh_type);
×
4058
    } else {
4059
      mesh_type = "regular";
×
4060
    }
4061

4062
    // determine the mesh library to use
4063
    std::string mesh_lib;
×
4064
    if (object_exists(mesh_group, "library")) {
×
4065
      read_dataset(mesh_group, "library", mesh_lib);
×
4066
    }
4067

4068
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4069
  }
×
4070
}
44✔
4071

4072
void meshes_to_hdf5(hid_t group)
7,568✔
4073
{
4074
  // Write number of meshes
4075
  hid_t meshes_group = create_group(group, "meshes");
7,568✔
4076
  int32_t n_meshes = model::meshes.size();
7,568✔
4077
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,568✔
4078

4079
  if (n_meshes > 0) {
7,568✔
4080
    // Write IDs of meshes
4081
    vector<int> ids;
2,304✔
4082
    for (const auto& m : model::meshes) {
5,253✔
4083
      m->to_hdf5(meshes_group);
2,949✔
4084
      ids.push_back(m->id_);
2,949✔
4085
    }
4086
    write_attribute(meshes_group, "ids", ids);
2,304✔
4087
  }
2,304✔
4088

4089
  close_group(meshes_group);
7,568✔
4090
}
7,568✔
4091

4092
void free_memory_mesh()
8,650✔
4093
{
4094
  model::meshes.clear();
8,650✔
4095
  model::mesh_map.clear();
8,650✔
4096
}
8,650✔
4097

4098
extern "C" int n_meshes()
308✔
4099
{
4100
  return model::meshes.size();
308✔
4101
}
4102

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