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

openmc-dev / openmc / 27042392828

05 Jun 2026 10:01PM UTC coverage: 81.349% (-0.007%) from 81.356%
27042392828

Pull #3960

github

web-flow
Merge 29a304f1f into 111eb7706
Pull Request #3960: Tally 32-bit Overflow Fix

18013 of 26111 branches covered (68.99%)

Branch coverage included in aggregate %.

15 of 19 new or added lines in 6 files covered. (78.95%)

1 existing line in 1 file now uncovered.

59164 of 68760 relevant lines covered (86.04%)

48503073.53 hits per line

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

70.08
/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 <limits>
10
#include <numeric> // for accumulate
11
#include <string>
12

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

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

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

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

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

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

59
namespace openmc {
60

61
//==============================================================================
62
// Global variables
63
//==============================================================================
64

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

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

75
namespace model {
76

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

80
} // namespace model
81

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

89
//==============================================================================
90
// Helper functions
91
//==============================================================================
92

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

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

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

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

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

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

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

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

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

188
inline void atomic_max_double(double* ptr, double value)
19,013,328✔
189
{
190
  atomic_update_double(ptr, value, false);
6,337,776✔
191
}
6,337,776✔
192

193
inline void atomic_min_double(double* ptr, double value)
19,013,328✔
194
{
195
  atomic_update_double(ptr, value, true);
6,337,776✔
196
}
197

198
namespace detail {
199

200
//==============================================================================
201
// MaterialVolumes implementation
202
//==============================================================================
203

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

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

221
    // Non-atomic read of current material
222
    int32_t current_val = *slot_ptr;
8,991,163✔
223

224
    // Found the desired material; accumulate volume and bbox
225
    if (current_val == index_material) {
8,991,163✔
226
#pragma omp atomic
5,191,836✔
227
      this->volumes(index_elem, slot) += volume;
8,989,589✔
228
      if (bbox) {
8,989,589✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,337,599✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,337,599✔
231
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,337,599✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,337,599✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,337,599✔
234
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,337,599✔
235
      }
236
      return;
8,989,589✔
237
    }
238

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

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

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

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

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

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

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

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

327
} // namespace detail
328

329
//==============================================================================
330
// Mesh implementation
331
//==============================================================================
332

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

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

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

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

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

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

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

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

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

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

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

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

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

424
vector<double> Mesh::volumes() const
287✔
425
{
426
  vector<double> volumes(n_bins());
287✔
427
  for (int i = 0; i < n_bins(); i++) {
1,122,895✔
428
    volumes[i] = this->volume(i);
1,122,608✔
429
  }
430
  return volumes;
287✔
431
}
×
432

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

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

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

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

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

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

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

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

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

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

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

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

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

515
      // Loop over rays on face of bounding box
516
#pragma omp for collapse(2)
517
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
17,600✔
518
        for (int i2 = 0; i2 < n2; ++i2) {
3,080,220✔
519
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,062,845✔
520
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,062,845✔
521

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

524
          // Determine particle's location
525
          if (!exhaustive_find_cell(p)) {
3,062,845✔
526
            out_of_model = true;
39,930✔
527
            continue;
39,930✔
528
          }
529

530
          // Set birth cell attribute
531
          if (p.cell_born() == C_NONE)
3,022,915!
532
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
533

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

540
          while (true) {
4,679,459✔
541
            // Ray trace from r_start to r_end
542
            Position r0 = p.r();
3,851,187✔
543
            double max_distance = bbox.max[axis] - r0[axis];
3,851,187✔
544

545
            // Find the distance to the nearest boundary
546
            BoundaryInfo boundary = distance_to_boundary(p);
3,851,187✔
547

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

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

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

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

573
                Position contrib_min = site.r;
2,863,752✔
574
                Position contrib_max = site.r;
2,863,752✔
575

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

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

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

594
            if (distance == max_distance)
3,851,187✔
595
              break;
596

597
            // cross next geometric surface
598
            for (int j = 0; j < p.n_coord(); ++j) {
1,656,544✔
599
              p.cell_last(j) = p.coord(j).cell();
828,272✔
600
            }
601
            p.n_coord_last() = p.n_coord();
828,272✔
602

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

762
  if (n_dimension_ > 2) {
5,160,280✔
763
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,144,341✔
764
  } else if (n_dimension_ > 1) {
15,939✔
765
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
15,664✔
766
  } else {
767
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
768
  }
769
}
770

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

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

783
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,411,367!
784
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,411,367!
785

786
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,411,367!
787
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,411,367!
788

789
  return {x_min + (x_max - x_min) * prn(seed),
1,411,367✔
790
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,411,367✔
791
}
792

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

966
  int num_elem_skipped = 0;
34✔
967

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

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

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

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

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

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

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

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

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

1034
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1035
      in_mesh = false;
105,186,981✔
1036
  }
1037
  return ijk;
1,593,517,400✔
1038
}
1039

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

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

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

1078
  // Convert indices to bin
1079
  return get_bin_from_indices(ijk);
392,413,699✔
1080
}
1081

