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

openmc-dev / openmc / 22920397172

10 Mar 2026 07:25PM UTC coverage: 81.514%. First build
22920397172

Pull #3857

github

web-flow
Merge af297eddf into 1dc4aa988
Pull Request #3857: Minimal implementation of hexagonal mesh

17738 of 25550 branches covered (69.42%)

Branch coverage included in aggregate %.

414 of 499 new or added lines in 5 files covered. (82.97%)

58323 of 67760 relevant lines covered (86.07%)

54221242.65 hits per line

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

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

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

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

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

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

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

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

58
namespace openmc {
59

60
//==============================================================================
61
// Global variables
62
//==============================================================================
63

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

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

74
namespace model {
75

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

79
} // namespace model
80

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

88
//==============================================================================
89
// Helper functions
90
//==============================================================================
91

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

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

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

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

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

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

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

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

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

187
inline void atomic_max_double(double* ptr, double value)
18,515,616 ✔
188
{
189
  atomic_update_double(ptr, value, false);
6,171,872 ✔
190
}
6,171,872 ✔
191

192
inline void atomic_min_double(double* ptr, double value)
18,515,616 ✔
193
{
194
  atomic_update_double(ptr, value, true);
6,171,872 ✔
195
}
196

197
namespace detail {
198

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

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

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

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

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

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

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

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

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

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

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

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

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

326
} // namespace detail
327

328
//==============================================================================
329
// Mesh implementation
330
//==============================================================================
331

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

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

367
  return model::meshes.back();
3,051 ✔
368
}
369

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

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

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

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

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

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

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

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

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

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

425
vector<double> Mesh::volumes() const
246 ✔
426
{
427
  vector<double> volumes(n_bins());
246 ✔
428
  for (int i = 0; i < n_bins(); i++) {
1,111,189 ✔
429
    volumes[i] = this->volume(i);
1,110,943 ✔
430
  }
431
  return volumes;
246 ✔
432
}
×
433

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

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

456
  Timer timer;
187 ✔
457
  timer.start();
187 ✔
458

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

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

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

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

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

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

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

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

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

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

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

523
          p.from_source(&site);
2,962,735 ✔
524

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

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

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

541
          while (true) {
4,658,817 ✔
542
            // Ray trace from r_start to r_end
543
            Position r0 = p.r();
3,790,811 ✔
544
            double max_distance = bbox.max[axis] - r0[axis];
3,790,811 ✔
545

546
            // Find the distance to the nearest boundary
547
            BoundaryInfo boundary = distance_to_boundary(p);
3,790,811 ✔
548

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

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

558
            // Add volumes to any mesh elements that were crossed
559
            int i_material = p.material();
3,790,811 ✔
560
            if (i_material != C_NONE) {
3,790,811 ✔
561
              i_material = model::materials[i_material]->id();
1,117,073 ✔
562
            }
563
            double cumulative_frac = 0.0;
3,790,811 ✔
564
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
7,800,272 ✔
565
              int mesh_index = bins[i_bin];
4,009,461 ✔
566
              double length = distance * length_fractions[i_bin];
4,009,461 ✔
567
              double volume = length * d1 * d2;
4,009,461 ✔
568

569
              if (compute_bboxes) {
4,009,461 ✔
570
                double axis_start = r0[axis] + distance * cumulative_frac;
2,803,376 ✔
571
                double axis_end = axis_start + length;
2,803,376 ✔
572
                cumulative_frac += length_fractions[i_bin];
2,803,376 ✔
573

574
                Position contrib_min = site.r;
2,803,376 ✔
575
                Position contrib_max = site.r;
2,803,376 ✔
576

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

584
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,803,376 ✔
585
                contrib_bbox &= bbox;
2,803,376 ✔
586

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

595
            if (distance == max_distance)
3,790,811 ✔
596
              break;
597

598
            // cross next geometric surface
599
            for (int j = 0; j < p.n_coord(); ++j) {
1,736,012 ✔
600
              p.cell_last(j) = p.coord(j).cell();
868,006 ✔
601
            }
602
            p.n_coord_last() = p.n_coord();
868,006 ✔
603

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

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

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

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

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

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

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

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

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

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

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

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

739
  // Write mesh type
740
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,993 ✔
741

742
  // Write mesh ID
743
  write_attribute(mesh_group, "id", id_);
2,993 ✔
744

745
  // Write mesh name
746
  write_dataset(mesh_group, "name", name_);
2,993 ✔
747

748
  // Write mesh data
749
  this->to_hdf5_inner(mesh_group);
2,993 ✔
750

751
  // Close group
752
  close_group(mesh_group);
2,993 ✔
753
}
2,993 ✔
754

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

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

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

772
std::string StructuredMesh::surface_label(int surface) const
1,396,868 ✔
773
{
774
  int axis = static_cast<int>(std::floor(surface / 4));
1,396,868 ✔
775
  std::string label = axes_labels_[axis];
1,396,868 ✔
776
  const std::vector<std::string> MINMAX = {"min", "max"};
4,190,604 !
777
  const std::vector<std::string> OUTIN = {"Outgoing", "Incoming"};
4,190,604 !
778
  auto minmax = MINMAX[static_cast<int>(std::floor((surface % 4) / 2))];
1,396,868 ✔
779
  auto outin = OUTIN[surface % 2];
1,396,868 ✔
780
  return fmt::format("{}, {}-{}", outin, minmax, label);
1,650,844 ✔
781
}
1,396,868 ✔
782

783
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,532 ✔
784
{
785
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,532 ✔
786
}
787

788
Position StructuredMesh::sample_element(
1,431,751 ✔
789
  const MeshIndex& ijk, uint64_t* seed) const
790
{
791
  // lookup the lower/upper bounds for the mesh element
792
  double x_min = negative_grid_boundary(ijk, 0);
1,431,751 ✔
793
  double x_max = positive_grid_boundary(ijk, 0);
1,431,751 ✔
794

795
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,431,751 !
796
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,431,751 !
797

798
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,431,751 !
799
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,431,751 !
800

801
  return {x_min + (x_max - x_min) * prn(seed),
1,431,751 ✔
802
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,431,751 ✔
803
}
804

805
//==============================================================================
806
// Unstructured Mesh implementation
807
//==============================================================================
808

809
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
47 !
810
{
811
  n_dimension_ = 3;
47 ✔
812

813
  // check the mesh type
814
  if (check_for_node(node, "type")) {
47 !
815
    auto temp = get_node_value(node, "type", true, true);
47 !
816
    if (temp != mesh_type) {
47 !
817
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
818
    }
819
  }
47 ✔
820

821
  // check if a length unit multiplier was specified
822
  if (check_for_node(node, "length_multiplier")) {
47 !
823
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
824
  }
825

826
  // get the filename of the unstructured mesh to load
827
  if (check_for_node(node, "filename")) {
47 !
828
    filename_ = get_node_value(node, "filename");
47 !
829
    if (!file_exists(filename_)) {
47 !
830
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
831
    }
832
  } else {
833
    fatal_error(fmt::format(
×
834
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
835
  }
836

837
  if (check_for_node(node, "options")) {
47 !
838
    options_ = get_node_value(node, "options");
16 !
839
  }
840

841
  // check if mesh tally data should be written with
842
  // statepoint files
843
  if (check_for_node(node, "output")) {
47 !
844
    output_ = get_node_value_bool(node, "output");
×
845
  }
846
}
47 ✔
847

848
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
849
{
850
  n_dimension_ = 3;
×
851

852
  // check the mesh type
853
  if (object_exists(group, "type")) {
×
854
    std::string temp;
×
855
    read_dataset(group, "type", temp);
×
856
    if (temp != mesh_type) {
×
857
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
858
    }
859
  }
×
860

861
  // check if a length unit multiplier was specified
862
  if (object_exists(group, "length_multiplier")) {
×
863
    read_dataset(group, "length_multiplier", length_multiplier_);
×
864
  }
865

866
  // get the filename of the unstructured mesh to load
867
  if (object_exists(group, "filename")) {
×
868
    read_dataset(group, "filename", filename_);
×
869
    if (!file_exists(filename_)) {
×
870
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
871
    }
872
  } else {
873
    fatal_error(fmt::format(
×
874
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
875
  }
876

877
  if (attribute_exists(group, "options")) {
×
878
    read_attribute(group, "options", options_);
×
879
  }
880

881
  // check if mesh tally data should be written with
882
  // statepoint files
883
  if (attribute_exists(group, "output")) {
×
884
    read_attribute(group, "output", output_);
×
885
  }
886
}
×
887

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

910
Position UnstructuredMesh::sample_tet(
601,230 ✔
911
  std::array<Position, 4> coords, uint64_t* seed) const
912
{
913
  // Uniform distribution
914
  double s = prn(seed);
601,230 ✔
915
  double t = prn(seed);
601,230 ✔
916
  double u = prn(seed);
601,230 ✔
917

918
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
919
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
920
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
921
  if (s + t > 1) {
601,230 ✔
922
    s = 1.0 - s;
301,197 ✔
923
    t = 1.0 - t;
301,197 ✔
924
  }
925
  if (s + t + u > 1) {
601,230 ✔
926
    if (t + u > 1) {
401,094 ✔
927
      double old_t = t;
200,402 ✔
928
      t = 1.0 - u;
200,402 ✔
929
      u = 1.0 - s - old_t;
200,402 ✔
930
    } else if (t + u <= 1) {
200,692 !
931
      double old_s = s;
200,692 ✔
932
      s = 1.0 - t - u;
200,692 ✔
933
      u = old_s + t + u - 1;
200,692 ✔
934
    }
935
  }
936
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690 ✔
937
         u * (coords[3] - coords[0]) + coords[0];
601,230 ✔
938
}
939

940
const std::string UnstructuredMesh::mesh_type = "unstructured";
941

942
std::string UnstructuredMesh::get_mesh_type() const
32 ✔
943
{
944
  return mesh_type;
32 ✔
945
}
946

947
void UnstructuredMesh::surface_bins_crossed(
×
948
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
949
{
950
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
951
}
952

953
std::string UnstructuredMesh::bin_label(int bin) const
205,736 ✔
954
{
955
  return fmt::format("Mesh Index ({})", bin);
205,736 ✔
956
};
957

958
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
32 ✔
959
{
960
  write_dataset(mesh_group, "filename", filename_);
32 !
961
  write_dataset(mesh_group, "library", this->library());
32 !
962
  if (!options_.empty()) {
32 ✔
963
    write_attribute(mesh_group, "options", options_);
8 ✔
964
  }
965

966
  if (length_multiplier_ > 0.0)
32 !
967
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
968

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

978
  int num_elem_skipped = 0;
32 ✔
979

980
  // write element types and connectivity
981
  vector<double> volumes;
32 !
982
  tensor::Tensor<int> connectivity(
32 ✔
983
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
32 !
984
  tensor::Tensor<int> elem_types(
32 ✔
985
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
32 !
986
  for (int i = 0; i < this->n_bins(); i++) {
349,768 !
987
    auto conn = this->connectivity(i);
349,736 !
988

989
    volumes.emplace_back(this->volume(i));
349,736 !
990

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

1008
  // warn users that some elements were skipped
1009
  if (num_elem_skipped > 0) {
32 !
1010
    warning(fmt::format("The connectivity of {} elements "
×
1011
                        "on mesh {} were not written "
1012
                        "because they are not of type linear tet/hex.",
1013
      num_elem_skipped, this->id_));
×
1014
  }
1015

1016
  write_dataset(mesh_group, "volumes", volumes);
32 !
1017
  write_dataset(mesh_group, "connectivity", connectivity);
32 !
1018
  write_dataset(mesh_group, "element_types", elem_types);
32 !
1019
}
96 ✔
1020

1021
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23 ✔
1022
{
1023
  length_multiplier_ = length_multiplier;
23 ✔
1024
}
23 ✔
1025

1026
ElementType UnstructuredMesh::element_type(int bin) const
120,000 ✔
1027
{
1028
  auto conn = connectivity(bin);
120,000 ✔
1029

1030
  if (conn.size() == 4)
120,000 !
1031
    return ElementType::LINEAR_TET;
1032
  else if (conn.size() == 8)
×
1033
    return ElementType::LINEAR_HEX;
1034
  else
1035
    return ElementType::UNSUPPORTED;
×
1036
}
120,000 ✔
1037

1038
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,191,127,812 ✔
1039
  Position r, bool& in_mesh) const
1040
{
1041
  MeshIndex ijk;
1,191,127,812 ✔
1042
  in_mesh = true;
1,191,127,812 ✔
1043
  for (int i = 0; i < n_dimension_; ++i) {
3,008,387,119 ✔
1044
    ijk[i] = get_index_in_direction(r[i], i);
2,788,779,450 ✔
1045

1046
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,788,779,450 ✔
1047
      in_mesh = false;
102,653,580 ✔
1048
  }
1049
  return ijk;
1,191,127,812 ✔
1050
}
1051

1052
bool StructuredMesh::valid_index(const MeshIndex& ijk, int k) const
752,109,830 ✔
1053
{
1054
  return ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
752,109,830 ✔
1055
}
1056

1057
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,754,035,230 ✔
1058
{
1059
  switch (n_dimension_) {
1,754,035,230 !
1060
  case 1:
880,605 ✔
1061
    return ijk[0] - 1;
880,605 ✔
1062
  case 2:
136,375,228 ✔
1063
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
136,375,228 ✔
1064
  case 3:
1,616,779,397 ✔
1065
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,616,779,397 ✔
1066
  default:
×
1067
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1068
  }
1069
}
1070

1071
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,768,886 ✔
1072
{
1073
  MeshIndex ijk;
7,768,886 ✔
1074
  if (n_dimension_ == 1) {
7,768,886 ✔
1075
    ijk[0] = bin + 1;
275 ✔
1076
  } else if (n_dimension_ == 2) {
7,768,611 ✔
1077
    ijk[0] = bin % shape_[0] + 1;
15,664 ✔
1078
    ijk[1] = bin / shape_[0] + 1;
15,664 ✔
1079
  } else if (n_dimension_ == 3) {
7,752,947 !
1080
    ijk[0] = bin % shape_[0] + 1;
7,752,947 ✔
1081
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,752,947 ✔
1082
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,752,947 ✔
1083
  }
1084
  return ijk;
7,768,886 ✔
1085
}
1086

1087
int StructuredMesh::get_bin(Position r) const
256,667,872 ✔
1088
{
1089
  // Determine indices
1090
  bool in_mesh;
256,667,872 ✔
1091
  MeshIndex ijk = get_indices(r, in_mesh);
256,667,872 ✔
1092
  if (!in_mesh)
256,667,872 ✔
1093
    return -1;
1094

1095
  // Convert indices to bin
1096
  return get_bin_from_indices(ijk);
235,360,543 ✔
1097
}
1098

1099
int StructuredMesh::n_bins() const
1,125,575 ✔
1100
{
1101
  return std::accumulate(
2,251,150 ✔
1102
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,125,575 ✔
1103
}
1104

1105
int StructuredMesh::n_surface_bins() const
392 ✔
1106
{
1107
  return 4 * n_dimension_ * n_bins();
392 ✔
1108
}
1109

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

1117
  // Create array of zeros
1118
  auto cnt = tensor::zeros<double>(shape);
×
1119
  bool outside_ = false;
1120

1121
  for (int64_t i = 0; i < length; i++) {
×
1122
    const auto& site = bank[i];
×
1123

1124
    // determine scoring bin for entropy mesh
1125
    int mesh_bin = get_bin(site.r);
×
1126

1127
    // if outside mesh, skip particle
1128
    if (mesh_bin < 0) {
×
1129
      outside_ = true;
×
1130
      continue;
×
1131
    }
1132

1133
    // Add to appropriate bin
1134
    cnt(mesh_bin) += site.wgt;
×
1135
  }
1136

1137
  // Create reduced count data
1138
  auto counts = tensor::zeros<double>(shape);
×
1139
  int total = cnt.size();
×
1140

1141
#ifdef OPENMC_MPI
1142
  // collect values from all processors
1143
  MPI_Reduce(
×
1144
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1145

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

1156
  return counts;
×
1157
}
×
1158

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

1172
  // Compute the length of the entire track.
1173
  double total_distance = (r1 - r0).norm();
944,628,787 ✔
1174
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
944,628,787 ✔
1175
    return;
1176

1177
  // keep a copy of the original global position to pass to get_indices,
1178
  // which performs its own transformation to local coordinates
1179
  Position global_r = r0;
932,532,839 ✔
1180
  Position local_r = local_coords(r0);
932,532,839 ✔
1181

1182
  const int n = n_dimension_;
932,532,839 ✔
1183

1184
  // Flag if position is inside the mesh
1185
  bool in_mesh;
1186

1187
  // Position is r = r0 + u * traveled_distance, start at r0
1188
  double traveled_distance {0.0};
932,532,839 ✔
1189

1190
  // Calculate index of current cell. Offset the position a tiny bit in
1191
  // direction of flight
1192
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
932,532,839 ✔
1193

1194
  // if track is very short, assume that it is completely inside one cell.
1195
  // Only the current cell will score and no surfaces
1196
  if (total_distance < 2 * TINY_BIT) {
932,532,839 ✔
1197
    if (in_mesh) {
331,923 ✔
1198
      tally.track(ijk, 1.0);
331,307 ✔
1199
    }
1200
    return;
331,923 ✔
1201
  }
1202

1203
  // Calculate initial distances to next surfaces in all three dimensions
1204
  std::array<MeshDistance, 4> distances;
2,659,659,592 ✔
1205
  for (int k = 0; k < n; ++k) {
2,813,977,337 ✔
1206
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,643,252,022 ✔
1207
  }
1208

1209
  // Loop until r = r1 is eventually reached
1210
  while (true) {
1211
    if (in_mesh) {
1,691,921,492 ✔
1212

1213
      // find surface with minimal distance to current position
1214
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,604,568,849 ✔
1215
                     distances.begin();
1,604,568,849 ✔
1216

1217
      // Tally track length delta since last step
1218
      tally.track(ijk,
1,604,568,849 ✔
1219
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,323,905,914 ✔
1220
          total_distance);
1221

1222
      // update position and leave, if we have reached end position
1223
      traveled_distance = distances[k].distance;
1,604,568,849 ✔
1224
      if (traveled_distance >= total_distance)
1,604,568,849 ✔
1225
        return;
1226

1227
      // If we have not reached r1, we have hit a surface. Tally outward
1228
      // current
1229
      tally.surface(ijk, k, distances[k].max_surface, false);
752,542,614 ✔
1230

1231
      // Update cell and calculate distance to next surface in correlated
1232
      // directions.
1233
      for (int j = 0; j < 3; ++j)
2,697,983,731 ✔
1234
        ijk[j] += distances[k].offset[j];
2,257,627,842 ✔
1235
      sanitize_index(ijk);
752,542,614 ✔
1236
      for (auto j : correlated_axes_[k])
1,505,944,790 ✔
1237
        distances[j] =
753,402,176 ✔
1238
          distance_to_grid_boundary(ijk, j, local_r, u, traveled_distance);
753,402,176 ✔
1239

1240
      // Check if we have left the interior of the mesh
1241
      in_mesh = valid_index(ijk, k);
752,542,614 ✔
1242

1243
      // If we are still inside the mesh, tally inward current for the next
1244
      // cell
1245
      if (in_mesh)
30,009,243 ✔
1246
        tally.surface(ijk, k, !distances[k].max_surface, true);
758,294,052 ✔
1247

1248
    } else { // not inside mesh
1249
      int k_max;
1250
      traveled_distance =
1251
        distance_to_mesh(ijk, distances, traveled_distance, k_max);
87,352,643 ✔
1252
      // If r1 is not inside the mesh, exit here
1253
      if (traveled_distance >= total_distance)
87,352,643 ✔
1254
        return;
80,174,681 ✔
1255

1256
      // Calculate the new cell index and update all distances to next
1257
      // surfaces.
1258
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,177,962 ✔
1259
      for (int k = 0; k < n; ++k) {
28,511,054 ✔
1260
        distances[k] =
21,333,092 ✔
1261
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,333,092 ✔
1262
      }
1263

1264
      // If inside the mesh, Tally inward current
1265
      if (in_mesh && k_max >= 0)
230,032 !
1266
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
205,634 ✔
1267
    }
1268
  }
1269
}
1270

1271
double StructuredMesh::distance_to_mesh(const MeshIndex& ijk,
86,270,573 ✔
1272
  const std::array<MeshDistance, 4>& distances, double traveled_distance,
1273
  int& k_max) const
1274
{
1275
  // For all directions outside the mesh, find the distance that we need
1276
  // to travel to reach the next surface. Use the largest distance, as
1277
  // only this will cross all outer surfaces.
1278
  const int n = n_dimension_;
86,270,573 ✔
1279
  k_max = -1;
86,270,573 ✔
1280
  for (int k = 0; k < n; ++k) {
343,637,926 ✔
1281
    if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,367,353 ✔
1282
        (distances[k].distance > traveled_distance)) {
94,278,488 ✔
1283
      traveled_distance = distances[k].distance;
89,294,964 ✔
1284
      k_max = k;
89,294,964 ✔
1285
    }
1286
  }
1287
  // Assure some distance is traveled
1288
  if (k_max == -1) {
86,270,573 ✔
1289
    traveled_distance += TINY_BIT;
110 ✔
1290
  }
1291
  return traveled_distance;
86,270,573 ✔
1292
}
1293

1294
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
831,012,680 ✔
1295
  vector<int>& bins, vector<double>& lengths) const
1296
{
1297

1298
  // Helper tally class.
1299
  // stores a pointer to the mesh class and references to bins and lengths
1300
  // parameters. Performs the actual tally through the track method.
1301
  struct TrackAggregator {
831,012,680 ✔
1302
    TrackAggregator(
831,012,680 ✔
1303
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1304
      : mesh(_mesh), bins(_bins), lengths(_lengths)
831,012,680 ✔
1305
    {}
1306
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1307
    void track(const MeshIndex& ijk, double l) const
1,463,192,150 ✔
1308
    {
1309
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,463,192,150 ✔
1310
      lengths.push_back(l);
1,463,192,150 ✔
1311
    }
1,463,192,150 ✔
1312

1313
    const StructuredMesh* mesh;
1314
    vector<int>& bins;
1315
    vector<double>& lengths;
1316
  };
1317

1318
  // Perform the mesh raytrace with the helper class.
1319
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
831,012,680 ✔
1320
}
831,012,680 ✔
1321

1322
void StructuredMesh::surface_bins_crossed(
113,616,107 ✔
1323
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1324
{
1325

1326
  // Helper tally class.
1327
  // stores a pointer to the mesh class and a reference to the bins parameter.
1328
  // Performs the actual tally through the surface method.
1329
  struct SurfaceAggregator {
113,616,107 ✔
1330
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
113,616,107 ✔
1331
      : mesh(_mesh), bins(_bins)
113,616,107 ✔
1332
    {}
1333
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
59,027,628 ✔
1334
    {
1335
      int i_bin =
59,027,628 ✔
1336
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
59,027,628 ✔
1337
      if (max)
59,027,628 ✔
1338
        i_bin += 2;
29,485,390 ✔
1339
      if (inward)
59,027,628 ✔
1340
        i_bin += 1;
29,018,385 ✔
1341
      bins.push_back(i_bin);
59,027,628 ✔
1342
    }
59,027,628 ✔
1343
    void track(const MeshIndex& idx, double l) const {}
1344

1345
    const StructuredMesh* mesh;
1346
    vector<int>& bins;
1347
  };
1348

1349
  // Perform the mesh raytrace with the helper class.
1350
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
113,616,107 ✔
1351
}
113,616,107 ✔
1352

1353
//==============================================================================
1354
// RegularMesh implementation
1355
//==============================================================================
1356

1357
int RegularMesh::set_grid()
2,126 ✔
1358
{
1359
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,126 ✔
1360

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

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

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

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

1389
    // Set width and upper right coordinate
1390
    upper_right_ = lower_left_ + shape * width_;
138 ✔
1391

1392
  } else if (upper_right_.size() > 0) {
2,080 !
1393

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

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

1409
    // Set width
1410
    width_ = (upper_right_ - lower_left_) / shape;
6,240 ✔
1411
  }
1412

1413
  // Set material volumes
1414
  volume_frac_ = 1.0 / shape.prod();
2,126 ✔
1415

1416
  element_volume_ = 1.0;
2,126 ✔
1417
  for (int i = 0; i < n_dimension_; i++) {
7,957 ✔
1418
    element_volume_ *= width_[i];
5,831 ✔
1419
  }
1420
  return 0;
1421
}
2,126 ✔
1422

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

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

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

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

1451
    width_ = get_node_tensor<double>(node, "width");
92 ✔
1452

1453
  } else if (check_for_node(node, "upper_right")) {
2,069 !
1454

1455
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,138 ✔
1456

1457
  } else {
1458
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1459
  }
1460

1461
  if (int err = set_grid()) {
2,115 !
1462
    fatal_error(openmc_err_msg);
×
1463
  }
1464
}
2,115 ✔
1465

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

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

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

1489
  if (object_exists(group, "upper_right")) {
11 !
1490

1491
    read_dataset(group, "upper_right", upper_right_);
11 ✔
1492

1493
  } else {
1494
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1495
  }
1496

1497
  if (int err = set_grid()) {
11 !
1498
    fatal_error(openmc_err_msg);
×
1499
  }
1500
}
11 ✔
1501

1502
int RegularMesh::get_index_in_direction(double r, int i) const
2,711,855,532 ✔
1503
{
1504
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,711,855,532 ✔
1505
}
1506

1507
const std::string RegularMesh::mesh_type = "regular";
1508

1509
std::string RegularMesh::get_mesh_type() const
3,225 ✔
1510
{
1511
  return mesh_type;
3,225 ✔
1512
}
1513

1514
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,486,391,798 ✔
1515
{
1516
  return lower_left_[i] + ijk[i] * width_[i];
1,486,391,798 ✔
1517
}
1518

1519
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,417,193,708 ✔
1520
{
1521
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,417,193,708 ✔
1522
}
1523

1524
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,685,023,285 ✔
1525
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1526
  double l) const
1527
{
1528
  MeshDistance d;
2,685,023,285 ✔
1529
  if (std::abs(u[i]) < FP_PRECISION)
2,685,023,285 ✔
1530
    return d;
1531

1532
  d.max_surface = (u[i] > 0);
2,682,371,741 ✔
1533
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,682,371,741 ✔
1534
    ++d.offset[i];
1,482,096,545 ✔
1535
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,482,096,545 ✔
1536
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,434,346,767 ✔
1537
    --d.offset[i];
1,412,898,455 ✔
1538
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,412,898,455 ✔
1539
  }
1540

1541
  return d;
1542
}
1543

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

1566
  // Get the coordinates of the mesh lines along both of the axes.
1567
  array<vector<double>, 2> axis_lines;
1568
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66 ✔
1569
    int axis = axes[i_ax];
44 !
1570
    if (axis == -1)
44 !
1571
      continue;
×
1572
    auto& lines {axis_lines[i_ax]};
44 ✔
1573

1574
    double coord = lower_left_[axis];
44 ✔
1575
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286 ✔
1576
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242 !
1577
        lines.push_back(coord);
242 ✔
1578
      coord += width_[axis];
242 ✔
1579
    }
1580
  }
1581

1582
  return {axis_lines[0], axis_lines[1]};
44 ✔
1583
}
1584

