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

openmc-dev / openmc / 22917034411

10 Mar 2026 06:03PM UTC coverage: 81.502%. First build
22917034411

Pull #3857

github

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

17740 of 25558 branches covered (69.41%)

Branch coverage included in aggregate %.

419 of 501 new or added lines in 5 files covered. (83.63%)

58275 of 67710 relevant lines covered (86.07%)

44657209.84 hits per line

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

70.59
/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,523✔
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,523✔
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)
36,734,854✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
32,641✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
36,734,736✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
36,734,736✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
36,734,736✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
36,734,736✔
155
  double current = bit_cast_value<double>(current_bits);
36,734,736✔
156
  while (is_min ? (value < current) : (value > current)) {
36,734,854✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
32,641✔
158
    uint64_t expected_bits = current_bits;
32,641✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
32,641✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
36,734,736✔
162
    }
163
    current_bits = expected_bits;
118✔
164
    current = bit_cast_value<double>(current_bits);
118✔
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,367,368✔
188
{
189
  atomic_update_double(ptr, value, false);
6,122,456✔
190
}
6,122,456✔
191

192
inline void atomic_min_double(double* ptr, double value)
18,367,368✔
193
{
194
  atomic_update_double(ptr, value, true);
6,122,456✔
195
}
196

197
namespace detail {
198

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

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

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

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

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,523!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,523✔
242
      bool claimed_slot =
1,523✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,523✔
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,523!
248
#pragma omp atomic
843✔
249
        this->volumes(index_elem, slot) += volume;
1,523✔
250
        if (bbox) {
1,523✔
251
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
126✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
126✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
126✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
126✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
126✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
126✔
257
        }
258
        return;
1,523✔
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,611,057✔
542
            // Ray trace from r_start to r_end
543
            Position r0 = p.r();
3,766,931✔
544
            double max_distance = bbox.max[axis] - r0[axis];
3,766,931✔
545

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

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

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

558
            // Add volumes to any mesh elements that were crossed
559
            int i_material = p.material();
3,766,931✔
560
            if (i_material != C_NONE) {
3,766,931✔
561
              i_material = model::materials[i_material]->id();
1,105,133✔
562
            }
563
            double cumulative_frac = 0.0;
3,766,931✔
564
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
7,752,512✔
565
              int mesh_index = bins[i_bin];
3,985,581✔
566
              double length = distance * length_fractions[i_bin];
3,985,581✔
567
              double volume = length * d1 * d2;
3,985,581✔
568

569
              if (compute_bboxes) {
3,985,581✔
570
                double axis_start = r0[axis] + distance * cumulative_frac;
2,779,496✔
571
                double axis_end = axis_start + length;
2,779,496✔
572
                cumulative_frac += length_fractions[i_bin];
2,779,496✔
573

574
                Position contrib_min = site.r;
2,779,496✔
575
                Position contrib_max = site.r;
2,779,496✔
576

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

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

587
                result.add_volume(
2,779,496✔
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,766,931✔
596
              break;
597

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

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

608
            if (boundary.lattice_translation()[0] != 0 ||
844,126!
609
                boundary.lattice_translation()[1] != 0 ||
844,126!
610
                boundary.lattice_translation()[2] != 0) {
844,126!
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()};
844,126✔
616
              p.cross_surface(*surf);
844,126✔
617
            }
618
          }
844,126✔
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,656✔
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,656✔
793
  double x_max = positive_grid_boundary(ijk, 0);
1,431,656✔
794

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

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

801
  return {x_min + (x_max - x_min) * prn(seed),
1,431,656✔
802
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,431,656✔
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;
300,418✔
923
    t = 1.0 - t;
300,418✔
924
  }
925
  if (s + t + u > 1) {
601,230✔
926
    if (t + u > 1) {
400,449✔
927
      double old_t = t;
200,459✔
928
      t = 1.0 - u;
200,459✔
929
      u = 1.0 - s - old_t;
200,459✔
930
    } else if (t + u <= 1) {
199,990!
931
      double old_s = s;
199,990✔
932
      s = 1.0 - t - u;
199,990✔
933
      u = old_s + t + u - 1;
199,990✔
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,087,654✔
1039
  Position r, bool& in_mesh) const
1040
{
1041
  MeshIndex ijk;
1,191,087,654✔
1042
  in_mesh = true;
1,191,087,654✔
1043
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1044
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1045

1046
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1047
      in_mesh = false;
102,653,580✔
1048
  }
1049
  return ijk;
1,191,087,654✔
1050
}
1051

1052
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,753,999,356✔
1053
{
1054
  switch (n_dimension_) {
1,753,999,356!
1055
  case 1:
880,605✔
1056
    return ijk[0] - 1;
880,605✔
1057
  case 2:
136,375,228✔
1058
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
136,375,228✔
1059
  case 3:
1,616,743,523✔
1060
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,616,743,523✔
1061
  default:
×
1062
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1063
  }
1064
}
1065

1066
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,768,791✔
1067
{
1068
  MeshIndex ijk;
7,768,791✔
1069
  if (n_dimension_ == 1) {
7,768,791✔
1070
    ijk[0] = bin + 1;
275✔
1071
  } else if (n_dimension_ == 2) {
7,768,516✔
1072
    ijk[0] = bin % shape_[0] + 1;
15,664✔
1073
    ijk[1] = bin / shape_[0] + 1;
15,664✔
1074
  } else if (n_dimension_ == 3) {
7,752,852!
1075
    ijk[0] = bin % shape_[0] + 1;
7,752,852✔
1076
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,752,852✔
1077
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,752,852✔
1078
  }
1079
  return ijk;
7,768,791✔
1080
}
1081

1082
int StructuredMesh::get_bin(Position r) const
256,670,746✔
1083
{
1084
  // Determine indices
1085
  bool in_mesh;
256,670,746✔
1086
  MeshIndex ijk = get_indices(r, in_mesh);
256,670,746✔
1087
  if (!in_mesh)
256,670,746✔
1088
    return -1;
1089

1090
  // Convert indices to bin
1091
  return get_bin_from_indices(ijk);
235,624,898✔
1092
}
1093

1094
int StructuredMesh::n_bins() const
1,125,575✔
1095
{
1096
  return std::accumulate(
2,251,150✔
1097
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,125,575✔
1098
}
1099

1100
int StructuredMesh::n_surface_bins() const
392✔
1101
{
1102
  return 4 * n_dimension_ * n_bins();
392✔
1103
}
1104

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

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

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

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

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

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

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

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

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

1151
  return counts;
×
1152
}
×
1153

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

1167
  // Compute the length of the entire track.
1168
  double total_distance = (r1 - r0).norm();
944,581,543✔
1169
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
944,581,543✔
1170
    return;
1171

1172
  // keep a copy of the original global position to pass to get_indices,
1173
  // which performs its own transformation to local coordinates
1174
  Position global_r = r0;
932,489,807✔
1175
  Position local_r = local_coords(r0);
932,489,807✔
1176

1177
  const int n = n_dimension_;
932,489,807✔
1178

1179
  // Flag if position is inside the mesh
1180
  bool inside_mesh;
1181

1182
  // Position is r = r0 + u * traveled_distance, start at r0
1183
  double traveled_distance {0.0};
932,489,807✔
1184

1185
  // Calculate index of current cell. Offset the position a tiny bit in
1186
  // direction of flight
1187
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, inside_mesh);
932,489,807✔
1188

1189
  // if track is very short, assume that it is completely inside one cell.
1190
  // Only the current cell will score and no surfaces
1191
  if (total_distance < 2 * TINY_BIT) {
932,489,807✔
1192
    if (inside_mesh) {
331,923✔
1193
      tally.track(ijk, 1.0);
331,307✔
1194
    }
1195
    return;
331,923✔
1196
  }
1197

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

1204
  // Loop until r = r1 is eventually reached
1205
  while (true) {
1206
    if (inside_mesh) {
1,692,056,554✔
1207

1208
      // find surface with minimal distance to current position
1209
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,605,782,374✔
1210
                     distances.begin();
1,605,782,374✔
1211

1212
      // Tally track length delta since last step
1213
      tally.track(ijk,
1,605,782,374✔
1214
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1215
          total_distance);
1216

1217
      // update position and leave, if we have reached end position
1218
      traveled_distance = distances[k].distance;
1,605,782,374✔
1219
      if (traveled_distance >= total_distance)
1,605,782,374✔
1220
        return;
1221

1222
      // If we have not reached r1, we have hit a surface. Tally outward
1223
      // current
1224
      tally.surface(ijk, k, distances[k].max_surface, false);
752,728,452✔
1225

1226
      // Update cell and calculate distance to next surface in correlated
1227
      // directions.
1228
      for (int j = 0; j < 3; ++j)
2,147,483,647✔
1229
        ijk[j] += distances[k].offset[j];
2,147,483,647✔
1230
      sanitize_index(ijk);
752,728,452✔
1231
      for (auto j : correlated_axes_[k])
1,506,678,366✔
1232
        distances[j] =
753,949,914✔
1233
          distance_to_grid_boundary(ijk, j, local_r, u, traveled_distance);
753,949,914✔
1234

1235
      // Check if we have left the interior of the mesh
1236
      inside_mesh = index_inside_mesh(ijk, k);
752,728,452✔
1237

1238
      // If we are still inside the mesh, tally inward current for the next
1239
      // cell
1240
      if (inside_mesh)
30,190,600✔
1241
        tally.surface(ijk, k, !distances[k].max_surface, true);
758,479,483✔
1242

1243
    } else { // not inside mesh
1244
      int k_max;
1245
      traveled_distance =
1246
        distance_to_mesh(ijk, distances, traveled_distance, k_max);
86,274,180✔
1247
      // If r1 is not inside the mesh, exit here
1248
      if (traveled_distance >= total_distance)
86,274,180✔
1249
        return;
79,103,962✔
1250

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

1260
      // If inside the mesh, Tally inward current
1261
      if (inside_mesh && k_max >= 0)
222,288!
1262
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
199,320✔
1263
    }
1264
  }
1265
}
1266

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

1290
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
830,965,436✔
1291
  vector<int>& bins, vector<double>& lengths) const
1292
{
1293

1294
  // Helper tally class.
1295
  // stores a pointer to the mesh class and references to bins and lengths
1296
  // parameters. Performs the actual tally through the track method.
1297
  struct TrackAggregator {
830,965,436✔
1298
    TrackAggregator(
830,965,436✔
1299
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1300
      : mesh(_mesh), bins(_bins), lengths(_lengths)
830,965,436✔
1301
    {}
1302
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1303
    void track(const MeshIndex& ijk, double l) const
1,463,969,844✔
1304
    {
1305
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,463,969,844✔
1306
      lengths.push_back(l);
1,463,969,844✔
1307
    }
1,463,969,844✔
1308

1309
    const StructuredMesh* mesh;
1310
    vector<int>& bins;
1311
    vector<double>& lengths;
1312
  };
1313

1314
  // Perform the mesh raytrace with the helper class.
1315
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
830,965,436✔
1316
}
830,965,436✔
1317

1318
void StructuredMesh::surface_bins_crossed(
113,616,107✔
1319
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1320
{
1321

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

1341
    const StructuredMesh* mesh;
1342
    vector<int>& bins;
1343
  };
1344

1345
  // Perform the mesh raytrace with the helper class.
1346
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
113,616,107✔
1347
}
113,616,107✔
1348

1349
//==============================================================================
1350
// RegularMesh implementation
1351
//==============================================================================
1352

1353
int RegularMesh::set_grid()
2,126✔
1354
{
1355
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,126✔
1356

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

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

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

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

1385
    // Set width and upper right coordinate
1386
    upper_right_ = lower_left_ + shape * width_;
138✔
1387

1388
  } else if (upper_right_.size() > 0) {
2,080!
1389

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

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

1405
    // Set width
1406
    width_ = (upper_right_ - lower_left_) / shape;
6,240✔
1407
  }
1408

1409
  // Set material volumes
1410
  volume_frac_ = 1.0 / shape.prod();
2,126✔
1411

1412
  element_volume_ = 1.0;
2,126✔
1413
  for (int i = 0; i < n_dimension_; i++) {
7,957✔
1414
    element_volume_ *= width_[i];
5,831✔
1415
  }
1416
  return 0;
1417
}
2,126✔
1418

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

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

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

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

1447
    width_ = get_node_tensor<double>(node, "width");
92✔
1448