1082
int StructuredMesh::n_bins() const
1,137,913✔
1083
{
1084
  // Bin indices are stored as 32-bit ints in the tally system.
1085
  int64_t n = 1;
1,137,913✔
1086
  for (int i = 0; i < n_dimension_; ++i)
4,551,240✔
1087
    n *= shape_[i];
3,413,327✔
1088
  if (n > std::numeric_limits<int>::max()) {
1,137,913!
NEW
1089
    fatal_error(fmt::format(
×
NEW
1090
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1091
  }
1092
  return static_cast<int>(n);
1,137,913✔
1093
}
1094

1095
int StructuredMesh::n_surface_bins() const
370✔
1096
{
1097
  // Surface bin indices are stored as 32-bit ints in the tally system.
1098
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
370✔
1099
  if (n > std::numeric_limits<int>::max()) {
370!
NEW
1100
    fatal_error(fmt::format(
×
NEW
1101
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1102
  }
1103
  return static_cast<int>(n);
370✔
1104
}
1105

1106
tensor::Tensor<double> StructuredMesh::count_sites(
×
1107
  const SourceSite* bank, int64_t length, bool* outside) const
1108
{
1109
  // Determine shape of array for counts
1110
  std::size_t m = this->n_bins();
×
1111
  vector<std::size_t> shape = {m};
×
1112

1113
  // Create array of zeros
1114
  auto cnt = tensor::zeros<double>(shape);
×
1115
  bool outside_ = false;
1116

1117
  for (int64_t i = 0; i < length; i++) {
×
1118
    const auto& site = bank[i];
×
1119

1120
    // determine scoring bin for entropy mesh
1121
    int mesh_bin = get_bin(site.r);
×
1122

1123
    // if outside mesh, skip particle
1124
    if (mesh_bin < 0) {
×
1125
      outside_ = true;
×
1126
      continue;
×
1127
    }
1128

1129
    // Add to appropriate bin
1130
    cnt(mesh_bin) += site.wgt;
×
1131
  }
1132

1133
  // Create reduced count data
1134
  auto counts = tensor::zeros<double>(shape);
×
1135
  int total = cnt.size();
×
1136

1137
#ifdef OPENMC_MPI
1138
  // collect values from all processors
1139
  MPI_Reduce(
×
1140
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1141

1142
  // Check if there were sites outside the mesh for any processor
1143
  if (outside) {
×
1144
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1145
  }
1146
#else
1147
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1148
  if (outside)
×
1149
    *outside = outside_;
1150
#endif
1151

1152
  return counts;
×
1153
}
×
1154

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

1168
  // Compute the length of the entire track.
1169
  double total_distance = (r1 - r0).norm();
1,216,819,930✔
1170
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,216,819,930✔
1171
    return;
1172

1173
  // keep a copy of the original global position to pass to get_indices,
1174
  // which performs its own transformation to local coordinates
1175
  Position global_r = r0;
1,172,744,885✔
1176
  Position local_r = local_coords(r0);
1,172,744,885✔
1177

1178
  const int n = n_dimension_;
1,172,744,885✔
1179

1180
  // Flag if position is inside the mesh
1181
  bool in_mesh;
1182

1183
  // Position is r = r0 + u * traveled_distance, start at r0
1184
  double traveled_distance {0.0};
1,172,744,885✔
1185

1186
  // Calculate index of current cell. Offset the position a tiny bit in
1187
  // direction of flight
1188
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,172,744,885✔
1189

1190
  // if track is very short, assume that it is completely inside one cell.
1191
  // Only the current cell will score and no surfaces
1192
  if (total_distance < 2 * TINY_BIT) {
1,172,744,885✔
1193
    if (in_mesh) {
361,844✔
1194
      tally.track(ijk, 1.0);
361,360✔
1195
    }
1196
    return;
361,844✔
1197
  }
1198

1199
  // Calculate initial distances to next surfaces in all three dimensions
1200
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1201
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1202
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1203
  }
1204

1205
  // Loop until r = r1 is eventually reached
1206
  while (true) {
1207

1208
    if (in_mesh) {
1,970,635,166✔
1209

1210
      // find surface with minimal distance to current position
1211
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,881,717,080✔
1212
                     distances.begin();
1,881,717,080✔
1213

1214
      // Tally track length delta since last step
1215
      tally.track(ijk,
1,881,717,080✔
1216
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1217
          total_distance);
1218

1219
      // update position and leave, if we have reached end position
1220
      traveled_distance = distances[k].distance;
1,881,717,080✔
1221
      if (traveled_distance >= total_distance)
1,881,717,080✔
1222
        return;
1223

1224
      // If we have not reached r1, we have hit a surface. Tally outward
1225
      // current
1226
      tally.surface(ijk, k, distances[k].max_surface, false);
790,987,725✔
1227

1228
      // Update cell and calculate distance to next surface in k-direction.
1229
      // The two other directions are still valid!
1230
      ijk[k] = distances[k].next_index;
790,987,725✔
1231
      distances[k] =
790,987,725✔
1232
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
790,987,725✔
1233

1234
      // Check if we have left the interior of the mesh
1235
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
797,892,128✔
1236

1237
      // If we are still inside the mesh, tally inward current for the next
1238
      // cell
1239
      if (in_mesh)
29,576,899✔
1240
        tally.surface(ijk, k, !distances[k].max_surface, true);
796,835,908✔
1241

1242
    } else { // not inside mesh
1243

1244
      // For all directions outside the mesh, find the distance that we need
1245
      // to travel to reach the next surface. Use the largest distance, as
1246
      // only this will cross all outer surfaces.
1247
      int k_max {-1};
1248
      for (int k = 0; k < n; ++k) {
354,227,978✔
1249
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
265,309,892✔
1250
            (distances[k].distance > traveled_distance)) {
96,926,001✔
1251
          traveled_distance = distances[k].distance;
1252
          k_max = k;
1253
        }
1254
      }
1255
      // Assure some distance is traveled
1256
      if (k_max == -1) {
88,918,086✔
1257
        traveled_distance += TINY_BIT;
110✔
1258
      }
1259

1260
      // If r1 is not inside the mesh, exit here
1261
      if (traveled_distance >= total_distance)
88,918,086✔
1262
        return;
1263

1264
      // Calculate the new cell index and update all distances to next
1265
      // surfaces.
1266
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,264,400✔
1267
      for (int k = 0; k < n; ++k) {
28,849,062✔
1268
        distances[k] =
21,584,662✔
1269
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,584,662✔
1270
      }
1271

1272
      // If inside the mesh, Tally inward current
1273
      if (in_mesh && k_max >= 0)
7,264,400!
1274
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
768,652,258✔
1275
    }
1276
  }
1277
}
1278

1279
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,104,692,365✔
1280
  vector<int>& bins, vector<double>& lengths) const
1281
{
1282

1283
  // Helper tally class.
1284
  // stores a pointer to the mesh class and references to bins and lengths
1285
  // parameters. Performs the actual tally through the track method.
1286
  struct TrackAggregator {
1,104,692,365✔
1287
    TrackAggregator(
1,104,692,365✔
1288
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1289
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,104,692,365✔
1290
    {}
1291
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1292
    void track(const MeshIndex& ijk, double l) const
1,742,033,876✔
1293
    {
1294
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,742,033,876✔
1295
      lengths.push_back(l);
1,742,033,876✔
1296
    }
1,742,033,876✔
1297

1298
    const StructuredMesh* mesh;
1299
    vector<int>& bins;
1300
    vector<double>& lengths;
1301
  };
1302

1303
  // Perform the mesh raytrace with the helper class.
1304
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,104,692,365✔
1305
}
1,104,692,365✔
1306

1307
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1308
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1309
{
1310

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

1330
    const StructuredMesh* mesh;
1331
    vector<int>& bins;
1332
  };
1333

1334
  // Perform the mesh raytrace with the helper class.
1335
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1336
}
112,127,565✔
1337

1338
//==============================================================================
1339
// RegularMesh implementation
1340
//==============================================================================
1341

1342
int RegularMesh::set_grid()
2,364✔
1343
{
1344
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,364✔
1345

1346
  // Check that dimensions are all greater than zero
1347
  if ((shape <= 0).any()) {
7,092!
1348
    set_errmsg("All entries for a regular mesh dimensions "
×
1349
               "must be positive.");
1350
    return OPENMC_E_INVALID_ARGUMENT;
×
1351
  }
1352

1353
  // Make sure lower_left and dimension match
1354
  if (lower_left_.size() != n_dimension_) {
2,364!
1355
    set_errmsg("Number of entries in lower_left must be the same "
×
1356
               "as the regular mesh dimensions.");
1357
    return OPENMC_E_INVALID_ARGUMENT;
×
1358
  }
1359
  if (width_.size() > 0) {
2,364✔
1360

1361
    // Check to ensure width has same dimensions
1362
    if (width_.size() != n_dimension_) {
46!
1363
      set_errmsg("Number of entries on width must be the same as "
×
1364
                 "the regular mesh dimensions.");
1365
      return OPENMC_E_INVALID_ARGUMENT;
×
1366
    }
1367

1368
    // Check for negative widths
1369
    if ((width_ < 0.0).any()) {
138!
1370
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1371
      return OPENMC_E_INVALID_ARGUMENT;
×
1372
    }
1373

1374
    // Set width and upper right coordinate
1375
    upper_right_ = lower_left_ + shape * width_;
138✔
1376

1377
  } else if (upper_right_.size() > 0) {
2,318!
1378

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

1386
    // Check that upper-right is above lower-left
1387
    if ((upper_right_ < lower_left_).any()) {
6,954!
1388
      set_errmsg(
×
1389
        "The upper_right coordinates of a regular mesh must be greater than "
1390
        "the lower_left coordinates.");
1391
      return OPENMC_E_INVALID_ARGUMENT;
×
1392
    }
1393

1394
    // Set width
1395
    width_ = (upper_right_ - lower_left_) / shape;
6,954✔
1396
  }
1397

1398
  // Set material volumes
1399
  volume_frac_ = 1.0 / shape.prod();
2,364✔
1400

1401
  element_volume_ = 1.0;
2,364✔
1402
  for (int i = 0; i < n_dimension_; i++) {
8,909✔
1403
    element_volume_ *= width_[i];
6,545✔
1404
  }
1405
  return 0;
1406
}
2,364✔
1407

1408
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,353✔
1409
{
1410
  // Determine number of dimensions for mesh
1411
  if (!check_for_node(node, "dimension")) {
2,353!
1412
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1413
  }
1414

1415
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,353✔
1416
  int n = n_dimension_ = shape.size();
2,353!
1417
  if (n != 1 && n != 2 && n != 3) {
2,353!
1418
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1419
  }
1420
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,353✔
1421

1422
  // Check for lower-left coordinates
1423
  if (check_for_node(node, "lower_left")) {
2,353!
1424
    // Read mesh lower-left corner location
1425
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,353✔
1426
  } else {
1427
    fatal_error("Must specify <lower_left> on a mesh.");
×
1428
  }
1429

1430
  if (check_for_node(node, "width")) {
2,353✔
1431
    // Make sure one of upper-right or width were specified
1432
    if (check_for_node(node, "upper_right")) {
46!
1433
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1434
    }
1435

1436
    width_ = get_node_tensor<double>(node, "width");
92✔
1437

1438
  } else if (check_for_node(node, "upper_right")) {
2,307!
1439

1440
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,614✔
1441

1442
  } else {
1443
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1444
  }
1445

1446
  if (int err = set_grid()) {
2,353!
1447
    fatal_error(openmc_err_msg);
×
1448
  }
1449
}
2,353✔
1450

1451
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
11✔
1452
{
1453
  // Determine number of dimensions for mesh
1454
  if (!object_exists(group, "dimension")) {
11!
1455
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1456
  }
1457

1458
  tensor::Tensor<int> shape;
11✔
1459
  read_dataset(group, "dimension", shape);
11✔
1460
  int n = n_dimension_ = shape.size();
11!
1461
  if (n != 1 && n != 2 && n != 3) {
11!
1462
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1463
  }
1464
  std::copy(shape.begin(), shape.end(), shape_.begin());
11✔
1465

1466
  // Check for lower-left coordinates
1467
  if (object_exists(group, "lower_left")) {
11!
1468
    // Read mesh lower-left corner location
1469
    read_dataset(group, "lower_left", lower_left_);
11✔
1470
  } else {
1471
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1472
  }
1473

1474
  if (object_exists(group, "upper_right")) {
11!
1475

1476
    read_dataset(group, "upper_right", upper_right_);
11✔
1477

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

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

1487
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1488
{
1489
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1490
}
1491

1492
const std::string RegularMesh::mesh_type = "regular";
1493

1494
std::string RegularMesh::get_mesh_type() const
3,478✔
1495
{
1496
  return mesh_type;
3,478✔
1497
}
1498

1499
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,871,413,723✔
1500
{
1501
  return lower_left_[i] + ijk[i] * width_[i];
1,871,413,723✔
1502
}
1503

1504
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,802,479,309✔
1505
{
1506
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,802,479,309✔
1507
}
1508

1509
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1510
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1511
  double l) const
1512
{
1513
  MeshDistance d;
2,147,483,647✔
1514
  d.next_index = ijk[i];
2,147,483,647✔
1515
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1516
    return d;
15,101,976✔
1517

1518
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1519
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1520
    d.next_index++;
1,867,179,622✔
1521
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,867,179,622✔
1522
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,821,237,821✔
1523
    d.next_index--;
1,798,245,208✔
1524
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,798,245,208✔
1525
  }
1526

1527
  return d;
2,147,483,647✔
1528
}
1529

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

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

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

1568
  return {axis_lines[0], axis_lines[1]};
44✔
1569
}
1570

1571
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,323✔
1572
{
1573
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,323✔
1574
  write_dataset(mesh_group, "lower_left", lower_left_);
2,323✔
1575
  write_dataset(mesh_group, "upper_right", upper_right_);
2,323✔
1576
  write_dataset(mesh_group, "width", width_);
2,323✔
1577
}
2,323✔
1578

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

1586
  // Create array of zeros
1587
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1588
  bool outside_ = false;
2,892✔
1589

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

1593
    // determine scoring bin for entropy mesh
1594
    int mesh_bin = get_bin(site.r);
7,667,451✔
1595

1596
    // if outside mesh, skip particle
1597
    if (mesh_bin < 0) {
7,667,451!
1598
      outside_ = true;
×
1599
      continue;
×
1600
    }
1601

1602
    // Add to appropriate bin
1603
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1604
  }
1605

1606
  // Create reduced count data
1607
  auto counts = tensor::zeros<double>(shape);
7,820✔
1608
  int total = cnt.size();
7,820✔
1609

1610
#ifdef OPENMC_MPI
1611
  // collect values from all processors
1612
  MPI_Reduce(
2,892✔
1613
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1614

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

1625
  return counts;
7,820✔
1626
}
7,820✔
1627

1628
double RegularMesh::volume(const MeshIndex& ijk) const
1,123,862✔
1629
{
1630
  return element_volume_;
1,123,862✔
1631
}
1632

1633
//==============================================================================
1634
// RectilinearMesh implementation
1635
//==============================================================================
1636

1637
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
122✔
1638
{
1639
  n_dimension_ = 3;
122✔
1640

1641
  grid_[0] = get_node_array<double>(node, "x_grid");
122✔
1642
  grid_[1] = get_node_array<double>(node, "y_grid");
122✔
1643
  grid_[2] = get_node_array<double>(node, "z_grid");
122✔
1644

1645
  if (int err = set_grid()) {
122!
1646
    fatal_error(openmc_err_msg);
×
1647
  }
1648
}
122✔
1649

1650
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1651
{
1652
  n_dimension_ = 3;
11✔
1653

1654
  read_dataset(group, "x_grid", grid_[0]);
11✔
1655
  read_dataset(group, "y_grid", grid_[1]);
11✔
1656
  read_dataset(group, "z_grid", grid_[2]);
11✔
1657

1658
  if (int err = set_grid()) {
11!
1659
    fatal_error(openmc_err_msg);
×
1660
  }
1661
}
11✔
1662

1663
const std::string RectilinearMesh::mesh_type = "rectilinear";
1664

1665
std::string RectilinearMesh::get_mesh_type() const
275✔
1666
{
1667
  return mesh_type;
275✔
1668
}
1669

1670
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1671
  const MeshIndex& ijk, int i) const
1672
{
1673
  return grid_[i][ijk[i]];
26,505,963✔
1674
}
1675