1585
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,092 ✔
1586
{
1587
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,092 ✔
1588
  write_dataset(mesh_group, "lower_left", lower_left_);
2,092 ✔
1589
  write_dataset(mesh_group, "upper_right", upper_right_);
2,092 ✔
1590
  write_dataset(mesh_group, "width", width_);
2,092 ✔
1591
}
2,092 ✔
1592

1593
tensor::Tensor<double> RegularMesh::count_sites(
7,820 ✔
1594
  const SourceSite* bank, int64_t length, bool* outside) const
1595
{
1596
  // Determine shape of array for counts
1597
  std::size_t m = this->n_bins();
7,820 ✔
1598
  vector<std::size_t> shape = {m};
7,820 ✔
1599

1600
  // Create array of zeros
1601
  auto cnt = tensor::zeros<double>(shape);
7,820 ✔
1602
  bool outside_ = false;
2,892 ✔
1603

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

1607
    // determine scoring bin for entropy mesh
1608
    int mesh_bin = get_bin(site.r);
7,667,451 ✔
1609

1610
    // if outside mesh, skip particle
1611
    if (mesh_bin < 0) {
7,667,451 !
1612
      outside_ = true;
×
1613
      continue;
×
1614
    }
1615

1616
    // Add to appropriate bin
1617
    cnt(mesh_bin) += site.wgt;
7,667,451 ✔
1618
  }
1619

1620
  // Create reduced count data
1621
  auto counts = tensor::zeros<double>(shape);
7,820 ✔
1622
  int total = cnt.size();
7,820 ✔
1623

1624
#ifdef OPENMC_MPI
1625
  // collect values from all processors
1626
  MPI_Reduce(
2,892 ✔
1627
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892 ✔
1628

1629
  // Check if there were sites outside the mesh for any processor
1630
  if (outside) {
2,892 !
1631
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892 ✔
1632
  }
1633
#else
1634
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928 ✔
1635
  if (outside)
4,928 !
1636
    *outside = outside_;
4,928 ✔
1637
#endif
1638

1639
  return counts;
7,820 ✔
1640
}
7,820 ✔
1641