1449
  } else if (check_for_node(node, "upper_right")) {
2,069!
1450

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

1453
  } else {
1454
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1455
  }
1456

1457
  if (int err = set_grid()) {
2,115!
1458
    fatal_error(openmc_err_msg);
×
1459
  }
1460
}
2,115✔
1461

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

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

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

1485
  if (object_exists(group, "upper_right")) {
11!
1486

1487
    read_dataset(group, "upper_right", upper_right_);
11✔
1488

1489
  } else {
1490
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1491
  }
1492

1493
  if (int err = set_grid()) {
11!
1494
    fatal_error(openmc_err_msg);
×
1495
  }
1496
}
11✔
1497

1498
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1499
{
1500
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1501
}
1502

1503
const std::string RegularMesh::mesh_type = "regular";
1504

1505
std::string RegularMesh::get_mesh_type() const
3,225✔
1506
{
1507
  return mesh_type;
3,225✔
1508
}
1509

1510
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,486,349,548✔
1511
{
1512
  return lower_left_[i] + ijk[i] * width_[i];
1,486,349,548✔
1513
}
1514

1515
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,417,206,358✔
1516
{
1517
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,417,206,358✔
1518
}
1519

1520
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1521
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1522
  double l) const
1523
{
1524
  MeshDistance d;
2,147,483,647✔
1525
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1526
    return d;
1527

1528
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1529
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1530
    ++d.offset[i];
1,482,054,580✔
1531
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,482,054,580✔
1532
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,434,359,702✔
1533
    --d.offset[i];
1,412,911,390✔
1534
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,412,911,390✔
1535
  }
1536

1537
  return d;
1538
}
1539

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

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

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

1578
  return {axis_lines[0], axis_lines[1]};
44✔
1579
}
1580

1581
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,092✔
1582
{
1583
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,092✔
1584
  write_dataset(mesh_group, "lower_left", lower_left_);
2,092✔
1585
  write_dataset(mesh_group, "upper_right", upper_right_);
2,092✔
1586
  write_dataset(mesh_group, "width", width_);
2,092✔
1587
}
2,092✔
1588

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

1596
  // Create array of zeros
1597
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1598
  bool outside_ = false;
2,892✔
1599

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

1603
    // determine scoring bin for entropy mesh
1604
    int mesh_bin = get_bin(site.r);
7,667,451✔
1605

1606
    // if outside mesh, skip particle
1607
    if (mesh_bin < 0) {
7,667,451!
1608
      outside_ = true;
×
1609
      continue;
×
1610
    }
1611

1612
    // Add to appropriate bin
1613
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1614
  }
1615

1616
  // Create reduced count data
1617
  auto counts = tensor::zeros<double>(shape);
7,820✔
1618
  int total = cnt.size();
7,820✔
1619

1620
#ifdef OPENMC_MPI
1621
  // collect values from all processors
1622
  MPI_Reduce(
2,892✔
1623
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1624

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

1635
  return counts;
7,820✔
1636
}
7,820✔
1637

1638
double RegularMesh::volume(const MeshIndex& ijk) const
1,112,175✔
1639
{
1640
  return element_volume_;
1,112,175✔
1641
}
1642

1643
//==============================================================================
1644
// RectilinearMesh implementation
1645
//==============================================================================
1646

1647
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
122✔
1648
{
1649
  n_dimension_ = 3;
122✔
1650

1651
  grid_[0] = get_node_array<double>(node, "x_grid");
122✔
1652
  grid_[1] = get_node_array<double>(node, "y_grid");
122✔
1653
  grid_[2] = get_node_array<double>(node, "z_grid");
122✔
1654

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

1660
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1661
{
1662
  n_dimension_ = 3;
11✔
1663

1664
  read_dataset(group, "x_grid", grid_[0]);
11✔
1665
  read_dataset(group, "y_grid", grid_[1]);
11✔
1666
  read_dataset(group, "z_grid", grid_[2]);
11✔
1667

1668
  if (int err = set_grid()) {
11!
1669
    fatal_error(openmc_err_msg);
×
1670
  }
1671
}
11✔
1672

1673
const std::string RectilinearMesh::mesh_type = "rectilinear";
1674

1675
std::string RectilinearMesh::get_mesh_type() const
275✔
1676
{
1677
  return mesh_type;
275✔
1678
}
1679

1680
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1681
  const MeshIndex& ijk, int i) const
1682
{
1683
  return grid_[i][ijk[i]];
26,505,963✔
1684
}
1685

1686
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1687
  const MeshIndex& ijk, int i) const
1688
{
1689
  return grid_[i][ijk[i] - 1];
25,739,406✔
1690
}
1691

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

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

1711
int RectilinearMesh::set_grid()
177✔
1712
{
1713
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
177✔
1714
    static_cast<int>(grid_[1].size()) - 1,
177✔
1715
    static_cast<int>(grid_[2].size()) - 1};
177✔
1716

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

1731
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
177✔
1732
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
177✔
1733

1734
  return 0;
177✔
1735
}
1736

1737
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892✔
1738
{
1739
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892✔
1740
}
1741

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

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

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

1769
  return {axis_lines[0], axis_lines[1]};
22✔
1770
}
1771

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

1779
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1780
{
1781
  double vol {1.0};
132✔
1782

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

1789
//==============================================================================
1790
// CylindricalMesh implementation
1791
//==============================================================================
1792

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

1802
  if (int err = set_grid()) {
400!
1803
    fatal_error(openmc_err_msg);
×
1804
  }
1805
}
400✔
1806

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

1815
  if (int err = set_grid()) {
11!
1816
    fatal_error(openmc_err_msg);
×
1817
  }
1818
}
11✔
1819

1820
const std::string CylindricalMesh::mesh_type = "cylindrical";
1821

1822
std::string CylindricalMesh::get_mesh_type() const
484✔
1823
{
1824
  return mesh_type;
484✔
1825
}
1826

1827
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1828
  Position r, bool& in_mesh) const
1829
{
1830
  r = local_coords(r);
47,732,091✔
1831

1832
  Position mapped_r;
47,732,091✔
1833
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1834
  mapped_r[2] = r[2];
47,732,091✔
1835

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

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

1846
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1847

1848
  return idx;
47,732,091✔
1849
}
1850

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

1857
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1858
  double phi_max = this->phi(ijk[1]);
88,110✔
1859

1860
  double z_min = this->z(ijk[2] - 1);
88,110✔
1861
  double z_max = this->z(ijk[2]);
88,110✔
1862

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

1869
  double x = r * std::cos(phi);
88,110✔
1870
  double y = r * std::sin(phi);
88,110✔
1871

1872
  return origin_ + Position(x, y, z);
88,110✔
1873
}
1874

1875
double CylindricalMesh::find_r_crossing(
142,586,902✔
1876
  const Position& r, const Direction& u, double l, int shell) const
1877
{
1878

1879
  if ((shell < 0) || (shell > shape_[0]))
142,586,902!
1880
    return INFTY;
1881

1882
  // solve r.x^2 + r.y^2 == r0^2
1883
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1884
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1885

1886
  const double r0 = grid_[0][shell];
124,673,038✔
1887
  if (r0 == 0.0)
124,673,038✔
1888
    return INFTY;
1889

1890
  const double denominator = u.x * u.x + u.y * u.y;
117,536,964✔
1891

1892
  // Direction of flight is in z-direction. Will never intersect r.
1893
  if (std::abs(denominator) < FP_PRECISION)
117,536,964✔
1894
    return INFTY;
1895

1896
  // inverse of dominator to help the compiler to speed things up
1897
  const double inv_denominator = 1.0 / denominator;
117,478,004✔
1898

1899
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,478,004✔
1900
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,478,004✔
1901
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,478,004✔
1902

1903
  if (D < 0.0)
117,478,004✔
1904
    return INFTY;
1905

1906
  D = std::sqrt(D);
107,741,882✔
1907

1908
  // Particle is already on the shell surface; avoid spurious crossing
1909
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,741,882✔
1910
    return INFTY;
1911

1912
  // Check -p - D first because it is always smaller as -p + D
1913
  if (-p - D > l)
101,108,508✔
1914
    return -p - D;
1915
  if (-p + D > l)
80,900,733✔
1916
    return -p + D;
50,077,816✔
1917

1918
  return INFTY;
1919
}
1920

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

1928
  shell = sanitize_phi(shell);
43,970,718✔
1929

1930
  const double p0 = grid_[1][shell];
43,970,718✔
1931

1932
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1933
  // => x(s) * cos(p0) = y(s) * sin(p0)
1934
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1935
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1936

1937
  const double c0 = std::cos(p0);
43,970,718✔
1938
  const double s0 = std::sin(p0);
43,970,718✔
1939

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

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

1951
  return INFTY;
1952
}
1953

1954
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1955
  const Position& r, const Direction& u, double l, int shell) const
1956
{
1957
  MeshDistance d;
36,695,747✔
1958

1959
  // Direction of flight is within xy-plane. Will never intersect z.
1960
  if (std::abs(u.z) < FP_PRECISION)
36,695,747✔
1961
    return d;
1962

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

1974
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,217,400✔
1975
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1976
  double l) const
1977
{
1978
  if (i == 0) {
145,217,400✔
1979
    return std::min(
142,586,902✔
1980
      MeshDistance({1, 0, 0}, true, find_r_crossing(r0, u, l, ijk[i])),
71,293,451✔
1981
      MeshDistance({-1, 0, 0}, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,586,902✔
1982

1983
  } else if (i == 1) {
73,923,949✔
1984

1985
    return std::min(
74,456,404✔
1986
      MeshDistance({0, 1, 0}, true, find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1987
      MeshDistance({0, -1, 0}, false, find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1988

1989
  } else {
1990
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1991
  }
1992
}
1993

1994
int CylindricalMesh::set_grid()
433✔
1995
{
1996
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
1997
    static_cast<int>(grid_[1].size()) - 1,
433✔
1998
    static_cast<int>(grid_[2].size()) - 1};
433✔
1999

2000
  axes_labels_ = {"r", "phi", "z"};
1,732!
2001

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

2029
    return OPENMC_E_INVALID_ARGUMENT;
×
2030
  }
2031

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

2034
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2035
    origin_[2] + grid_[2].front()};
433✔
2036
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2037
    origin_[2] + grid_[2].back()};
433✔
2038

2039
  return 0;
433✔
2040
}
2041

2042
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2043
{
2044
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2045
}
2046

2047
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2048
  Position plot_ll, Position plot_ur) const
2049
{
2050
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2051

2052
  // Figure out which axes lie in the plane of the plot.
2053
  array<vector<double>, 2> axis_lines;
2054
  return {axis_lines[0], axis_lines[1]};
2055
}
2056

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

2065
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2066
{
2067
  double r_i = grid_[0][ijk[0] - 1];
792✔
2068
  double r_o = grid_[0][ijk[0]];
792✔
2069

2070
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2071
  double phi_o = grid_[1][ijk[1]];
792✔
2072

2073
  double z_i = grid_[2][ijk[2] - 1];
792✔
2074
  double z_o = grid_[2][ijk[2]];
792✔
2075

2076
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2077
}
2078

2079
//==============================================================================
2080
// SphericalMesh implementation
2081
//==============================================================================
2082

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

2092
  if (int err = set_grid()) {
345!
2093
    fatal_error(openmc_err_msg);
×
2094
  }
2095
}
345✔
2096

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

2105
  if (int err = set_grid()) {
11!
2106
    fatal_error(openmc_err_msg);
×
2107
  }
2108
}
11✔
2109

2110
const std::string SphericalMesh::mesh_type = "spherical";
2111

2112
std::string SphericalMesh::get_mesh_type() const
385✔
2113
{
2114
  return mesh_type;
385✔
2115
}
2116

2117
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2118
  Position r, bool& in_mesh) const
2119
{
2120
  r = local_coords(r);
68,592,128✔
2121

2122
  Position mapped_r;
68,592,128✔
2123
  mapped_r[0] = r.norm();
68,592,128✔
2124

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

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

2137
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2138
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2139

2140
  return idx;
68,592,128✔
2141
}
2142

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

2149
  double theta_min = this->theta(ijk[1] - 1);
110✔
2150
  double theta_max = this->theta(ijk[1]);
110✔
2151

2152
  double phi_min = this->phi(ijk[2] - 1);
110✔
2153
  double phi_max = this->phi(ijk[2]);
110✔
2154

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