1676
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1677
  const MeshIndex& ijk, int i) const
1678
{
1679
  return grid_[i][ijk[i] - 1];
25,739,406✔
1680
}
1681

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

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

1702
int RectilinearMesh::set_grid()
177✔
1703
{
1704
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
177✔
1705
    static_cast<int>(grid_[1].size()) - 1,
177✔
1706
    static_cast<int>(grid_[2].size()) - 1};
177✔
1707

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

1722
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
177✔
1723
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
177✔
1724

1725
  return 0;
177✔
1726
}
1727

1728
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892✔
1729
{
1730
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892✔
1731
}
1732

1733
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1734
  Position plot_ll, Position plot_ur) const
1735
{
1736
  // Figure out which axes lie in the plane of the plot.
1737
  array<int, 2> axes {-1, -1};
11✔
1738
  if (plot_ur.z == plot_ll.z) {
11!
1739
    axes = {0, 1};
×
1740
  } else if (plot_ur.y == plot_ll.y) {
11!
1741
    axes = {0, 2};
11✔
1742
  } else if (plot_ur.x == plot_ll.x) {
×
1743
    axes = {1, 2};
×
1744
  } else {
1745
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1746
  }
1747

1748
  // Get the coordinates of the mesh lines along both of the axes.
1749
  array<vector<double>, 2> axis_lines;
1750
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1751
    int axis = axes[i_ax];
22✔
1752
    vector<double>& lines {axis_lines[i_ax]};
22✔
1753

1754
    for (auto coord : grid_[axis]) {
110✔
1755
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1756
        lines.push_back(coord);
88✔
1757
    }
1758
  }
1759

1760
  return {axis_lines[0], axis_lines[1]};
22✔
1761
}
1762

1763
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1764
{
1765
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1766
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1767
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1768
}
110✔
1769

1770
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1771
{
1772
  double vol {1.0};
132✔
1773

1774
  for (int i = 0; i < n_dimension_; i++) {
528✔
1775
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1776
  }
1777
  return vol;
132✔
1778
}
1779

1780
//==============================================================================
1781
// CylindricalMesh implementation
1782
//==============================================================================
1783

1784
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
400✔
1785
  : PeriodicStructuredMesh {node}
400✔
1786
{
1787
  n_dimension_ = 3;
400✔
1788
  grid_[0] = get_node_array<double>(node, "r_grid");
400✔
1789
  grid_[1] = get_node_array<double>(node, "phi_grid");
400✔
1790
  grid_[2] = get_node_array<double>(node, "z_grid");
400✔
1791
  origin_ = get_node_position(node, "origin");
400✔
1792

1793
  if (int err = set_grid()) {
400!
1794
    fatal_error(openmc_err_msg);
×
1795
  }
1796
}
400✔
1797

1798
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1799
{
1800
  n_dimension_ = 3;
11✔
1801
  read_dataset(group, "r_grid", grid_[0]);
11✔
1802
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1803
  read_dataset(group, "z_grid", grid_[2]);
11✔
1804
  read_dataset(group, "origin", origin_);
11✔
1805

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

1811
const std::string CylindricalMesh::mesh_type = "cylindrical";
1812

1813
std::string CylindricalMesh::get_mesh_type() const
484✔
1814
{
1815
  return mesh_type;
484✔
1816
}
1817

1818
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1819
  Position r, bool& in_mesh) const
1820
{
1821
  r = local_coords(r);
47,732,091✔
1822

1823
  Position mapped_r;
47,732,091✔
1824
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1825
  mapped_r[2] = r[2];
47,732,091✔
1826

1827
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1828
    mapped_r[1] = 0.0;
1829
  } else {
1830
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1831
    if (mapped_r[1] < 0)
47,732,091✔
1832
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1833
  }
1834

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

1837
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1838

1839
  return idx;
47,732,091✔
1840
}
1841

1842
Position CylindricalMesh::sample_element(
88,110✔
1843
  const MeshIndex& ijk, uint64_t* seed) const
1844
{
1845
  double r_min = this->r(ijk[0] - 1);
88,110✔
1846
  double r_max = this->r(ijk[0]);
88,110✔
1847

1848
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1849
  double phi_max = this->phi(ijk[1]);
88,110✔
1850

1851
  double z_min = this->z(ijk[2] - 1);
88,110✔
1852
  double z_max = this->z(ijk[2]);
88,110✔
1853

1854
  double r_min_sq = r_min * r_min;
88,110✔
1855
  double r_max_sq = r_max * r_max;
88,110✔
1856
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1857
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1858
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1859

1860
  double x = r * std::cos(phi);
88,110✔
1861
  double y = r * std::sin(phi);
88,110✔
1862

1863
  return origin_ + Position(x, y, z);
88,110✔
1864
}
1865

1866
double CylindricalMesh::find_r_crossing(
142,588,486✔
1867
  const Position& r, const Direction& u, double l, int shell) const
1868
{
1869

1870
  if ((shell < 0) || (shell > shape_[0]))
142,588,486!
1871
    return INFTY;
1872

1873
  // solve r.x^2 + r.y^2 == r0^2
1874
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1875
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1876

1877
  const double r0 = grid_[0][shell];
124,674,511✔
1878
  if (r0 == 0.0)
124,674,511✔
1879
    return INFTY;
1880

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

1883
  // Direction of flight is in z-direction. Will never intersect r.
1884
  if (std::abs(denominator) < FP_PRECISION)
117,538,437✔
1885
    return INFTY;
1886

1887
  // inverse of dominator to help the compiler to speed things up
1888
  const double inv_denominator = 1.0 / denominator;
117,479,477✔
1889

1890
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,479,477✔
1891
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,479,477✔
1892
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,479,477✔
1893

1894
  if (D < 0.0)
117,479,477✔
1895
    return INFTY;
1896

1897
  D = std::sqrt(D);
107,743,355✔
1898

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

1903
  // Check -p - D first because it is always smaller as -p + D
1904
  if (-p - D > l)
101,109,981✔
1905
    return -p - D;
1906
  if (-p + D > l)
80,902,376✔
1907
    return -p + D;
50,078,497✔
1908

1909
  return INFTY;
1910
}
1911

1912
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1913
  const Position& r, const Direction& u, double l, int shell) const
1914
{
1915
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1916
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1917
    return INFTY;
1918

1919
  shell = sanitize_phi(shell);
43,970,718✔
1920

1921
  const double p0 = grid_[1][shell];
43,970,718✔
1922

1923
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1924
  // => x(s) * cos(p0) = y(s) * sin(p0)
1925
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1926
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1927

1928
  const double c0 = std::cos(p0);
43,970,718✔
1929
  const double s0 = std::sin(p0);
43,970,718✔
1930

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

1933
  // Check if direction of flight is not parallel to phi surface
1934
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1935
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1936
    // Check if solution is in positive direction of flight and crosses the
1937
    // correct phi surface (not -phi)
1938
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1939
      return s;
20,219,859✔
1940
  }
1941

1942
  return INFTY;
1943
}
1944

1945
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1946
  const Position& r, const Direction& u, double l, int shell) const
1947
{
1948
  MeshDistance d;
36,695,747✔
1949
  d.next_index = shell;
36,695,747✔
1950

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

1955
  d.max_surface = (u.z > 0.0);
35,577,531✔
1956
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1957
    d.next_index += 1;
16,875,892✔
1958
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1959
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1960
    d.next_index -= 1;
16,846,225✔
1961
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1962
  }
1963
  return d;
35,577,531✔
1964
}
1965

1966
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,192✔
1967
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1968
  double l) const
1969
{
1970
  if (i == 0) {
145,218,192✔
1971

1972
    return std::min(
142,588,486✔
1973
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,243✔
1974
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,486✔
1975

1976
  } else if (i == 1) {
73,923,949✔
1977

1978
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1979
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1980
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1981
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1982

1983
  } else {
1984
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1985
  }
1986
}
1987

1988
int CylindricalMesh::set_grid()
433✔
1989
{
1990
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
1991
    static_cast<int>(grid_[1].size()) - 1,
433✔
1992
    static_cast<int>(grid_[2].size()) - 1};
433✔
1993

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

2021
    return OPENMC_E_INVALID_ARGUMENT;
×
2022
  }
2023

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

2026
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2027
    origin_[2] + grid_[2].front()};
433✔
2028
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2029
    origin_[2] + grid_[2].back()};
433✔
2030

2031
  return 0;
433✔
2032
}
2033

2034
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2035
{
2036
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2037
}
2038

2039
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2040
  Position plot_ll, Position plot_ur) const
2041
{
2042
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2043

2044
  // Figure out which axes lie in the plane of the plot.
2045
  array<vector<double>, 2> axis_lines;
2046
  return {axis_lines[0], axis_lines[1]};
2047
}
2048

2049
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2050
{
2051
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2052
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2053
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2054
  write_dataset(mesh_group, "origin", origin_);
374✔
2055
}
374✔
2056

2057
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2058
{
2059
  double r_i = grid_[0][ijk[0] - 1];
792✔
2060
  double r_o = grid_[0][ijk[0]];
792✔
2061

2062
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2063
  double phi_o = grid_[1][ijk[1]];
792✔
2064

2065
  double z_i = grid_[2][ijk[2] - 1];
792✔
2066
  double z_o = grid_[2][ijk[2]];
792✔
2067

2068
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2069
}
2070

2071
//==============================================================================
2072
// SphericalMesh implementation
2073
//==============================================================================
2074

2075
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2076
  : PeriodicStructuredMesh {node}
345✔
2077
{
2078
  n_dimension_ = 3;
345✔
2079

2080
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2081
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2082
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2083
  origin_ = get_node_position(node, "origin");
345✔
2084

2085
  if (int err = set_grid()) {
345!
2086
    fatal_error(openmc_err_msg);
×
2087
  }
2088
}
345✔
2089

2090
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2091
{
2092
  n_dimension_ = 3;
11✔
2093

2094
  read_dataset(group, "r_grid", grid_[0]);
11✔
2095
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2096
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2097
  read_dataset(group, "origin", origin_);
11✔
2098

2099
  if (int err = set_grid()) {
11!
2100
    fatal_error(openmc_err_msg);
×
2101
  }
2102
}
11✔
2103

2104
const std::string SphericalMesh::mesh_type = "spherical";
2105

2106
std::string SphericalMesh::get_mesh_type() const
385✔
2107
{
2108
  return mesh_type;
385✔
2109
}
2110

2111
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2112
  Position r, bool& in_mesh) const
2113
{
2114
  r = local_coords(r);
68,592,128✔
2115

2116
  Position mapped_r;
68,592,128✔
2117
  mapped_r[0] = r.norm();
68,592,128✔
2118

2119
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2120
    mapped_r[1] = 0.0;
2121
    mapped_r[2] = 0.0;
2122
  } else {
2123
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2124
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2125
    if (mapped_r[2] < 0)
68,592,128✔
2126
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2127
  }