1642
double RegularMesh::volume(const MeshIndex& ijk) const
1,112,175 ✔
1643
{
1644
  return element_volume_;
1,112,175 ✔
1645
}
1646

1647
//==============================================================================
1648
// RectilinearMesh implementation
1649
//==============================================================================
1650

1651
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
122 ✔
1652
{
1653
  n_dimension_ = 3;
122 ✔
1654

1655
  grid_[0] = get_node_array<double>(node, "x_grid");
122 ✔
1656
  grid_[1] = get_node_array<double>(node, "y_grid");
122 ✔
1657
  grid_[2] = get_node_array<double>(node, "z_grid");
122 ✔
1658

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

1664
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11 ✔
1665
{
1666
  n_dimension_ = 3;
11 ✔
1667

1668
  read_dataset(group, "x_grid", grid_[0]);
11 ✔
1669
  read_dataset(group, "y_grid", grid_[1]);
11 ✔
1670
  read_dataset(group, "z_grid", grid_[2]);
11 ✔
1671

1672
  if (int err = set_grid()) {
11 !
1673
    fatal_error(openmc_err_msg);
×
1674
  }
1675
}
11 ✔
1676

1677
const std::string RectilinearMesh::mesh_type = "rectilinear";
1678

1679
std::string RectilinearMesh::get_mesh_type() const
275 ✔
1680
{
1681
  return mesh_type;
275 ✔
1682
}
1683

1684
double RectilinearMesh::positive_grid_boundary(
26,505,963 ✔
1685
  const MeshIndex& ijk, int i) const
1686
{
1687
  return grid_[i][ijk[i]];
26,505,963 ✔
1688
}
1689

1690
double RectilinearMesh::negative_grid_boundary(
25,739,406 ✔
1691
  const MeshIndex& ijk, int i) const
1692
{
1693
  return grid_[i][ijk[i] - 1];
25,739,406 ✔
1694
}
1695

1696
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087 ✔
1697
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1698
  double l) const
1699
{
1700
  MeshDistance d;
53,602,087 ✔
1701
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087 ✔
1702
    return d;
1703

1704
  d.max_surface = (u[i] > 0);
53,030,263 ✔
1705
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263 ✔
1706
    ++d.offset[i];
26,505,963 ✔
1707
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963 ✔
1708
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300 ✔
1709
    --d.offset[i];
25,739,406 ✔
1710
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406 ✔
1711
  }
1712
  return d;
1713
}
1714

1715
int RectilinearMesh::set_grid()
177 ✔
1716
{
1717
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
177 ✔
1718
    static_cast<int>(grid_[1].size()) - 1,
177 ✔
1719
    static_cast<int>(grid_[2].size()) - 1};
177 ✔
1720

1721
  for (const auto& g : grid_) {
708 ✔
1722
    if (g.size() < 2) {
531 !
1723
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1724
                 "must each have at least 2 points");
1725
      return OPENMC_E_INVALID_ARGUMENT;
×
1726
    }
1727
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
531 !
1728
        g.end()) {
531 !
1729
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1730
                 "rectilinear meshes must be sorted and unique.");
1731
      return OPENMC_E_INVALID_ARGUMENT;
×
1732
    }
1733
  }
1734

1735
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
177 ✔
1736
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
177 ✔
1737

1738
  return 0;
177 ✔
1739
}
1740

1741
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892 ✔
1742
{
1743
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892 ✔
1744
}
1745

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

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

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

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

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

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

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

1793
//==============================================================================
1794
// CylindricalMesh implementation
1795
//==============================================================================
1796

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1907
  if (D < 0.0)
117,479,187 ✔
1908
    return INFTY;
1909

1910
  D = std::sqrt(D);
107,743,065 ✔
1911

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

1916
  // Check -p - D first because it is always smaller as -p + D
1917
  if (-p - D > l)
101,109,691 ✔
1918
    return -p - D;
1919
  if (-p + D > l)
80,901,724 ✔
1920
    return -p + D;
50,078,385 ✔
1921

1922
  return INFTY;
1923
}
1924

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

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

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

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

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

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

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

1955
  return INFTY;
1956
}
1957

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

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

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

1978
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,014 ✔
1979
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1980
  double l) const