2164
  double x = r * std::cos(phi) * sin_theta;
110✔
2165
  double y = r * std::sin(phi) * sin_theta;
110✔
2166
  double z = r * cos_theta;
110✔
2167

2168
  return origin_ + Position(x, y, z);
110✔
2169
}
2170

2171
double SphericalMesh::find_r_crossing(
444,039,772✔
2172
  const Position& r, const Direction& u, double l, int shell) const
2173
{
2174
  if ((shell < 0) || (shell > shape_[0]))
444,039,772✔
2175
    return INFTY;
2176

2177
  // solve |r+s*u| = r0
2178
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2179
  const double r0 = grid_[0][shell];
404,418,685✔
2180
  if (r0 == 0.0)
404,418,685✔
2181
    return INFTY;
2182
  const double p = r.dot(u);
396,740,168✔
2183
  double R = r.norm();
396,740,168✔
2184
  double D = p * p - (R - r0) * (R + r0);
396,740,168✔
2185

2186
  // Particle is already on the shell surface; avoid spurious crossing
2187
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,740,168✔
2188
    return INFTY;
2189

2190
  if (D >= 0.0) {
386,031,514✔
2191
    D = std::sqrt(D);
358,154,566✔
2192
    // Check -p - D first because it is always smaller as -p + D
2193
    if (-p - D > l)
358,154,566✔
2194
      return -p - D;
2195
    if (-p + D > l)
293,824,322✔
2196
      return -p + D;
177,271,072✔
2197
  }
2198

2199
  return INFTY;
2200
}
2201

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

2209
  shell = sanitize_theta(shell);
38,358,540✔
2210

2211
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2212
  // yields
2213
  // a*s^2 + 2*b*s + c == 0 with
2214
  // a = cos(theta)^2 - u.z * u.z
2215
  // b = r*u * cos(theta)^2 - u.z * r.z
2216
  // c = r*r * cos(theta)^2 - r.z^2
2217

2218
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2219
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2220
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2221

2222
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2223
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2224
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2225

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

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

2240
    // no crossing is possible
2241
    return INFTY;
2242
  }
2243

2244
  const double p = b / a;
37,875,992✔
2245
  double D = p * p - c / a;
37,875,992✔
2246

2247
  if (D < 0.0)
37,875,992✔
2248
    return INFTY;
2249

2250
  D = std::sqrt(D);
26,921,004✔
2251

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

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

2263
  return INFTY;
2264
}
2265

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

2273
  shell = sanitize_phi(shell);
39,948,018✔
2274

2275
  const double p0 = grid_[2][shell];
39,948,018✔
2276

2277
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2278
  // => x(s) * cos(p0) = y(s) * sin(p0)
2279
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2280
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2281

2282
  const double c0 = std::cos(p0);
39,948,018✔
2283
  const double s0 = std::sin(p0);
39,948,018✔
2284

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

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

2296
  return INFTY;
2297
}
2298

2299
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,975,973✔
2300
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2301
  double l) const