2128

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

2131
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2132
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2133

2134
  return idx;
68,592,128✔
2135
}
2136

2137
Position SphericalMesh::sample_element(
110✔
2138
  const MeshIndex& ijk, uint64_t* seed) const
2139
{
2140
  double r_min = this->r(ijk[0] - 1);
110✔
2141
  double r_max = this->r(ijk[0]);
110✔
2142

2143
  double theta_min = this->theta(ijk[1] - 1);
110✔
2144
  double theta_max = this->theta(ijk[1]);
110✔
2145

2146
  double phi_min = this->phi(ijk[2] - 1);
110✔
2147
  double phi_max = this->phi(ijk[2]);
110✔
2148

2149
  double cos_theta =
110✔
2150
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2151
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2152
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2153
  double r_min_cub = std::pow(r_min, 3);
110✔
2154
  double r_max_cub = std::pow(r_max, 3);
110✔
2155
  // might be faster to do rejection here?
2156
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2157

2158
  double x = r * std::cos(phi) * sin_theta;
110✔
2159
  double y = r * std::sin(phi) * sin_theta;
110✔
2160
  double z = r * cos_theta;
110✔
2161

2162
  return origin_ + Position(x, y, z);
110✔
2163
}
2164

2165
double SphericalMesh::find_r_crossing(
443,981,868✔
2166
  const Position& r, const Direction& u, double l, int shell) const
2167
{
2168
  if ((shell < 0) || (shell > shape_[0]))
443,981,868✔
2169
    return INFTY;
2170

2171
  // solve |r+s*u| = r0
2172
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2173
  const double r0 = grid_[0][shell];
404,360,781✔
2174
  if (r0 == 0.0)
404,360,781✔
2175
    return INFTY;
2176
  const double p = r.dot(u);
396,682,264✔
2177
  double R = r.norm();
396,682,264✔
2178
  double D = p * p - (R - r0) * (R + r0);
396,682,264✔
2179

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

2184
  if (D >= 0.0) {
385,973,610✔
2185
    D = std::sqrt(D);
358,096,662✔
2186
    // Check -p - D first because it is always smaller as -p + D
2187
    if (-p - D > l)
358,096,662✔
2188
      return -p - D;
2189
    if (-p + D > l)
293,782,962✔
2190
      return -p + D;
177,242,120✔
2191
  }
2192

2193
  return INFTY;
2194
}
2195

2196
double SphericalMesh::find_theta_crossing(
110,161,348✔
2197
  const Position& r, const Direction& u, double l, int shell) const
2198
{
2199
  // Theta grid is [0, π], thus there is no real surface to cross
2200
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2201
    return INFTY;
2202

2203
  shell = sanitize_theta(shell);
38,358,540✔
2204

2205
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2206
  // yields
2207
  // a*s^2 + 2*b*s + c == 0 with
2208
  // a = cos(theta)^2 - u.z * u.z
2209
  // b = r*u * cos(theta)^2 - u.z * r.z
2210
  // c = r*r * cos(theta)^2 - r.z^2
2211

2212
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2213
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2214
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2215

2216
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2217
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2218
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2219

2220
  // if factor of s^2 is zero, direction of flight is parallel to theta
2221
  // surface
2222
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2223
    // if b vanishes, direction of flight is within theta surface and crossing
2224
    // is not possible
2225
    if (std::abs(b) < FP_PRECISION)
482,548!
2226
      return INFTY;
2227

2228
    const double s = -0.5 * c / b;
×
2229
    // Check if solution is in positive direction of flight and has correct
2230
    // sign
2231
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2232
      return s;
×
2233

2234
    // no crossing is possible
2235
    return INFTY;
2236
  }
2237

2238
  const double p = b / a;
37,875,992✔
2239
  double D = p * p - c / a;
37,875,992✔
2240

2241
  if (D < 0.0)
37,875,992✔
2242
    return INFTY;
2243

2244
  D = std::sqrt(D);
26,921,004✔
2245

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

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

2257
  return INFTY;
2258
}
2259

2260
double SphericalMesh::find_phi_crossing(
111,750,826✔
2261
  const Position& r, const Direction& u, double l, int shell) const
2262
{
2263
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2264
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2265
    return INFTY;
2266

2267
  shell = sanitize_phi(shell);
39,948,018✔
2268

2269
  const double p0 = grid_[2][shell];
39,948,018✔
2270

2271
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2272
  // => x(s) * cos(p0) = y(s) * sin(p0)
2273
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2274
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2275

2276
  const double c0 = std::cos(p0);
39,948,018✔
2277
  const double s0 = std::sin(p0);
39,948,018✔
2278

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

2281
  // Check if direction of flight is not parallel to phi surface
2282
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2283
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2284
    // Check if solution is in positive direction of flight and crosses the
2285
    // correct phi surface (not -phi)
2286
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2287
      return s;
17,579,452✔
2288
  }
2289

2290
  return INFTY;
2291
}
2292

2293
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,947,021✔
2294
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2295
  double l) const
2296
{
2297

2298
  if (i == 0) {
332,947,021✔
2299
    return std::min(
443,981,868✔
2300
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,990,934✔
2301
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,981,868✔
2302

2303
  } else if (i == 1) {
110,956,087✔
2304
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2305
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2306
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2307
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2308

2309
  } else {
2310
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2311
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2312
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2313
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2314
  }
2315
}
2316

2317
int SphericalMesh::set_grid()
378✔
2318
{
2319
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2320
    static_cast<int>(grid_[1].size()) - 1,
378✔
2321
    static_cast<int>(grid_[2].size()) - 1};
378✔
2322

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

2345
    return OPENMC_E_INVALID_ARGUMENT;
×
2346
  }
2347
  if (grid_[2].back() > 2 * PI) {
378!
2348
    set_errmsg("phi-grids for "
×
2349
               "spherical meshes must end with phi <= 2*pi.");
2350
    return OPENMC_E_INVALID_ARGUMENT;
×
2351
  }
2352

2353
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2354
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2355

2356
  double r = grid_[0].back();
378✔
2357
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2358
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2359

2360
  return 0;
378✔
2361
}
2362

2363
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2364
{
2365
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2366
}
2367

2368
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2369
  Position plot_ll, Position plot_ur) const
2370
{
2371
  fatal_error("Plot of spherical Mesh not implemented");
×
2372

2373
  // Figure out which axes lie in the plane of the plot.
2374
  array<vector<double>, 2> axis_lines;
2375
  return {axis_lines[0], axis_lines[1]};
2376
}
2377

2378
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2379
{
2380
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2381
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2382
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2383
  write_dataset(mesh_group, "origin", origin_);
319✔
2384
}
319✔
2385

2386
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2387
{
2388
  double r_i = grid_[0][ijk[0] - 1];
935✔
2389
  double r_o = grid_[0][ijk[0]];
935✔
2390

2391
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2392
  double theta_o = grid_[1][ijk[1]];
935✔
2393

2394
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2395
  double phi_o = grid_[2][ijk[2]];
935✔
2396

2397
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2398
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2399
}
2400

2401
//==============================================================================
2402
// Helper functions for the C API
2403
//==============================================================================
2404

2405
int check_mesh(int32_t index)
6,490✔
2406
{
2407
  if (index < 0 || index >= model::meshes.size()) {
6,490!
2408
    set_errmsg("Index in meshes array is out of bounds.");
×
2409
    return OPENMC_E_OUT_OF_BOUNDS;
×
2410
  }
2411
  return 0;
2412
}
2413

2414
template<class T>
2415
int check_mesh_type(int32_t index)
1,100✔
2416
{
2417
  if (int err = check_mesh(index))
1,100!
2418
    return err;
2419

2420
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2421
  if (!mesh) {
1,100!
2422
    set_errmsg("This function is not valid for input mesh.");
×
2423
    return OPENMC_E_INVALID_TYPE;
×
2424
  }
2425
  return 0;
2426
}
2427

2428
template<class T>
2429
bool is_mesh_type(int32_t index)
2430
{
2431
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2432
  return mesh;
2433
}
2434

2435
//==============================================================================
2436
// C API functions
2437
//==============================================================================
2438

2439
// Return the type of mesh as a C string
2440
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2441
{
2442
  if (int err = check_mesh(index))
1,496!
2443
    return err;
2444

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

2447
  return 0;
1,496✔
2448
}
2449

2450
//! Extend the meshes array by n elements
2451
extern "C" int openmc_extend_meshes(
253✔
2452
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2453
{
2454
  if (index_start)
253!
2455
    *index_start = model::meshes.size();
253✔
2456
  std::string mesh_type;
253✔
2457

2458
  for (int i = 0; i < n; ++i) {
506✔
2459
    if (RegularMesh::mesh_type == type) {
253✔
2460
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2461
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2462
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2463
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2464
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2465
    } else if (SphericalMesh::mesh_type == type) {
22!
2466
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2467
    } else {
2468
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2469
    }
2470
  }
2471
  if (index_end)
253!
2472
    *index_end = model::meshes.size() - 1;
×
2473

2474
  return 0;
253✔
2475
}
253✔
2476

2477
//! Adds a new unstructured mesh to OpenMC
2478
extern "C" int openmc_add_unstructured_mesh(
×
2479
  const char filename[], const char library[], int* id)
2480
{
2481
  std::string lib_name(library);
×
2482
  std::string mesh_file(filename);
×
2483
  bool valid_lib = false;
×
2484

2485
#ifdef OPENMC_DAGMC_ENABLED
2486
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2487
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2488
    valid_lib = true;
2489
  }
2490
#endif
2491

2492
#ifdef OPENMC_LIBMESH_ENABLED
2493
  if (lib_name == LibMesh::mesh_lib_type) {
×
2494
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2495
    valid_lib = true;
2496
  }
2497
#endif
2498

2499
  if (!valid_lib) {
×
2500
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2501
                           "by this build of OpenMC",
2502
      lib_name));
2503
    return OPENMC_E_INVALID_ARGUMENT;
×
2504
  }
2505

2506
  // auto-assign new ID
2507
  model::meshes.back()->set_id(-1);
×
2508
  *id = model::meshes.back()->id_;
2509

2510
  return 0;
2511
}
×
2512

2513
//! Return the index in the meshes array of a mesh with a given ID
2514
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2515
{
2516
  auto pair = model::mesh_map.find(id);
429!
2517
  if (pair == model::mesh_map.end()) {
429!
2518
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2519
    return OPENMC_E_INVALID_ID;
×
2520
  }
2521
  *index = pair->second;
429✔
2522
  return 0;
429✔
2523
}
2524

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