1981
{
1982
  if (i == 0) {
145,218,014 ✔
1983
    return std::min(
142,588,130 ✔
1984
      MeshDistance({1, 0, 0}, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,065 ✔
1985
      MeshDistance({-1, 0, 0}, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,130 ✔
1986

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

1989
    return std::min(
74,456,404 ✔
1990
      MeshDistance({0, 1, 0}, true, find_phi_crossing(r0, u, l, ijk[i])),
37,228,202 ✔
1991
      MeshDistance({0, -1, 0}, false, find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404 ✔
1992

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

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

2004
  axes_labels_ = {"r", "phi", "z"};
1,732 !
2005

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

2033
    return OPENMC_E_INVALID_ARGUMENT;
×
2034
  }
2035

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

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

2043
  return 0;
433 ✔
2044
}
2045

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

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

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

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

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

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

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

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

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

2087
SphericalMesh::SphericalMesh(pugi::xml_node node)
345 ✔
2088
  : PeriodicStructuredMesh {node}
345 ✔
2089
{
2090
  n_dimension_ = 3;
345 ✔
2091
  grid_[0] = get_node_array<double>(node, "r_grid");
345 ✔
2092
  grid_[1] = get_node_array<double>(node, "theta_grid");
345 ✔
2093
  grid_[2] = get_node_array<double>(node, "phi_grid");
345 ✔
2094
  origin_ = get_node_position(node, "origin");
345 ✔
2095

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

2101
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11 ✔
2102
{
2103
  n_dimension_ = 3;
11 ✔
2104
  read_dataset(group, "r_grid", grid_[0]);
11 ✔
2105
  read_dataset(group, "theta_grid", grid_[1]);
11 ✔
2106
  read_dataset(group, "phi_grid", grid_[2]);
11 ✔
2107
  read_dataset(group, "origin", origin_);
11 ✔
2108

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

2114
const std::string SphericalMesh::mesh_type = "spherical";
2115

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

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

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

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

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

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

2144
  return idx;
68,592,128 ✔
2145
}
2146

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

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

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

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

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

2172
  return origin_ + Position(x, y, z);
110 ✔
2173
}
2174

2175
double SphericalMesh::find_r_crossing(
444,032,534 ✔
2176
  const Position& r, const Direction& u, double l, int shell) const
2177
{
2178
  if ((shell < 0) || (shell > shape_[0]))
444,032,534 ✔
2179
    return INFTY;
2180

2181
  // solve |r+s*u| = r0
2182
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2183
  const double r0 = grid_[0][shell];
404,411,447 ✔
2184
  if (r0 == 0.0)
404,411,447 ✔
2185
    return INFTY;
2186
  const double p = r.dot(u);
396,732,930 ✔
2187
  double R = r.norm();
396,732,930 ✔
2188
  double D = p * p - (R - r0) * (R + r0);
396,732,930 ✔
2189

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

2194
  if (D >= 0.0) {
386,024,276 ✔
2195
    D = std::sqrt(D);
358,147,328 ✔
2196
    // Check -p - D first because it is always smaller as -p + D
2197
    if (-p - D > l)
358,147,328 ✔
2198
      return -p - D;
2199
    if (-p + D > l)
293,819,152 ✔
2200
      return -p + D;
177,267,453 ✔
2201
  }
2202

2203
  return INFTY;
2204
}
2205

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

2213
  shell = sanitize_theta(shell);
38,358,540 ✔
2214

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

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

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

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

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

2244
    // no crossing is possible
2245
    return INFTY;
2246
  }
2247

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

2251
  if (D < 0.0)
37,875,992 ✔
2252
    return INFTY;
2253

2254
  D = std::sqrt(D);
26,921,004 ✔
2255

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

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

2267
  return INFTY;
2268
}
2269

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

2277
  shell = sanitize_phi(shell);
39,948,018 ✔
2278

2279
  const double p0 = grid_[2][shell];
39,948,018 ✔
2280

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

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

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

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

2300
  return INFTY;
2301
}
2302

2303
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,972,354 ✔
2304
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2305
  double l) const
2306
{
2307

2308
  if (i == 0) {
332,972,354 ✔
2309
    return std::min(
444,032,534 ✔
2310
      MeshDistance({1, 0, 0}, true, find_r_crossing(r0, u, l, ijk[i])),
222,016,267 ✔
2311
      MeshDistance({-1, 0, 0}, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
444,032,534 ✔
2312

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

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

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

2332
  axes_labels_ = {"r", "theta", "phi"};
1,512 !
2333

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

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

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

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

2371
  return 0;
378 ✔
2372
}
2373

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

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

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

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

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

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

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

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

2412
//==============================================================================
2413
// HexagonalMesh implementation
2414
//==============================================================================
2415

2416
HexagonalMesh::HexagonalMesh(pugi::xml_node node)
66 ✔
2417
  : PeriodicStructuredMesh {node}
66 ✔
2418
{
2419
  grid_ = get_node_array<double>(node, "z_grid");
66 ✔
2420
  num_rings_ = std::stoi(get_node_value(node, "num_rings"));
132 ✔
2421
  pitch_ = std::stod(get_node_value(node, "pitch"));
132 ✔
2422
  origin_ = get_node_position(node, "origin");
66 ✔
2423

2424
  // Read the orientation.  Default to 'y'.
2425
  if (check_for_node(node, "orientation")) {
66 !
2426
    std::string orientation = get_node_value(node, "orientation");
66 ✔
2427
    if (orientation == "x") {
66 ✔
2428
      orientation_ = Orientation::x;
33 ✔
2429
    } else if (orientation != "y") {
33 !
NEW
2430
      fatal_error("Unrecognized orientation '" + orientation + "'");
×
2431
    }
2432
  }
66 ✔
2433

2434
  if (int err = set_grid()) {
66 !
NEW
2435
    fatal_error(openmc_err_msg);
×
2436
  }
2437
}
66 ✔
2438

NEW
2439
HexagonalMesh::HexagonalMesh(hid_t group) : PeriodicStructuredMesh {group}
×
2440
{
NEW
2441
  read_dataset(group, "z_grid", grid_);
×
NEW
2442
  read_attribute(group, "num_rings", num_rings_);
×
NEW
2443
  read_attribute(group, "pitch", pitch_);
×
NEW
2444
  read_dataset(group, "origin", origin_);
×
2445

NEW
2446
  if (attribute_exists(group, "orientation")) {
×
NEW
2447
    std::string orientation;
×
NEW
2448
    read_attribute(group, "orientation", orientation);
×
NEW
2449
    if (orientation == "x") {
×
NEW
2450
      orientation_ = Orientation::x;
×
NEW
2451
    } else if (orientation != "y") {
×
NEW
2452
      fatal_error("Unrecognized orientation '" + orientation + "'");
×
2453
    }
NEW
2454
  }
×
NEW
2455
  if (int err = set_grid()) {
×
NEW
2456
    fatal_error(openmc_err_msg);
×
2457
  }
NEW
2458
}
×
2459

2460
const std::string HexagonalMesh::mesh_type = "hexagonal";
2461

2462
std::string HexagonalMesh::get_mesh_type() const
66 ✔
2463
{
2464
  return mesh_type;
66 ✔
2465
}
2466

2467
std::string HexagonalMesh::bin_label(int bin) const
7,524 ✔
2468
{
2469
  MeshIndex ijk = get_indices_from_bin(bin);
7,524 ✔
2470
  return fmt::format(
7,524 ✔
2471
    "Mesh Index ({}, {}, {}, {})", ijk[0], ijk[1], -ijk[0] - ijk[1], ijk[2]);
7,524 ✔
2472
}
2473

2474
std::string HexagonalMesh::surface_label(int surface) const
6,688 ✔
2475
{
2476
  int axis = static_cast<int>(std::floor(surface / 4));
6,688 ✔
2477
  int max = static_cast<int>(std::floor((surface % 4) / 2));
6,688 ✔
2478
  const std::vector<std::string> MINMAX = {"min", "max"};
20,064 !
2479
  const std::vector<std::string> OUTIN = {"Outgoing", "Incoming"};
20,064 !
2480
  auto minmax = MINMAX[max];
6,688 ✔
2481
  auto outin = OUTIN[surface % 2];
6,688 ✔
2482
  std::string label = axes_labels_[axis];
6,688 ✔
2483
  if (axis == 3) {
6,688 ✔
2484
    return fmt::format("{}, {}-{}", outin, label, minmax);
1,976 ✔
2485
  }
2486
  auto minmax2 = MINMAX[1 - max];
5,016 ✔
2487
  std::string label2 = axes_labels_[(axis + 1) % 2];
5,016 ✔
2488
  return fmt::format("{}, {}-{} {}-{}", outin, label, minmax, label2, minmax2);
5,928 ✔
2489
}
11,704 ✔
2490

2491
int HexagonalMesh::n_bins() const
66 ✔
2492
{
2493
  return (1 + 3 * (num_rings_ + 1) * num_rings_) * (grid_.size() - 1);
66 ✔
2494
}
2495

2496
bool HexagonalMesh::valid_index(const MeshIndex& ijk, int k) const
432,784 ✔
2497
{
2498
  if (k == 3)
432,784 ✔
2499
    return ((ijk[2] >= 1) && (ijk[2] < grid_.size()));
3,003 !
2500
  int ring =
429,781 ✔
2501
    std::max({std::abs(ijk[0]), std::abs(ijk[1]), std::abs(ijk[0] + ijk[1])});
429,781 ✔
2502
  return (ring < num_rings_);
429,781 ✔
2503
}
2504

2505
int HexagonalMesh::get_bin_from_indices(const MeshIndex& ijk) const
3,545,091 ✔
2506
{
2507
  int q = ijk[0];
3,545,091 ✔
2508
  int r = ijk[1];
3,545,091 ✔
2509
  int k = ijk[2];
3,545,091 ✔
2510
  int hexes = 3 * num_rings_ * (num_rings_ + 1) + 1;
3,545,091 ✔
2511
  int bin = (k - 1) * (grid_.size() - 1) * hexes;
3,545,091 ✔
2512
  int rad = std::max({std::abs(r), std::abs(q), std::abs(r + q)});
3,545,091 ✔
2513
  if (rad == 0)
3,545,091 ✔
2514
    return bin;
2515

2516
  bin += 3 * rad * (rad - 1) + 1;
2,214,663 ✔
2517

2518
  if ((q >= 0) and (r >= 0)) {
2,214,663 ✔
2519
    bin += q;
718,905 ✔
2520
  } else if ((r < 0) && ((-r - q) < 0)) {
1,495,758 !
NEW
2521
    bin += (rad - r);
×
2522
  } else if ((q >= 0) && ((-q - r) >= 0)) {
1,495,758 !
2523
    bin += (2 * rad - q - r);
746,856 ✔
2524
  } else if ((q < 0) && (r < 0)) {
748,902 !
NEW
2525
    bin += (3 * rad - q);
×
2526
  } else if ((r >= 0) && ((-q - r) >= 0)) {
748,902 !
2527
    bin += (4 * rad + r);
748,902 ✔
2528
  } else {
NEW
2529
    bin += (5 * rad + q + r);
×
2530
  }
2531
  return bin;
2532
}
2533

2534
StructuredMesh::MeshIndex HexagonalMesh::get_indices(
5,250,861 ✔
2535
  Position r, bool& in_mesh) const
2536
{
2537
  r = local_coords(r);
5,250,861 ✔
2538

2539
  double q = q_dual_.dot(r);
5,250,861 ✔
2540
  double r0 = r_dual_.dot(r);
5,250,861 ✔
2541
  double s = -q - r0;
5,250,861 ✔
2542

2543
  double q_r = std::round(q);
5,250,861 ✔
2544
  double r_r = std::round(r0);
5,250,861 ✔
2545
  double s_r = std::round(s);
5,250,861 ✔
2546
  std::array<double, 3> diff = {
5,250,861 ✔
2547
    std::abs(q - q_r), std::abs(r0 - r_r), std::abs(s - s_r)};
5,250,861 ✔
2548
  auto max_it = std::max_element(diff.begin(), diff.end());
5,250,861 ✔
2549
  int i = static_cast<int>(std::distance(diff.begin(), max_it));
5,250,861 ✔
2550

2551
  if (i == 0)
5,250,861 ✔
2552
    q_r = -s_r - r_r;
1,759,725 ✔
2553
  else if (i == 1)
3,491,136 ✔
2554
    r_r = -q_r - s_r;
1,748,901 ✔
2555

2556
  int z_i = get_index_in_z_direction(r.z);
5,250,861 ✔
2557
  int q_i = static_cast<int>(q_r);
5,250,861 ✔
2558
  int r_i = static_cast<int>(r_r);
5,250,861 ✔
2559
  int s_i = -q_i - r_i;
5,250,861 ✔
2560

2561
  MeshIndex ijk;
5,250,861 ✔
2562
  in_mesh = true;
5,250,861 ✔
2563

2564
  ijk[0] = q_i;
5,250,861 ✔
2565
  ijk[1] = r_i;
5,250,861 ✔
2566
  ijk[2] = z_i;
5,250,861 ✔
2567

2568
  if (std::max({std::abs(q_i), std::abs(r_i), std::abs(s_i)}) >= num_rings_)
5,250,861 ✔
2569
    in_mesh = false;
1,340,548 ✔
2570
  if (ijk[2] < 1 || ijk[2] > grid_.size() - 1)
5,250,861 !
NEW
2571
    in_mesh = false;
×
2572

2573
  return ijk;
5,250,861 ✔
2574
}
2575

2576
StructuredMesh::MeshIndex HexagonalMesh::get_indices_from_bin(int bin) const
7,524 ✔
2577
{
2578
  MeshIndex ijk = {0, 0, 0};
7,524 ✔
2579
  int hexes = 3 * num_rings_ * (num_rings_ + 1) + 1;
7,524 ✔
2580
  ijk[2] = static_cast<int>(std::floor(bin / hexes)) + 1;
7,524 ✔
2581
  int sp_idx = bin % hexes;
7,524 ✔
2582
  if (sp_idx == 0) {
7,524 ✔
2583
    return ijk;
396 ✔
2584
  }
2585
  int rad = static_cast<int>(std::floor((3 + std::sqrt(12 * sp_idx - 3)) / 6));
7,128 !
2586
  int offset = sp_idx - (3 * rad * (rad - 1) + 1);
7,128 ✔
2587
  int side = (offset / rad) % 6;
7,128 ✔
2588
  int dist = offset % rad;
7,128 ✔
2589
  switch (side) {
7,128 !
2590
  case 0:
1,188 ✔
2591
    ijk[0] = dist;
1,188 ✔
2592
    ijk[1] = rad - dist;
1,188 ✔
2593
    break;
1,188 ✔
2594
  case 1:
1,188 ✔
2595
    ijk[0] = rad;
1,188 ✔
2596
    ijk[1] = -dist;
1,188 ✔
2597
    break;
1,188 ✔
2598
  case 2:
1,188 ✔
2599
    ijk[0] = rad - dist;
1,188 ✔
2600
    ijk[1] = -rad;
1,188 ✔
2601
    break;
1,188 ✔
2602
  case 3:
1,188 ✔
2603
    ijk[0] = -dist;
1,188 ✔
2604
    ijk[1] = dist - rad;
1,188 ✔
2605
    break;
1,188 ✔
2606
  case 4:
1,188 ✔
2607
    ijk[0] = -rad;
1,188 ✔
2608
    ijk[1] = dist;
1,188 ✔
2609
    break;
1,188 ✔
2610
  case 5:
1,188 ✔
2611
    ijk[0] = dist - rad;
1,188 ✔
2612
    ijk[1] = rad;
1,188 ✔
2613
    break;
1,188 ✔
2614
  }
2615
  return ijk;
7,128 ✔
2616
}
2617

NEW
2618
Position HexagonalMesh::sample_element(
×
2619
  const MeshIndex& ijk, uint64_t* seed) const
2620
{
NEW
2621
  double radius = pitch_ / std::sqrt(3.0);
×
NEW
2622
  double q0 = ijk[0];
×
NEW
2623
  double r0 = ijk[1];
×
NEW
2624
  double z = uniform_distribution(grid_[ijk[2] - 1], grid_[ijk[2]], seed);
×
NEW
2625
  double q, r, s;
×
NEW
2626
  do {
×
NEW
2627
    double rad = std::cbrt(prn(seed)) * radius;
×
NEW
2628
    double phi = uniform_distribution(0.0, 2 * PI, seed);
×
NEW
2629
    double x = rad * std::cos(phi);
×
NEW
2630
    double y = rad * std::sin(phi);
×
NEW
2631
    q = q_dual_[0] * x + q_dual_[1] * y;
×
NEW
2632
    r = r_dual_[0] * x + r_dual_[1] * y;
×
NEW
2633
    s = -q - r;
×
NEW
2634
  } while (std::max({std::abs(q), std::abs(r), std::abs(s)}) > 1);
×
2635

NEW
2636
  return origin_ + radius * ((q + q0) * q_ + (r + r0) * r_) + z;
×
2637
}
2638

2639
StructuredMesh::MeshDistance HexagonalMesh::find_z_crossing(
4,203,903 ✔
2640
  const Position& r, const Direction& u, double l, int shell) const
2641
{
2642
  MeshDistance d;
4,203,903 ✔
2643

2644
  // Direction of flight is within xy-plane. Will never intersect z.
2645
  if (std::abs(u.z) < FP_PRECISION)
4,203,903 !
2646
    return d;
2647

2648
  d.max_surface = (u.z > 0.0);
4,203,903 ✔
2649
  if (d.max_surface && (shell < grid_.size())) {
4,203,903 ✔
2650
    ++d.offset[2];
2,106,346 ✔
2651
    d.distance = (grid_[shell] - r.z) / u.z;
2,106,346 ✔
2652
  } else if (!d.max_surface && (shell > 0)) {
2,097,557 ✔
2653
    --d.offset[2];
2,094,554 ✔
2654
    d.distance = (grid_[shell - 1] - r.z) / u.z;
2,094,554 ✔
2655
  }
2656
  return d;
2657
}
2658

2659
StructuredMesh::MeshDistance HexagonalMesh::distance_to_grid_boundary(
18,095,946 ✔
2660
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2661
  double l) const
2662
{
2663
  auto r = local_coords(r0);
18,095,946 ✔
2664
  if (i == 3)
18,095,946 ✔
2665
    return find_z_crossing(r, u, l, ijk[2]);
4,203,903 ✔
2666
  r.z = 0.0;
13,892,043 ✔
2667

2668
  MeshDistance d;
13,892,043 ✔
2669
  Direction s_ = -q_ - r_;
13,892,043 ✔
2670
  Direction dir;
13,892,043 ✔
2671
  MeshIndex idx = {ijk[0], ijk[1], -ijk[0] - ijk[1]};
13,892,043 ✔
2672
  MeshIndex offset = {0, 0, 0};
13,892,043 ✔
2673
  double distance;
13,892,043 ✔
2674
  if (i == 0) {
13,892,043 ✔
2675
    dir = 0.5 * (q_ - r_);
4,630,681 ✔
2676
    ++offset[0];
4,630,681 ✔
2677
    --offset[1];
4,630,681 ✔
2678
  } else if (i == 1) {
9,261,362 ✔
2679
    dir = 0.5 * (r_ - s_);
4,630,681 ✔
2680
    ++offset[1];
4,630,681 ✔
2681
    --offset[2];
4,630,681 ✔
2682
  } else {
2683
    dir = 0.5 * (s_ - q_);
4,630,681 ✔
2684
    --offset[0];
4,630,681 ✔
2685
    ++offset[2];
4,630,681 ✔
2686
  }
2687
  dir /= dir.norm();
13,892,043 ✔
2688
  if (std::abs(u.dot(dir)) < FP_PRECISION)
13,892,043 !
NEW
2689
    return d;
×
2690

2691
  d.max_surface = (u.dot(dir) > 0.0);
13,892,043 ✔
2692
  if (d.max_surface) {
13,892,043 ✔
2693
    distance = (idx[0] * q_ + idx[1] * r_ + dir - r).norm() / u.dot(dir);
6,958,996 ✔
2694
    idx[0] += offset[0];
6,958,996 ✔
2695
    idx[1] += offset[1];
6,958,996 ✔
2696
    idx[2] += offset[2];
6,958,996 ✔
2697
  } else {
2698
    distance = -(idx[0] * q_ + idx[1] * r_ - dir - r).norm() / u.dot(dir);
6,933,047 ✔
2699
    idx[0] -= offset[0];
6,933,047 ✔
2700
    idx[1] -= offset[1];
6,933,047 ✔
2701
    idx[2] -= offset[2];
6,933,047 ✔
2702
  }
2703
  int radius = std::max({std::abs(idx[0]), std::abs(idx[1]), std::abs(idx[2])});
13,892,043 ✔
2704
  if (d.max_surface && (radius < num_rings_)) {
13,892,043 ✔
2705
    d.offset[0] += offset[0];
2706
    d.offset[1] += offset[1];
2707
    d.distance = distance;
2708
  } else if (!d.max_surface && (radius < num_rings_)) {
10,758,297 ✔
2709
    d.offset[0] -= offset[0];
3,127,487 ✔
2710
    d.offset[1] -= offset[1];
3,127,487 ✔
2711
    d.distance = distance;
3,127,487 ✔
2712
  }
2713
  return d;
13,892,043 ✔
2714
}
2715

2716
double HexagonalMesh::distance_to_mesh(const MeshIndex& ijk,
1,082,070 ✔
2717
  const std::array<MeshDistance, 4>& distances, double traveled_distance,
2718
  int& k_max) const
2719
{
2720
  // For all directions outside the mesh, find the distance that we need
2721
  // to travel to reach the next surface. Use the largest distance, as
2722
  // only this will cross all outer surfaces.
2723
  const int n = n_dimension_;
1,082,070 ✔
2724
  k_max = -1;
1,082,070 ✔
2725

2726
  for (int k = 0; k < n; ++k) {
5,410,350 ✔
2727
    if (distances[k].distance <= traveled_distance)
4,328,280 ✔
2728
      continue;
2,167,561 ✔
2729
    if ((k < 2) && (std::abs(ijk[k]) < num_rings_))
2,160,719 ✔
2730
      continue;
847,748 ✔
2731
    if ((k == 2) && (std::abs(ijk[0] + ijk[1]) < num_rings_))
1,312,971 ✔
2732
      continue;
84,623 ✔
2733
    if ((k == 3) && (ijk[2] >= 1) && (ijk[2] < grid_.size()))
1,228,348 ✔
2734
      continue;
112,035 ✔
2735
    traveled_distance = distances[k].distance;
1,116,313 ✔
2736
    k_max = k;
1,116,313 ✔
2737
  }
2738
  // Assure some distance is traveled
2739
  if (k_max == -1) {
1,082,070 !
NEW
2740
    traveled_distance += TINY_BIT;
×
2741
  }
2742
  return traveled_distance;
1,082,070 ✔
2743
}
2744

2745
int HexagonalMesh::set_grid()
66 ✔
2746
{
2747
  n_dimension_ = 4;
66 ✔
2748
  correlated_axes_ = {{0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {3}};
330 !
2749

2750
  axes_labels_ = {"r", "q", "s", "z"};
330 !
2751

2752
  if (orientation_ == Orientation::x) {
66 ✔
2753
    q_ = {std::sqrt(3.0), 0.0, 0.0};
33 ✔
2754
    r_ = {0.5 * std::sqrt(3), -1.5, 0.0};
33 ✔
2755
    q_dual_ = {std::sqrt(3.0) / 3.0, 1.0 / 3.0, 0.0};
33 ✔
2756
    r_dual_ = {0.0, -2.0 / 3.0, 0.0};
33 ✔
2757
  } else {
2758
    q_ = {1.5, -0.5 * std::sqrt(3.0), 0.0};
33 ✔
2759
    r_ = {0.0, -std::sqrt(3.0), 0.0};
33 ✔
2760
    q_dual_ = {2.0 / 3.0, 0.0, 0.0};
33 ✔
2761
    r_dual_ = {-1.0 / 3.0, -std::sqrt(3.0) / 3.0, 0.0};
33 ✔
2762
  }
2763

2764
  double size = pitch_ / std::sqrt(3.0);
66 ✔
2765

2766
  q_ *= size;
66 ✔
2767
  r_ *= size;
66 ✔
2768
  q_dual_ /= size;
66 ✔
2769
  r_dual_ /= size;
66 ✔
2770

2771
  if (grid_.size() < 2) {
66 !
NEW
2772
    set_errmsg("z- grid for hexagonal meshes "
×
2773
               "must have at least 2 points");
NEW
2774
    return OPENMC_E_INVALID_ARGUMENT;
×
2775
  }
2776
  if (std::adjacent_find(grid_.begin(), grid_.end(), std::greater_equal<>()) !=
66 ✔
2777
      grid_.end()) {
66 !
NEW
2778
    set_errmsg("Values in z- grid for "
×
2779
               "hexagonal meshes must be sorted and unique.");
NEW
2780
    return OPENMC_E_INVALID_ARGUMENT;
×
2781
  }
2782
  return 0;
2783
}
2784

2785
int HexagonalMesh::get_index_in_z_direction(double z) const
5,250,861 ✔
2786
{
2787
  return lower_bound_index(grid_.begin(), grid_.end(), z) + 1;
5,250,861 ✔
2788
}
2789

NEW
2790
std::pair<vector<double>, vector<double>> HexagonalMesh::plot(
×
2791
  Position plot_ll, Position plot_ur) const
2792
{
NEW
2793
  fatal_error("Plot of hexagonal Mesh not implemented");
×
2794

2795
  // Figure out which axes lie in the plane of the plot.
2796
  array<vector<double>, 2> axis_lines;
2797
  return {axis_lines[0], axis_lines[1]};
2798
}
2799

2800
void HexagonalMesh::to_hdf5_inner(hid_t mesh_group) const
66 ✔
2801
{
2802
  write_dataset(mesh_group, "z_grid", grid_);
66 ✔
2803
  if (orientation_ == Orientation::x)
66 ✔
2804
    write_attribute(mesh_group, "orientation", "x");
33 ✔
2805
  write_attribute(mesh_group, "num_rings", num_rings_);
66 ✔
2806
  write_attribute(mesh_group, "pitch", pitch_);
66 ✔
2807
  write_dataset(mesh_group, "origin", origin_);
66 ✔
2808
}
66 ✔
2809

NEW
2810
double HexagonalMesh::volume(const MeshIndex& ijk) const
×
2811
{
NEW
2812
  double f = 1.5 * std::sqrt(3.0);
×
NEW
2813
  double size = pitch_ / std::sqrt(3.0);
×
NEW
2814
  double z_i = grid_[ijk[2] - 1];
×
NEW
2815
  double z_o = grid_[ijk[2]];
×
NEW
2816
  return f * (z_o - z_i) * size * size;
×
2817
}
2818

2819
//==============================================================================
2820
// Helper functions for the C API
2821
//==============================================================================
2822

2823
int check_mesh(int32_t index)
6,380 ✔
2824
{
2825
  if (index < 0 || index >= model::meshes.size()) {
6,380 !
2826
    set_errmsg("Index in meshes array is out of bounds.");
×
2827
    return OPENMC_E_OUT_OF_BOUNDS;
×
2828
  }
2829
  return 0;
2830
}
2831

2832
template<class T>
2833
int check_mesh_type(int32_t index)
1,100 ✔
2834
{
2835
  if (int err = check_mesh(index))
1,100 !
2836
    return err;
2837

2838
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100 !
2839
  if (!mesh) {
1,100 !
2840
    set_errmsg("This function is not valid for input mesh.");
×
2841
    return OPENMC_E_INVALID_TYPE;
×
2842
  }
2843
  return 0;
2844
}
2845

2846
template<class T>
2847
bool is_mesh_type(int32_t index)
2848
{
2849
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2850
  return mesh;
2851
}
2852

2853
//==============================================================================
2854
// C API functions
2855
//==============================================================================
2856

2857
// Return the type of mesh as a C string
2858
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,474 ✔
2859
{
2860
  if (int err = check_mesh(index))
1,474 !
2861
    return err;
2862

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

2865
  return 0;
1,474 ✔
2866
}
2867

2868
//! Extend the meshes array by n elements
2869
extern "C" int openmc_extend_meshes(
253 ✔
2870
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2871
{
2872
  if (index_start)
253 !
2873
    *index_start = model::meshes.size();
253 ✔
2874
  std::string mesh_type;
253 ✔
2875

2876
  for (int i = 0; i < n; ++i) {
506 ✔
2877
    if (RegularMesh::mesh_type == type) {
253 ✔
2878
      model::meshes.push_back(make_unique<RegularMesh>());
165 ✔
2879
    } else if (RectilinearMesh::mesh_type == type) {
88 ✔
2880
      model::meshes.push_back(make_unique<RectilinearMesh>());
44 ✔
2881
    } else if (CylindricalMesh::mesh_type == type) {
44 ✔
2882
      model::meshes.push_back(make_unique<CylindricalMesh>());
22 ✔
2883
    } else if (SphericalMesh::mesh_type == type) {
22 !
2884
      model::meshes.push_back(make_unique<SphericalMesh>());
22 ✔
NEW
2885
    } else if (HexagonalMesh::mesh_type == type) {
×
NEW
2886
      model::meshes.push_back(make_unique<HexagonalMesh>());
×
2887
    } else {
2888
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2889
    }
2890
  }
2891
  if (index_end)
253 !
2892
    *index_end = model::meshes.size() - 1;
×
2893

2894
  return 0;
253 ✔
2895
}
253 ✔
2896

2897
//! Adds a new unstructured mesh to OpenMC
2898
extern "C" int openmc_add_unstructured_mesh(
×
2899
  const char filename[], const char library[], int* id)
2900
{
2901
  std::string lib_name(library);
×
2902
  std::string mesh_file(filename);
×
2903
  bool valid_lib = false;
×
2904

2905
#ifdef OPENMC_DAGMC_ENABLED
2906
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2907
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2908
    valid_lib = true;
2909
  }
2910
#endif
2911

2912
#ifdef OPENMC_LIBMESH_ENABLED
2913
  if (lib_name == LibMesh::mesh_lib_type) {
×
2914
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2915
    valid_lib = true;
2916
  }
2917
#endif
2918

2919
  if (!valid_lib) {
×
2920
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2921
                           "by this build of OpenMC",
2922
      lib_name));
2923
    return OPENMC_E_INVALID_ARGUMENT;
×
2924
  }
2925

2926
  // auto-assign new ID
2927
  model::meshes.back()->set_id(-1);
×
2928
  *id = model::meshes.back()->id_;
2929

2930
  return 0;
2931
}
×
2932

2933
//! Return the index in the meshes array of a mesh with a given ID
2934
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429 ✔
2935
{
2936
  auto pair = model::mesh_map.find(id);
429 !
2937
  if (pair == model::mesh_map.end()) {
429 !
2938
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2939
    return OPENMC_E_INVALID_ID;
×
2940
  }
2941
  *index = pair->second;
429 ✔
2942
  return 0;
429 ✔
2943
}
2944

2945
//! Return the ID of a mesh
2946
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,805 ✔
2947
{
2948
  if (int err = check_mesh(index))
2,805 !
2949
    return err;
2950
  *id = model::meshes[index]->id_;
2,805 ✔
2951
  return 0;
2,805 ✔
2952
}
2953

2954
//! Set the ID of a mesh
2955
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253 ✔
2956
{
2957
  if (int err = check_mesh(index))
253 !
2958
    return err;
2959
  model::meshes[index]->id_ = id;
253 ✔
2960
  model::mesh_map[id] = index;
253 ✔
2961
  return 0;
253 ✔
2962
}
2963

2964
//! Get the number of elements in a mesh
2965
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
275 ✔
2966
{
2967
  if (int err = check_mesh(index))
275 !
2968
    return err;
2969
  *n = model::meshes[index]->n_bins();
275 ✔
2970
  return 0;
275 ✔
2971
}
2972

2973
//! Get the volume of each element in the mesh
2974
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88 ✔
2975
{
2976
  if (int err = check_mesh(index))
88 !
2977
    return err;
2978
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968 ✔
2979
    volumes[i] = model::meshes[index]->volume(i);
880 ✔
2980
  }
2981
  return 0;
2982
}
2983

2984
//! Get the bounding box of a mesh
2985
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
154 ✔
2986
{
2987
  if (int err = check_mesh(index))
154 !
2988
    return err;
2989

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

2992
  // set lower left corner values
2993
  ll[0] = bbox.min.x;
154 ✔
2994
  ll[1] = bbox.min.y;
154 ✔
2995
  ll[2] = bbox.min.z;
154 ✔
2996

2997
  // set upper right corner values
2998
  ur[0] = bbox.max.x;
154 ✔
2999
  ur[1] = bbox.max.y;
154 ✔
3000
  ur[2] = bbox.max.z;
154 ✔
3001
  return 0;
154 ✔
3002
}
3003

3004
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
187 ✔
3005
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
3006
{
3007
  if (int err = check_mesh(index))
187 !
3008
    return err;
3009

3010
  try {
187 ✔
3011
    model::meshes[index]->material_volumes(
187 ✔
3012
      nx, ny, nz, table_size, materials, volumes, bboxes);
3013
  } catch (const std::exception& e) {
11 !
3014
    set_errmsg(e.what());
11 ✔
3015
    if (starts_with(e.what(), "Mesh")) {
11 !
3016
      return OPENMC_E_GEOMETRY;
11 ✔
3017
    } else {
3018
      return OPENMC_E_ALLOCATE;
×
3019
    }
3020
  }
11 ✔
3021

3022
  return 0;
3023
}
3024

3025
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44 ✔
3026
  Position width, int basis, int* pixels, int32_t* data)
3027
{
3028
  if (int err = check_mesh(index))
44 !
3029
    return err;
3030
  const auto& mesh = model::meshes[index].get();
44 !
3031

3032
  int pixel_width = pixels[0];
44 ✔
3033
  int pixel_height = pixels[1];
44 ✔
3034

3035
  // get pixel size
3036
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44 ✔
3037
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44 ✔
3038

3039
  // setup basis indices and initial position centered on pixel
3040
  int in_i, out_i;
44 ✔
3041
  Position xyz = origin;
44 ✔
3042
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44 ✔
3043
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44 ✔
3044
  switch (basis_enum) {
44 !
3045
  case PlotBasis::xy:
3046
    in_i = 0;
3047
    out_i = 1;
3048
    break;
3049
  case PlotBasis::xz:
3050
    in_i = 0;
3051
    out_i = 2;
3052
    break;
3053
  case PlotBasis::yz:
3054
    in_i = 1;
3055
    out_i = 2;
3056
    break;
3057
  default:
×
3058
    UNREACHABLE();
×
3059
  }
3060

3061
  // set initial position
3062
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44 ✔
3063
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44 ✔
3064

3065
#pragma omp parallel
24 ✔
3066
  {
20 ✔
3067
    Position r = xyz;
20 ✔
3068

3069
#pragma omp for
3070
    for (int y = 0; y < pixel_height; y++) {
420 ✔
3071
      r[out_i] = xyz[out_i] - out_pixel * y;
400 ✔
3072
      for (int x = 0; x < pixel_width; x++) {
8,400 ✔
3073
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000 ✔
3074
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000 ✔
3075
      }
3076
    }
3077
  }
3078

3079
  return 0;
44 ✔
3080
}
3081

3082
//! Get the dimension of a regular mesh
3083
extern "C" int openmc_regular_mesh_get_dimension(
11 ✔
3084
  int32_t index, int** dims, int* n)
3085
{
3086
  if (int err = check_mesh_type<RegularMesh>(index))
11 !
3087
    return err;
3088
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11 !
3089
  *dims = mesh->shape_.data();
11 ✔
3090
  *n = mesh->n_dimension_;
11 ✔
3091
  return 0;
11 ✔
3092
}
3093

3094
//! Set the dimension of a regular mesh
3095
extern "C" int openmc_regular_mesh_set_dimension(
187 ✔
3096
  int32_t index, int n, const int* dims)
3097
{
3098
  if (int err = check_mesh_type<RegularMesh>(index))
187 !
3099
    return err;
3100
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187 !
3101

3102
  // Copy dimension
3103
  mesh->n_dimension_ = n;
187 ✔
3104
  std::copy(dims, dims + n, mesh->shape_.begin());
187 ✔
3105
  return 0;
187 ✔
3106
}
3107

3108
//! Get the regular mesh parameters
3109
extern "C" int openmc_regular_mesh_get_params(
209 ✔
3110
  int32_t index, double** ll, double** ur, double** width, int* n)
3111
{
3112
  if (int err = check_mesh_type<RegularMesh>(index))
209 !
3113
    return err;
3114
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209 !
3115

3116
  if (m->lower_left_.empty()) {
209 !
3117
    set_errmsg("Mesh parameters have not been set.");
×
3118
    return OPENMC_E_ALLOCATE;
×
3119
  }
3120

3121
  *ll = m->lower_left_.data();
209 ✔
3122
  *ur = m->upper_right_.data();
209 ✔
3123
  *width = m->width_.data();
209 ✔
3124
  *n = m->n_dimension_;
209 ✔
3125
  return 0;
209 ✔
3126
}
3127

3128
//! Set the regular mesh parameters
3129
extern "C" int openmc_regular_mesh_set_params(
220 ✔
3130
  int32_t index, int n, const double* ll, const double* ur, const double* width)
3131
{
3132
  if (int err = check_mesh_type<RegularMesh>(index))
220 !
3133
    return err;
3134
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220 !
3135

3136
  if (m->n_dimension_ == -1) {
220 !
3137
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
3138
    return OPENMC_E_UNASSIGNED;
×
3139
  }
3140

3141
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220 ✔
3142
  if (ll && ur) {
220 ✔
3143
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198 ✔
3144
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198 ✔
3145
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792 ✔
3146
  } else if (ll && width) {
22 ✔
3147
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11 ✔
3148
    m->width_ = tensor::Tensor<double>(width, n);
11 ✔
3149
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44 ✔
3150
  } else if (ur && width) {
11 !
3151
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11 ✔
3152
    m->width_ = tensor::Tensor<double>(width, n);
11 ✔
3153
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44 ✔
3154
  } else {
3155
    set_errmsg("At least two parameters must be specified.");
×
3156
    return OPENMC_E_INVALID_ARGUMENT;
×
3157
  }
3158

3159
  // Set material volumes
3160

3161
  // TODO: incorporate this into method in RegularMesh that can be called from
3162
  // here and from constructor
3163
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220 ✔
3164
  m->element_volume_ = 1.0;
220 ✔
3165
  for (int i = 0; i < m->n_dimension_; i++) {
880 ✔
3166
    m->element_volume_ *= m->width_[i];
660 ✔
3167
  }
3168

3169
  return 0;
3170
}
220 ✔
3171

3172
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
3173
template<class C>
3174
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88 ✔
3175
  const int nx, const double* grid_y, const int ny, const double* grid_z,
3176
  const int nz)