2302
{
2303

2304
  if (i == 0) {
332,975,973✔
2305
    return std::min(
444,039,772✔
2306
      MeshDistance({1, 0, 0}, true, find_r_crossing(r0, u, l, ijk[i])),
222,019,886✔
2307
      MeshDistance({-1, 0, 0}, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
444,039,772✔
2308

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

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

2322
int SphericalMesh::set_grid()
378✔
2323
{
2324
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2325
    static_cast<int>(grid_[1].size()) - 1,
378✔
2326
    static_cast<int>(grid_[2].size()) - 1};
378✔
2327

2328
  axes_labels_ = {"r", "theta", "phi"};
1,512!
2329

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

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

2360
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2361
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2362

2363
  double r = grid_[0].back();
378✔
2364
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2365
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2366

2367
  return 0;
378✔
2368
}
2369

2370
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2371
{
2372
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2373
}
2374

2375
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2376
  Position plot_ll, Position plot_ur) const
2377
{
2378
  fatal_error("Plot of spherical Mesh not implemented");
×
2379

2380
  // Figure out which axes lie in the plane of the plot.
2381
  array<vector<double>, 2> axis_lines;
2382
  return {axis_lines[0], axis_lines[1]};
2383
}
2384

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

2393
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2394
{
2395
  double r_i = grid_[0][ijk[0] - 1];
935✔
2396
  double r_o = grid_[0][ijk[0]];
935✔
2397

2398
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2399
  double theta_o = grid_[1][ijk[1]];
935✔
2400

2401
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2402
  double phi_o = grid_[2][ijk[2]];
935✔
2403

2404
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2405
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2406
}
2407

2408
//==============================================================================
2409
// HexagonalMesh implementation
2410
//==============================================================================
2411

2412
HexagonalMesh::HexagonalMesh(pugi::xml_node node)
66✔
2413
  : PeriodicStructuredMesh {node}
66✔
2414
{
2415
  grid_ = get_node_array<double>(node, "grid");
66✔
2416
  radius_ = std::stoi(get_node_value(node, "radius"));
132✔
2417
  size_ = std::stod(get_node_value(node, "size"));
132✔
2418
  origin_ = get_node_position(node, "origin");
66✔
2419

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

2430
  if (int err = set_grid()) {
66!
NEW
2431
    fatal_error(openmc_err_msg);
×
2432
  }
2433
}
66✔
2434

NEW
2435
HexagonalMesh::HexagonalMesh(hid_t group) : PeriodicStructuredMesh {group}
×
2436
{
NEW
2437
  read_dataset(group, "grid", grid_);
×
NEW
2438
  read_attribute(group, "radius", radius_);
×
NEW
2439
  read_attribute(group, "size", size_);
×
NEW
2440
  read_dataset(group, "origin", origin_);
×
2441

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

2456
const std::string HexagonalMesh::mesh_type = "hexagonal";
2457

2458
std::string HexagonalMesh::get_mesh_type() const
66✔
2459
{
2460
  return mesh_type;
66✔
2461
}
2462

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

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

2487
int HexagonalMesh::n_bins() const
66✔
2488
{
2489
  return (1 + 3 * (radius_ + 1) * radius_) * (grid_.size() - 1);
66✔
2490
}
2491

2492
int HexagonalMesh::get_bin_from_indices(const MeshIndex& ijk) const
4,979,007✔
2493
{
2494
  int q = ijk[0];
4,979,007✔
2495
  int r = ijk[1];
4,979,007✔
2496
  int k = ijk[2];
4,979,007✔
2497
  int hexes = 3 * radius_ * (radius_ + 1) + 1;
4,979,007✔
2498
  int bin = (k - 1) * (grid_.size() - 1) * hexes;
4,979,007✔
2499
  int rad = std::max({std::abs(r), std::abs(q), std::abs(r + q)});
4,979,007✔
2500
  if (rad == 0)
4,979,007✔
2501
    return bin;
2502

2503
  bin += 3 * rad * (rad - 1) + 1;
3,648,227✔
2504

2505
  if ((q >= 0) and (r >= 0)) {
3,648,227✔
2506
    bin += q;
1,076,240✔
2507
  } else if ((r < 0) && ((-r - q) < 0)) {
2,571,987✔
2508
    bin += (rad - r);
124,322✔
2509
  } else if ((q >= 0) && ((-q - r) >= 0)) {
2,447,665!
2510
    bin += (2 * rad - q - r);
1,096,964✔
2511
  } else if ((q < 0) && (r < 0)) {
1,350,701✔
2512
    bin += (3 * rad - q);
130,152✔
2513
  } else if ((r >= 0) && ((-q - r) >= 0)) {
1,220,549!
2514
    bin += (4 * rad + r);
1,097,228✔
2515
  } else {
2516
    bin += (5 * rad + q + r);
123,321✔
2517
  }
2518
  return bin;
2519
}
2520

2521
StructuredMesh::MeshIndex HexagonalMesh::get_indices(
5,243,117✔
2522
  Position r, bool& in_mesh) const
2523
{
2524
  r = local_coords(r);
5,243,117✔
2525

2526
  double q = q_dual_.dot(r);
5,243,117✔
2527
  double r0 = r_dual_.dot(r);
5,243,117✔
2528
  double s = -q - r0;
5,243,117✔
2529

2530
  double q_r = std::round(q);
5,243,117✔
2531
  double r_r = std::round(r0);
5,243,117✔
2532
  double s_r = std::round(s);
5,243,117✔
2533
  std::array<double, 3> diff = {
5,243,117✔
2534
    std::abs(q - q_r), std::abs(r0 - r_r), std::abs(s - s_r)};
5,243,117✔
2535
  auto max_it = std::max_element(diff.begin(), diff.end());
5,243,117✔
2536
  int i = static_cast<int>(std::distance(diff.begin(), max_it));
5,243,117✔
2537

2538
  if (i == 0)
5,243,117✔
2539
    q_r = -s_r - r_r;
1,756,656✔
2540
  else if (i == 1)
3,486,461✔
2541
    r_r = -q_r - s_r;
1,745,469✔
2542

2543
  int z_i = get_index_in_z_direction(r.z);
5,243,117✔
2544
  int q_i = static_cast<int>(q_r);
5,243,117✔
2545
  int r_i = static_cast<int>(r_r);
5,243,117✔
2546
  int s_i = -q_i - r_i;
5,243,117✔
2547

2548
  MeshIndex ijk;
5,243,117✔
2549
  in_mesh = true;
5,243,117✔
2550

2551
  ijk[0] = q_i;
5,243,117!
2552
  ijk[1] = r_i;
5,243,117✔
2553
  ijk[2] = z_i;
5,243,117✔
2554

2555
  if (std::max({std::abs(q_i), std::abs(r_i), std::abs(s_i)}) > radius_)
5,243,117!
NEW
2556
    in_mesh = false;
×
2557
  if (ijk[2] < 1 || ijk[2] > grid_.size() - 1)
5,243,117!
NEW
2558
    in_mesh = false;
×
2559

2560
  return ijk;
5,243,117✔
2561
}
2562

2563
StructuredMesh::MeshIndex HexagonalMesh::get_indices_from_bin(int bin) const
7,524✔
2564
{
2565
  MeshIndex ijk = {0, 0, 0};
7,524✔
2566
  int hexes = 3 * radius_ * (radius_ + 1) + 1;
7,524✔
2567
  ijk[2] = static_cast<int>(std::floor(bin / hexes)) + 1;
7,524✔
2568
  int sp_idx = bin % hexes;
7,524✔
2569
  if (sp_idx == 0) {
7,524✔
2570
    return ijk;
396✔
2571
  }
2572
  int rad = static_cast<int>(std::floor((3 + std::sqrt(12 * sp_idx - 3)) / 6));
7,128!
2573
  int offset = sp_idx - (3 * rad * (rad - 1) + 1);
7,128✔
2574
  int side = (offset / rad) % 6;
7,128✔
2575
  int dist = offset % rad;
7,128✔
2576
  switch (side) {
7,128!
2577
  case 0:
1,188✔
2578
    ijk[0] = dist;
1,188✔
2579
    ijk[1] = rad - dist;
1,188✔
2580
    break;
1,188✔
2581
  case 1:
1,188✔
2582
    ijk[0] = rad;
1,188✔
2583
    ijk[1] = -dist;
1,188✔
2584
    break;
1,188✔
2585
  case 2:
1,188✔
2586
    ijk[0] = rad - dist;
1,188✔
2587
    ijk[1] = -rad;
1,188✔
2588
    break;
1,188✔
2589
  case 3:
1,188✔
2590
    ijk[0] = -dist;
1,188✔
2591
    ijk[1] = dist - rad;
1,188✔
2592
    break;
1,188✔
2593
  case 4:
1,188✔
2594
    ijk[0] = -rad;
1,188✔
2595
    ijk[1] = dist;
1,188✔
2596
    break;
1,188✔
2597
  case 5:
1,188✔
2598
    ijk[0] = dist - rad;
1,188✔
2599
    ijk[1] = rad;
1,188✔
2600
    break;
1,188✔
2601
  }
2602
  return ijk;
7,128✔
2603
}
2604

NEW
2605
Position HexagonalMesh::sample_element(
×
2606
  const MeshIndex& ijk, uint64_t* seed) const
2607
{
NEW
2608
  double q0 = ijk[0];
×
NEW
2609
  double r0 = ijk[1];
×
NEW
2610
  double z = uniform_distribution(grid_[ijk[2] - 1], grid_[ijk[2]], seed);
×
NEW
2611
  double q, r, s;
×
NEW
2612
  do {
×
NEW
2613
    double rad = std::cbrt(uniform_distribution(0.0, std::pow(size_, 3), seed));
×
NEW
2614
    double phi = uniform_distribution(0.0, 2 * PI, seed);
×
NEW
2615
    double x = rad * std::cos(phi);
×
NEW
2616
    double y = rad * std::sin(phi);
×
NEW
2617
    q = q_dual_[0] * x + q_dual_[1] * y;
×
NEW
2618
    r = r_dual_[0] * x + r_dual_[1] * y;
×
NEW
2619
    s = -q - r;
×
NEW
2620
  } while (std::max({std::abs(q), std::abs(r), std::abs(s)}) > 1);
×
2621

NEW
2622
  return origin_ + size_ * ((q + q0) * q_ + (r + r0) * r_) + z;
×
2623
}
2624

2625
StructuredMesh::MeshDistance HexagonalMesh::find_z_crossing(
4,196,808✔
2626
  const Position& r, const Direction& u, double l, int shell) const
2627
{
2628
  MeshDistance d;
4,196,808✔
2629

2630
  // Direction of flight is within xy-plane. Will never intersect z.
2631
  if (std::abs(u.z) < FP_PRECISION)
4,196,808!
2632
    return d;
2633

2634
  d.max_surface = (u.z > 0.0);
4,196,808✔
2635
  if (d.max_surface && (shell < grid_.size())) {
4,196,808✔
2636
    ++d.offset[2];
2,102,243✔
2637
    d.distance = (grid_[shell] - r.z) / u.z;
2,102,243✔
2638
  } else if (!d.max_surface && (shell > 0)) {
2,094,565✔
2639
    --d.offset[2];
2,090,913✔
2640
    d.distance = (grid_[shell - 1] - r.z) / u.z;
2,090,913✔
2641
  }
2642
  return d;
2643
}
2644

2645
StructuredMesh::MeshDistance HexagonalMesh::distance_to_grid_boundary(
18,608,469✔
2646
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2647
  double l) const
2648
{
2649
  auto r = local_coords(r0);
18,608,469✔
2650
  if (i == 3)
18,608,469✔
2651
    return find_z_crossing(r, u, l, ijk[2]);
4,196,808✔
2652
  r.z = 0.0;
14,411,661✔
2653

2654
  MeshDistance d;
14,411,661✔
2655
  Direction s_ = -q_ - r_;
14,411,661✔
2656
  Direction dir;
14,411,661✔
2657
  MeshIndex idx = {ijk[0], ijk[1], -ijk[0] - ijk[1]};
14,411,661✔
2658
  MeshIndex offset = {0, 0, 0};
14,411,661✔
2659
  double distance;
14,411,661✔
2660
  if (i == 0) {
14,411,661✔
2661
    dir = 0.5 * (q_ - r_);
4,803,887✔
2662
    ++offset[0];
4,803,887✔
2663
    --offset[1];
4,803,887✔
2664
  } else if (i == 1) {
9,607,774✔
2665
    dir = 0.5 * (r_ - s_);
4,803,887✔
2666
    ++offset[1];
4,803,887✔
2667
    --offset[2];
4,803,887✔
2668
  } else {
2669
    dir = 0.5 * (s_ - q_);
4,803,887✔
2670
    --offset[0];
4,803,887✔
2671
    ++offset[2];
4,803,887✔
2672
  }
2673
  dir /= dir.norm();
14,411,661✔
2674
  if (std::abs(u.dot(dir)) < FP_PRECISION)
14,411,661!
NEW
2675
    return d;
×
2676

2677
  d.max_surface = (u.dot(dir) > 0.0);
14,411,661✔
2678
  if (d.max_surface) {
14,411,661✔
2679
    distance = (idx[0] * q_ + idx[1] * r_ + dir - r).norm() / u.dot(dir);
7,218,387✔
2680
    idx[0] += offset[0];
7,218,387✔
2681
    idx[1] += offset[1];
7,218,387✔
2682
    idx[2] += offset[2];
7,218,387✔
2683
  } else {
2684
    distance = -(idx[0] * q_ + idx[1] * r_ - dir - r).norm() / u.dot(dir);
7,193,274✔
2685
    idx[0] -= offset[0];
7,193,274✔
2686
    idx[1] -= offset[1];
7,193,274✔
2687
    idx[2] -= offset[2];
7,193,274✔
2688
  }
2689
  int radius = std::max({std::abs(idx[0]), std::abs(idx[1]), std::abs(idx[2])});
14,411,661✔
2690
  if (d.max_surface && radius <= radius_) {
14,411,661✔
2691
    d.offset[0] += offset[0];
2692
    d.offset[1] += offset[1];
2693
    d.distance = distance;
2694
  } else if (!d.max_surface && radius <= radius_) {
8,441,906✔
2695
    d.offset[0] -= offset[0];
5,937,932✔
2696
    d.offset[1] -= offset[1];
5,937,932✔
2697
    d.distance = distance;
5,937,932✔
2698
  }
2699
  return d;
14,411,661✔
2700
}
2701

2702
double HexagonalMesh::distance_to_mesh(const MeshIndex& ijk,
3,652✔
2703
  const std::array<MeshDistance, 4>& distances, double traveled_distance,
2704
  int& k_max) const
2705
{
2706
  // For all directions outside the mesh, find the distance that we need
2707
  // to travel to reach the next surface. Use the largest distance, as
2708
  // only this will cross all outer surfaces.
2709
  const int n = n_dimension_;
3,652✔
2710
  k_max = -1;
3,652✔
2711

2712
  for (int k = 0; k < n; ++k) {
18,260✔
2713
    if (distances[k].distance <= traveled_distance)
14,608!
NEW
2714
      continue;
×
2715
    if ((k < 2) && (std::abs(ijk[k]) <= radius_))
14,608!
2716
      continue;
7,304✔
2717
    if ((k == 2) && std::abs(ijk[0] + ijk[1]) <= radius_)
7,304!
2718
      continue;
3,652✔
2719
    if ((k == 3) && ijk[2] >= 1 && ijk[2] < grid_.size())
3,652!
NEW
2720
      continue;
×
2721
    traveled_distance = distances[k].distance;
3,652✔
2722
    k_max = k;
3,652✔
2723
  }
2724
  // Assure some distance is traveled
2725
  if (k_max == -1) {
3,652!
NEW
2726
    traveled_distance += TINY_BIT;
×
2727
  }
2728
  return traveled_distance;
3,652✔
2729
}
2730

2731
int HexagonalMesh::set_grid()
66✔
2732
{
2733
  n_dimension_ = 4;
66✔
2734
  correlated_axes_ = {{0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {3}};
330!
2735

2736
  axes_labels_ = {"r", "q", "s", "z"};
330!
2737

2738
  if (orientation_ == Orientation::x) {
66✔
2739
    q_ = {std::sqrt(3.0), 0.0, 0.0};
33✔
2740
    r_ = {0.5 * std::sqrt(3), -1.5, 0.0};
33✔
2741
    q_dual_ = {std::sqrt(3.0) / 3.0, 1.0 / 3.0, 0.0};
33✔
2742
    r_dual_ = {0.0, -2.0 / 3.0, 0.0};
33✔
2743
  } else {
2744
    q_ = {1.5, -0.5 * std::sqrt(3.0), 0.0};
33✔
2745
    r_ = {0.0, -std::sqrt(3.0), 0.0};
33✔
2746
    q_dual_ = {2.0 / 3.0, 0.0, 0.0};
33✔
2747
    r_dual_ = {-1.0 / 3.0, -std::sqrt(3.0) / 3.0, 0.0};
33✔
2748
  }
2749

2750
  q_ *= size_;
66✔
2751
  r_ *= size_;
66✔
2752
  q_dual_ /= size_;
66✔
2753
  r_dual_ /= size_;
66✔
2754

2755
  if (grid_.size() < 2) {
66!
NEW
2756
    set_errmsg("z- grid for hexagonal meshes "
×
2757
               "must have at least 2 points");
NEW
2758
    return OPENMC_E_INVALID_ARGUMENT;
×
2759
  }
2760
  if (std::adjacent_find(grid_.begin(), grid_.end(), std::greater_equal<>()) !=
66✔
2761
      grid_.end()) {
66!
NEW
2762
    set_errmsg("Values in z- grid for "
×
2763
               "hexagonal meshes must be sorted and unique.");
NEW
2764
    return OPENMC_E_INVALID_ARGUMENT;
×
2765
  }
2766
  return 0;
2767
}
2768

2769
int HexagonalMesh::get_index_in_z_direction(double z) const
5,243,117✔
2770
{
2771
  return lower_bound_index(grid_.begin(), grid_.end(), z) + 1;
5,243,117✔
2772
}
2773

NEW
2774
std::pair<vector<double>, vector<double>> HexagonalMesh::plot(
×
2775
  Position plot_ll, Position plot_ur) const
2776
{
NEW
2777
  fatal_error("Plot of hexagonal Mesh not implemented");
×
2778

2779
  // Figure out which axes lie in the plane of the plot.
2780
  array<vector<double>, 2> axis_lines;
2781
  return {axis_lines[0], axis_lines[1]};
2782
}
2783

2784
void HexagonalMesh::to_hdf5_inner(hid_t mesh_group) const
66✔
2785
{
2786
  write_dataset(mesh_group, "grid", grid_);
66✔
2787
  if (orientation_ == Orientation::x)
66✔
2788
    write_attribute(mesh_group, "orientation", "x");
33✔
2789
  write_attribute(mesh_group, "radius", radius_);
66✔
2790
  write_attribute(mesh_group, "size", size_);
66✔
2791
  write_dataset(mesh_group, "origin", origin_);
66✔
2792
}
66✔
2793

NEW
2794
double HexagonalMesh::volume(const MeshIndex& ijk) const
×
2795
{
NEW
2796
  double f = 1.5 * std::sqrt(3.0);
×
NEW
2797
  double z_i = grid_[ijk[2] - 1];
×
NEW
2798
  double z_o = grid_[ijk[2]];
×
NEW
2799
  return f * (z_o - z_i) * size_ * size_;
×
2800
}
2801

2802
//==============================================================================
2803
// Helper functions for the C API
2804
//==============================================================================
2805

2806
int check_mesh(int32_t index)
6,380✔
2807
{
2808
  if (index < 0 || index >= model::meshes.size()) {
6,380!
2809
    set_errmsg("Index in meshes array is out of bounds.");
×
2810
    return OPENMC_E_OUT_OF_BOUNDS;
×
2811
  }
2812
  return 0;
2813
}
2814

2815
template<class T>
2816
int check_mesh_type(int32_t index)
1,100✔
2817
{
2818
  if (int err = check_mesh(index))
1,100!
2819
    return err;
2820

2821
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2822
  if (!mesh) {
1,100!
2823
    set_errmsg("This function is not valid for input mesh.");
×
2824
    return OPENMC_E_INVALID_TYPE;
×
2825
  }
2826
  return 0;
2827
}
2828

2829
template<class T>
2830
bool is_mesh_type(int32_t index)
2831
{
2832
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2833
  return mesh;
2834
}
2835

2836
//==============================================================================
2837
// C API functions
2838
//==============================================================================
2839

2840
// Return the type of mesh as a C string
2841
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,474✔
2842
{
2843
  if (int err = check_mesh(index))
1,474!
2844
    return err;
2845

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

2848
  return 0;
1,474✔
2849
}
2850

2851
//! Extend the meshes array by n elements
2852
extern "C" int openmc_extend_meshes(
253✔
2853
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2854
{
2855
  if (index_start)
253!
2856
    *index_start = model::meshes.size();
253✔
2857
  std::string mesh_type;
253✔
2858

2859
  for (int i = 0; i < n; ++i) {
506✔
2860
    if (RegularMesh::mesh_type == type) {
253✔
2861
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2862
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2863
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2864
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2865
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2866
    } else if (SphericalMesh::mesh_type == type) {
22!
2867
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2868
    } else if (HexagonalMesh::mesh_type == type) {
×
NEW
2869
      model::meshes.push_back(make_unique<HexagonalMesh>());
×
2870
    } else {
2871
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2872
    }
2873
  }
2874
  if (index_end)
253!
2875
    *index_end = model::meshes.size() - 1;
×
2876

2877
  return 0;
253✔
2878
}
253✔
2879

2880
//! Adds a new unstructured mesh to OpenMC
2881
extern "C" int openmc_add_unstructured_mesh(
×
2882
  const char filename[], const char library[], int* id)
2883
{
2884
  std::string lib_name(library);
×
2885
  std::string mesh_file(filename);
×
2886
  bool valid_lib = false;
×
2887

2888
#ifdef OPENMC_DAGMC_ENABLED
2889
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2890
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2891
    valid_lib = true;
2892
  }
2893
#endif
2894

2895
#ifdef OPENMC_LIBMESH_ENABLED
2896
  if (lib_name == LibMesh::mesh_lib_type) {
×
2897
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2898
    valid_lib = true;
2899
  }
2900
#endif
2901

2902
  if (!valid_lib) {
×
2903
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2904
                           "by this build of OpenMC",
2905
      lib_name));
2906
    return OPENMC_E_INVALID_ARGUMENT;
×
2907
  }
2908

2909
  // auto-assign new ID
2910
  model::meshes.back()->set_id(-1);
×
2911
  *id = model::meshes.back()->id_;
2912

2913
  return 0;
2914
}
×
2915

2916
//! Return the index in the meshes array of a mesh with a given ID
2917
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2918
{
2919
  auto pair = model::mesh_map.find(id);
429!
2920
  if (pair == model::mesh_map.end()) {
429!
2921
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2922
    return OPENMC_E_INVALID_ID;
×
2923
  }
2924
  *index = pair->second;
429✔
2925
  return 0;
429✔
2926
}
2927

2928
//! Return the ID of a mesh
2929
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,805✔
2930
{
2931
  if (int err = check_mesh(index))
2,805!
2932
    return err;
2933
  *id = model::meshes[index]->id_;
2,805✔
2934
  return 0;
2,805✔
2935
}
2936

2937
//! Set the ID of a mesh
2938
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2939
{
2940
  if (int err = check_mesh(index))
253!
2941
    return err;
2942
  model::meshes[index]->id_ = id;
253✔
2943
  model::mesh_map[id] = index;
253✔
2944
  return 0;
253✔
2945
}
2946

2947
//! Get the number of elements in a mesh
2948
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
275✔
2949
{
2950
  if (int err = check_mesh(index))
275!
2951
    return err;
2952
  *n = model::meshes[index]->n_bins();
275✔
2953
  return 0;
275✔
2954
}
2955

2956
//! Get the volume of each element in the mesh
2957
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2958
{
2959
  if (int err = check_mesh(index))
88!
2960
    return err;
2961
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2962
    volumes[i] = model::meshes[index]->volume(i);
880✔
2963
  }
2964
  return 0;
2965
}
2966

2967
//! Get the bounding box of a mesh
2968
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
154✔
2969
{
2970
  if (int err = check_mesh(index))
154!
2971
    return err;
2972

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

2975
  // set lower left corner values
2976
  ll[0] = bbox.min.x;
154✔
2977
  ll[1] = bbox.min.y;
154✔
2978
  ll[2] = bbox.min.z;
154✔
2979

2980
  // set upper right corner values
2981
  ur[0] = bbox.max.x;
154✔
2982
  ur[1] = bbox.max.y;
154✔
2983
  ur[2] = bbox.max.z;
154✔
2984
  return 0;
154✔
2985
}
2986

2987
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
187✔
2988
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2989
{
2990
  if (int err = check_mesh(index))
187!
2991
    return err;
2992

2993
  try {
187✔
2994
    model::meshes[index]->material_volumes(
187✔
2995
      nx, ny, nz, table_size, materials, volumes, bboxes);
2996
  } catch (const std::exception& e) {
11!
2997
    set_errmsg(e.what());
11✔
2998
    if (starts_with(e.what(), "Mesh")) {
11!
2999
      return OPENMC_E_GEOMETRY;
11✔
3000
    } else {
3001
      return OPENMC_E_ALLOCATE;
×
3002
    }
3003
  }
11✔
3004

3005
  return 0;
3006
}
3007

3008
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
3009
  Position width, int basis, int* pixels, int32_t* data)