2534
//! Set the ID of a mesh
2535
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2536
{
2537
  if (int err = check_mesh(index))
253!
2538
    return err;
2539
  model::meshes[index]->id_ = id;
253✔
2540
  model::mesh_map[id] = index;
253✔
2541
  return 0;
253✔
2542
}
2543

2544
//! Get the number of elements in a mesh
2545
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2546
{
2547
  if (int err = check_mesh(index))
297!
2548
    return err;
2549
  *n = model::meshes[index]->n_bins();
297✔
2550
  return 0;
297✔
2551
}
2552

2553
//! Get the volume of each element in the mesh
2554
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2555
{
2556
  if (int err = check_mesh(index))
88!
2557
    return err;
2558
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2559
    volumes[i] = model::meshes[index]->volume(i);
880✔
2560
  }
2561
  return 0;
2562
}
2563

2564
//! Get the bounding box of a mesh
2565
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2566
{
2567
  if (int err = check_mesh(index))
176!
2568
    return err;
2569

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

2572
  // set lower left corner values
2573
  ll[0] = bbox.min.x;
176✔
2574
  ll[1] = bbox.min.y;
176✔
2575
  ll[2] = bbox.min.z;
176✔
2576

2577
  // set upper right corner values
2578
  ur[0] = bbox.max.x;
176✔
2579
  ur[1] = bbox.max.y;
176✔
2580
  ur[2] = bbox.max.z;
176✔
2581
  return 0;
176✔
2582
}
2583

2584
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2585
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2586
{
2587
  if (int err = check_mesh(index))
209!
2588
    return err;
2589

2590
  try {
209✔
2591
    model::meshes[index]->material_volumes(
209✔
2592
      nx, ny, nz, table_size, materials, volumes, bboxes);
2593
  } catch (const std::exception& e) {
11!
2594
    set_errmsg(e.what());
11✔
2595
    if (starts_with(e.what(), "Mesh")) {
11!
2596
      return OPENMC_E_GEOMETRY;
11✔
2597
    } else {
2598
      return OPENMC_E_ALLOCATE;
×
2599
    }
2600
  }
11✔
2601

2602
  return 0;
2603
}
2604

2605
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2606
  Position width, int basis, int* pixels, int32_t* data)
2607
{
2608
  if (int err = check_mesh(index))
44!
2609
    return err;
2610
  const auto& mesh = model::meshes[index].get();
44!
2611

2612
  int pixel_width = pixels[0];
44✔
2613
  int pixel_height = pixels[1];
44✔
2614

2615
  // get pixel size
2616
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2617
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2618

2619
  // setup basis indices and initial position centered on pixel
2620
  int in_i, out_i;
44✔
2621
  Position xyz = origin;
44✔
2622
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2623
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2624
  switch (basis_enum) {
44!
2625
  case PlotBasis::xy:
2626
    in_i = 0;
2627
    out_i = 1;
2628
    break;
2629
  case PlotBasis::xz:
2630
    in_i = 0;
2631
    out_i = 2;
2632
    break;
2633
  case PlotBasis::yz:
2634
    in_i = 1;
2635
    out_i = 2;
2636
    break;
2637
  default:
×
2638
    UNREACHABLE();
×
2639
  }
2640

2641
  // set initial position
2642
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2643
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2644

2645
#pragma omp parallel
24✔
2646
  {
20✔
2647
    Position r = xyz;
20✔
2648

2649
#pragma omp for
2650
    for (int y = 0; y < pixel_height; y++) {
420✔
2651
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2652
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2653
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2654
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2655
      }
2656
    }
2657
  }
2658

2659
  return 0;
44✔
2660
}
2661

2662
//! Get the dimension of a regular mesh
2663
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2664
  int32_t index, int** dims, int* n)
2665
{
2666
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2667
    return err;
2668
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2669
  *dims = mesh->shape_.data();
11✔
2670
  *n = mesh->n_dimension_;
11✔
2671
  return 0;
11✔
2672
}
2673

2674
//! Set the dimension of a regular mesh
2675
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2676
  int32_t index, int n, const int* dims)
2677
{
2678
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2679
    return err;
2680
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2681

2682
  // Copy dimension
2683
  mesh->n_dimension_ = n;
187✔
2684
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2685
  return 0;
187✔
2686
}
2687

2688
//! Get the regular mesh parameters
2689
extern "C" int openmc_regular_mesh_get_params(
209✔
2690
  int32_t index, double** ll, double** ur, double** width, int* n)
2691
{
2692
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2693
    return err;
2694
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2695

2696
  if (m->lower_left_.empty()) {
209!
2697
    set_errmsg("Mesh parameters have not been set.");
×
2698
    return OPENMC_E_ALLOCATE;
×
2699
  }
2700

2701
  *ll = m->lower_left_.data();
209✔
2702
  *ur = m->upper_right_.data();
209✔
2703
  *width = m->width_.data();
209✔
2704
  *n = m->n_dimension_;
209✔
2705
  return 0;
209✔
2706
}
2707

2708
//! Set the regular mesh parameters
2709
extern "C" int openmc_regular_mesh_set_params(
220✔
2710
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2711
{
2712
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2713
    return err;
2714
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2715

2716
  if (m->n_dimension_ == -1) {
220!
2717
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2718
    return OPENMC_E_UNASSIGNED;
×
2719
  }
2720

2721
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2722
  if (ll && ur) {
220✔
2723
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2724
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2725
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2726
  } else if (ll && width) {
22✔
2727
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2728
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2729
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2730
  } else if (ur && width) {
11!
2731
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2732
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2733
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2734
  } else {
2735
    set_errmsg("At least two parameters must be specified.");
×
2736
    return OPENMC_E_INVALID_ARGUMENT;
×
2737
  }
2738

2739
  // Set material volumes
2740

2741
  // TODO: incorporate this into method in RegularMesh that can be called from
2742
  // here and from constructor
2743
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2744
  m->element_volume_ = 1.0;
220✔
2745
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2746
    m->element_volume_ *= m->width_[i];
660✔
2747
  }
2748

2749
  return 0;
2750
}
220✔
2751

2752
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2753
template<class C>
2754
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2755
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2756
  const int nz)
2757
{
2758
  if (int err = check_mesh_type<C>(index))
88!
2759
    return err;
2760

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

2763
  m->n_dimension_ = 3;
88✔
2764

2765
  m->grid_[0].reserve(nx);
88✔
2766
  m->grid_[1].reserve(ny);
88✔
2767
  m->grid_[2].reserve(nz);
88✔
2768

2769
  for (int i = 0; i < nx; i++) {
572✔
2770
    m->grid_[0].push_back(grid_x[i]);
484✔
2771
  }
2772
  for (int i = 0; i < ny; i++) {
341✔
2773
    m->grid_[1].push_back(grid_y[i]);
253✔
2774
  }
2775
  for (int i = 0; i < nz; i++) {
319✔
2776
    m->grid_[2].push_back(grid_z[i]);
231✔
2777
  }
2778

2779
  int err = m->set_grid();
88✔
2780
  return err;
88✔
2781
}
2782

2783
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2784
template<class C>
2785
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2786
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2787
{
2788
  if (int err = check_mesh_type<C>(index))
385!
2789
    return err;
2790
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2791

2792
  if (m->lower_left_.empty()) {
385!
2793
    set_errmsg("Mesh parameters have not been set.");
×
2794
    return OPENMC_E_ALLOCATE;
×
2795
  }
2796

2797
  *grid_x = m->grid_[0].data();
385✔
2798
  *nx = m->grid_[0].size();
385✔
2799
  *grid_y = m->grid_[1].data();
385✔
2800
  *ny = m->grid_[1].size();
385✔
2801
  *grid_z = m->grid_[2].data();
385✔
2802
  *nz = m->grid_[2].size();
385✔
2803

2804
  return 0;
385✔
2805
}
2806

2807
//! Get the rectilinear mesh grid
2808
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2809
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2810
{
2811
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2812
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2813
}
2814

2815
//! Set the rectilienar mesh parameters
2816
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2817
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2818
  const double* grid_z, const int nz)
2819
{
2820
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2821
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2822
}
2823

2824
//! Get the cylindrical mesh grid
2825
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2826
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2827
{
2828
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2829
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2830
}
2831

2832
//! Set the cylindrical mesh parameters
2833
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2834
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2835
  const double* grid_z, const int nz)
2836
{
2837
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2838
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2839
}
2840

2841
//! Get the spherical mesh grid
2842
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2843
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2844
{
2845

2846
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2847
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2848
  ;
121✔
2849
}
2850

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

2860
#ifdef OPENMC_DAGMC_ENABLED
2861

2862
const std::string MOABMesh::mesh_lib_type = "moab";
2863

2864
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2865
{
2866
  initialize();
24✔
2867
}
24!
2868

2869
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2870
{
2871
  initialize();
×
2872
}
×
2873

2874
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2875
  : UnstructuredMesh()
×
2876
{
2877
  n_dimension_ = 3;
2878
  filename_ = filename;
×
2879
  set_length_multiplier(length_multiplier);
×
2880
  initialize();
×
2881
}
×
2882

2883
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2884
{
2885
  mbi_ = external_mbi;
1✔
2886
  filename_ = "unknown (external file)";
1✔
2887
  this->initialize();
1✔
2888
}
1!
2889

2890
void MOABMesh::initialize()
25✔
2891
{
2892

2893
  // Create the MOAB interface and load data from file
2894
  this->create_interface();
25✔
2895

2896
  // Initialise MOAB error code
2897
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2898

2899
  // Set the dimension
2900
  n_dimension_ = 3;
25✔
2901

2902
  // set member range of tetrahedral entities
2903
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2904
  if (rval != moab::MB_SUCCESS) {
25!
2905
    fatal_error("Failed to get all tetrahedral elements");
2906
  }
2907

2908
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2909
    warning("Non-tetrahedral elements found in unstructured "
×
2910
            "mesh file: " +
2911
            filename_);
2912
  }
2913

2914
  // set member range of vertices
2915
  int vertex_dim = 0;
25✔
2916
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2917
  if (rval != moab::MB_SUCCESS) {
25!
2918
    fatal_error("Failed to get all vertex handles");
2919
  }
2920

2921
  // make an entity set for all tetrahedra
2922
  // this is used for convenience later in output
2923
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2924
  if (rval != moab::MB_SUCCESS) {
25!
2925
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2926
  }
2927

2928
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2929
  if (rval != moab::MB_SUCCESS) {
25!
2930
    fatal_error("Failed to add tetrahedra to an entity set.");
2931
  }
2932

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

2961
  // Determine bounds of mesh
2962
  this->determine_bounds();
25✔
2963
}
25✔
2964