3177
{
3178
  if (int err = check_mesh_type<C>(index))
88 !
3179
    return err;
3180

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

3183
  m->n_dimension_ = 3;
88 ✔
3184

3185
  m->grid_[0].reserve(nx);
88 ✔
3186
  m->grid_[1].reserve(ny);
88 ✔
3187
  m->grid_[2].reserve(nz);
88 ✔
3188

3189
  for (int i = 0; i < nx; i++) {
572 ✔
3190
    m->grid_[0].push_back(grid_x[i]);
484 ✔
3191
  }
3192
  for (int i = 0; i < ny; i++) {
341 ✔
3193
    m->grid_[1].push_back(grid_y[i]);
253 ✔
3194
  }
3195
  for (int i = 0; i < nz; i++) {
319 ✔
3196
    m->grid_[2].push_back(grid_z[i]);
231 ✔
3197
  }
3198

3199
  int err = m->set_grid();
88 ✔
3200
  return err;
88 ✔
3201
}
3202

3203
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
3204
template<class C>
3205
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385 ✔
3206
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3207
{
3208
  if (int err = check_mesh_type<C>(index))
385 !
3209
    return err;
3210
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385 !
3211

3212
  if (m->lower_left_.empty()) {
385 !
3213
    set_errmsg("Mesh parameters have not been set.");
×
3214
    return OPENMC_E_ALLOCATE;
×
3215
  }
3216

3217
  *grid_x = m->grid_[0].data();
385 ✔
3218
  *nx = m->grid_[0].size();
385 ✔
3219
  *grid_y = m->grid_[1].data();
385 ✔
3220
  *ny = m->grid_[1].size();
385 ✔
3221
  *grid_z = m->grid_[2].data();
385 ✔
3222
  *nz = m->grid_[2].size();
385 ✔
3223

3224
  return 0;
385 ✔
3225
}
3226