3010
{
3011
  if (int err = check_mesh(index))
44!
3012
    return err;
3013
  const auto& mesh = model::meshes[index].get();
44!
3014

3015
  int pixel_width = pixels[0];
44✔
3016
  int pixel_height = pixels[1];
44✔
3017

3018
  // get pixel size
3019
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
3020
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
3021

3022
  // setup basis indices and initial position centered on pixel
3023
  int in_i, out_i;
44✔
3024
  Position xyz = origin;
44✔
3025
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
3026
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
3027
  switch (basis_enum) {
44!
3028
  case PlotBasis::xy:
3029
    in_i = 0;
3030
    out_i = 1;
3031
    break;
3032
  case PlotBasis::xz:
3033
    in_i = 0;
3034
    out_i = 2;
3035
    break;
3036
  case PlotBasis::yz:
3037
    in_i = 1;
3038
    out_i = 2;
3039
    break;
3040
  default:
×
3041
    UNREACHABLE();
×
3042
  }
3043

3044
  // set initial position
3045
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
3046
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
3047

3048
#pragma omp parallel
24✔
3049
  {
20✔
3050
    Position r = xyz;
20✔
3051

3052
#pragma omp for
3053
    for (int y = 0; y < pixel_height; y++) {
420✔
3054
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
3055
      for (int x = 0; x < pixel_width; x++) {
8,400✔
3056
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
3057
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
3058
      }
3059
    }
3060
  }
3061

3062
  return 0;
44✔
3063
}
3064

3065
//! Get the dimension of a regular mesh
3066
extern "C" int openmc_regular_mesh_get_dimension(
11✔
3067
  int32_t index, int** dims, int* n)
3068
{
3069
  if (int err = check_mesh_type<RegularMesh>(index))
11!
3070
    return err;
3071
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
3072
  *dims = mesh->shape_.data();
11✔
3073
  *n = mesh->n_dimension_;
11✔
3074
  return 0;
11✔
3075
}
3076

3077
//! Set the dimension of a regular mesh
3078
extern "C" int openmc_regular_mesh_set_dimension(
187✔
3079
  int32_t index, int n, const int* dims)
3080
{
3081
  if (int err = check_mesh_type<RegularMesh>(index))
187!
3082
    return err;
3083
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
3084

3085
  // Copy dimension
3086
  mesh->n_dimension_ = n;
187✔
3087
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
3088
  return 0;
187✔
3089
}
3090

3091
//! Get the regular mesh parameters
3092
extern "C" int openmc_regular_mesh_get_params(
209✔
3093
  int32_t index, double** ll, double** ur, double** width, int* n)
3094
{
3095
  if (int err = check_mesh_type<RegularMesh>(index))
209!
3096
    return err;
3097
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
3098

3099
  if (m->lower_left_.empty()) {
209!
3100
    set_errmsg("Mesh parameters have not been set.");
×
3101
    return OPENMC_E_ALLOCATE;
×
3102
  }
3103

3104
  *ll = m->lower_left_.data();
209✔
3105
  *ur = m->upper_right_.data();
209✔
3106
  *width = m->width_.data();
209✔
3107
  *n = m->n_dimension_;
209✔
3108
  return 0;
209✔
3109
}
3110

3111
//! Set the regular mesh parameters
3112
extern "C" int openmc_regular_mesh_set_params(
220✔
3113
  int32_t index, int n, const double* ll, const double* ur, const double* width)
3114
{
3115
  if (int err = check_mesh_type<RegularMesh>(index))
220!
3116
    return err;
3117
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
3118

3119
  if (m->n_dimension_ == -1) {
220!
3120
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
3121
    return OPENMC_E_UNASSIGNED;
×
3122
  }
3123

3124
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
3125
  if (ll && ur) {
220✔
3126
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
3127
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
3128
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
3129
  } else if (ll && width) {
22✔
3130
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
3131
    m->width_ = tensor::Tensor<double>(width, n);
11✔
3132
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
3133
  } else if (ur && width) {
11!
3134
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
3135
    m->width_ = tensor::Tensor<double>(width, n);
11✔
3136
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
3137
  } else {
3138
    set_errmsg("At least two parameters must be specified.");
×
3139
    return OPENMC_E_INVALID_ARGUMENT;
×
3140
  }
3141

3142
  // Set material volumes
3143

3144
  // TODO: incorporate this into method in RegularMesh that can be called from
3145
  // here and from constructor
3146
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
3147
  m->element_volume_ = 1.0;
220✔
3148
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
3149
    m->element_volume_ *= m->width_[i];
660✔
3150
  }
3151

3152
  return 0;
3153
}
220✔
3154

3155
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
3156
template<class C>
3157
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
3158
  const int nx, const double* grid_y, const int ny, const double* grid_z,
3159
  const int nz)
3160
{
3161
  if (int err = check_mesh_type<C>(index))
88!
3162
    return err;
3163

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

3166
  m->n_dimension_ = 3;
88✔
3167

3168
  m->grid_[0].reserve(nx);
88✔
3169
  m->grid_[1].reserve(ny);
88✔
3170
  m->grid_[2].reserve(nz);
88✔
3171

3172
  for (int i = 0; i < nx; i++) {
572✔
3173
    m->grid_[0].push_back(grid_x[i]);
484✔
3174
  }
3175
  for (int i = 0; i < ny; i++) {
341✔
3176
    m->grid_[1].push_back(grid_y[i]);
253✔
3177
  }
3178
  for (int i = 0; i < nz; i++) {
319✔
3179
    m->grid_[2].push_back(grid_z[i]);
231✔
3180
  }
3181

3182
  int err = m->set_grid();
88✔
3183
  return err;
88✔
3184
}
3185

3186
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
3187
template<class C>
3188
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
3189
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3190
{
3191
  if (int err = check_mesh_type<C>(index))
385!
3192
    return err;
3193
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
3194

3195
  if (m->lower_left_.empty()) {
385!
3196
    set_errmsg("Mesh parameters have not been set.");
×
3197
    return OPENMC_E_ALLOCATE;
×
3198
  }
3199

3200
  *grid_x = m->grid_[0].data();
385✔
3201
  *nx = m->grid_[0].size();
385✔
3202
  *grid_y = m->grid_[1].data();
385✔
3203
  *ny = m->grid_[1].size();
385✔
3204
  *grid_z = m->grid_[2].data();
385✔
3205
  *nz = m->grid_[2].size();
385✔
3206

3207
  return 0;
385✔
3208
}
3209

3210
//! Get the rectilinear mesh grid
3211
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
3212
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3213
{
3214
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
3215
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
3216
}
3217

3218
//! Set the rectilienar mesh parameters
3219
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
3220
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3221
  const double* grid_z, const int nz)
3222
{
3223
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
3224
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
3225
}
3226

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

3235
//! Set the cylindrical mesh parameters
3236
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
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<CylindricalMesh>(
22✔
3241
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
3242
}
3243

3244
//! Get the spherical mesh grid
3245
extern "C" int openmc_spherical_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

3249
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
3250
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
3251
  ;
121✔
3252
}
3253

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

3263
#ifdef OPENMC_DAGMC_ENABLED
3264

3265
const std::string MOABMesh::mesh_lib_type = "moab";
3266

3267
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
3268
{
3269
  initialize();
24✔
3270
}
24!
3271

3272
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
3273
{
3274
  initialize();
×
3275
}
×
3276

3277
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
3278
  : UnstructuredMesh()
×
3279
{
3280
  n_dimension_ = 3;
3281
  filename_ = filename;
×
3282
  set_length_multiplier(length_multiplier);
×
3283
  initialize();
×
3284
}
×
3285

3286
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
3287
{
3288
  mbi_ = external_mbi;
1✔
3289
  filename_ = "unknown (external file)";
1✔
3290
  this->initialize();
1✔
3291
}
1!
3292

3293
void MOABMesh::initialize()
25✔
3294
{
3295

3296
  // Create the MOAB interface and load data from file
3297
  this->create_interface();
25✔
3298

3299
  // Initialise MOAB error code
3300
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
3301

3302
  // Set the dimension
3303
  n_dimension_ = 3;
25✔
3304

3305
  // set member range of tetrahedral entities
3306
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
3307
  if (rval != moab::MB_SUCCESS) {
25!
3308
    fatal_error("Failed to get all tetrahedral elements");
3309
  }
3310

3311
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
3312
    warning("Non-tetrahedral elements found in unstructured "
×
3313
            "mesh file: " +
3314
            filename_);
3315
  }