2965
void MOABMesh::prepare_for_point_location()
21✔
2966
{
2967
  // if the KDTree has already been constructed, do nothing
2968
  if (kdtree_)
21!
2969
    return;
2970

2971
  // build acceleration data structures
2972
  compute_barycentric_data(ehs_);
21✔
2973
  build_kdtree(ehs_);
21✔
2974
}
2975

2976
void MOABMesh::create_interface()
25✔
2977
{
2978
  // Do not create a MOAB instance if one is already in memory
2979
  if (mbi_)
25✔
2980
    return;
2981

2982
  // create MOAB instance
2983
  mbi_ = std::make_shared<moab::Core>();
24!
2984

2985
  // load unstructured mesh file
2986
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2987
  if (rval != moab::MB_SUCCESS) {
24!
2988
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2989
  }
2990
}
2991

2992
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
2993
{
2994
  moab::Range all_tris;
21✔
2995
  int adj_dim = 2;
21✔
2996
  write_message("Getting tet adjacencies...", 7);
21✔
2997
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
2998
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2999
  if (rval != moab::MB_SUCCESS) {
21!
3000
    fatal_error("Failed to get adjacent triangles for tets");
3001
  }
3002

3003
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3004
    warning("Non-triangle elements found in tet adjacencies in "
×
3005
            "unstructured mesh file: " +
3006
            filename_);
×
3007
  }
3008

3009
  // combine into one range
3010
  moab::Range all_tets_and_tris;
21✔
3011
  all_tets_and_tris.merge(all_tets);
21✔
3012
  all_tets_and_tris.merge(all_tris);
21✔
3013

3014
  // create a kd-tree instance
3015
  write_message(
21✔
3016
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3017
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3018

3019
  // Determine what options to use
3020
  std::ostringstream options_stream;
21✔
3021
  if (options_.empty()) {
21✔
3022
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3023
  } else {
3024
    options_stream << options_;
16✔
3025
  }
3026
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3027

3028
  // Build the k-d tree
3029
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3030
  if (rval != moab::MB_SUCCESS) {
21!
3031
    fatal_error("Failed to construct KDTree for the "
3032
                "unstructured mesh file: " +
3033
                filename_);
×
3034
  }
3035
}
21✔
3036

3037
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3038
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3039
{
3040
  hits.clear();
1,543,584!
3041

3042
  moab::ErrorCode rval;
1,543,584✔
3043
  vector<moab::EntityHandle> tris;
1,543,584✔
3044
  // get all intersections with triangles in the tet mesh
3045
  // (distances are relative to the start point, not the previous
3046
  // intersection)
3047
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3048
    dir.array(), start.array(), tris, hits, 0, track_len);
3049
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3050
    fatal_error(
3051
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3052
  }
3053

3054
  // remove duplicate intersection distances
3055
  std::unique(hits.begin(), hits.end());
1,543,584✔
3056

3057
  // sorts by first component of std::pair by default
3058
  std::sort(hits.begin(), hits.end());
1,543,584✔
3059
}
1,543,584✔
3060

3061
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3062
  vector<int>& bins, vector<double>& lengths) const
3063
{
3064
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3065
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3066
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3067
  dir.normalize();
1,543,584✔
3068

3069
  double track_len = (end - start).length();
1,543,584✔
3070
  if (track_len == 0.0)
1,543,584!
3071
    return;
721,692✔
3072

3073
  start -= TINY_BIT * dir;
1,543,584✔
3074
  end += TINY_BIT * dir;
1,543,584✔
3075

3076
  vector<double> hits;
1,543,584✔
3077
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3078

3079
  bins.clear();
1,543,584!
3080
  lengths.clear();
1,543,584!
3081

3082
  // if there are no intersections the track may lie entirely
3083
  // within a single tet. If this is the case, apply entire
3084
  // score to that tet and return.
3085
  if (hits.size() == 0) {
1,543,584✔
3086
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3087
    int bin = this->get_bin(midpoint);
721,692✔
3088
    if (bin != -1) {
721,692✔
3089
      bins.push_back(bin);
242,866✔
3090
      lengths.push_back(1.0);
242,866✔
3091
    }
3092
    return;
721,692✔
3093
  }
3094

3095
  // for each segment in the set of tracks, try to look up a tet
3096
  // at the midpoint of the segment
3097
  Position current = r0;
3098
  double last_dist = 0.0;
3099
  for (const auto& hit : hits) {
5,516,161✔
3100
    // get the segment length
3101
    double segment_length = hit - last_dist;
4,694,269✔
3102
    last_dist = hit;
4,694,269✔
3103
    // find the midpoint of this segment
3104
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3105
    // try to find a tet for this position
3106
    int bin = this->get_bin(midpoint);
4,694,269✔
3107

3108
    // determine the start point for this segment
3109
    current = r0 + u * hit;
4,694,269✔
3110

3111
    if (bin == -1) {
4,694,269✔
3112
      continue;
20,522✔
3113
    }
3114

3115
    bins.push_back(bin);
4,673,747✔
3116
    lengths.push_back(segment_length / track_len);
4,673,747✔
3117
  }
3118

3119
  // tally remaining portion of track after last hit if
3120
  // the last segment of the track is in the mesh but doesn't
3121
  // reach the other side of the tet
3122
  if (hits.back() < track_len) {
821,892!
3123
    Position segment_start = r0 + u * hits.back();
821,892✔
3124
    double segment_length = track_len - hits.back();
821,892✔
3125
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3126
    int bin = this->get_bin(midpoint);
821,892✔
3127
    if (bin != -1) {
821,892✔
3128
      bins.push_back(bin);
766,509✔
3129
      lengths.push_back(segment_length / track_len);
766,509✔
3130
    }
3131
  }
3132
};
1,543,584✔
3133

3134
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3135
{
3136
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3137
  // find the leaf of the kd-tree for this position
3138
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3139
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3140
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3141
    return 0;
3142
  }
3143

3144
  // retrieve the tet elements of this leaf
3145
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3146
  moab::Range tets;
6,305,335✔
3147
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3148
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3149
    warning("MOAB error finding tets.");
×
3150
  }
3151

3152
  // loop over the tets in this leaf, returning the containing tet if found
3153
  for (const auto& tet : tets) {
260,211,273✔
3154
    if (point_in_tet(pos, tet)) {
260,208,426✔
3155
      return tet;
6,302,488✔
3156
    }
3157
  }
3158

3159
  // if no tet is found, return an invalid handle
3160
  return 0;
2,847✔
3161
}
14,634,464✔
3162

3163
double MOABMesh::volume(int bin) const
167,880✔
3164
{
3165
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3166
}
3167

3168
std::string MOABMesh::library() const
34✔
3169
{
3170
  return mesh_lib_type;
34✔
3171
}
3172

3173
// Sample position within a tet for MOAB type tets
3174
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3175
{
3176

3177
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3178

3179
  // Get vertex coordinates for MOAB tet
3180
  const moab::EntityHandle* conn1;
200,410✔
3181
  int conn1_size;
200,410✔
3182
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3183
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3184
    fatal_error(fmt::format(
3185
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3186
      conn1_size));
3187
  }
3188
  moab::CartVect p[4];
200,410✔
3189
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3190
  if (rval != moab::MB_SUCCESS) {
200,410!
3191
    fatal_error("Failed to get tet coords");
3192
  }
3193

3194
  std::array<Position, 4> tet_verts;
200,410✔
3195
  for (int i = 0; i < 4; i++) {
1,002,050✔
3196
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3197
  }
3198
  // Samples position within tet using Barycentric stuff
3199
  return this->sample_tet(tet_verts, seed);
200,410✔
3200
}
3201

3202
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3203
{
3204
  vector<moab::EntityHandle> conn;
167,880✔
3205
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3206
  if (rval != moab::MB_SUCCESS) {
167,880!
3207
    fatal_error("Failed to get tet connectivity");
3208
  }
3209

3210
  moab::CartVect p[4];
167,880✔
3211
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3212
  if (rval != moab::MB_SUCCESS) {
167,880!
3213
    fatal_error("Failed to get tet coords");
3214
  }
3215

3216
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3217
}
167,880✔
3218

3219
int MOABMesh::get_bin(Position r) const
7,317,232✔
3220
{
3221
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3222
  if (tet == 0) {
7,317,232✔
3223
    return -1;
3224
  } else {
3225
    return get_bin_from_ent_handle(tet);
6,302,488✔
3226
  }
3227
}
3228

3229
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3230
{
3231
  moab::ErrorCode rval;
21✔
3232

3233
  baryc_data_.clear();
21!
3234
  baryc_data_.resize(tets.size());
21✔
3235

3236
  // compute the barycentric data for each tet element
3237
  // and store it as a 3x3 matrix
3238
  for (auto& tet : tets) {
239,757✔
3239
    vector<moab::EntityHandle> verts;
239,736✔
3240
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3241
    if (rval != moab::MB_SUCCESS) {
239,736!
3242
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3243
    }
3244

3245
    moab::CartVect p[4];
239,736✔
3246
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3247
    if (rval != moab::MB_SUCCESS) {
239,736!
3248
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3249
    }
3250

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

3253
    // invert now to avoid this cost later
3254
    a = a.transpose().inverse();
239,736✔
3255
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3256
  }
239,736✔
3257
}
21✔
3258

3259
bool MOABMesh::point_in_tet(
260,208,426✔
3260
  const moab::CartVect& r, moab::EntityHandle tet) const
3261
{
3262

3263
  moab::ErrorCode rval;
260,208,426✔
3264

3265
  // get tet vertices
3266
  vector<moab::EntityHandle> verts;
260,208,426✔
3267
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3268
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3269
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3270
    return false;
3271
  }
3272

3273
  // first vertex is used as a reference point for the barycentric data -
3274
  // retrieve its coordinates
3275
  moab::CartVect p_zero;
260,208,426✔
3276
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3277
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3278
    warning("Failed to get coordinates of a vertex in "
×
3279
            "unstructured mesh: " +
3280
            filename_);
×
3281
    return false;
3282
  }
3283

3284
  // look up barycentric data
3285
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3286
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3287

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

3290
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3291
          bary_coords[2] >= 0.0 &&
318,957,185✔
3292
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3293
}
260,208,426✔
3294

3295
int MOABMesh::get_bin_from_index(int idx) const
3296
{
3297
  if (idx >= n_bins()) {
×
3298
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3299
  }
3300
  return ehs_[idx] - ehs_[0];
3301
}
3302

3303
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3304
{
3305
  int bin = get_bin(r);
3306
  *in_mesh = bin != -1;
3307
  return bin;
3308
}
3309

3310
int MOABMesh::get_index_from_bin(int bin) const
3311
{
3312
  return bin;
3313
}
3314

3315
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3316
  Position plot_ll, Position plot_ur) const
3317
{
3318
  // TODO: Implement mesh lines
3319
  return {};
3320
}
3321