3227
//! Get the rectilinear mesh grid
3228
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143 ✔
3229
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3230
{
3231
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143 ✔
3232
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143 ✔
3233
}
3234

3235
//! Set the rectilienar mesh parameters
3236
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44 ✔
3237
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3238
  const double* grid_z, const int nz)
3239
{
3240
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44 ✔
3241
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44 ✔
3242
}
3243

3244
//! Get the cylindrical mesh grid
3245
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121 ✔
3246
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3247
{
3248
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121 ✔
3249
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121 ✔
3250
}
3251

3252
//! Set the cylindrical mesh parameters
3253
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22 ✔
3254
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3255
  const double* grid_z, const int nz)
3256
{
3257
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22 ✔
3258
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22 ✔
3259
}
3260

3261
//! Get the spherical mesh grid
3262
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121 ✔
3263
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3264
{
3265

3266
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121 ✔
3267
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121 ✔
3268
  ;
121 ✔
3269
}
3270

3271
//! Set the spherical mesh parameters
3272
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22 ✔
3273
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3274
  const double* grid_z, const int nz)
3275
{
3276
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22 ✔
3277
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22 ✔
3278
}
3279

3280
#ifdef OPENMC_DAGMC_ENABLED
3281

3282
const std::string MOABMesh::mesh_lib_type = "moab";
3283

3284
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24 ✔
3285
{
3286
  initialize();
24 ✔
3287
}
24 !
3288

3289
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
3290
{
3291
  initialize();
×
3292
}
×
3293

3294
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
3295
  : UnstructuredMesh()
×
3296
{
3297
  n_dimension_ = 3;
3298
  filename_ = filename;
×
3299
  set_length_multiplier(length_multiplier);
×
3300
  initialize();
×
3301
}
×
3302

3303
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1 ✔
3304
{
3305
  mbi_ = external_mbi;
1 ✔
3306
  filename_ = "unknown (external file)";
1 ✔
3307
  this->initialize();
1 ✔
3308
}
1 !
3309

3310
void MOABMesh::initialize()
25 ✔
3311
{
3312

3313
  // Create the MOAB interface and load data from file
3314
  this->create_interface();
25 ✔
3315

3316
  // Initialise MOAB error code
3317
  moab::ErrorCode rval = moab::MB_SUCCESS;
25 ✔
3318

3319
  // Set the dimension
3320
  n_dimension_ = 3;
25 ✔
3321

3322
  // set member range of tetrahedral entities
3323
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25 ✔
3324
  if (rval != moab::MB_SUCCESS) {
25 !
3325
    fatal_error("Failed to get all tetrahedral elements");
3326
  }
3327

3328
  if (!ehs_.all_of_type(moab::MBTET)) {
25 !
3329
    warning("Non-tetrahedral elements found in unstructured "
×
3330
            "mesh file: " +
3331
            filename_);
3332
  }
3333

3334
  // set member range of vertices
3335
  int vertex_dim = 0;
25 ✔
3336
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25 ✔
3337
  if (rval != moab::MB_SUCCESS) {
25 !
3338
    fatal_error("Failed to get all vertex handles");
3339
  }
3340

3341
  // make an entity set for all tetrahedra
3342
  // this is used for convenience later in output
3343
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25 ✔
3344
  if (rval != moab::MB_SUCCESS) {
25 !
3345
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3346
  }
3347

3348
  rval = mbi_->add_entities(tetset_, ehs_);
25 ✔
3349
  if (rval != moab::MB_SUCCESS) {
25 !
3350
    fatal_error("Failed to add tetrahedra to an entity set.");
3351
  }
3352

3353
  if (length_multiplier_ > 0.0) {
25 !
3354
    // get the connectivity of all tets
3355
    moab::Range adj;
×
3356
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
3357
    if (rval != moab::MB_SUCCESS) {
×
3358
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3359
    }
3360
    // scale all vertex coords by multiplier (done individually so not all
3361
    // coordinates are in memory twice at once)
3362
    for (auto vert : adj) {
×
3363
      // retrieve coords
3364
      std::array<double, 3> coord;
3365
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
3366
      if (rval != moab::MB_SUCCESS) {
×
3367
        fatal_error("Could not get coordinates of vertex.");
3368
      }
3369
      // scale coords
3370
      for (auto& c : coord) {
×
3371
        c *= length_multiplier_;
3372
      }
3373
      // set new coords
3374
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
3375
      if (rval != moab::MB_SUCCESS) {
×
3376
        fatal_error("Failed to set new vertex coordinates");
3377
      }
3378
    }
3379
  }
3380

3381
  // Determine bounds of mesh
3382
  this->determine_bounds();
25 ✔
3383
}
25 ✔
3384

3385
void MOABMesh::prepare_for_point_location()
21 ✔
3386
{
3387
  // if the KDTree has already been constructed, do nothing
3388
  if (kdtree_)
21 !
3389
    return;
3390

3391
  // build acceleration data structures
3392
  compute_barycentric_data(ehs_);
21 ✔
3393
  build_kdtree(ehs_);
21 ✔
3394
}
3395

3396
void MOABMesh::create_interface()
25 ✔
3397
{
3398
  // Do not create a MOAB instance if one is already in memory
3399
  if (mbi_)
25 ✔
3400
    return;
3401

3402
  // create MOAB instance
3403
  mbi_ = std::make_shared<moab::Core>();
24 !
3404

3405
  // load unstructured mesh file
3406
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24 ✔
3407
  if (rval != moab::MB_SUCCESS) {
24 !
3408
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3409
  }
3410
}
3411

3412
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21 ✔
3413
{
3414
  moab::Range all_tris;
21 ✔
3415
  int adj_dim = 2;
21 ✔
3416
  write_message("Getting tet adjacencies...", 7);
21 ✔
3417
  moab::ErrorCode rval = mbi_->get_adjacencies(
21 ✔
3418
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3419
  if (rval != moab::MB_SUCCESS) {
21 !
3420
    fatal_error("Failed to get adjacent triangles for tets");
3421
  }
3422

3423
  if (!all_tris.all_of_type(moab::MBTRI)) {
21 !
3424
    warning("Non-triangle elements found in tet adjacencies in "
×
3425
            "unstructured mesh file: " +
3426
            filename_);
×
3427
  }
3428

3429
  // combine into one range
3430
  moab::Range all_tets_and_tris;
21 ✔
3431
  all_tets_and_tris.merge(all_tets);
21 ✔
3432
  all_tets_and_tris.merge(all_tris);
21 ✔
3433

3434
  // create a kd-tree instance
3435
  write_message(
21 ✔
3436
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21 ✔
3437
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21 ✔
3438

3439
  // Determine what options to use
3440
  std::ostringstream options_stream;
21 ✔
3441
  if (options_.empty()) {
21 ✔
3442
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5 ✔
3443
  } else {
3444
    options_stream << options_;
16 ✔
3445
  }
3446
  moab::FileOptions file_opts(options_stream.str().c_str());
21 ✔
3447

3448
  // Build the k-d tree
3449
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21 ✔
3450
  if (rval != moab::MB_SUCCESS) {
21 !
3451
    fatal_error("Failed to construct KDTree for the "
3452
                "unstructured mesh file: " +
3453
                filename_);
×
3454
  }
3455
}
21 ✔
3456

3457
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584 ✔
3458
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3459
{
3460
  hits.clear();
1,543,584 !
3461

3462
  moab::ErrorCode rval;
1,543,584 ✔
3463
  vector<moab::EntityHandle> tris;
1,543,584 ✔
3464
  // get all intersections with triangles in the tet mesh
3465
  // (distances are relative to the start point, not the previous
3466
  // intersection)
3467
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584 ✔
3468
    dir.array(), start.array(), tris, hits, 0, track_len);
3469
  if (rval != moab::MB_SUCCESS) {
1,543,584 !
3470
    fatal_error(
3471
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3472
  }
3473

3474
  // remove duplicate intersection distances
3475
  std::unique(hits.begin(), hits.end());
1,543,584 ✔
3476

3477
  // sorts by first component of std::pair by default
3478
  std::sort(hits.begin(), hits.end());
1,543,584 ✔
3479
}
1,543,584 ✔
3480

3481
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584 ✔
3482
  vector<int>& bins, vector<double>& lengths) const
3483
{
3484
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584 ✔
3485
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584 ✔
3486
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584 ✔
3487
  dir.normalize();
1,543,584 ✔
3488

3489
  double track_len = (end - start).length();
1,543,584 ✔
3490
  if (track_len == 0.0)
1,543,584 !
3491
    return;
721,692 ✔
3492

3493
  start -= TINY_BIT * dir;
1,543,584 ✔
3494
  end += TINY_BIT * dir;
1,543,584 ✔
3495

3496
  vector<double> hits;
1,543,584 ✔
3497
  intersect_track(start, dir, track_len, hits);
1,543,584 ✔
3498

3499
  bins.clear();
1,543,584 !
3500
  lengths.clear();
1,543,584 !
3501

3502
  // if there are no intersections the track may lie entirely
3503
  // within a single tet. If this is the case, apply entire
3504
  // score to that tet and return.
3505
  if (hits.size() == 0) {
1,543,584 ✔
3506
    Position midpoint = r0 + u * (track_len * 0.5);
721,692 ✔
3507
    int bin = this->get_bin(midpoint);
721,692 ✔
3508
    if (bin != -1) {
721,692 ✔
3509
      bins.push_back(bin);
242,866 ✔
3510
      lengths.push_back(1.0);
242,866 ✔
3511
    }
3512
    return;
721,692 ✔
3513
  }
3514

3515
  // for each segment in the set of tracks, try to look up a tet
3516
  // at the midpoint of the segment
3517
  Position current = r0;
3518
  double last_dist = 0.0;
3519
  for (const auto& hit : hits) {
5,516,161 ✔
3520
    // get the segment length
3521
    double segment_length = hit - last_dist;
4,694,269 ✔
3522
    last_dist = hit;
4,694,269 ✔
3523
    // find the midpoint of this segment
3524
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269 ✔
3525
    // try to find a tet for this position
3526
    int bin = this->get_bin(midpoint);
4,694,269 ✔
3527

3528
    // determine the start point for this segment
3529
    current = r0 + u * hit;
4,694,269 ✔
3530

3531
    if (bin == -1) {
4,694,269 ✔
3532
      continue;
20,522 ✔
3533
    }
3534

3535
    bins.push_back(bin);
4,673,747 ✔
3536
    lengths.push_back(segment_length / track_len);
4,673,747 ✔
3537
  }
3538

3539
  // tally remaining portion of track after last hit if
3540
  // the last segment of the track is in the mesh but doesn't
3541
  // reach the other side of the tet
3542
  if (hits.back() < track_len) {
821,892 !
3543
    Position segment_start = r0 + u * hits.back();
821,892 ✔
3544
    double segment_length = track_len - hits.back();
821,892 ✔
3545
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892 ✔
3546
    int bin = this->get_bin(midpoint);
821,892 ✔
3547
    if (bin != -1) {
821,892 ✔
3548
      bins.push_back(bin);
766,509 ✔
3549
      lengths.push_back(segment_length / track_len);
766,509 ✔
3550
    }
3551
  }
3552
};
1,543,584 ✔
3553

3554
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232 ✔
3555
{
3556
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232 ✔
3557
  // find the leaf of the kd-tree for this position
3558
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232 ✔
3559
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232 ✔
3560
  if (rval != moab::MB_SUCCESS) {
7,317,232 ✔
3561
    return 0;
3562
  }
3563

3564
  // retrieve the tet elements of this leaf
3565
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335 ✔
3566
  moab::Range tets;
6,305,335 ✔
3567
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335 ✔
3568
  if (rval != moab::MB_SUCCESS) {
6,305,335 !
3569
    warning("MOAB error finding tets.");
×
3570
  }
3571

3572
  // loop over the tets in this leaf, returning the containing tet if found
3573
  for (const auto& tet : tets) {
260,211,273 ✔
3574
    if (point_in_tet(pos, tet)) {
260,208,426 ✔
3575
      return tet;
6,302,488 ✔
3576
    }
3577
  }
3578

3579
  // if no tet is found, return an invalid handle
3580
  return 0;
2,847 ✔
3581
}
14,634,464 ✔
3582

3583
double MOABMesh::volume(int bin) const
167,880 ✔
3584
{
3585
  return tet_volume(get_ent_handle_from_bin(bin));
167,880 ✔
3586
}
3587

3588
std::string MOABMesh::library() const
34 ✔
3589
{
3590
  return mesh_lib_type;
34 ✔
3591
}
3592

3593
// Sample position within a tet for MOAB type tets
3594
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410 ✔
3595
{
3596

3597
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410 ✔
3598

3599
  // Get vertex coordinates for MOAB tet
3600
  const moab::EntityHandle* conn1;
200,410 ✔
3601
  int conn1_size;
200,410 ✔
3602
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410 ✔
3603
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410 !
3604
    fatal_error(fmt::format(
3605
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3606
      conn1_size));
3607
  }
3608
  moab::CartVect p[4];
200,410 ✔
3609
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410 ✔
3610
  if (rval != moab::MB_SUCCESS) {
200,410 !
3611
    fatal_error("Failed to get tet coords");
3612
  }
3613

3614
  std::array<Position, 4> tet_verts;
200,410 ✔
3615
  for (int i = 0; i < 4; i++) {
1,002,050 ✔
3616
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640 ✔
3617
  }
3618
  // Samples position within tet using Barycentric stuff
3619
  return this->sample_tet(tet_verts, seed);
200,410 ✔
3620
}
3621

3622
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880 ✔
3623
{
3624
  vector<moab::EntityHandle> conn;
167,880 ✔
3625
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880 ✔
3626
  if (rval != moab::MB_SUCCESS) {
167,880 !
3627
    fatal_error("Failed to get tet connectivity");
3628
  }
3629

3630
  moab::CartVect p[4];
167,880 ✔
3631
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880 ✔
3632
  if (rval != moab::MB_SUCCESS) {
167,880 !
3633
    fatal_error("Failed to get tet coords");
3634
  }
3635

3636
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880 ✔
3637
}
167,880 ✔
3638

3639
int MOABMesh::get_bin(Position r) const
7,317,232 ✔
3640
{
3641
  moab::EntityHandle tet = get_tet(r);
7,317,232 ✔
3642
  if (tet == 0) {
7,317,232 ✔
3643
    return -1;
3644
  } else {
3645
    return get_bin_from_ent_handle(tet);
6,302,488 ✔
3646
  }
3647
}
3648