3316

3317
  // set member range of vertices
3318
  int vertex_dim = 0;
25✔
3319
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
3320
  if (rval != moab::MB_SUCCESS) {
25!
3321
    fatal_error("Failed to get all vertex handles");
3322
  }
3323

3324
  // make an entity set for all tetrahedra
3325
  // this is used for convenience later in output
3326
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
3327
  if (rval != moab::MB_SUCCESS) {
25!
3328
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3329
  }
3330

3331
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
3332
  if (rval != moab::MB_SUCCESS) {
25!
3333
    fatal_error("Failed to add tetrahedra to an entity set.");
3334
  }
3335

3336
  if (length_multiplier_ > 0.0) {
25!
3337
    // get the connectivity of all tets
3338
    moab::Range adj;
×
3339
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
3340
    if (rval != moab::MB_SUCCESS) {
×
3341
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3342
    }
3343
    // scale all vertex coords by multiplier (done individually so not all
3344
    // coordinates are in memory twice at once)
3345
    for (auto vert : adj) {
×
3346
      // retrieve coords
3347
      std::array<double, 3> coord;
3348
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
3349
      if (rval != moab::MB_SUCCESS) {
×
3350
        fatal_error("Could not get coordinates of vertex.");
3351
      }
3352
      // scale coords
3353
      for (auto& c : coord) {
×
3354
        c *= length_multiplier_;
3355
      }
3356
      // set new coords
3357
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
3358
      if (rval != moab::MB_SUCCESS) {
×
3359
        fatal_error("Failed to set new vertex coordinates");
3360
      }
3361
    }
3362
  }
3363

3364
  // Determine bounds of mesh
3365
  this->determine_bounds();
25✔
3366
}
25✔
3367

3368
void MOABMesh::prepare_for_point_location()
21✔
3369
{
3370
  // if the KDTree has already been constructed, do nothing
3371
  if (kdtree_)
21!
3372
    return;
3373

3374
  // build acceleration data structures
3375
  compute_barycentric_data(ehs_);
21✔
3376
  build_kdtree(ehs_);
21✔
3377
}
3378

3379
void MOABMesh::create_interface()
25✔
3380
{
3381
  // Do not create a MOAB instance if one is already in memory
3382
  if (mbi_)
25✔
3383
    return;
3384

3385
  // create MOAB instance
3386
  mbi_ = std::make_shared<moab::Core>();
24!
3387

3388
  // load unstructured mesh file
3389
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
3390
  if (rval != moab::MB_SUCCESS) {
24!
3391
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3392
  }
3393
}
3394

3395
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
3396
{
3397
  moab::Range all_tris;
21✔
3398
  int adj_dim = 2;
21✔
3399
  write_message("Getting tet adjacencies...", 7);
21✔
3400
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
3401
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3402
  if (rval != moab::MB_SUCCESS) {
21!
3403
    fatal_error("Failed to get adjacent triangles for tets");
3404
  }
3405

3406
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3407
    warning("Non-triangle elements found in tet adjacencies in "
×
3408
            "unstructured mesh file: " +
3409
            filename_);
×
3410
  }
3411

3412
  // combine into one range
3413
  moab::Range all_tets_and_tris;
21✔
3414
  all_tets_and_tris.merge(all_tets);
21✔
3415
  all_tets_and_tris.merge(all_tris);
21✔
3416

3417
  // create a kd-tree instance
3418
  write_message(
21✔
3419
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3420
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3421

3422
  // Determine what options to use
3423
  std::ostringstream options_stream;
21✔
3424
  if (options_.empty()) {
21✔
3425
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3426
  } else {
3427
    options_stream << options_;
16✔
3428
  }
3429
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3430

3431
  // Build the k-d tree
3432
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3433
  if (rval != moab::MB_SUCCESS) {
21!
3434
    fatal_error("Failed to construct KDTree for the "
3435
                "unstructured mesh file: " +
3436
                filename_);
×
3437
  }
3438
}
21✔
3439

3440
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3441
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3442
{
3443
  hits.clear();
1,543,584!
3444

3445
  moab::ErrorCode rval;
1,543,584✔
3446
  vector<moab::EntityHandle> tris;
1,543,584✔
3447
  // get all intersections with triangles in the tet mesh
3448
  // (distances are relative to the start point, not the previous
3449
  // intersection)
3450
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3451
    dir.array(), start.array(), tris, hits, 0, track_len);
3452
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3453
    fatal_error(
3454
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3455
  }
3456

3457
  // remove duplicate intersection distances
3458
  std::unique(hits.begin(), hits.end());
1,543,584✔
3459

3460
  // sorts by first component of std::pair by default
3461
  std::sort(hits.begin(), hits.end());
1,543,584✔
3462
}
1,543,584✔
3463

3464
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3465
  vector<int>& bins, vector<double>& lengths) const
3466
{
3467
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3468
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3469
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3470
  dir.normalize();
1,543,584✔
3471

3472
  double track_len = (end - start).length();
1,543,584✔
3473
  if (track_len == 0.0)
1,543,584!
3474
    return;
721,692✔
3475

3476
  start -= TINY_BIT * dir;
1,543,584✔
3477
  end += TINY_BIT * dir;
1,543,584✔
3478

3479
  vector<double> hits;
1,543,584✔
3480
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3481

3482
  bins.clear();
1,543,584!
3483
  lengths.clear();
1,543,584!
3484

3485
  // if there are no intersections the track may lie entirely
3486
  // within a single tet. If this is the case, apply entire
3487
  // score to that tet and return.
3488
  if (hits.size() == 0) {
1,543,584✔
3489
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3490
    int bin = this->get_bin(midpoint);
721,692✔
3491
    if (bin != -1) {
721,692✔
3492
      bins.push_back(bin);
242,866✔
3493
      lengths.push_back(1.0);
242,866✔
3494
    }
3495
    return;
721,692✔
3496
  }
3497

3498
  // for each segment in the set of tracks, try to look up a tet
3499
  // at the midpoint of the segment
3500
  Position current = r0;
3501
  double last_dist = 0.0;
3502
  for (const auto& hit : hits) {
5,516,161✔
3503
    // get the segment length
3504
    double segment_length = hit - last_dist;
4,694,269✔
3505
    last_dist = hit;
4,694,269✔
3506
    // find the midpoint of this segment
3507
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3508
    // try to find a tet for this position
3509
    int bin = this->get_bin(midpoint);
4,694,269✔
3510

3511
    // determine the start point for this segment
3512
    current = r0 + u * hit;
4,694,269✔
3513

3514
    if (bin == -1) {
4,694,269✔
3515
      continue;
20,522✔
3516
    }
3517

3518
    bins.push_back(bin);
4,673,747✔
3519
    lengths.push_back(segment_length / track_len);
4,673,747✔
3520
  }
3521

3522
  // tally remaining portion of track after last hit if
3523
  // the last segment of the track is in the mesh but doesn't
3524
  // reach the other side of the tet
3525
  if (hits.back() < track_len) {
821,892!
3526
    Position segment_start = r0 + u * hits.back();
821,892✔
3527
    double segment_length = track_len - hits.back();
821,892✔
3528
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3529
    int bin = this->get_bin(midpoint);
821,892✔
3530
    if (bin != -1) {
821,892✔
3531
      bins.push_back(bin);
766,509✔
3532
      lengths.push_back(segment_length / track_len);
766,509✔
3533
    }
3534
  }
3535
};
1,543,584✔
3536

3537
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3538
{
3539
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3540
  // find the leaf of the kd-tree for this position
3541
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3542
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3543
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3544
    return 0;
3545
  }
3546

3547
  // retrieve the tet elements of this leaf
3548
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3549
  moab::Range tets;
6,305,335✔
3550
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3551
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3552
    warning("MOAB error finding tets.");
×
3553
  }
3554

3555
  // loop over the tets in this leaf, returning the containing tet if found
3556
  for (const auto& tet : tets) {
260,211,273✔
3557
    if (point_in_tet(pos, tet)) {
260,208,426✔
3558
      return tet;
6,302,488✔
3559
    }
3560
  }
3561

3562
  // if no tet is found, return an invalid handle
3563
  return 0;
2,847✔
3564
}
14,634,464✔
3565

3566
double MOABMesh::volume(int bin) const
167,880✔
3567
{
3568
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3569
}
3570

3571
std::string MOABMesh::library() const
34✔
3572
{
3573
  return mesh_lib_type;
34✔
3574
}
3575

3576
// Sample position within a tet for MOAB type tets
3577
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3578
{
3579

3580
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3581

3582
  // Get vertex coordinates for MOAB tet
3583
  const moab::EntityHandle* conn1;
200,410✔
3584
  int conn1_size;
200,410✔
3585
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3586
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3587
    fatal_error(fmt::format(
3588
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3589
      conn1_size));
3590
  }
3591
  moab::CartVect p[4];
200,410✔
3592
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3593
  if (rval != moab::MB_SUCCESS) {
200,410!
3594
    fatal_error("Failed to get tet coords");
3595
  }
3596

3597
  std::array<Position, 4> tet_verts;
200,410✔
3598
  for (int i = 0; i < 4; i++) {
1,002,050✔
3599
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3600
  }
3601
  // Samples position within tet using Barycentric stuff
3602
  return this->sample_tet(tet_verts, seed);
200,410✔
3603
}
3604

3605
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3606
{
3607
  vector<moab::EntityHandle> conn;
167,880✔
3608
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3609
  if (rval != moab::MB_SUCCESS) {
167,880!
3610
    fatal_error("Failed to get tet connectivity");
3611
  }
3612

3613
  moab::CartVect p[4];
167,880✔
3614
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3615
  if (rval != moab::MB_SUCCESS) {
167,880!
3616
    fatal_error("Failed to get tet coords");
3617
  }
3618

3619
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3620
}
167,880✔
3621

3622
int MOABMesh::get_bin(Position r) const
7,317,232✔
3623
{
3624
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3625
  if (tet == 0) {
7,317,232✔
3626
    return -1;
3627
  } else {
3628
    return get_bin_from_ent_handle(tet);
6,302,488✔
3629
  }
3630
}
3631

3632
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3633
{
3634
  moab::ErrorCode rval;
21✔
3635

3636
  baryc_data_.clear();
21!
3637
  baryc_data_.resize(tets.size());
21✔
3638

3639
  // compute the barycentric data for each tet element
3640
  // and store it as a 3x3 matrix
3641
  for (auto& tet : tets) {
239,757✔
3642
    vector<moab::EntityHandle> verts;
239,736✔
3643
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3644
    if (rval != moab::MB_SUCCESS) {
239,736!
3645
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3646
    }
3647

3648
    moab::CartVect p[4];
239,736✔
3649
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3650
    if (rval != moab::MB_SUCCESS) {
239,736!
3651
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3652
    }
3653

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

3656
    // invert now to avoid this cost later
3657
    a = a.transpose().inverse();
239,736✔
3658
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3659
  }
239,736✔
3660
}
21✔
3661

3662
bool MOABMesh::point_in_tet(
260,208,426✔
3663
  const moab::CartVect& r, moab::EntityHandle tet) const
3664
{
3665

3666
  moab::ErrorCode rval;
260,208,426✔
3667

3668
  // get tet vertices
3669
  vector<moab::EntityHandle> verts;
260,208,426✔
3670
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3671
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3672
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3673
    return false;
3674
  }
3675

3676
  // first vertex is used as a reference point for the barycentric data -
3677
  // retrieve its coordinates
3678
  moab::CartVect p_zero;
260,208,426✔
3679
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3680
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3681
    warning("Failed to get coordinates of a vertex in "
×
3682
            "unstructured mesh: " +
3683
            filename_);
×
3684
    return false;
3685
  }
3686

3687
  // look up barycentric data
3688
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3689
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3690

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

3693
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3694
          bary_coords[2] >= 0.0 &&
318,957,185✔
3695
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3696
}
260,208,426✔
3697

3698
int MOABMesh::get_bin_from_index(int idx) const
3699
{
3700
  if (idx >= n_bins()) {
×
3701
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3702
  }
3703
  return ehs_[idx] - ehs_[0];
3704
}
3705

3706
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3707
{
3708
  int bin = get_bin(r);
3709
  *in_mesh = bin != -1;
3710
  return bin;
3711
}
3712

3713
int MOABMesh::get_index_from_bin(int bin) const
3714
{
3715
  return bin;
3716
}
3717