3322
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3323
{
3324
  int idx = vert - verts_[0];
815,520✔
3325
  if (idx >= n_vertices()) {
815,520!
3326
    fatal_error(
3327
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3328
  }
3329
  return idx;
815,520✔
3330
}
3331

3332
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3333
{
3334
  int bin = eh - ehs_[0];
266,750,650✔
3335
  if (bin >= n_bins()) {
266,750,650!
3336
    fatal_error(fmt::format("Invalid bin: {}", bin));
3337
  }
3338
  return bin;
266,750,650✔
3339
}
3340

3341
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3342
{
3343
  if (bin >= n_bins()) {
572,170!
3344
    fatal_error(fmt::format("Invalid bin index: ", bin));
3345
  }
3346
  return ehs_[0] + bin;
572,170✔
3347
}
3348

3349
int MOABMesh::n_bins() const
267,526,773✔
3350
{
3351
  return ehs_.size();
267,526,773✔
3352
}
3353

3354
int MOABMesh::n_surface_bins() const
3355
{
3356
  // collect all triangles in the set of tets for this mesh
3357
  moab::Range tris;
×
3358
  moab::ErrorCode rval;
3359
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3360
  if (rval != moab::MB_SUCCESS) {
×
3361
    warning("Failed to get all triangles in the mesh instance");
×
3362
    return -1;
3363
  }
3364
  return 2 * tris.size();
×
3365
}
3366

3367
Position MOABMesh::centroid(int bin) const
3368
{
3369
  moab::ErrorCode rval;
3370

3371
  auto tet = this->get_ent_handle_from_bin(bin);
3372

3373
  // look up the tet connectivity
3374
  vector<moab::EntityHandle> conn;
×
3375
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3376
  if (rval != moab::MB_SUCCESS) {
×
3377
    warning("Failed to get connectivity of a mesh element.");
×
3378
    return {};
3379
  }
3380

3381
  // get the coordinates
3382
  vector<moab::CartVect> coords(conn.size());
×
3383
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3384
  if (rval != moab::MB_SUCCESS) {
×
3385
    warning("Failed to get the coordinates of a mesh element.");
×
3386
    return {};
3387
  }
3388

3389
  // compute the centroid of the element vertices
3390
  moab::CartVect centroid(0.0, 0.0, 0.0);
3391
  for (const auto& coord : coords) {
×
3392
    centroid += coord;
3393
  }
3394
  centroid /= double(coords.size());
3395

3396
  return {centroid[0], centroid[1], centroid[2]};
3397
}
3398

3399
int MOABMesh::n_vertices() const
845,874✔
3400
{
3401
  return verts_.size();
845,874✔
3402
}
3403

3404
Position MOABMesh::vertex(int id) const
86,227✔
3405
{
3406

3407
  moab::ErrorCode rval;
86,227✔
3408

3409
  moab::EntityHandle vert = verts_[id];
86,227✔
3410

3411
  moab::CartVect coords;
86,227✔
3412
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3413
  if (rval != moab::MB_SUCCESS) {
86,227!
3414
    fatal_error("Failed to get the coordinates of a vertex.");
3415
  }
3416

3417
  return {coords[0], coords[1], coords[2]};
86,227✔
3418
}
3419

3420
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3421
{
3422
  moab::ErrorCode rval;
203,880✔
3423

3424
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3425

3426
  // look up the tet connectivity
3427
  vector<moab::EntityHandle> conn;
203,880✔
3428
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3429
  if (rval != moab::MB_SUCCESS) {
203,880!
3430
    fatal_error("Failed to get connectivity of a mesh element.");
3431
    return {};
3432
  }
3433

3434
  std::vector<int> verts(4);
203,880✔
3435
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3436
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3437
  }
3438

3439
  return verts;
203,880✔
3440
}
203,880✔
3441

3442
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3443
  std::string score) const
3444
{
3445
  moab::ErrorCode rval;
3446
  // add a tag to the mesh
3447
  // all scores are treated as a single value
3448
  // with an uncertainty
3449
  moab::Tag value_tag;
3450

3451
  // create the value tag if not present and get handle
3452
  double default_val = 0.0;
3453
  auto val_string = score + "_mean";
3454
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3455
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3456
  if (rval != moab::MB_SUCCESS) {
×
3457
    auto msg =
3458
      fmt::format("Could not create or retrieve the value tag for the score {}"
3459
                  " on unstructured mesh {}",
3460
        score, id_);
×
3461
    fatal_error(msg);
3462
  }
3463

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

3477
  // return the populated tag handles
3478
  return {value_tag, error_tag};
3479
}
3480

3481
void MOABMesh::add_score(const std::string& score)
3482
{
3483
  auto score_tags = get_score_tags(score);
×
3484
  tag_names_.push_back(score);
3485
}
3486

3487
void MOABMesh::remove_scores()
3488
{
3489
  for (const auto& name : tag_names_) {
×
3490
    auto value_name = name + "_mean";
3491
    moab::Tag tag;
3492
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3493
    if (rval != moab::MB_SUCCESS)
×
3494
      return;
3495

3496
    rval = mbi_->tag_delete(tag);
×
3497
    if (rval != moab::MB_SUCCESS) {
×
3498
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3499
                             " on unstructured mesh {}",
3500
        name, id_);
×
3501
      fatal_error(msg);
3502
    }
3503

3504
    auto std_dev_name = name + "_std_dev";
×
3505
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3506
    if (rval != moab::MB_SUCCESS) {
×
3507
      auto msg =
3508
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3509
                    " on unstructured mesh {}",
3510
          name, id_);
×
3511
    }
3512

3513
    rval = mbi_->tag_delete(tag);
×
3514
    if (rval != moab::MB_SUCCESS) {
×
3515
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3516
                             " on unstructured mesh {}",
3517
        name, id_);
×
3518
      fatal_error(msg);
3519
    }
3520
  }
3521
  tag_names_.clear();
3522
}
3523

3524
void MOABMesh::set_score_data(const std::string& score,
3525
  const vector<double>& values, const vector<double>& std_dev)
3526
{
3527
  auto score_tags = this->get_score_tags(score);
×
3528

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

3539
  // set the error value
3540
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3541
  if (rval != moab::MB_SUCCESS) {
×
3542
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3543
                           "on unstructured mesh {}",
3544
      score, id_);
3545
    warning(msg);
×
3546
  }
3547
}
3548

3549
void MOABMesh::write(const std::string& base_filename) const
3550
{
3551
  // add extension to the base name
3552
  auto filename = base_filename + ".vtk";
3553
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3554
  filename = settings::path_output + filename;
×
3555

3556
  // write the tetrahedral elements of the mesh only
3557
  // to avoid clutter from zero-value data on other
3558
  // elements during visualization
3559
  moab::ErrorCode rval;
3560
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3561
  if (rval != moab::MB_SUCCESS) {
×
3562
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3563
    warning(msg);
×
3564
  }
3565
}
3566

3567
#endif
3568

3569
#ifdef OPENMC_LIBMESH_ENABLED
3570

3571
const std::string LibMesh::mesh_lib_type = "libmesh";
3572

3573
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3574
{
3575
  // filename_ and length_multiplier_ will already be set by the
3576
  // UnstructuredMesh constructor
3577
  set_mesh_pointer_from_filename(filename_);
25✔
3578
  set_length_multiplier(length_multiplier_);
25✔
3579
  initialize();
25✔
3580
}
25✔
3581

3582
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3583
{
3584
  // filename_ and length_multiplier_ will already be set by the
3585
  // UnstructuredMesh constructor
3586
  set_mesh_pointer_from_filename(filename_);
×
3587
  set_length_multiplier(length_multiplier_);
×
3588
  initialize();
×
3589
}
3590

3591
// create the mesh from a pointer to a libMesh Mesh
3592
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3593
{
3594
  if (!input_mesh.is_replicated()) {
×
3595
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3596
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3597
  }
3598

3599
  m_ = &input_mesh;
3600
  set_length_multiplier(length_multiplier);
×
3601
  initialize();
×
3602
}
3603

3604
// create the mesh from an input file
3605
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3606
{
3607
  n_dimension_ = 3;
3608
  set_mesh_pointer_from_filename(filename);
×
3609
  set_length_multiplier(length_multiplier);
×
3610
  initialize();
×
3611
}
3612

3613
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3614
{
3615
  filename_ = filename;
25✔
3616
  unique_m_ =
25✔
3617
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3618
  m_ = unique_m_.get();
25✔
3619
  m_->read(filename_);
25✔
3620
}
25✔
3621

3622
// build a libMesh equation system for storing values
3623
void LibMesh::build_eqn_sys()
17✔
3624
{
3625
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3626
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3627
  libMesh::ExplicitSystem& eq_sys =
17✔
3628
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3629
}
17✔
3630

3631
// intialize from mesh file
3632
void LibMesh::initialize()
25✔
3633
{
3634
  if (!settings::libmesh_comm) {
25!
3635
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3636
                "communicator.");
3637
  }
3638

3639
  // assuming that unstructured meshes used in OpenMC are 3D
3640
  n_dimension_ = 3;
25✔
3641

3642
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3643
  // Otherwise assume that it is prepared by its owning application
3644
  if (unique_m_) {
25!
3645
    m_->prepare_for_use();
25✔
3646
  }
3647

3648
  // ensure that the loaded mesh is 3 dimensional
3649
  if (m_->mesh_dimension() != n_dimension_) {
25!
3650
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3651
                            "mesh is not a 3D mesh.",
3652
      filename_));
3653
  }
3654

3655
  for (int i = 0; i < num_threads(); i++) {
75✔
3656
    pl_.emplace_back(m_->sub_point_locator());
50✔
3657
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
50✔
3658
    pl_.back()->enable_out_of_mesh_mode();
50✔
3659
  }
3660

3661
  // store first element in the mesh to use as an offset for bin indices
3662
  auto first_elem = *m_->elements_begin();
50✔
3663
  first_element_id_ = first_elem->id();
25✔
3664

3665
  // bounding box for the mesh for quick rejection checks
3666
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3667
  libMesh::Point ll = bbox_.min();
25!
3668
  libMesh::Point ur = bbox_.max();
25!
3669
  if (length_multiplier_ > 0.0) {
25!
3670
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3671
      length_multiplier_ * ll(2)};
3672
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3673
      length_multiplier_ * ur(2)};
3674
  } else {
3675
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3676
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3677
  }
3678
}
25✔
3679

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

3699
Position LibMesh::centroid(int bin) const
3700
{
3701
  const auto& elem = this->get_element_from_bin(bin);
3702
  auto centroid = elem.vertex_average();
3703
  if (length_multiplier_ > 0.0) {
×
3704
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3705
  } else {
3706
    return {centroid(0), centroid(1), centroid(2)};
3707
  }
3708
}
3709