3649
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21 ✔
3650
{
3651
  moab::ErrorCode rval;
21 ✔
3652

3653
  baryc_data_.clear();
21 !
3654
  baryc_data_.resize(tets.size());
21 ✔
3655

3656
  // compute the barycentric data for each tet element
3657
  // and store it as a 3x3 matrix
3658
  for (auto& tet : tets) {
239,757 ✔
3659
    vector<moab::EntityHandle> verts;
239,736 ✔
3660
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736 ✔
3661
    if (rval != moab::MB_SUCCESS) {
239,736 !
3662
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3663
    }
3664

3665
    moab::CartVect p[4];
239,736 ✔
3666
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736 ✔
3667
    if (rval != moab::MB_SUCCESS) {
239,736 !
3668
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3669
    }
3670

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

3673
    // invert now to avoid this cost later
3674
    a = a.transpose().inverse();
239,736 ✔
3675
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736 ✔
3676
  }
239,736 ✔
3677
}
21 ✔
3678

3679
bool MOABMesh::point_in_tet(
260,208,426 ✔
3680
  const moab::CartVect& r, moab::EntityHandle tet) const
3681
{
3682

3683
  moab::ErrorCode rval;
260,208,426 ✔
3684

3685
  // get tet vertices
3686
  vector<moab::EntityHandle> verts;
260,208,426 ✔
3687
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426 ✔
3688
  if (rval != moab::MB_SUCCESS) {
260,208,426 !
3689
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3690
    return false;
3691
  }
3692

3693
  // first vertex is used as a reference point for the barycentric data -
3694
  // retrieve its coordinates
3695
  moab::CartVect p_zero;
260,208,426 ✔
3696
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426 ✔
3697
  if (rval != moab::MB_SUCCESS) {
260,208,426 !
3698
    warning("Failed to get coordinates of a vertex in "
×
3699
            "unstructured mesh: " +
3700
            filename_);
×
3701
    return false;
3702
  }
3703

3704
  // look up barycentric data
3705
  int idx = get_bin_from_ent_handle(tet);
260,208,426 ✔
3706
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426 ✔
3707

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

3710
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987 ✔
3711
          bary_coords[2] >= 0.0 &&
318,957,185 ✔
3712
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225 ✔
3713
}
260,208,426 ✔
3714

3715
int MOABMesh::get_bin_from_index(int idx) const
3716
{
3717
  if (idx >= n_bins()) {
×
3718
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3719
  }
3720
  return ehs_[idx] - ehs_[0];
3721
}
3722

3723
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3724
{
3725
  int bin = get_bin(r);
3726
  *in_mesh = bin != -1;
3727
  return bin;
3728
}
3729

3730
int MOABMesh::get_index_from_bin(int bin) const
3731
{
3732
  return bin;
3733
}
3734

3735
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3736
  Position plot_ll, Position plot_ur) const
3737
{
3738
  // TODO: Implement mesh lines
3739
  return {};
3740
}
3741

3742
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520 ✔
3743
{
3744
  int idx = vert - verts_[0];
815,520 ✔
3745
  if (idx >= n_vertices()) {
815,520 !
3746
    fatal_error(
3747
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3748
  }
3749
  return idx;
815,520 ✔
3750
}
3751

3752
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650 ✔
3753
{
3754
  int bin = eh - ehs_[0];
266,750,650 ✔
3755
  if (bin >= n_bins()) {
266,750,650 !
3756
    fatal_error(fmt::format("Invalid bin: {}", bin));
3757
  }
3758
  return bin;
266,750,650 ✔
3759
}
3760

3761
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170 ✔
3762
{
3763
  if (bin >= n_bins()) {
572,170 !
3764
    fatal_error(fmt::format("Invalid bin index: ", bin));
3765
  }
3766
  return ehs_[0] + bin;
572,170 ✔
3767
}
3768

3769
int MOABMesh::n_bins() const
267,526,773 ✔
3770
{
3771
  return ehs_.size();
267,526,773 ✔
3772
}
3773

3774
int MOABMesh::n_surface_bins() const
3775
{
3776
  // collect all triangles in the set of tets for this mesh
3777
  moab::Range tris;
×
3778
  moab::ErrorCode rval;
3779
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3780
  if (rval != moab::MB_SUCCESS) {
×
3781
    warning("Failed to get all triangles in the mesh instance");
×
3782
    return -1;
3783
  }
3784
  return 2 * tris.size();
×
3785
}
3786

3787
Position MOABMesh::centroid(int bin) const
3788
{
3789
  moab::ErrorCode rval;
3790

3791
  auto tet = this->get_ent_handle_from_bin(bin);
3792

3793
  // look up the tet connectivity
3794
  vector<moab::EntityHandle> conn;
×
3795
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3796
  if (rval != moab::MB_SUCCESS) {
×
3797
    warning("Failed to get connectivity of a mesh element.");
×
3798
    return {};
3799
  }
3800

3801
  // get the coordinates
3802
  vector<moab::CartVect> coords(conn.size());
×
3803
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3804
  if (rval != moab::MB_SUCCESS) {
×
3805
    warning("Failed to get the coordinates of a mesh element.");
×
3806
    return {};
3807
  }
3808

3809
  // compute the centroid of the element vertices
3810
  moab::CartVect centroid(0.0, 0.0, 0.0);
3811
  for (const auto& coord : coords) {
×
3812
    centroid += coord;
3813
  }
3814
  centroid /= double(coords.size());
3815

3816
  return {centroid[0], centroid[1], centroid[2]};
3817
}
3818

3819
int MOABMesh::n_vertices() const
845,874 ✔
3820
{
3821
  return verts_.size();
845,874 ✔
3822
}
3823

3824
Position MOABMesh::vertex(int id) const
86,227 ✔
3825
{
3826

3827
  moab::ErrorCode rval;
86,227 ✔
3828

3829
  moab::EntityHandle vert = verts_[id];
86,227 ✔
3830

3831
  moab::CartVect coords;
86,227 ✔
3832
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227 ✔
3833
  if (rval != moab::MB_SUCCESS) {
86,227 !
3834
    fatal_error("Failed to get the coordinates of a vertex.");
3835
  }
3836

3837
  return {coords[0], coords[1], coords[2]};
86,227 ✔
3838
}
3839

3840
std::vector<int> MOABMesh::connectivity(int bin) const
203,880 ✔
3841
{
3842
  moab::ErrorCode rval;
203,880 ✔
3843

3844
  auto tet = get_ent_handle_from_bin(bin);
203,880 ✔
3845

3846
  // look up the tet connectivity
3847
  vector<moab::EntityHandle> conn;
203,880 ✔
3848
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880 ✔
3849
  if (rval != moab::MB_SUCCESS) {
203,880 !
3850
    fatal_error("Failed to get connectivity of a mesh element.");
3851
    return {};
3852
  }
3853

3854
  std::vector<int> verts(4);
203,880 ✔
3855
  for (int i = 0; i < verts.size(); i++) {
1,019,400 ✔
3856
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520 ✔
3857
  }
3858

3859
  return verts;
203,880 ✔
3860
}
203,880 ✔
3861

3862
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3863
  std::string score) const
3864
{
3865
  moab::ErrorCode rval;
3866
  // add a tag to the mesh
3867
  // all scores are treated as a single value
3868
  // with an uncertainty
3869
  moab::Tag value_tag;
3870

3871
  // create the value tag if not present and get handle
3872
  double default_val = 0.0;
3873
  auto val_string = score + "_mean";
3874
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3875
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3876
  if (rval != moab::MB_SUCCESS) {
×
3877
    auto msg =
3878
      fmt::format("Could not create or retrieve the value tag for the score {}"
3879
                  " on unstructured mesh {}",
3880
        score, id_);
×
3881
    fatal_error(msg);
3882
  }
3883

3884
  // create the std dev tag if not present and get handle
3885
  moab::Tag error_tag;
3886
  std::string err_string = score + "_std_dev";
×
3887
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3888
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3889
  if (rval != moab::MB_SUCCESS) {
×
3890
    auto msg =
3891
      fmt::format("Could not create or retrieve the error tag for the score {}"
3892
                  " on unstructured mesh {}",
3893
        score, id_);
×
3894
    fatal_error(msg);
3895
  }
3896

3897
  // return the populated tag handles
3898
  return {value_tag, error_tag};
3899
}
3900

3901
void MOABMesh::add_score(const std::string& score)
3902
{
3903
  auto score_tags = get_score_tags(score);
×
3904
  tag_names_.push_back(score);
3905
}
3906

3907
void MOABMesh::remove_scores()
3908
{
3909
  for (const auto& name : tag_names_) {
×
3910
    auto value_name = name + "_mean";
3911
    moab::Tag tag;
3912
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3913
    if (rval != moab::MB_SUCCESS)
×
3914
      return;
3915

3916
    rval = mbi_->tag_delete(tag);
×
3917
    if (rval != moab::MB_SUCCESS) {
×
3918
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3919
                             " on unstructured mesh {}",
3920
        name, id_);
×
3921
      fatal_error(msg);
3922
    }
3923

3924
    auto std_dev_name = name + "_std_dev";
×
3925
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3926
    if (rval != moab::MB_SUCCESS) {
×
3927
      auto msg =
3928
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3929
                    " on unstructured mesh {}",
3930
          name, id_);
×
3931
    }
3932

3933
    rval = mbi_->tag_delete(tag);
×
3934
    if (rval != moab::MB_SUCCESS) {
×
3935
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3936
                             " on unstructured mesh {}",
3937
        name, id_);
×
3938
      fatal_error(msg);
3939
    }
3940
  }
3941
  tag_names_.clear();
3942
}
3943

3944
void MOABMesh::set_score_data(const std::string& score,
3945
  const vector<double>& values, const vector<double>& std_dev)
3946
{
3947
  auto score_tags = this->get_score_tags(score);
×
3948

3949
  moab::ErrorCode rval;
3950
  // set the score value
3951
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3952
  if (rval != moab::MB_SUCCESS) {
×
3953
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3954
                           "on unstructured mesh {}",
3955
      score, id_);
3956
    warning(msg);
×
3957
  }
3958

3959
  // set the error value
3960
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3961
  if (rval != moab::MB_SUCCESS) {
×
3962
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3963
                           "on unstructured mesh {}",
3964
      score, id_);
3965
    warning(msg);
×
3966
  }
3967
}
3968

3969
void MOABMesh::write(const std::string& base_filename) const
3970
{
3971
  // add extension to the base name
3972
  auto filename = base_filename + ".vtk";
3973
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3974
  filename = settings::path_output + filename;
×
3975

3976
  // write the tetrahedral elements of the mesh only
3977
  // to avoid clutter from zero-value data on other
3978
  // elements during visualization
3979
  moab::ErrorCode rval;
3980
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3981
  if (rval != moab::MB_SUCCESS) {
×
3982
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3983
    warning(msg);
×
3984
  }
3985
}
3986

3987
#endif
3988

3989
#ifdef OPENMC_LIBMESH_ENABLED
3990

3991
const std::string LibMesh::mesh_lib_type = "libmesh";
3992

3993
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23 ✔
3994
{
3995
  // filename_ and length_multiplier_ will already be set by the
3996
  // UnstructuredMesh constructor
3997
  set_mesh_pointer_from_filename(filename_);
23 ✔
3998
  set_length_multiplier(length_multiplier_);
23 ✔
3999
  initialize();
23 ✔
4000
}
23 ✔
4001

4002
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
4003
{
4004
  // filename_ and length_multiplier_ will already be set by the
4005
  // UnstructuredMesh constructor
4006
  set_mesh_pointer_from_filename(filename_);
×
4007
  set_length_multiplier(length_multiplier_);
×
4008
  initialize();
×
4009
}
4010

4011
// create the mesh from a pointer to a libMesh Mesh
4012
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
4013
{
4014
  if (!input_mesh.is_replicated()) {
×
4015
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
4016
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
4017
  }
4018

4019
  m_ = &input_mesh;
4020
  set_length_multiplier(length_multiplier);
×
4021
  initialize();
×
4022
}
4023

4024
// create the mesh from an input file
4025
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
4026
{
4027
  n_dimension_ = 3;
4028
  set_mesh_pointer_from_filename(filename);
×
4029
  set_length_multiplier(length_multiplier);
×
4030
  initialize();
×
4031
}
4032

4033
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23 ✔
4034
{
4035
  filename_ = filename;
23 ✔
4036
  unique_m_ =
23 ✔
4037
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23 ✔
4038
  m_ = unique_m_.get();
23 ✔
4039
  m_->read(filename_);
23 ✔
4040
}
23 ✔
4041

4042
// build a libMesh equation system for storing values
4043
void LibMesh::build_eqn_sys()
15 ✔
4044
{
4045
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
15 ✔
4046
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15 ✔
4047
  libMesh::ExplicitSystem& eq_sys =
15 ✔
4048
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15 ✔
4049
}
15 ✔
4050

4051
// intialize from mesh file
4052
void LibMesh::initialize()
23 ✔
4053
{
4054
  if (!settings::libmesh_comm) {
23 !
4055
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
4056
                "communicator.");
4057
  }
4058

4059
  // assuming that unstructured meshes used in OpenMC are 3D
4060
  n_dimension_ = 3;
23 ✔
4061

4062
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
4063
  // Otherwise assume that it is prepared by its owning application
4064
  if (unique_m_) {
23 !
4065
    m_->prepare_for_use();
23 ✔
4066
  }
4067

4068
  // ensure that the loaded mesh is 3 dimensional
4069
  if (m_->mesh_dimension() != n_dimension_) {
23 !
4070
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
4071
                            "mesh is not a 3D mesh.",
4072
      filename_));
4073
  }
4074

4075
  for (int i = 0; i < num_threads(); i++) {
69 ✔
4076
    pl_.emplace_back(m_->sub_point_locator());
46 ✔
4077
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46 ✔
4078
    pl_.back()->enable_out_of_mesh_mode();
46 ✔
4079
  }
4080

4081
  // store first element in the mesh to use as an offset for bin indices
4082
  auto first_elem = *m_->elements_begin();
46 ✔
4083
  first_element_id_ = first_elem->id();
23 ✔
4084

4085
  // bounding box for the mesh for quick rejection checks
4086
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23 !
4087
  libMesh::Point ll = bbox_.min();
23 !
4088
  libMesh::Point ur = bbox_.max();
23 !
4089
  if (length_multiplier_ > 0.0) {
23 !
4090
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
4091
      length_multiplier_ * ll(2)};
4092
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
4093
      length_multiplier_ * ur(2)};
4094
  } else {
4095
    lower_left_ = {ll(0), ll(1), ll(2)};
23 ✔
4096
    upper_right_ = {ur(0), ur(1), ur(2)};
23 ✔
4097
  }