3718
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3719
  Position plot_ll, Position plot_ur) const
3720
{
3721
  // TODO: Implement mesh lines
3722
  return {};
3723
}
3724

3725
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3726
{
3727
  int idx = vert - verts_[0];
815,520✔
3728
  if (idx >= n_vertices()) {
815,520!
3729
    fatal_error(
3730
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3731
  }
3732
  return idx;
815,520✔
3733
}
3734

3735
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3736
{
3737
  int bin = eh - ehs_[0];
266,750,650✔
3738
  if (bin >= n_bins()) {
266,750,650!
3739
    fatal_error(fmt::format("Invalid bin: {}", bin));
3740
  }
3741
  return bin;
266,750,650✔
3742
}
3743

3744
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3745
{
3746
  if (bin >= n_bins()) {
572,170!
3747
    fatal_error(fmt::format("Invalid bin index: ", bin));
3748
  }
3749
  return ehs_[0] + bin;
572,170✔
3750
}
3751

3752
int MOABMesh::n_bins() const
267,526,773✔
3753
{
3754
  return ehs_.size();
267,526,773✔
3755
}
3756

3757
int MOABMesh::n_surface_bins() const
3758
{
3759
  // collect all triangles in the set of tets for this mesh
3760
  moab::Range tris;
×
3761
  moab::ErrorCode rval;
3762
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3763
  if (rval != moab::MB_SUCCESS) {
×
3764
    warning("Failed to get all triangles in the mesh instance");
×
3765
    return -1;
3766
  }
3767
  return 2 * tris.size();
×
3768
}
3769

3770
Position MOABMesh::centroid(int bin) const
3771
{
3772
  moab::ErrorCode rval;
3773

3774
  auto tet = this->get_ent_handle_from_bin(bin);
3775

3776
  // look up the tet connectivity
3777
  vector<moab::EntityHandle> conn;
×
3778
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3779
  if (rval != moab::MB_SUCCESS) {
×
3780
    warning("Failed to get connectivity of a mesh element.");
×
3781
    return {};
3782
  }
3783

3784
  // get the coordinates
3785
  vector<moab::CartVect> coords(conn.size());
×
3786
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3787
  if (rval != moab::MB_SUCCESS) {
×
3788
    warning("Failed to get the coordinates of a mesh element.");
×
3789
    return {};
3790
  }
3791

3792
  // compute the centroid of the element vertices
3793
  moab::CartVect centroid(0.0, 0.0, 0.0);
3794
  for (const auto& coord : coords) {
×
3795
    centroid += coord;
3796
  }
3797
  centroid /= double(coords.size());
3798

3799
  return {centroid[0], centroid[1], centroid[2]};
3800
}
3801

3802
int MOABMesh::n_vertices() const
845,874✔
3803
{
3804
  return verts_.size();
845,874✔
3805
}
3806

3807
Position MOABMesh::vertex(int id) const
86,227✔
3808
{
3809

3810
  moab::ErrorCode rval;
86,227✔
3811

3812
  moab::EntityHandle vert = verts_[id];
86,227✔
3813

3814
  moab::CartVect coords;
86,227✔
3815
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3816
  if (rval != moab::MB_SUCCESS) {
86,227!
3817
    fatal_error("Failed to get the coordinates of a vertex.");
3818
  }
3819

3820
  return {coords[0], coords[1], coords[2]};
86,227✔
3821
}
3822

3823
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3824
{
3825
  moab::ErrorCode rval;
203,880✔
3826

3827
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3828

3829
  // look up the tet connectivity
3830
  vector<moab::EntityHandle> conn;
203,880✔
3831
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3832
  if (rval != moab::MB_SUCCESS) {
203,880!
3833
    fatal_error("Failed to get connectivity of a mesh element.");
3834
    return {};
3835
  }
3836

3837
  std::vector<int> verts(4);
203,880✔
3838
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3839
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3840
  }
3841

3842
  return verts;
203,880✔
3843
}
203,880✔
3844

3845
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3846
  std::string score) const
3847
{
3848
  moab::ErrorCode rval;
3849
  // add a tag to the mesh
3850
  // all scores are treated as a single value
3851
  // with an uncertainty
3852
  moab::Tag value_tag;
3853

3854
  // create the value tag if not present and get handle
3855
  double default_val = 0.0;
3856
  auto val_string = score + "_mean";
3857
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3858
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3859
  if (rval != moab::MB_SUCCESS) {
×
3860
    auto msg =
3861
      fmt::format("Could not create or retrieve the value tag for the score {}"
3862
                  " on unstructured mesh {}",
3863
        score, id_);
×
3864
    fatal_error(msg);
3865
  }
3866

3867
  // create the std dev tag if not present and get handle
3868
  moab::Tag error_tag;
3869
  std::string err_string = score + "_std_dev";
×
3870
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3871
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3872
  if (rval != moab::MB_SUCCESS) {
×
3873
    auto msg =
3874
      fmt::format("Could not create or retrieve the error tag for the score {}"
3875
                  " on unstructured mesh {}",
3876
        score, id_);
×
3877
    fatal_error(msg);
3878
  }
3879

3880
  // return the populated tag handles
3881
  return {value_tag, error_tag};
3882
}
3883

3884
void MOABMesh::add_score(const std::string& score)
3885
{
3886
  auto score_tags = get_score_tags(score);
×
3887
  tag_names_.push_back(score);
3888
}
3889

3890
void MOABMesh::remove_scores()
3891
{
3892
  for (const auto& name : tag_names_) {
×
3893
    auto value_name = name + "_mean";
3894
    moab::Tag tag;
3895
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3896
    if (rval != moab::MB_SUCCESS)
×
3897
      return;
3898

3899
    rval = mbi_->tag_delete(tag);
×
3900
    if (rval != moab::MB_SUCCESS) {
×
3901
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3902
                             " on unstructured mesh {}",
3903
        name, id_);
×
3904
      fatal_error(msg);
3905
    }
3906

3907
    auto std_dev_name = name + "_std_dev";
×
3908
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3909
    if (rval != moab::MB_SUCCESS) {
×
3910
      auto msg =
3911
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3912
                    " on unstructured mesh {}",
3913
          name, id_);
×
3914
    }
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
  tag_names_.clear();
3925
}
3926

3927
void MOABMesh::set_score_data(const std::string& score,
3928
  const vector<double>& values, const vector<double>& std_dev)
3929
{
3930
  auto score_tags = this->get_score_tags(score);
×
3931

3932
  moab::ErrorCode rval;
3933
  // set the score value
3934
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3935
  if (rval != moab::MB_SUCCESS) {
×
3936
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3937
                           "on unstructured mesh {}",
3938
      score, id_);
3939
    warning(msg);
×
3940
  }
3941

3942
  // set the error value
3943
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3944
  if (rval != moab::MB_SUCCESS) {
×
3945
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3946
                           "on unstructured mesh {}",
3947
      score, id_);
3948
    warning(msg);
×
3949
  }
3950
}
3951

3952
void MOABMesh::write(const std::string& base_filename) const
3953
{
3954
  // add extension to the base name
3955
  auto filename = base_filename + ".vtk";
3956
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3957
  filename = settings::path_output + filename;
×
3958

3959
  // write the tetrahedral elements of the mesh only
3960
  // to avoid clutter from zero-value data on other
3961
  // elements during visualization
3962
  moab::ErrorCode rval;
3963
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3964
  if (rval != moab::MB_SUCCESS) {
×
3965
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3966
    warning(msg);
×
3967
  }
3968
}
3969

3970
#endif
3971

3972
#ifdef OPENMC_LIBMESH_ENABLED
3973

3974
const std::string LibMesh::mesh_lib_type = "libmesh";
3975

3976
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
3977
{
3978
  // filename_ and length_multiplier_ will already be set by the
3979
  // UnstructuredMesh constructor
3980
  set_mesh_pointer_from_filename(filename_);
23✔
3981
  set_length_multiplier(length_multiplier_);
23✔
3982
  initialize();
23✔
3983
}
23✔
3984

3985
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3986
{
3987
  // filename_ and length_multiplier_ will already be set by the
3988
  // UnstructuredMesh constructor
3989
  set_mesh_pointer_from_filename(filename_);
×
3990
  set_length_multiplier(length_multiplier_);
×
3991
  initialize();
×
3992
}
3993

3994
// create the mesh from a pointer to a libMesh Mesh
3995
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3996
{
3997
  if (!input_mesh.is_replicated()) {
×
3998
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3999
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
4000
  }
4001

4002
  m_ = &input_mesh;
4003
  set_length_multiplier(length_multiplier);
×
4004
  initialize();
×
4005
}
4006

4007
// create the mesh from an input file
4008
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
4009
{
4010
  n_dimension_ = 3;
4011
  set_mesh_pointer_from_filename(filename);
×
4012
  set_length_multiplier(length_multiplier);
×
4013
  initialize();
×
4014
}
4015

4016
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23✔
4017
{
4018
  filename_ = filename;
23✔
4019
  unique_m_ =
23✔
4020
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23✔
4021
  m_ = unique_m_.get();
23✔
4022
  m_->read(filename_);
23✔
4023
}
23✔
4024

4025
// build a libMesh equation system for storing values
4026
void LibMesh::build_eqn_sys()
15✔
4027
{
4028
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
15✔
4029
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15✔
4030
  libMesh::ExplicitSystem& eq_sys =
15✔
4031
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15✔
4032
}
15✔
4033

4034
// intialize from mesh file
4035
void LibMesh::initialize()
23✔
4036
{
4037
  if (!settings::libmesh_comm) {
23!
4038
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
4039
                "communicator.");
4040
  }
4041

4042
  // assuming that unstructured meshes used in OpenMC are 3D
4043
  n_dimension_ = 3;
23✔
4044

4045
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
4046
  // Otherwise assume that it is prepared by its owning application
4047
  if (unique_m_) {
23!
4048
    m_->prepare_for_use();
23✔
4049
  }
4050

4051
  // ensure that the loaded mesh is 3 dimensional
4052
  if (m_->mesh_dimension() != n_dimension_) {
23!
4053
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
4054
                            "mesh is not a 3D mesh.",
4055
      filename_));
4056
  }
4057

4058
  for (int i = 0; i < num_threads(); i++) {
69✔
4059
    pl_.emplace_back(m_->sub_point_locator());
46✔
4060
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
4061
    pl_.back()->enable_out_of_mesh_mode();
46✔
4062
  }
4063

4064
  // store first element in the mesh to use as an offset for bin indices
4065
  auto first_elem = *m_->elements_begin();
46✔
4066
  first_element_id_ = first_elem->id();
23✔
4067

4068
  // bounding box for the mesh for quick rejection checks
4069
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23!
4070
  libMesh::Point ll = bbox_.min();
23!
4071
  libMesh::Point ur = bbox_.max();
23!
4072
  if (length_multiplier_ > 0.0) {
23!
4073
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
4074
      length_multiplier_ * ll(2)};
4075
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
4076
      length_multiplier_ * ur(2)};
4077
  } else {
4078
    lower_left_ = {ll(0), ll(1), ll(2)};
23✔
4079
    upper_right_ = {ur(0), ur(1), ur(2)};
23✔
4080
  }
4081
}
23✔
4082

4083
// Sample position within a tet for LibMesh type tets
4084
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
4085
{
4086
  const auto& elem = get_element_from_bin(bin);
400,820✔
4087
  // Get tet vertex coordinates from LibMesh
4088
  std::array<Position, 4> tet_verts;
400,820✔
4089
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
4090
    auto node_ref = elem.node_ref(i);
1,603,280✔
4091
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
4092
  }
1,603,280✔
4093
  // Samples position within tet using Barycentric coordinates
4094
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
4095
  if (length_multiplier_ > 0.0) {
400,820!
4096
    return length_multiplier_ * sampled_position;
4097
  } else {
4098
    return sampled_position;
400,820✔
4099
  }
4100
}
4101

4102
Position LibMesh::centroid(int bin) const
4103
{
4104
  const auto& elem = this->get_element_from_bin(bin);
4105
  auto centroid = elem.vertex_average();
4106
  if (length_multiplier_ > 0.0) {
×
4107
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
4108
  } else {
4109
    return {centroid(0), centroid(1), centroid(2)};
4110
  }
4111
}
4112

4113
int LibMesh::n_vertices() const
39,978✔
4114
{
4115
  return m_->n_nodes();
39,978✔
4116
}
4117