3710
int LibMesh::n_vertices() const
42,644✔
3711
{
3712
  return m_->n_nodes();
42,644✔
3713
}
3714

3715
Position LibMesh::vertex(int vertex_id) const
42,604✔
3716
{
3717
  const auto node_ref = m_->node_ref(vertex_id);
42,604✔
3718
  if (length_multiplier_ > 0.0) {
42,604!
3719
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3720
  } else {
3721
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3722
  }
3723
}
42,604✔
3724

3725
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3726
{
3727
  std::vector<int> conn;
267,856✔
3728
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3729
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3730
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3731
  }
3732
  return conn;
267,856✔
3733
}
3734

3735
std::string LibMesh::library() const
37✔
3736
{
3737
  return mesh_lib_type;
37✔
3738
}
3739

3740
int LibMesh::n_bins() const
1,788,419✔
3741
{
3742
  return m_->n_elem();
1,788,419✔
3743
}
3744

3745
int LibMesh::n_surface_bins() const
3746
{
3747
  int n_bins = 0;
3748
  for (int i = 0; i < this->n_bins(); i++) {
×
3749
    const libMesh::Elem& e = get_element_from_bin(i);
3750
    n_bins += e.n_faces();
3751
    // if this is a boundary element, it will only be visited once,
3752
    // the number of surface bins is incremented to
3753
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3754
      // null neighbor pointer indicates a boundary face
3755
      if (!neighbor_ptr) {
×
3756
        n_bins++;
3757
      }
3758
    }
3759
  }
3760
  return n_bins;
3761
}
3762

3763
void LibMesh::add_score(const std::string& var_name)
17✔
3764
{
3765
  if (!equation_systems_) {
17!
3766
    build_eqn_sys();
17✔
3767
  }
3768

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

3778
  std::string std_dev_name = var_name + "_std_dev";
17✔
3779
  // check if this is a new variable
3780
  if (!variable_map_.count(std_dev_name)) {
17✔
3781
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3782
    auto var_num =
17✔
3783
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3784
    variable_map_[std_dev_name] = var_num;
17✔
3785
  }
3786
}
17✔
3787

3788
void LibMesh::remove_scores()
17✔
3789
{
3790
  if (equation_systems_) {
17!
3791
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3792
    eqn_sys.clear();
17✔
3793
    variable_map_.clear();
17✔
3794
  }
3795
}
17✔
3796

3797
void LibMesh::set_score_data(const std::string& var_name,
17✔
3798
  const vector<double>& values, const vector<double>& std_dev)
3799
{
3800
  if (!equation_systems_) {
17!
3801
    build_eqn_sys();
3802
  }
3803

3804
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3805

3806
  if (!eqn_sys.is_initialized()) {
17!
3807
    equation_systems_->init();
17✔
3808
  }
3809

3810
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3811

3812
  // look up the value variable
3813
  std::string value_name = var_name + "_mean";
17✔
3814
  unsigned int value_num = variable_map_.at(value_name);
17✔
3815
  // look up the std dev variable
3816
  std::string std_dev_name = var_name + "_std_dev";
17✔
3817
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3818

3819
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3820
       it++) {
3821
    if (!(*it)->active()) {
99,856!
3822
      continue;
3823
    }
3824

3825
    auto bin = get_bin_from_element(*it);
99,856✔
3826

3827
    // set value
3828
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3829
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3830
    assert(value_dof_indices.size() == 1);
99,856✔
3831
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3832

3833
    // set std dev
3834
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3835
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3836
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3837
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3838
  }
99,873✔
3839
}
17✔
3840

3841
void LibMesh::write(const std::string& filename) const
17✔
3842
{
3843
  write_message(fmt::format(
17✔
3844
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3845
  libMesh::ExodusII_IO exo(*m_);
17✔
3846
  std::set<std::string> systems_out = {eq_system_name_};
34!
3847
  exo.write_discontinuous_exodusII(
17✔
3848
    filename + ".e", *equation_systems_, &systems_out);
34✔
3849
}
17✔
3850

3851
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3852
  vector<int>& bins, vector<double>& lengths) const
3853
{
3854
  // TODO: Implement triangle crossings here
3855
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3856
}
3857

3858
int LibMesh::get_bin(Position r) const
2,340,604✔
3859
{
3860
  // look-up a tet using the point locator
3861
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3862

3863
  if (length_multiplier_ > 0.0) {
2,340,604!
3864
    // Scale the point down
3865
    p /= length_multiplier_;
2,340,604✔
3866
  }
3867

3868
  // quick rejection check
3869
  if (!bbox_.contains_point(p)) {
2,340,604✔
3870
    return -1;
3871
  }
3872

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

3875
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3876
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3877
}
2,340,604✔
3878

3879
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3880
{
3881
  int bin = elem->id() - first_element_id_;
1,520,434✔
3882
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3883
    fatal_error(fmt::format("Invalid bin: {}", bin));
3884
  }
3885
  return bin;
1,520,434✔
3886
}
3887

3888
std::pair<vector<double>, vector<double>> LibMesh::plot(
3889
  Position plot_ll, Position plot_ur) const
3890
{
3891
  return {};
3892
}
3893

3894
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3895
{
3896
  return m_->elem_ref(bin);
769,460✔
3897
}
3898

3899
double LibMesh::volume(int bin) const
368,640✔
3900
{
3901
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3902
         length_multiplier_ * length_multiplier_;
368,640✔
3903
}
3904

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

3932
int AdaptiveLibMesh::n_bins() const
3933
{
3934
  return num_active_;
3935
}
3936

3937
void AdaptiveLibMesh::add_score(const std::string& var_name)
3938
{
3939
  warning(fmt::format(
×
3940
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3941
    this->id_));
3942
}
3943

3944
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3945
  const vector<double>& values, const vector<double>& std_dev)
3946
{
3947
  warning(fmt::format(
×
3948
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3949
    this->id_));
3950
}
3951

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

3959
int AdaptiveLibMesh::get_bin(Position r) const
3960
{
3961
  // look-up a tet using the point locator
3962
  libMesh::Point p(r.x, r.y, r.z);
×
3963

3964
  if (length_multiplier_ > 0.0) {
×
3965
    // Scale the point down
3966
    p /= length_multiplier_;
3967
  }
3968

3969
  // quick rejection check
3970
  if (!bbox_.contains_point(p)) {
×
3971
    return -1;
3972
  }
3973

3974
  const auto& point_locator = pl_.at(thread_num());
×
3975

3976
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3977
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3978
}
3979

3980
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3981
{
3982
  int bin = elem_to_bin_map_[elem->id()];
3983
  if (bin >= n_bins() || bin < 0) {
×
3984
    fatal_error(fmt::format("Invalid bin: {}", bin));
3985
  }
3986
  return bin;
3987
}
3988

3989
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3990
{
3991
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3992
}
3993

3994
#endif // OPENMC_LIBMESH_ENABLED
3995

3996
//==============================================================================
3997
// Non-member functions
3998
//==============================================================================
3999

4000
void read_meshes(pugi::xml_node root)
13,394✔
4001
{
4002
  std::unordered_set<int> mesh_ids;
13,394✔
4003

4004
  for (auto node : root.children("mesh")) {
16,619✔
4005
    // Check to make sure multiple meshes in the same file don't share IDs
4006
    int id = std::stoi(get_node_value(node, "id"));
6,450✔
4007
    if (contains(mesh_ids, id)) {
6,450!
4008
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4009
                              "'{}' in the same input file",
4010
        id));
4011
    }
4012
    mesh_ids.insert(id);
3,225✔
4013

4014
    // If we've already read a mesh with the same ID in a *different* file,
4015
    // assume it is the same here
4016
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,225!
4017
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4018
      continue;
×
4019
    }
4020

4021
    std::string mesh_type;
3,225✔
4022
    if (check_for_node(node, "type")) {
3,225✔
4023
      mesh_type = get_node_value(node, "type", true, true);
950✔
4024
    } else {
4025
      mesh_type = "regular";
2,275✔
4026
    }
4027

4028
    // determine the mesh library to use
4029
    std::string mesh_lib;
3,225✔
4030
    if (check_for_node(node, "library")) {
3,225✔
4031
      mesh_lib = get_node_value(node, "library", true, true);
49!
4032
    }
4033

4034
    Mesh::create(node, mesh_type, mesh_lib);
3,225✔
4035
  }
3,225✔
4036
}
13,394✔
4037

4038
void read_meshes(hid_t group)
22✔
4039
{
4040
  std::unordered_set<int> mesh_ids;
22✔
4041

4042
  std::vector<int> ids;
22✔
4043
  read_attribute(group, "ids", ids);
22✔
4044

4045
  for (auto id : ids) {
55✔
4046

4047
    // Check to make sure multiple meshes in the same file don't share IDs
4048
    if (contains(mesh_ids, id)) {
66!
4049
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4050
                              "'{}' in the same HDF5 input file",
4051
        id));
4052
    }
4053
    mesh_ids.insert(id);
33✔
4054

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

4062
    std::string name = fmt::format("mesh {}", id);
×
4063
    hid_t mesh_group = open_group(group, name.c_str());
×
4064

4065
    std::string mesh_type;
×
4066
    if (object_exists(mesh_group, "type")) {
×
4067
      read_dataset(mesh_group, "type", mesh_type);
×
4068
    } else {
4069
      mesh_type = "regular";
×
4070
    }
4071

4072
    // determine the mesh library to use
4073
    std::string mesh_lib;
×
4074
    if (object_exists(mesh_group, "library")) {
×
4075
      read_dataset(mesh_group, "library", mesh_lib);
×
4076
    }
4077

4078
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4079
  }
×
4080
}
44✔
4081

4082
void meshes_to_hdf5(hid_t group)
7,623✔
4083
{
4084
  // Write number of meshes
4085
  hid_t meshes_group = create_group(group, "meshes");
7,623✔
4086
  int32_t n_meshes = model::meshes.size();
7,623✔
4087
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,623✔
4088

4089
  if (n_meshes > 0) {
7,623✔
4090
    // Write IDs of meshes
4091
    vector<int> ids;
2,304✔
4092
    for (const auto& m : model::meshes) {
5,253✔
4093
      m->to_hdf5(meshes_group);
2,949✔
4094
      ids.push_back(m->id_);
2,949✔
4095
    }
4096
    write_attribute(meshes_group, "ids", ids);
2,304✔
4097
  }
2,304✔
4098

4099
  close_group(meshes_group);
7,623✔
4100
}
7,623✔
4101

4102
void free_memory_mesh()
8,721✔
4103
{
4104
  model::meshes.clear();
8,721✔
4105
  model::mesh_map.clear();
8,721✔
4106
}
8,721✔
4107

4108
extern "C" int n_meshes()
308✔
4109
{
4110
  return model::meshes.size();
308✔
4111
}
4112

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