4098
}
23 ✔
4099

4100
// Sample position within a tet for LibMesh type tets
4101
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820 ✔
4102
{
4103
  const auto& elem = get_element_from_bin(bin);
400,820 ✔
4104
  // Get tet vertex coordinates from LibMesh
4105
  std::array<Position, 4> tet_verts;
400,820 ✔
4106
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100 ✔
4107
    auto node_ref = elem.node_ref(i);
1,603,280 ✔
4108
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280 ✔
4109
  }
1,603,280 ✔
4110
  // Samples position within tet using Barycentric coordinates
4111
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820 ✔
4112
  if (length_multiplier_ > 0.0) {
400,820 !
4113
    return length_multiplier_ * sampled_position;
4114
  } else {
4115
    return sampled_position;
400,820 ✔
4116
  }
4117
}
4118

4119
Position LibMesh::centroid(int bin) const
4120
{
4121
  const auto& elem = this->get_element_from_bin(bin);
4122
  auto centroid = elem.vertex_average();
4123
  if (length_multiplier_ > 0.0) {
×
4124
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
4125
  } else {
4126
    return {centroid(0), centroid(1), centroid(2)};
4127
  }
4128
}
4129

4130
int LibMesh::n_vertices() const
39,978 ✔
4131
{
4132
  return m_->n_nodes();
39,978 ✔
4133
}
4134

4135
Position LibMesh::vertex(int vertex_id) const
39,942 ✔
4136
{
4137
  const auto node_ref = m_->node_ref(vertex_id);
39,942 ✔
4138
  if (length_multiplier_ > 0.0) {
39,942 !
4139
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
4140
  } else {
4141
    return {node_ref(0), node_ref(1), node_ref(2)};
39,942 ✔
4142
  }
4143
}
39,942 ✔
4144

4145
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856 ✔
4146
{
4147
  std::vector<int> conn;
265,856 ✔
4148
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856 ✔
4149
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280 ✔
4150
    conn.push_back(elem_ptr->node_id(i));
1,071,424 ✔
4151
  }
4152
  return conn;
265,856 ✔
4153
}
4154

4155
std::string LibMesh::library() const
33 ✔
4156
{
4157
  return mesh_lib_type;
33 ✔
4158
}
4159

4160
int LibMesh::n_bins() const
1,784,407 ✔
4161
{
4162
  return m_->n_elem();
1,784,407 ✔
4163
}
4164

4165
int LibMesh::n_surface_bins() const
4166
{
4167
  int n_bins = 0;
4168
  for (int i = 0; i < this->n_bins(); i++) {
×
4169
    const libMesh::Elem& e = get_element_from_bin(i);
4170
    n_bins += e.n_faces();
4171
    // if this is a boundary element, it will only be visited once,
4172
    // the number of surface bins is incremented to
4173
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
4174
      // null neighbor pointer indicates a boundary face
4175
      if (!neighbor_ptr) {
×
4176
        n_bins++;
4177
      }
4178
    }
4179
  }
4180
  return n_bins;
4181
}
4182

4183
void LibMesh::add_score(const std::string& var_name)
15 ✔
4184
{
4185
  if (!equation_systems_) {
15 !
4186
    build_eqn_sys();
15 ✔
4187
  }
4188

4189
  // check if this is a new variable
4190
  std::string value_name = var_name + "_mean";
15 ✔
4191
  if (!variable_map_.count(value_name)) {
15 ✔
4192
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15 ✔
4193
    auto var_num =
15 ✔
4194
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15 ✔
4195
    variable_map_[value_name] = var_num;
15 ✔
4196
  }
4197

4198
  std::string std_dev_name = var_name + "_std_dev";
15 ✔
4199
  // check if this is a new variable
4200
  if (!variable_map_.count(std_dev_name)) {
15 ✔
4201
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15 ✔
4202
    auto var_num =
15 ✔
4203
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15 ✔
4204
    variable_map_[std_dev_name] = var_num;
15 ✔
4205
  }
4206
}
15 ✔
4207

4208
void LibMesh::remove_scores()
15 ✔
4209
{
4210
  if (equation_systems_) {
15 !
4211
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15 ✔
4212
    eqn_sys.clear();
15 ✔
4213
    variable_map_.clear();
15 ✔
4214
  }
4215
}
15 ✔
4216

4217
void LibMesh::set_score_data(const std::string& var_name,
15 ✔
4218
  const vector<double>& values, const vector<double>& std_dev)
4219
{
4220
  if (!equation_systems_) {
15 !
4221
    build_eqn_sys();
4222
  }
4223

4224
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15 ✔
4225

4226
  if (!eqn_sys.is_initialized()) {
15 !
4227
    equation_systems_->init();
15 ✔
4228
  }
4229

4230
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15 ✔
4231

4232
  // look up the value variable
4233
  std::string value_name = var_name + "_mean";
15 ✔
4234
  unsigned int value_num = variable_map_.at(value_name);
15 ✔
4235
  // look up the std dev variable
4236
  std::string std_dev_name = var_name + "_std_dev";
15 ✔
4237
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15 ✔
4238

4239
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
195,757 ✔
4240
       it++) {
4241
    if (!(*it)->active()) {
97,856 !
4242
      continue;
4243
    }
4244

4245
    auto bin = get_bin_from_element(*it);
97,856 ✔
4246

4247
    // set value
4248
    vector<libMesh::dof_id_type> value_dof_indices;
97,856 ✔
4249
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856 ✔
4250
    assert(value_dof_indices.size() == 1);
97,856 ✔
4251
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856 ✔
4252

4253
    // set std dev
4254
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856 ✔
4255
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856 ✔
4256
    assert(std_dev_dof_indices.size() == 1);
97,856 ✔
4257
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856 ✔
4258
  }
97,871 ✔
4259
}
15 ✔
4260

4261
void LibMesh::write(const std::string& filename) const
15 ✔
4262
{
4263
  write_message(fmt::format(
15 ✔
4264
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15 ✔
4265
  libMesh::ExodusII_IO exo(*m_);
15 ✔
4266
  std::set<std::string> systems_out = {eq_system_name_};
30 !
4267
  exo.write_discontinuous_exodusII(
15 ✔
4268
    filename + ".e", *equation_systems_, &systems_out);
30 ✔
4269
}
15 ✔
4270

4271
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
4272
  vector<int>& bins, vector<double>& lengths) const
4273
{
4274
  // TODO: Implement triangle crossings here
4275
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
4276
}
4277

4278
int LibMesh::get_bin(Position r) const
2,340,604 ✔
4279
{
4280
  // look-up a tet using the point locator
4281
  libMesh::Point p(r.x, r.y, r.z);
2,340,604 !
4282

4283
  if (length_multiplier_ > 0.0) {
2,340,604 !
4284
    // Scale the point down
4285
    p /= length_multiplier_;
2,340,604 ✔
4286
  }
4287

4288
  // quick rejection check
4289
  if (!bbox_.contains_point(p)) {
2,340,604 ✔
4290
    return -1;
4291
  }
4292

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

4295
  const auto elem_ptr = (*point_locator)(p);
1,421,808 ✔
4296
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808 ✔
4297
}
2,340,604 ✔
4298

4299
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,434 ✔
4300
{
4301
  int bin = elem->id() - first_element_id_;
1,518,434 ✔
4302
  if (bin >= n_bins() || bin < 0) {
1,518,434 !
4303
    fatal_error(fmt::format("Invalid bin: {}", bin));
4304
  }
4305
  return bin;
1,518,434 ✔
4306
}
4307

4308
std::pair<vector<double>, vector<double>> LibMesh::plot(
4309
  Position plot_ll, Position plot_ur) const
4310
{
4311
  return {};
4312
}
4313

4314
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460 ✔
4315
{
4316
  return m_->elem_ref(bin);
765,460 ✔
4317
}
4318

4319
double LibMesh::volume(int bin) const
364,640 ✔
4320
{
4321
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
364,640 ✔
4322
         length_multiplier_ * length_multiplier_;
364,640 ✔
4323
}
4324

4325
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4326
  double length_multiplier,
4327
  const std::set<libMesh::subdomain_id_type>& block_ids)
4328
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4329
    block_restrict_(!block_ids_.empty()),
×
4330
    num_active_(
×
4331
      block_restrict_
4332
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
4333
            m_->active_subdomain_set_elements_end(block_ids_))
×
4334
        : m_->n_active_elem())
×
4335
{
4336
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4337
  // contiguous in ID space, so we need to map from bin indices (defined over
4338
  // active elements) to global dof ids
4339
  bin_to_elem_map_.reserve(num_active_);
×
4340
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
4341
  auto begin = block_restrict_
4342
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
4343
                 : m_->active_elements_begin();
×
4344
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
4345
                             : m_->active_elements_end();
×
4346
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
4347
    bin_to_elem_map_.push_back(elem->id());
×
4348
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
4349
  }
4350
}
4351

4352
int AdaptiveLibMesh::n_bins() const
4353
{
4354
  return num_active_;
4355
}
4356

4357
void AdaptiveLibMesh::add_score(const std::string& var_name)
4358
{
4359
  warning(fmt::format(
×
4360
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4361
    this->id_));
4362
}
4363

4364
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4365
  const vector<double>& values, const vector<double>& std_dev)
4366
{
4367
  warning(fmt::format(
×
4368
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4369
    this->id_));
4370
}
4371

4372
void AdaptiveLibMesh::write(const std::string& filename) const
4373
{
4374
  warning(fmt::format(
×
4375
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4376
    this->id_));
4377
}
4378

4379
int AdaptiveLibMesh::get_bin(Position r) const
4380
{
4381
  // look-up a tet using the point locator
4382
  libMesh::Point p(r.x, r.y, r.z);
×
4383

4384
  if (length_multiplier_ > 0.0) {
×
4385
    // Scale the point down
4386
    p /= length_multiplier_;
4387
  }
4388

4389
  // quick rejection check
4390
  if (!bbox_.contains_point(p)) {
×
4391
    return -1;
4392
  }
4393

4394
  const auto& point_locator = pl_.at(thread_num());
×
4395

4396
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4397
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4398
}
4399

4400
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4401
{
4402
  int bin = elem_to_bin_map_[elem->id()];
4403
  if (bin >= n_bins() || bin < 0) {
×
4404
    fatal_error(fmt::format("Invalid bin: {}", bin));
4405
  }
4406
  return bin;
4407
}
4408

4409
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4410
{
4411
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4412
}
4413

4414
#endif // OPENMC_LIBMESH_ENABLED
4415

4416
//==============================================================================
4417
// Non-member functions
4418
//==============================================================================
4419

4420
void read_meshes(pugi::xml_node root)
12,775 ✔
4421
{
4422
  std::unordered_set<int> mesh_ids;
12,775 ✔
4423

4424
  for (auto node : root.children("mesh")) {
15,826 ✔
4425
    // Check to make sure multiple meshes in the same file don't share IDs
4426
    int id = std::stoi(get_node_value(node, "id"));
6,102 ✔
4427
    if (contains(mesh_ids, id)) {
6,102 !
4428
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4429
                              "'{}' in the same input file",
4430
        id));
4431
    }
4432
    mesh_ids.insert(id);
3,051 ✔
4433

4434
    // If we've already read a mesh with the same ID in a *different* file,
4435
    // assume it is the same here
4436
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,051 !
4437
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4438
      continue;
×
4439
    }
4440

4441
    std::string mesh_type;
3,051 ✔
4442
    if (check_for_node(node, "type")) {
3,051 ✔
4443
      mesh_type = get_node_value(node, "type", true, true);
1,014 ✔
4444
    } else {
4445
      mesh_type = "regular";
2,037 ✔
4446
    }
4447

4448
    // determine the mesh library to use
4449
    std::string mesh_lib;
3,051 ✔
4450
    if (check_for_node(node, "library")) {
3,051 ✔
4451
      mesh_lib = get_node_value(node, "library", true, true);
47 !
4452
    }
4453

4454
    Mesh::create(node, mesh_type, mesh_lib);
3,051 ✔
4455
  }
3,051 ✔
4456
}
12,775 ✔
4457

4458
void read_meshes(hid_t group)
22 ✔
4459
{
4460
  std::unordered_set<int> mesh_ids;
22 ✔
4461

4462
  std::vector<int> ids;
22 ✔
4463
  read_attribute(group, "ids", ids);
22 ✔
4464

4465
  for (auto id : ids) {
55 ✔
4466

4467
    // Check to make sure multiple meshes in the same file don't share IDs
4468
    if (contains(mesh_ids, id)) {
66 !
4469
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4470
                              "'{}' in the same HDF5 input file",
4471
        id));
4472
    }
4473
    mesh_ids.insert(id);
33 ✔
4474

4475
    // If we've already read a mesh with the same ID in a *different* file,
4476
    // assume it is the same here
4477
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33 !
4478
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33 ✔
4479
      continue;
33 ✔
4480
    }
4481

4482
    std::string name = fmt::format("mesh {}", id);
×
4483
    hid_t mesh_group = open_group(group, name.c_str());
×
4484

4485
    std::string mesh_type;
×
4486
    if (object_exists(mesh_group, "type")) {
×
4487
      read_dataset(mesh_group, "type", mesh_type);
×
4488
    } else {
4489
      mesh_type = "regular";
×
4490
    }
4491

4492
    // determine the mesh library to use
4493
    std::string mesh_lib;
×
4494
    if (object_exists(mesh_group, "library")) {
×
4495
      read_dataset(mesh_group, "library", mesh_lib);
×
4496
    }
4497

4498
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4499
  }
×
4500
}
44 ✔
4501

4502
void meshes_to_hdf5(hid_t group)
7,120 ✔
4503
{
4504
  // Write number of meshes
4505
  hid_t meshes_group = create_group(group, "meshes");
7,120 ✔
4506
  int32_t n_meshes = model::meshes.size();
7,120 ✔
4507
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,120 ✔
4508

4509
  if (n_meshes > 0) {
7,120 ✔
4510
    // Write IDs of meshes
4511
    vector<int> ids;
2,236 ✔
4512
    for (const auto& m : model::meshes) {
5,051 ✔
4513
      m->to_hdf5(meshes_group);
2,815 ✔
4514
      ids.push_back(m->id_);
2,815 ✔
4515
    }
4516
    write_attribute(meshes_group, "ids", ids);
2,236 ✔
4517
  }
2,236 ✔
4518

4519
  close_group(meshes_group);
7,120 ✔
4520
}
7,120 ✔
4521

4522
void free_memory_mesh()
8,355 ✔
4523
{
4524
  model::meshes.clear();
8,355 ✔
4525
  model::mesh_map.clear();
8,355 ✔
4526
}
8,355 ✔
4527

4528
extern "C" int n_meshes()
308 ✔
4529
{
4530
  return model::meshes.size();
308 ✔
4531
}
4532

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

© 2026 Coveralls, Inc