4118
Position LibMesh::vertex(int vertex_id) const
39,942✔
4119
{
4120
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
4121
  if (length_multiplier_ > 0.0) {
39,942!
4122
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
4123
  } else {
4124
    return {node_ref(0), node_ref(1), node_ref(2)};
39,942✔
4125
  }
4126
}
39,942✔
4127

4128
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
4129
{
4130
  std::vector<int> conn;
265,856✔
4131
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
4132
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
4133
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
4134
  }
4135
  return conn;
265,856✔
4136
}
4137

4138
std::string LibMesh::library() const
33✔
4139
{
4140
  return mesh_lib_type;
33✔
4141
}
4142

4143
int LibMesh::n_bins() const
1,784,407✔
4144
{
4145
  return m_->n_elem();
1,784,407✔
4146
}
4147

4148
int LibMesh::n_surface_bins() const
4149
{
4150
  int n_bins = 0;
4151
  for (int i = 0; i < this->n_bins(); i++) {
×
4152
    const libMesh::Elem& e = get_element_from_bin(i);
4153
    n_bins += e.n_faces();
4154
    // if this is a boundary element, it will only be visited once,
4155
    // the number of surface bins is incremented to
4156
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
4157
      // null neighbor pointer indicates a boundary face
4158
      if (!neighbor_ptr) {
×
4159
        n_bins++;
4160
      }
4161
    }
4162
  }
4163
  return n_bins;
4164
}
4165

4166
void LibMesh::add_score(const std::string& var_name)
15✔
4167
{
4168
  if (!equation_systems_) {
15!
4169
    build_eqn_sys();
15✔
4170
  }
4171

4172
  // check if this is a new variable
4173
  std::string value_name = var_name + "_mean";
15✔
4174
  if (!variable_map_.count(value_name)) {
15✔
4175
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
4176
    auto var_num =
15✔
4177
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
4178
    variable_map_[value_name] = var_num;
15✔
4179
  }
4180

4181
  std::string std_dev_name = var_name + "_std_dev";
15✔
4182
  // check if this is a new variable
4183
  if (!variable_map_.count(std_dev_name)) {
15✔
4184
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
4185
    auto var_num =
15✔
4186
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
4187
    variable_map_[std_dev_name] = var_num;
15✔
4188
  }
4189
}
15✔
4190

4191
void LibMesh::remove_scores()
15✔
4192
{
4193
  if (equation_systems_) {
15!
4194
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
4195
    eqn_sys.clear();
15✔
4196
    variable_map_.clear();
15✔
4197
  }
4198
}
15✔
4199

4200
void LibMesh::set_score_data(const std::string& var_name,
15✔
4201
  const vector<double>& values, const vector<double>& std_dev)
4202
{
4203
  if (!equation_systems_) {
15!
4204
    build_eqn_sys();
4205
  }
4206

4207
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
4208

4209
  if (!eqn_sys.is_initialized()) {
15!
4210
    equation_systems_->init();
15✔
4211
  }
4212

4213
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
4214

4215
  // look up the value variable
4216
  std::string value_name = var_name + "_mean";
15✔
4217
  unsigned int value_num = variable_map_.at(value_name);
15✔
4218
  // look up the std dev variable
4219
  std::string std_dev_name = var_name + "_std_dev";
15✔
4220
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15✔
4221

4222
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
195,757✔
4223
       it++) {
4224
    if (!(*it)->active()) {
97,856!
4225
      continue;
4226
    }
4227

4228
    auto bin = get_bin_from_element(*it);
97,856✔
4229

4230
    // set value
4231
    vector<libMesh::dof_id_type> value_dof_indices;
97,856✔
4232
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856✔
4233
    assert(value_dof_indices.size() == 1);
97,856✔
4234
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856✔
4235

4236
    // set std dev
4237
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
4238
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
4239
    assert(std_dev_dof_indices.size() == 1);
97,856✔
4240
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
4241
  }
97,871✔
4242
}
15✔
4243

4244
void LibMesh::write(const std::string& filename) const
15✔
4245
{
4246
  write_message(fmt::format(
15✔
4247
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15✔
4248
  libMesh::ExodusII_IO exo(*m_);
15✔
4249
  std::set<std::string> systems_out = {eq_system_name_};
30!
4250
  exo.write_discontinuous_exodusII(
15✔
4251
    filename + ".e", *equation_systems_, &systems_out);
30✔
4252
}
15✔
4253

4254
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
4255
  vector<int>& bins, vector<double>& lengths) const
4256
{
4257
  // TODO: Implement triangle crossings here
4258
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
4259
}
4260

4261
int LibMesh::get_bin(Position r) const
2,340,604✔
4262
{
4263
  // look-up a tet using the point locator
4264
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
4265

4266
  if (length_multiplier_ > 0.0) {
2,340,604!
4267
    // Scale the point down
4268
    p /= length_multiplier_;
2,340,604✔
4269
  }
4270

4271
  // quick rejection check
4272
  if (!bbox_.contains_point(p)) {
2,340,604✔
4273
    return -1;
4274
  }
4275

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

4278
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
4279
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
4280
}
2,340,604✔
4281

4282
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,434✔
4283
{
4284
  int bin = elem->id() - first_element_id_;
1,518,434✔
4285
  if (bin >= n_bins() || bin < 0) {
1,518,434!
4286
    fatal_error(fmt::format("Invalid bin: {}", bin));
4287
  }
4288
  return bin;
1,518,434✔
4289
}
4290

4291
std::pair<vector<double>, vector<double>> LibMesh::plot(
4292
  Position plot_ll, Position plot_ur) const
4293
{
4294
  return {};
4295
}
4296

4297
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
4298
{
4299
  return m_->elem_ref(bin);
765,460✔
4300
}
4301

4302
double LibMesh::volume(int bin) const
364,640✔
4303
{
4304
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
364,640✔
4305
         length_multiplier_ * length_multiplier_;
364,640✔
4306
}
4307

4308
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4309
  double length_multiplier,
4310
  const std::set<libMesh::subdomain_id_type>& block_ids)
4311
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4312
    block_restrict_(!block_ids_.empty()),
×
4313
    num_active_(
×
4314
      block_restrict_
4315
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
4316
            m_->active_subdomain_set_elements_end(block_ids_))
×
4317
        : m_->n_active_elem())
×
4318
{
4319
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4320
  // contiguous in ID space, so we need to map from bin indices (defined over
4321
  // active elements) to global dof ids
4322
  bin_to_elem_map_.reserve(num_active_);
×
4323
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
4324
  auto begin = block_restrict_
4325
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
4326
                 : m_->active_elements_begin();
×
4327
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
4328
                             : m_->active_elements_end();
×
4329
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
4330
    bin_to_elem_map_.push_back(elem->id());
×
4331
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
4332
  }
4333
}
4334

4335
int AdaptiveLibMesh::n_bins() const
4336
{
4337
  return num_active_;
4338
}
4339

4340
void AdaptiveLibMesh::add_score(const std::string& var_name)
4341
{
4342
  warning(fmt::format(
×
4343
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4344
    this->id_));
4345
}
4346

4347
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4348
  const vector<double>& values, const vector<double>& std_dev)
4349
{
4350
  warning(fmt::format(
×
4351
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4352
    this->id_));
4353
}
4354

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

4362
int AdaptiveLibMesh::get_bin(Position r) const
4363
{
4364
  // look-up a tet using the point locator
4365
  libMesh::Point p(r.x, r.y, r.z);
×
4366

4367
  if (length_multiplier_ > 0.0) {
×
4368
    // Scale the point down
4369
    p /= length_multiplier_;
4370
  }
4371

4372
  // quick rejection check
4373
  if (!bbox_.contains_point(p)) {
×
4374
    return -1;
4375
  }
4376

4377
  const auto& point_locator = pl_.at(thread_num());
×
4378

4379
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4380
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4381
}
4382

4383
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4384
{
4385
  int bin = elem_to_bin_map_[elem->id()];
4386
  if (bin >= n_bins() || bin < 0) {
×
4387
    fatal_error(fmt::format("Invalid bin: {}", bin));
4388
  }
4389
  return bin;
4390
}
4391

4392
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4393
{
4394
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4395
}
4396

4397
#endif // OPENMC_LIBMESH_ENABLED
4398

4399
//==============================================================================
4400
// Non-member functions
4401
//==============================================================================
4402

4403
void read_meshes(pugi::xml_node root)
12,771✔
4404
{
4405
  std::unordered_set<int> mesh_ids;
12,771✔
4406

4407
  for (auto node : root.children("mesh")) {
15,822✔
4408
    // Check to make sure multiple meshes in the same file don't share IDs
4409
    int id = std::stoi(get_node_value(node, "id"));
6,102✔
4410
    if (contains(mesh_ids, id)) {
6,102!
4411
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4412
                              "'{}' in the same input file",
4413
        id));
4414
    }
4415
    mesh_ids.insert(id);
3,051✔
4416

4417
    // If we've already read a mesh with the same ID in a *different* file,
4418
    // assume it is the same here
4419
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,051!
4420
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4421
      continue;
×
4422
    }
4423

4424
    std::string mesh_type;
3,051✔
4425
    if (check_for_node(node, "type")) {
3,051✔
4426
      mesh_type = get_node_value(node, "type", true, true);
1,014✔
4427
    } else {
4428
      mesh_type = "regular";
2,037✔
4429
    }
4430

4431
    // determine the mesh library to use
4432
    std::string mesh_lib;
3,051✔
4433
    if (check_for_node(node, "library")) {
3,051✔
4434
      mesh_lib = get_node_value(node, "library", true, true);
47!
4435
    }
4436

4437
    Mesh::create(node, mesh_type, mesh_lib);
3,051✔
4438
  }
3,051✔
4439
}
12,771✔
4440

4441
void read_meshes(hid_t group)
22✔
4442
{
4443
  std::unordered_set<int> mesh_ids;
22✔
4444

4445
  std::vector<int> ids;
22✔
4446
  read_attribute(group, "ids", ids);
22✔
4447

4448
  for (auto id : ids) {
55✔
4449

4450
    // Check to make sure multiple meshes in the same file don't share IDs
4451
    if (contains(mesh_ids, id)) {
66!
4452
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4453
                              "'{}' in the same HDF5 input file",
4454
        id));
4455
    }
4456
    mesh_ids.insert(id);
33✔
4457

4458
    // If we've already read a mesh with the same ID in a *different* file,
4459
    // assume it is the same here
4460
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
4461
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4462
      continue;
33✔
4463
    }
4464

4465
    std::string name = fmt::format("mesh {}", id);
×
4466
    hid_t mesh_group = open_group(group, name.c_str());
×
4467

4468
    std::string mesh_type;
×
4469
    if (object_exists(mesh_group, "type")) {
×
4470
      read_dataset(mesh_group, "type", mesh_type);
×
4471
    } else {
4472
      mesh_type = "regular";
×
4473
    }
4474

4475
    // determine the mesh library to use
4476
    std::string mesh_lib;
×
4477
    if (object_exists(mesh_group, "library")) {
×
4478
      read_dataset(mesh_group, "library", mesh_lib);
×
4479
    }
4480

4481
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4482
  }
×
4483
}
44✔
4484

4485
void meshes_to_hdf5(hid_t group)
7,115✔
4486
{
4487
  // Write number of meshes
4488
  hid_t meshes_group = create_group(group, "meshes");
7,115✔
4489
  int32_t n_meshes = model::meshes.size();
7,115✔
4490
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,115✔
4491

4492
  if (n_meshes > 0) {
7,115✔
4493
    // Write IDs of meshes
4494
    vector<int> ids;
2,236✔
4495
    for (const auto& m : model::meshes) {
5,051✔
4496
      m->to_hdf5(meshes_group);
2,815✔
4497
      ids.push_back(m->id_);
2,815✔
4498
    }
4499
    write_attribute(meshes_group, "ids", ids);
2,236✔
4500
  }
2,236✔
4501

4502
  close_group(meshes_group);
7,115✔
4503
}
7,115✔
4504

4505
void free_memory_mesh()
8,353✔
4506
{
4507
  model::meshes.clear();
8,353✔
4508
  model::mesh_map.clear();
8,353✔
4509
}
8,353✔
4510

4511
extern "C" int n_meshes()
308✔
4512
{
4513
  return model::meshes.size();
308✔
4514
}
4515

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

© 2026 Coveralls, Inc