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

openmc-dev / openmc / 29123958173

10 Jul 2026 09:12PM UTC coverage: 80.472% (-0.8%) from 81.292%
29123958173

Pull #3951

github

web-flow
Merge 62dca9136 into 7256d5046
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16757 of 24275 branches covered (69.03%)

Branch coverage included in aggregate %.

70 of 138 new or added lines in 10 files covered. (50.72%)

876 existing lines in 50 files now uncovered.

57507 of 68010 relevant lines covered (84.56%)

23274270.93 hits per line

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

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

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

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

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

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

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

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

59
#include "hdf5.h"
60

61
namespace openmc {
62

63
//==============================================================================
64
// Global variables
65
//==============================================================================
66

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

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

77
namespace model {
78

79
std::unordered_map<int32_t, int32_t> mesh_map;
80
vector<unique_ptr<Mesh>> meshes;
81

82
} // namespace model
83

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

91
//==============================================================================
92
// Helper functions
93
//==============================================================================
94

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

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

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

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

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

143
// Helper function equivalent to std::bit_cast in C++20
144
template<typename To, typename From>
145
inline To bit_cast_value(const From& value)
10,584,864✔
146
{
147
  To out;
148
  std::memcpy(&out, &value, sizeof(To));
11,021✔
149
  return out;
150
}
151

152
inline void atomic_update_double(double* ptr, double value, bool is_min)
10,584,864✔
153
{
154
#if defined(__GNUC__) || defined(__clang__)
155
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
10,584,864✔
156
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
10,584,864✔
157
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
10,584,864✔
158
  double current = bit_cast_value<double>(current_bits);
10,584,864✔
159
  while (is_min ? (value < current) : (value > current)) {
10,584,864✔
160
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
11,021✔
161
    uint64_t expected_bits = current_bits;
11,021✔
162
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
11,021!
163
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
164
      return;
10,584,864✔
165
    }
UNCOV
166
    current_bits = expected_bits;
×
UNCOV
167
    current = bit_cast_value<double>(current_bits);
×
168
  }
169

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

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

190
inline void atomic_max_double(double* ptr, double value)
5,292,432✔
191
{
192
  atomic_update_double(ptr, value, false);
1,764,144✔
193
}
1,764,144✔
194

195
inline void atomic_min_double(double* ptr, double value)
5,292,432✔
196
{
197
  atomic_update_double(ptr, value, true);
1,764,144✔
198
}
199

200
namespace detail {
201

202
//==============================================================================
203
// MaterialVolumes implementation
204
//==============================================================================
205

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

215
  // Loop for linear probing
216
  for (int attempt = 0; attempt < table_size_; ++attempt) {
2,487,795!
217
    // Determine slot to check, making sure it is positive
218
    int slot = (index_material + attempt) % table_size_;
2,487,795✔
219
    if (slot < 0)
2,487,795✔
220
      slot += table_size_;
1,601,394✔
221
    int32_t* slot_ptr = &this->materials(index_elem, slot);
2,487,795✔
222

223
    // Non-atomic read of current material
224
    int32_t current_val = *slot_ptr;
2,487,795✔
225

226
    // Found the desired material; accumulate volume and bbox
227
    if (current_val == index_material) {
2,487,795✔
228
#pragma omp atomic
229
      this->volumes(index_elem, slot) += volume;
2,487,372✔
230
      if (bbox) {
2,487,372✔
231
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
1,764,099✔
232
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
1,764,099✔
233
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
1,764,099✔
234
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
1,764,099✔
235
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
1,764,099✔
236
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
1,764,099✔
237
      }
238
      return;
2,487,372✔
239
    }
240

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

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

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

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

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

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

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

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

329
} // namespace detail
330

331
//==============================================================================
332
// Mesh implementation
333
//==============================================================================
334

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

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

368
  return model::meshes.back();
798✔
369
}
370

371
Mesh::Mesh(pugi::xml_node node)
810✔
372
{
373
  // Read mesh id
374
  id_ = std::stoi(get_node_value(node, "id"));
1,620✔
375
  if (check_for_node(node, "name"))
810✔
376
    name_ = get_node_value(node, "name");
3✔
377
}
810✔
378

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

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

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

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

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

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

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

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

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

426
vector<double> Mesh::volumes() const
69✔
427
{
428
  vector<double> volumes(n_bins());
69✔
429
  for (int i = 0; i < n_bins(); i++) {
290,253✔
430
    volumes[i] = this->volume(i);
290,184✔
431
  }
432
  return volumes;
69✔
433
}
×
434

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

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

457
  Timer timer;
57✔
458
  timer.start();
57✔
459

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

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

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

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

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

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

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

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

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

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

517
      // Loop over rays on face of bounding box
518
#pragma omp for collapse(2)
519
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
10,560✔
520
        for (int i2 = 0; i2 < n2; ++i2) {
1,848,132✔
521
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
1,837,707✔
522
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
1,837,707✔
523

524
          p.from_source(&site);
1,837,707✔
525

526
          // Determine particle's location
527
          if (!exhaustive_find_cell(p)) {
1,837,707✔
528
            out_of_model = true;
23,958✔
529
            continue;
23,958✔
530
          }
531

532
          // Set birth cell attribute
533
          if (p.cell_born() == C_NONE)
1,813,749!
534
            p.cell_born() = p.lowest_coord().cell();
1,813,749✔
535

536
          // Initialize last cells from current cell
537
          for (int j = 0; j < p.n_coord(); ++j) {
3,627,498✔
538
            p.cell_last(j) = p.coord(j).cell();
1,813,749✔
539
          }
540
          p.n_coord_last() = p.n_coord();
1,813,749✔
541

542
          while (true) {
2,899,461✔
543
            // Ray trace from r_start to r_end
544
            Position r0 = p.r();
2,356,605✔
545
            double max_distance = bbox.max[axis] - r0[axis];
2,356,605✔
546

547
            // Find the distance to the nearest boundary
548
            BoundaryInfo boundary = distance_to_boundary(p);
2,356,605✔
549

550
            // Advance particle forward
551
            double distance = std::min(boundary.distance(), max_distance);
2,356,605✔
552
            p.move_distance(distance);
2,356,605✔
553

554
            // Determine what mesh elements were crossed by particle
555
            bins.clear();
2,356,605✔
556
            length_fractions.clear();
2,356,605✔
557
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
2,356,605✔
558

559
            // Add volumes to any mesh elements that were crossed
560
            int i_material = p.material();
2,356,605✔
561
            if (i_material != C_NONE) {
2,356,605✔
562
              i_material = model::materials[i_material]->id();
748,791✔
563
            }
564
            double cumulative_frac = 0.0;
2,356,605✔
565
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
4,844,400✔
566
              int mesh_index = bins[i_bin];
2,487,795✔
567
              double length = distance * length_fractions[i_bin];
2,487,795✔
568
              double volume = length * d1 * d2;
2,487,795✔
569

570
              if (compute_bboxes) {
2,487,795✔
571
                double axis_start = r0[axis] + distance * cumulative_frac;
1,764,144✔
572
                double axis_end = axis_start + length;
1,764,144✔
573
                cumulative_frac += length_fractions[i_bin];
1,764,144✔
574

575
                Position contrib_min = site.r;
1,764,144✔
576
                Position contrib_max = site.r;
1,764,144✔
577

578
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
1,764,144✔
579
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
1,764,144✔
580
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
1,764,144✔
581
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
1,764,144✔
582
                contrib_min[axis] = std::min(axis_start, axis_end);
1,764,144!
583
                contrib_max[axis] = std::max(axis_start, axis_end);
3,528,288!
584

585
                BoundingBox contrib_bbox {contrib_min, contrib_max};
1,764,144✔
586
                contrib_bbox &= bbox;
1,764,144✔
587

588
                result.add_volume(
1,764,144✔
589
                  mesh_index, i_material, volume, &contrib_bbox);
590
              } else {
591
                // Add volume to result
592
                result.add_volume(mesh_index, i_material, volume);
723,651✔
593
              }
594
            }
595

596
            if (distance == max_distance)
2,356,605✔
597
              break;
598

599
            // cross next geometric surface
600
            for (int j = 0; j < p.n_coord(); ++j) {
1,085,712✔
601
              p.cell_last(j) = p.coord(j).cell();
542,856✔
602
            }
603
            p.n_coord_last() = p.n_coord();
542,856✔
604

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

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

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

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

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

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

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

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

700
  // Normalize based on known volumes of elements
701
  for (int i = 0; i < this->n_bins(); ++i) {
303✔
702
    // Estimated total volume in element i
703
    double volume = 0.0;
704
    for (int j = 0; j < table_size; ++j) {
2,277✔
705
      volume += result.volumes(i, j);
2,028✔
706
    }
707
    // Renormalize volumes based on known volume of element i
708
    double norm = this->volume(i) / volume;
249✔
709
    for (int j = 0; j < table_size; ++j) {
2,277✔
710
      result.volumes(i, j) *= norm;
2,028✔
711
    }
712
  }
713

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

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

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

740
  // Write mesh type
741
  write_dataset(mesh_group, "type", this->get_mesh_type());
858✔
742

743
  // Write mesh ID
744
  write_attribute(mesh_group, "id", id_);
858✔
745

746
  // Write mesh name
747
  write_dataset(mesh_group, "name", name_);
858✔
748

749
  // Write mesh data
750
  this->to_hdf5_inner(mesh_group);
858✔
751

752
  // Close group
753
  close_group(mesh_group);
858✔
754
}
858✔
755

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

760
std::string StructuredMesh::bin_label(int bin) const
1,411,548✔
761
{
762
  MeshIndex ijk = get_indices_from_bin(bin);
1,411,548✔
763

764
  if (n_dimension_ > 2) {
1,411,548✔
765
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
1,407,093✔
766
  } else if (n_dimension_ > 1) {
4,455✔
767
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
4,380✔
768
  } else {
769
    return fmt::format("Mesh Index ({})", ijk[0]);
75✔
770
  }
771
}
772

773
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
762✔
774
{
775
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
762✔
776
}
777

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

785
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
393,268!
786
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
393,268!
787

788
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
393,268!
789
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
393,268!
790

791
  return {x_min + (x_max - x_min) * prn(seed),
393,268✔
792
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
393,268✔
793
}
794

795
//==============================================================================
796
// Unstructured Mesh implementation
797
//==============================================================================
798

UNCOV
799
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
×
800
{
UNCOV
801
  n_dimension_ = 3;
×
802

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

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

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

UNCOV
827
  if (check_for_node(node, "options")) {
×
UNCOV
828
    options_ = get_node_value(node, "options");
×
829
  }
830

831
  // check if mesh tally data should be written with
832
  // statepoint files
UNCOV
833
  if (check_for_node(node, "output")) {
×
834
    output_ = get_node_value_bool(node, "output");
×
835
  }
UNCOV
836
}
×
837

838
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
839
{
840
  n_dimension_ = 3;
×
841

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

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

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

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

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

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

UNCOV
900
Position UnstructuredMesh::sample_tet(
×
901
  std::array<Position, 4> coords, uint64_t* seed) const
902
{
903
  // Uniform distribution
UNCOV
904
  double s = prn(seed);
×
UNCOV
905
  double t = prn(seed);
×
UNCOV
906
  double u = prn(seed);
×
907

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

930
const std::string UnstructuredMesh::mesh_type = "unstructured";
931

UNCOV
932
std::string UnstructuredMesh::get_mesh_type() const
×
933
{
UNCOV
934
  return mesh_type;
×
935
}
936

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

UNCOV
943
std::string UnstructuredMesh::bin_label(int bin) const
×
944
{
UNCOV
945
  return fmt::format("Mesh Index ({})", bin);
×
946
};
947

UNCOV
948
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
×
949
{
NEW
950
  write_message(2, "line 1");
×
UNCOV
951
  write_dataset(mesh_group, "filename", filename_);
×
NEW
952
  write_message(2, "line 2");
×
UNCOV
953
  write_dataset(mesh_group, "library", this->library());
×
NEW
954
  write_message(2, "line 3");  
×
UNCOV
955
  if (!options_.empty()) {
×
UNCOV
956
    write_attribute(mesh_group, "options", options_);
×
957
  }
NEW
958
  write_message(2, "line 4");
×
959
  
960
  if (length_multiplier_ > 0.0)
×
961
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
NEW
962
  write_message(2, "line 5");    
×
963

964
  // write vertex coordinates
UNCOV
965
  tensor::Tensor<double> vertices(
×
UNCOV
966
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
×
UNCOV
967
  for (int i = 0; i < this->n_vertices(); i++) {
×
UNCOV
968
    auto v = this->vertex(i);
×
UNCOV
969
    vertices.slice(i) = {v.x, v.y, v.z};
×
970
  }
UNCOV
971
  write_dataset(mesh_group, "vertices", vertices);
×
972
  
NEW
973
  write_message(2, "line 6");  
×
974

UNCOV
975
  int num_elem_skipped = 0;
×
976

977
  // write element types and connectivity
UNCOV
978
  vector<double> volumes;
×
UNCOV
979
  tensor::Tensor<int> connectivity(
×
UNCOV
980
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
×
UNCOV
981
  tensor::Tensor<int> elem_types(
×
UNCOV
982
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
×
UNCOV
983
  for (int i = 0; i < this->n_bins(); i++) {
×
UNCOV
984
    auto conn = this->connectivity(i);
×
985

UNCOV
986
    volumes.emplace_back(this->volume(i));
×
987

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

NEW
1005
  write_message(2, "line 7");
×
1006

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

NEW
1015
  write_message(2, "line 8");
×
1016

UNCOV
1017
  write_dataset(mesh_group, "volumes", volumes);
×
1018
  
NEW
1019
  write_message(2, "line 9");  
×
UNCOV
1020
  write_dataset(mesh_group, "connectivity", connectivity);
×
1021
  
NEW
1022
  write_message(2, "line 10");  
×
UNCOV
1023
  write_dataset(mesh_group, "element_types", elem_types);
×
1024
  
NEW
1025
  write_message(2, "line 11");  
×
UNCOV
1026
}
×
1027

UNCOV
1028
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
×
1029
{
UNCOV
1030
  length_multiplier_ = length_multiplier;
×
UNCOV
1031
}
×
1032

UNCOV
1033
ElementType UnstructuredMesh::element_type(int bin) const
×
1034
{
UNCOV
1035
  auto conn = connectivity(bin);
×
1036

UNCOV
1037
  if (conn.size() == 4)
×
1038
    return ElementType::LINEAR_TET;
1039
  else if (conn.size() == 8)
×
1040
    return ElementType::LINEAR_HEX;
1041
  else
1042
    return ElementType::UNSUPPORTED;
×
UNCOV
1043
}
×
1044

1045
StructuredMesh::MeshIndex StructuredMesh::get_indices(
443,354,427✔
1046
  Position r, bool& in_mesh) const
1047
{
1048
  MeshIndex ijk;
443,354,427✔
1049
  in_mesh = true;
443,354,427✔
1050
  for (int i = 0; i < n_dimension_; ++i) {
1,745,886,219✔
1051
    ijk[i] = get_index_in_direction(r[i], i);
1,302,531,792✔
1052

1053
    if (ijk[i] < 1 || ijk[i] > shape_[i])
1,302,531,792✔
1054
      in_mesh = false;
28,069,455✔
1055
  }
1056
  return ijk;
443,354,427✔
1057
}
1058

1059
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
607,602,644✔
1060
{
1061
  switch (n_dimension_) {
607,602,644!
1062
  case 1:
240,165✔
1063
    return ijk[0] - 1;
240,165✔
1064
  case 2:
38,635,431✔
1065
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
38,635,431✔
1066
  case 3:
568,727,048✔
1067
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
568,727,048✔
1068
  default:
×
1069
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1070
  }
1071
}
1072

1073
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
2,119,909✔
1074
{
1075
  MeshIndex ijk;
2,119,909✔
1076
  if (n_dimension_ == 1) {
2,119,909✔
1077
    ijk[0] = bin + 1;
75✔
1078
  } else if (n_dimension_ == 2) {
2,119,834✔
1079
    ijk[0] = bin % shape_[0] + 1;
4,380✔
1080
    ijk[1] = bin / shape_[0] + 1;
4,380✔
1081
  } else if (n_dimension_ == 3) {
2,115,454!
1082
    ijk[0] = bin % shape_[0] + 1;
2,115,454✔
1083
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
2,115,454✔
1084
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
2,115,454✔
1085
  }
1086
  return ijk;
2,119,909✔
1087
}
1088

1089
int StructuredMesh::get_bin(Position r) const
116,084,652✔
1090
{
1091
  // Determine indices
1092
  bool in_mesh;
116,084,652✔
1093
  MeshIndex ijk = get_indices(r, in_mesh);
116,084,652✔
1094
  if (!in_mesh)
116,084,652✔
1095
    return -1;
1096

1097
  // Convert indices to bin
1098
  return get_bin_from_indices(ijk);
110,711,685✔
1099
}
1100

1101
int StructuredMesh::n_bins() const
294,267✔
1102
{
1103
  // Bin indices are stored as 32-bit ints in the tally system.
1104
  int64_t n = 1;
294,267✔
1105
  for (int i = 0; i < n_dimension_; ++i)
1,176,981✔
1106
    n *= shape_[i];
882,714✔
1107
  if (n > std::numeric_limits<int>::max()) {
294,267!
1108
    fatal_error(fmt::format(
×
1109
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1110
  }
1111
  return static_cast<int>(n);
294,267✔
1112
}
1113

1114
int StructuredMesh::n_surface_bins() const
90✔
1115
{
1116
  // Surface bin indices are stored as 32-bit ints in the tally system.
1117
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
90✔
1118
  if (n > std::numeric_limits<int>::max()) {
90!
1119
    fatal_error(fmt::format(
×
1120
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1121
  }
1122
  return static_cast<int>(n);
90✔
1123
}
1124

1125
tensor::Tensor<double> StructuredMesh::count_sites(
×
1126
  const SourceSite* bank, int64_t length, bool* outside) const
1127
{
1128
  // Determine shape of array for counts
1129
  std::size_t m = this->n_bins();
×
1130
  vector<std::size_t> shape = {m};
×
1131

1132
  // Create array of zeros
1133
  auto cnt = tensor::zeros<double>(shape);
×
1134
  bool outside_ = false;
1135

1136
  for (int64_t i = 0; i < length; i++) {
×
1137
    const auto& site = bank[i];
×
1138

1139
    // determine scoring bin for entropy mesh
1140
    int mesh_bin = get_bin(site.r);
×
1141

1142
    // if outside mesh, skip particle
1143
    if (mesh_bin < 0) {
×
1144
      outside_ = true;
×
1145
      continue;
×
1146
    }
1147

1148
    // Add to appropriate bin
1149
    cnt(mesh_bin) += site.wgt;
×
1150
  }
1151

1152
  // Create reduced count data
1153
  auto counts = tensor::zeros<double>(shape);
×
1154
  int total = cnt.size();
×
1155

1156
#ifdef OPENMC_MPI
1157
  // collect values from all processors
1158
  MPI_Reduce(
1159
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
1160

1161
  // Check if there were sites outside the mesh for any processor
1162
  if (outside) {
1163
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1164
  }
1165
#else
UNCOV
1166
  std::copy(cnt.data(), cnt.data() + total, counts.data());
×
UNCOV
1167
  if (outside)
×
UNCOV
1168
    *outside = outside_;
×
1169
#endif
1170

1171
  return counts;
×
1172
}
×
1173

1174
// raytrace through the mesh. The template class T will do the tallying.
1175
// A modern optimizing compiler can recognize the noop method of T and
1176
// eliminate that call entirely.
1177
template<class T>
1178
void StructuredMesh::raytrace_mesh(
339,383,778✔
1179
  Position r0, Position r1, const Direction& u, T tally) const
1180
{
1181
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1182
  // enable/disable tally calls for now, T template type needs to provide both
1183
  // surface and track methods, which might be empty. modern optimizing
1184
  // compilers will (hopefully) eliminate the complete code (including
1185
  // calculation of parameters) but for the future: be explicit
1186

1187
  // Compute the length of the entire track.
1188
  double total_distance = (r1 - r0).norm();
339,383,778✔
1189
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
339,383,778✔
1190
    return;
1191

1192
  // keep a copy of the original global position to pass to get_indices,
1193
  // which performs its own transformation to local coordinates
1194
  Position global_r = r0;
325,298,799✔
1195
  Position local_r = local_coords(r0);
325,298,799✔
1196

1197
  const int n = n_dimension_;
325,298,799✔
1198

1199
  // Flag if position is inside the mesh
1200
  bool in_mesh;
1201

1202
  // Position is r = r0 + u * traveled_distance, start at r0
1203
  double traveled_distance {0.0};
325,298,799✔
1204

1205
  // Calculate index of current cell. Offset the position a tiny bit in
1206
  // direction of flight
1207
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
325,298,799✔
1208

1209
  // if track is very short, assume that it is completely inside one cell.
1210
  // Only the current cell will score and no surfaces
1211
  if (total_distance < 2 * TINY_BIT) {
325,298,799✔
1212
    if (in_mesh) {
98,649✔
1213
      tally.track(ijk, 1.0);
98,517✔
1214
    }
1215
    return;
98,649✔
1216
  }
1217

1218
  // Calculate initial distances to next surfaces in all three dimensions
1219
  std::array<MeshDistance, 3> distances;
650,400,300✔
1220
  for (int k = 0; k < n; ++k) {
1,273,804,974✔
1221
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
948,604,824✔
1222
  }
1223

1224
  // Loop until r = r1 is eventually reached
1225
  while (true) {
1226

1227
    if (in_mesh) {
543,223,871✔
1228

1229
      // find surface with minimal distance to current position
1230
      const auto k = std::min_element(distances.begin(), distances.end()) -
519,124,817✔
1231
                     distances.begin();
519,124,817✔
1232

1233
      // Tally track length delta since last step
1234
      tally.track(ijk,
519,124,817✔
1235
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
786,258,296✔
1236
          total_distance);
1237

1238
      // update position and leave, if we have reached end position
1239
      traveled_distance = distances[k].distance;
519,124,817✔
1240
      if (traveled_distance >= total_distance)
519,124,817✔
1241
        return;
1242

1243
      // If we have not reached r1, we have hit a surface. Tally outward
1244
      // current
1245
      tally.surface(ijk, k, distances[k].max_surface, false);
216,052,745✔
1246

1247
      // Update cell and calculate distance to next surface in k-direction.
1248
      // The two other directions are still valid!
1249
      ijk[k] = distances[k].next_index;
216,052,745✔
1250
      distances[k] =
216,052,745✔
1251
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
216,052,745✔
1252

1253
      // Check if we have left the interior of the mesh
1254
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
217,930,577✔
1255

1256
      // If we are still inside the mesh, tally inward current for the next
1257
      // cell
1258
      if (in_mesh)
8,066,427✔
1259
        tally.surface(ijk, k, !distances[k].max_surface, true);
217,637,480✔
1260

1261
    } else { // not inside mesh
1262

1263
      // For all directions outside the mesh, find the distance that we need
1264
      // to travel to reach the next surface. Use the largest distance, as
1265
      // only this will cross all outer surfaces.
1266
      int k_max {-1};
1267
      for (int k = 0; k < n; ++k) {
95,995,590✔
1268
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
71,896,536✔
1269
            (distances[k].distance > traveled_distance)) {
26,257,965✔
1270
          traveled_distance = distances[k].distance;
1271
          k_max = k;
1272
        }
1273
      }
1274
      // Assure some distance is traveled
1275
      if (k_max == -1) {
24,099,054✔
1276
        traveled_distance += TINY_BIT;
30✔
1277
      }
1278

1279
      // If r1 is not inside the mesh, exit here
1280
      if (traveled_distance >= total_distance)
24,099,054✔
1281
        return;
1282

1283
      // Calculate the new cell index and update all distances to next
1284
      // surfaces.
1285
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
1,970,976✔
1286
      for (int k = 0; k < n; ++k) {
7,827,030✔
1287
        distances[k] =
5,856,054✔
1288
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
5,856,054✔
1289
      }
1290

1291
      // If inside the mesh, Tally inward current
1292
      if (in_mesh && k_max >= 0)
1,970,976!
1293
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
209,951,030✔
1294
    }
1295
  }
1296
}
1297

1298
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
308,803,533✔
1299
  vector<int>& bins, vector<double>& lengths) const
1300
{
1301

1302
  // Helper tally class.
1303
  // stores a pointer to the mesh class and references to bins and lengths
1304
  // parameters. Performs the actual tally through the track method.
1305
  struct TrackAggregator {
308,803,533✔
1306
    TrackAggregator(
308,803,533✔
1307
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1308
      : mesh(_mesh), bins(_bins), lengths(_lengths)
308,803,533✔
1309
    {}
1310
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1311
    void track(const MeshIndex& ijk, double l) const
481,029,362✔
1312
    {
1313
      bins.push_back(mesh->get_bin_from_indices(ijk));
481,029,362✔
1314
      lengths.push_back(l);
481,029,362✔
1315
    }
481,029,362✔
1316

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

1322
  // Perform the mesh raytrace with the helper class.
1323
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
308,803,533✔
1324
}
308,803,533✔
1325

1326
void StructuredMesh::surface_bins_crossed(
30,580,245✔
1327
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1328
{
1329

1330
  // Helper tally class.
1331
  // stores a pointer to the mesh class and a reference to the bins parameter.
1332
  // Performs the actual tally through the surface method.
1333
  struct SurfaceAggregator {
30,580,245✔
1334
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
30,580,245✔
1335
      : mesh(_mesh), bins(_bins)
30,580,245✔
1336
    {}
1337
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
15,861,597✔
1338
    {
1339
      int i_bin =
15,861,597✔
1340
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
15,861,597✔
1341
      if (max)
15,861,597✔
1342
        i_bin += 2;
7,923,120✔
1343
      if (inward)
15,861,597✔
1344
        i_bin += 1;
7,795,170✔
1345
      bins.push_back(i_bin);
15,861,597✔
1346
    }
15,861,597✔
1347
    void track(const MeshIndex& idx, double l) const {}
1348

1349
    const StructuredMesh* mesh;
1350
    vector<int>& bins;
1351
  };
1352

1353
  // Perform the mesh raytrace with the helper class.
1354
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
30,580,245✔
1355
}
30,580,245✔
1356

1357
//==============================================================================
1358
// RegularMesh implementation
1359
//==============================================================================
1360

1361
int RegularMesh::set_grid()
585✔
1362
{
1363
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
585✔
1364

1365
  // Check that dimensions are all greater than zero
1366
  if ((shape <= 0).any()) {
1,755!
1367
    set_errmsg("All entries for a regular mesh dimensions "
×
1368
               "must be positive.");
1369
    return OPENMC_E_INVALID_ARGUMENT;
×
1370
  }
1371

1372
  // Make sure lower_left and dimension match
1373
  if (lower_left_.size() != n_dimension_) {
585!
1374
    set_errmsg("Number of entries in lower_left must be the same "
×
1375
               "as the regular mesh dimensions.");
1376
    return OPENMC_E_INVALID_ARGUMENT;
×
1377
  }
1378
  if (width_.size() > 0) {
585✔
1379

1380
    // Check to ensure width has same dimensions
1381
    if (width_.size() != n_dimension_) {
9!
1382
      set_errmsg("Number of entries on width must be the same as "
×
1383
                 "the regular mesh dimensions.");
1384
      return OPENMC_E_INVALID_ARGUMENT;
×
1385
    }
1386

1387
    // Check for negative widths
1388
    if ((width_ < 0.0).any()) {
27!
1389
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1390
      return OPENMC_E_INVALID_ARGUMENT;
×
1391
    }
1392

1393
    // Set width and upper right coordinate
1394
    upper_right_ = lower_left_ + shape * width_;
27✔
1395

1396
  } else if (upper_right_.size() > 0) {
576!
1397

1398
    // Check to ensure upper_right_ has same dimensions
1399
    if (upper_right_.size() != n_dimension_) {
576!
1400
      set_errmsg("Number of entries on upper_right must be the "
×
1401
                 "same as the regular mesh dimensions.");
1402
      return OPENMC_E_INVALID_ARGUMENT;
×
1403
    }
1404

1405
    // Check that upper-right is above lower-left
1406
    if ((upper_right_ < lower_left_).any()) {
1,728!
1407
      set_errmsg(
×
1408
        "The upper_right coordinates of a regular mesh must be greater than "
1409
        "the lower_left coordinates.");
1410
      return OPENMC_E_INVALID_ARGUMENT;
×
1411
    }
1412

1413
    // Set width
1414
    width_ = (upper_right_ - lower_left_) / shape;
1,728✔
1415
  }
1416

1417
  // Set material volumes
1418
  volume_frac_ = 1.0 / shape.prod();
585✔
1419

1420
  element_volume_ = 1.0;
585✔
1421
  for (int i = 0; i < n_dimension_; i++) {
2,226✔
1422
    element_volume_ *= width_[i];
1,641✔
1423
  }
1424
  return 0;
1425
}
585✔
1426

1427
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
582✔
1428
{
1429
  // Determine number of dimensions for mesh
1430
  if (!check_for_node(node, "dimension")) {
582!
1431
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1432
  }
1433

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

1441
  // Check for lower-left coordinates
1442
  if (check_for_node(node, "lower_left")) {
582!
1443
    // Read mesh lower-left corner location
1444
    lower_left_ = get_node_tensor<double>(node, "lower_left");
582✔
1445
  } else {
1446
    fatal_error("Must specify <lower_left> on a mesh.");
×
1447
  }
1448

1449
  if (check_for_node(node, "width")) {
582✔
1450
    // Make sure one of upper-right or width were specified
1451
    if (check_for_node(node, "upper_right")) {
9!
1452
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1453
    }
1454

1455
    width_ = get_node_tensor<double>(node, "width");
18✔
1456

1457
  } else if (check_for_node(node, "upper_right")) {
573!
1458

1459
    upper_right_ = get_node_tensor<double>(node, "upper_right");
1,146✔
1460

1461
  } else {
1462
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1463
  }
1464

1465
  if (int err = set_grid()) {
582!
1466
    fatal_error(openmc_err_msg);
×
1467
  }
1468
}
582✔
1469

1470
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
3✔
1471
{
1472
  // Determine number of dimensions for mesh
1473
  if (!object_exists(group, "dimension")) {
3!
1474
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1475
  }
1476

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

1485
  // Check for lower-left coordinates
1486
  if (object_exists(group, "lower_left")) {
3!
1487
    // Read mesh lower-left corner location
1488
    read_dataset(group, "lower_left", lower_left_);
3✔
1489
  } else {
1490
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1491
  }
1492

1493
  if (object_exists(group, "upper_right")) {
3!
1494

1495
    read_dataset(group, "upper_right", upper_right_);
3✔
1496

1497
  } else {
1498
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1499
  }
1500

1501
  if (int err = set_grid()) {
3!
1502
    fatal_error(openmc_err_msg);
×
1503
  }
1504
}
3✔
1505

1506
int RegularMesh::get_index_in_direction(double r, int i) const
1,187,145,915✔
1507
{
1508
  return std::ceil((r - lower_left_[i]) / width_[i]);
1,187,145,915✔
1509
}
1510

1511
const std::string RegularMesh::mesh_type = "regular";
1512

1513
std::string RegularMesh::get_mesh_type() const
957✔
1514
{
1515
  return mesh_type;
957✔
1516
}
1517

1518
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
518,184,729✔
1519
{
1520
  return lower_left_[i] + ijk[i] * width_[i];
518,184,729✔
1521
}
1522

1523
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
499,300,767✔
1524
{
1525
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
499,300,767✔
1526
}
1527

1528
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1,025,484,213✔
1529
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1530
  double l) const
1531
{
1532
  MeshDistance d;
1,025,484,213✔
1533
  d.next_index = ijk[i];
1,025,484,213✔
1534
  if (std::abs(u[i]) < FP_PRECISION)
1,025,484,213✔
1535
    return d;
4,190,040✔
1536

1537
  d.max_surface = (u[i] > 0);
1,021,294,173✔
1538
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1,021,294,173✔
1539
    d.next_index++;
517,004,925✔
1540
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
517,004,925✔
1541
  } else if (!d.max_surface && (ijk[i] >= 1)) {
504,289,248✔
1542
    d.next_index--;
498,120,963✔
1543
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
498,120,963✔
1544
  }
1545

1546
  return d;
1,021,294,173✔
1547
}
1548

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

1571
  // Get the coordinates of the mesh lines along both of the axes.
1572
  array<vector<double>, 2> axis_lines;
1573
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
18✔
1574
    int axis = axes[i_ax];
12!
1575
    if (axis == -1)
12!
1576
      continue;
×
1577
    auto& lines {axis_lines[i_ax]};
12✔
1578

1579
    double coord = lower_left_[axis];
12✔
1580
    for (int i = 0; i < shape_[axis] + 1; ++i) {
78✔
1581
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
66!
1582
        lines.push_back(coord);
66✔
1583
      coord += width_[axis];
66✔
1584
    }
1585
  }
1586

1587
  return {axis_lines[0], axis_lines[1]};
12✔
1588
}
1589

1590
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
642✔
1591
{
1592
  write_dataset(mesh_group, "dimension", get_shape_tensor());
642✔
1593
  write_dataset(mesh_group, "lower_left", lower_left_);
642✔
1594
  write_dataset(mesh_group, "upper_right", upper_right_);
642✔
1595
  write_dataset(mesh_group, "width", width_);
642✔
1596
}
642✔
1597

1598
tensor::Tensor<double> RegularMesh::count_sites(
2,112✔
1599
  const SourceSite* bank, int64_t length, bool* outside) const
1600
{
1601
  // Determine shape of array for counts
1602
  std::size_t m = this->n_bins();
2,112✔
1603
  vector<std::size_t> shape = {m};
2,112✔
1604

1605
  // Create array of zeros
1606
  auto cnt = tensor::zeros<double>(shape);
2,112✔
1607
  bool outside_ = false;
1608

1609
  for (int64_t i = 0; i < length; i++) {
2,093,235✔
1610
    const auto& site = bank[i];
2,091,123✔
1611

1612
    // determine scoring bin for entropy mesh
1613
    int mesh_bin = get_bin(site.r);
2,091,123✔
1614

1615
    // if outside mesh, skip particle
1616
    if (mesh_bin < 0) {
2,091,123!
1617
      outside_ = true;
×
1618
      continue;
×
1619
    }
1620

1621
    // Add to appropriate bin
1622
    cnt(mesh_bin) += site.wgt;
2,091,123✔
1623
  }
1624

1625
  // Create reduced count data
1626
  auto counts = tensor::zeros<double>(shape);
2,112✔
1627
  int total = cnt.size();
2,112✔
1628

1629
#ifdef OPENMC_MPI
1630
  // collect values from all processors
1631
  MPI_Reduce(
1632
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
1633

1634
  // Check if there were sites outside the mesh for any processor
1635
  if (outside) {
1636
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1637
  }
1638
#else
1639
  std::copy(cnt.data(), cnt.data() + total, counts.data());
2,112✔
1640
  if (outside)
2,112!
1641
    *outside = outside_;
2,112✔
1642
#endif
1643

1644
  return counts;
2,112✔
1645
}
2,112✔
1646

1647
double RegularMesh::volume(const MeshIndex& ijk) const
290,526✔
1648
{
1649
  return element_volume_;
290,526✔
1650
}
1651

1652
//==============================================================================
1653
// RectilinearMesh implementation
1654
//==============================================================================
1655

1656
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
27✔
1657
{
1658
  n_dimension_ = 3;
27✔
1659

1660
  grid_[0] = get_node_array<double>(node, "x_grid");
27✔
1661
  grid_[1] = get_node_array<double>(node, "y_grid");
27✔
1662
  grid_[2] = get_node_array<double>(node, "z_grid");
27✔
1663

1664
  if (int err = set_grid()) {
27!
1665
    fatal_error(openmc_err_msg);
×
1666
  }
1667
}
27✔
1668

1669
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
3✔
1670
{
1671
  n_dimension_ = 3;
3✔
1672

1673
  read_dataset(group, "x_grid", grid_[0]);
3✔
1674
  read_dataset(group, "y_grid", grid_[1]);
3✔
1675
  read_dataset(group, "z_grid", grid_[2]);
3✔
1676

1677
  if (int err = set_grid()) {
3!
1678
    fatal_error(openmc_err_msg);
×
1679
  }
1680
}
3✔
1681

1682
const std::string RectilinearMesh::mesh_type = "rectilinear";
1683

1684
std::string RectilinearMesh::get_mesh_type() const
72✔
1685
{
1686
  return mesh_type;
72✔
1687
}
1688

1689
double RectilinearMesh::positive_grid_boundary(
7,228,899✔
1690
  const MeshIndex& ijk, int i) const
1691
{
1692
  return grid_[i][ijk[i]];
7,228,899✔
1693
}
1694

1695
double RectilinearMesh::negative_grid_boundary(
7,019,838✔
1696
  const MeshIndex& ijk, int i) const
1697
{
1698
  return grid_[i][ijk[i] - 1];
7,019,838✔
1699
}
1700

1701
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
14,618,751✔
1702
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1703
  double l) const
1704
{
1705
  MeshDistance d;
14,618,751✔
1706
  d.next_index = ijk[i];
14,618,751✔
1707
  if (std::abs(u[i]) < FP_PRECISION)
14,618,751✔
1708
    return d;
155,952✔
1709

1710
  d.max_surface = (u[i] > 0);
14,462,799✔
1711
  if (d.max_surface && (ijk[i] <= shape_[i])) {
14,462,799✔
1712
    d.next_index++;
7,228,899✔
1713
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
7,228,899✔
1714
  } else if (!d.max_surface && (ijk[i] > 0)) {
7,233,900✔
1715
    d.next_index--;
7,019,838✔
1716
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
7,019,838✔
1717
  }
1718
  return d;
14,462,799✔
1719
}
1720

1721
int RectilinearMesh::set_grid()
42✔
1722
{
1723
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
42✔
1724
    static_cast<int>(grid_[1].size()) - 1,
42✔
1725
    static_cast<int>(grid_[2].size()) - 1};
42✔
1726

1727
  for (const auto& g : grid_) {
168✔
1728
    if (g.size() < 2) {
126!
1729
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1730
                 "must each have at least 2 points");
1731
      return OPENMC_E_INVALID_ARGUMENT;
×
1732
    }
1733
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
126!
1734
        g.end()) {
126!
1735
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1736
                 "rectilinear meshes must be sorted and unique.");
1737
      return OPENMC_E_INVALID_ARGUMENT;
×
1738
    }
1739
  }
1740

1741
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
42✔
1742
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
42✔
1743

1744
  return 0;
42✔
1745
}
1746

1747
int RectilinearMesh::get_index_in_direction(double r, int i) const
20,211,516✔
1748
{
1749
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
20,211,516✔
1750
}
1751

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

1767
  // Get the coordinates of the mesh lines along both of the axes.
1768
  array<vector<double>, 2> axis_lines;
1769
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
9✔
1770
    int axis = axes[i_ax];
6✔
1771
    vector<double>& lines {axis_lines[i_ax]};
6✔
1772

1773
    for (auto coord : grid_[axis]) {
30✔
1774
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
24!
1775
        lines.push_back(coord);
24✔
1776
    }
1777
  }
1778

1779
  return {axis_lines[0], axis_lines[1]};
6✔
1780
}
1781

1782
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
27✔
1783
{
1784
  write_dataset(mesh_group, "x_grid", grid_[0]);
27✔
1785
  write_dataset(mesh_group, "y_grid", grid_[1]);
27✔
1786
  write_dataset(mesh_group, "z_grid", grid_[2]);
27✔
1787
}
27✔
1788

1789
double RectilinearMesh::volume(const MeshIndex& ijk) const
36✔
1790
{
1791
  double vol {1.0};
36✔
1792

1793
  for (int i = 0; i < n_dimension_; i++) {
144✔
1794
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
108✔
1795
  }
1796
  return vol;
36✔
1797
}
1798

1799
//==============================================================================
1800
// CylindricalMesh implementation
1801
//==============================================================================
1802

1803
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
108✔
1804
  : PeriodicStructuredMesh {node}
108✔
1805
{
1806
  n_dimension_ = 3;
108✔
1807
  grid_[0] = get_node_array<double>(node, "r_grid");
108✔
1808
  grid_[1] = get_node_array<double>(node, "phi_grid");
108✔
1809
  grid_[2] = get_node_array<double>(node, "z_grid");
108✔
1810
  origin_ = get_node_position(node, "origin");
108✔
1811

1812
  if (int err = set_grid()) {
108!
1813
    fatal_error(openmc_err_msg);
×
1814
  }
1815
}
108✔
1816

1817
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
3✔
1818
{
1819
  n_dimension_ = 3;
3✔
1820
  read_dataset(group, "r_grid", grid_[0]);
3✔
1821
  read_dataset(group, "phi_grid", grid_[1]);
3✔
1822
  read_dataset(group, "z_grid", grid_[2]);
3✔
1823
  read_dataset(group, "origin", origin_);
3✔
1824

1825
  if (int err = set_grid()) {
3!
1826
    fatal_error(openmc_err_msg);
×
1827
  }
1828
}
3✔
1829

1830
const std::string CylindricalMesh::mesh_type = "cylindrical";
1831

1832
std::string CylindricalMesh::get_mesh_type() const
132✔
1833
{
1834
  return mesh_type;
132✔
1835
}
1836

1837
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
13,017,843✔
1838
  Position r, bool& in_mesh) const
1839
{
1840
  r = local_coords(r);
13,017,843✔
1841

1842
  Position mapped_r;
13,017,843✔
1843
  mapped_r[0] = std::hypot(r.x, r.y);
13,017,843✔
1844
  mapped_r[2] = r[2];
13,017,843✔
1845

1846
  if (mapped_r[0] < FP_PRECISION) {
13,017,843!
1847
    mapped_r[1] = 0.0;
1848
  } else {
1849
    mapped_r[1] = std::atan2(r.y, r.x);
13,017,843✔
1850
    if (mapped_r[1] < 0)
13,017,843✔
1851
      mapped_r[1] += 2 * M_PI;
6,511,326✔
1852
  }
1853

1854
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
13,017,843✔
1855

1856
  idx[1] = sanitize_phi(idx[1]);
13,017,843✔
1857

1858
  return idx;
13,017,843✔
1859
}
1860

1861
Position CylindricalMesh::sample_element(
24,030✔
1862
  const MeshIndex& ijk, uint64_t* seed) const
1863
{
1864
  double r_min = this->r(ijk[0] - 1);
24,030✔
1865
  double r_max = this->r(ijk[0]);
24,030✔
1866

1867
  double phi_min = this->phi(ijk[1] - 1);
24,030✔
1868
  double phi_max = this->phi(ijk[1]);
24,030✔
1869

1870
  double z_min = this->z(ijk[2] - 1);
24,030✔
1871
  double z_max = this->z(ijk[2]);
24,030✔
1872

1873
  double r_min_sq = r_min * r_min;
24,030✔
1874
  double r_max_sq = r_max * r_max;
24,030✔
1875
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
24,030✔
1876
  double phi = uniform_distribution(phi_min, phi_max, seed);
24,030✔
1877
  double z = uniform_distribution(z_min, z_max, seed);
24,030✔
1878

1879
  double x = r * std::cos(phi);
24,030✔
1880
  double y = r * std::sin(phi);
24,030✔
1881

1882
  return origin_ + Position(x, y, z);
24,030✔
1883
}
1884

1885
double CylindricalMesh::find_r_crossing(
38,888,408✔
1886
  const Position& r, const Direction& u, double l, int shell) const
1887
{
1888

1889
  if ((shell < 0) || (shell > shape_[0]))
38,888,408!
1890
    return INFTY;
1891

1892
  // solve r.x^2 + r.y^2 == r0^2
1893
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1894
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1895

1896
  const double r0 = grid_[0][shell];
34,002,743✔
1897
  if (r0 == 0.0)
34,002,743✔
1898
    return INFTY;
1899

1900
  const double denominator = u.x * u.x + u.y * u.y;
32,056,541✔
1901

1902
  // Direction of flight is in z-direction. Will never intersect r.
1903
  if (std::abs(denominator) < FP_PRECISION)
32,056,541✔
1904
    return INFTY;
1905

1906
  // inverse of dominator to help the compiler to speed things up
1907
  const double inv_denominator = 1.0 / denominator;
32,040,461✔
1908

1909
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
32,040,461✔
1910
  double R = std::sqrt(r.x * r.x + r.y * r.y);
32,040,461✔
1911
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
32,040,461✔
1912

1913
  if (D < 0.0)
32,040,461✔
1914
    return INFTY;
1915

1916
  D = std::sqrt(D);
29,385,155✔
1917

1918
  // Particle is already on the shell surface; avoid spurious crossing
1919
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
29,385,155✔
1920
    return INFTY;
1921

1922
  // Check -p - D first because it is always smaller as -p + D
1923
  if (-p - D > l)
27,576,053✔
1924
    return -p - D;
1925
  if (-p + D > l)
22,064,883✔
1926
    return -p + D;
13,658,056✔
1927

1928
  return INFTY;
1929
}
1930

1931
double CylindricalMesh::find_phi_crossing(
20,306,292✔
1932
  const Position& r, const Direction& u, double l, int shell) const
1933
{
1934
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1935
  if (full_phi_ && (shape_[1] == 1))
20,306,292✔
1936
    return INFTY;
1937

1938
  shell = sanitize_phi(shell);
11,992,014✔
1939

1940
  const double p0 = grid_[1][shell];
11,992,014✔
1941

1942
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1943
  // => x(s) * cos(p0) = y(s) * sin(p0)
1944
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1945
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1946

1947
  const double c0 = std::cos(p0);
11,992,014✔
1948
  const double s0 = std::sin(p0);
11,992,014✔
1949

1950
  const double denominator = (u.x * s0 - u.y * c0);
11,992,014✔
1951

1952
  // Check if direction of flight is not parallel to phi surface
1953
  if (std::abs(denominator) > FP_PRECISION) {
11,992,014✔
1954
    const double s = -(r.x * s0 - r.y * c0) / denominator;
11,920,902✔
1955
    // Check if solution is in positive direction of flight and crosses the
1956
    // correct phi surface (not -phi)
1957
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
11,920,902✔
1958
      return s;
5,514,507✔
1959
  }
1960

1961
  return INFTY;
1962
}
1963

1964
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
10,007,931✔
1965
  const Position& r, const Direction& u, double l, int shell) const
1966
{
1967
  MeshDistance d;
10,007,931✔
1968
  d.next_index = shell;
10,007,931✔
1969

1970
  // Direction of flight is within xy-plane. Will never intersect z.
1971
  if (std::abs(u.z) < FP_PRECISION)
10,007,931✔
1972
    return d;
304,968✔
1973

1974
  d.max_surface = (u.z > 0.0);
9,702,963✔
1975
  if (d.max_surface && (shell <= shape_[2])) {
9,702,963✔
1976
    d.next_index += 1;
4,602,516✔
1977
    d.distance = (grid_[2][shell] - r.z) / u.z;
4,602,516✔
1978
  } else if (!d.max_surface && (shell > 0)) {
5,100,447✔
1979
    d.next_index -= 1;
4,594,425✔
1980
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
4,594,425✔
1981
  }
1982
  return d;
9,702,963✔
1983
}
1984

1985
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
39,605,281✔
1986
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1987
  double l) const
1988
{
1989
  if (i == 0) {
39,605,281✔
1990

1991
    return std::min(
38,888,408✔
1992
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
19,444,204✔
1993
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
38,888,408✔
1994

1995
  } else if (i == 1) {
20,161,077✔
1996

1997
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
10,153,146✔
1998
                      find_phi_crossing(r0, u, l, ijk[i])),
10,153,146✔
1999
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
10,153,146✔
2000
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
20,306,292✔
2001

2002
  } else {
2003
    return find_z_crossing(r0, u, l, ijk[i]);
10,007,931✔
2004
  }
2005
}
2006

2007
int CylindricalMesh::set_grid()
117✔
2008
{
2009
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
117✔
2010
    static_cast<int>(grid_[1].size()) - 1,
117✔
2011
    static_cast<int>(grid_[2].size()) - 1};
117✔
2012

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

2040
    return OPENMC_E_INVALID_ARGUMENT;
×
2041
  }
2042

2043
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
117!
2044

2045
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
117✔
2046
    origin_[2] + grid_[2].front()};
117✔
2047
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
117✔
2048
    origin_[2] + grid_[2].back()};
117✔
2049

2050
  return 0;
117✔
2051
}
2052

2053
int CylindricalMesh::get_index_in_direction(double r, int i) const
39,053,529✔
2054
{
2055
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
39,053,529✔
2056
}
2057

2058
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2059
  Position plot_ll, Position plot_ur) const
2060
{
2061
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2062

2063
  // Figure out which axes lie in the plane of the plot.
2064
  array<vector<double>, 2> axis_lines;
2065
  return {axis_lines[0], axis_lines[1]};
2066
}
2067

2068
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
102✔
2069
{
2070
  write_dataset(mesh_group, "r_grid", grid_[0]);
102✔
2071
  write_dataset(mesh_group, "phi_grid", grid_[1]);
102✔
2072
  write_dataset(mesh_group, "z_grid", grid_[2]);
102✔
2073
  write_dataset(mesh_group, "origin", origin_);
102✔
2074
}
102✔
2075

2076
double CylindricalMesh::volume(const MeshIndex& ijk) const
216✔
2077
{
2078
  double r_i = grid_[0][ijk[0] - 1];
216✔
2079
  double r_o = grid_[0][ijk[0]];
216✔
2080

2081
  double phi_i = grid_[1][ijk[1] - 1];
216✔
2082
  double phi_o = grid_[1][ijk[1]];
216✔
2083

2084
  double z_i = grid_[2][ijk[2] - 1];
216✔
2085
  double z_o = grid_[2][ijk[2]];
216✔
2086

2087
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
216✔
2088
}
2089

2090
//==============================================================================
2091
// SphericalMesh implementation
2092
//==============================================================================
2093

2094
SphericalMesh::SphericalMesh(pugi::xml_node node)
93✔
2095
  : PeriodicStructuredMesh {node}
93✔
2096
{
2097
  n_dimension_ = 3;
93✔
2098

2099
  grid_[0] = get_node_array<double>(node, "r_grid");
93✔
2100
  grid_[1] = get_node_array<double>(node, "theta_grid");
93✔
2101
  grid_[2] = get_node_array<double>(node, "phi_grid");
93✔
2102
  origin_ = get_node_position(node, "origin");
93✔
2103

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

2109
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
3✔
2110
{
2111
  n_dimension_ = 3;
3✔
2112

2113
  read_dataset(group, "r_grid", grid_[0]);
3✔
2114
  read_dataset(group, "theta_grid", grid_[1]);
3✔
2115
  read_dataset(group, "phi_grid", grid_[2]);
3✔
2116
  read_dataset(group, "origin", origin_);
3✔
2117

2118
  if (int err = set_grid()) {
3!
2119
    fatal_error(openmc_err_msg);
×
2120
  }
2121
}
3✔
2122

2123
const std::string SphericalMesh::mesh_type = "spherical";
2124

2125
std::string SphericalMesh::get_mesh_type() const
105✔
2126
{
2127
  return mesh_type;
105✔
2128
}
2129

2130
StructuredMesh::MeshIndex SphericalMesh::get_indices(
18,706,944✔
2131
  Position r, bool& in_mesh) const
2132
{
2133
  r = local_coords(r);
18,706,944✔
2134

2135
  Position mapped_r;
18,706,944✔
2136
  mapped_r[0] = r.norm();
18,706,944✔
2137

2138
  if (mapped_r[0] < FP_PRECISION) {
18,706,944!
2139
    mapped_r[1] = 0.0;
2140
    mapped_r[2] = 0.0;
2141
  } else {
2142
    mapped_r[1] = std::acos(r.z / mapped_r.x);
18,706,944✔
2143
    mapped_r[2] = std::atan2(r.y, r.x);
18,706,944✔
2144
    if (mapped_r[2] < 0)
18,706,944✔
2145
      mapped_r[2] += 2 * M_PI;
9,346,005✔
2146
  }
2147

2148
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
18,706,944✔
2149

2150
  idx[1] = sanitize_theta(idx[1]);
18,706,944✔
2151
  idx[2] = sanitize_phi(idx[2]);
18,706,944✔
2152

2153
  return idx;
18,706,944✔
2154
}
2155

2156
Position SphericalMesh::sample_element(
30✔
2157
  const MeshIndex& ijk, uint64_t* seed) const
2158
{
2159
  double r_min = this->r(ijk[0] - 1);
30✔
2160
  double r_max = this->r(ijk[0]);
30✔
2161

2162
  double theta_min = this->theta(ijk[1] - 1);
30✔
2163
  double theta_max = this->theta(ijk[1]);
30✔
2164

2165
  double phi_min = this->phi(ijk[2] - 1);
30✔
2166
  double phi_max = this->phi(ijk[2]);
30✔
2167

2168
  double cos_theta =
30✔
2169
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
30✔
2170
  double sin_theta = std::sin(std::acos(cos_theta));
30✔
2171
  double phi = uniform_distribution(phi_min, phi_max, seed);
30✔
2172
  double r_min_cub = std::pow(r_min, 3);
30✔
2173
  double r_max_cub = std::pow(r_max, 3);
30✔
2174
  // might be faster to do rejection here?
2175
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
30✔
2176

2177
  double x = r * std::cos(phi) * sin_theta;
30✔
2178
  double y = r * std::sin(phi) * sin_theta;
30✔
2179
  double z = r * cos_theta;
30✔
2180

2181
  return origin_ + Position(x, y, z);
30✔
2182
}
2183

2184
double SphericalMesh::find_r_crossing(
121,089,254✔
2185
  const Position& r, const Direction& u, double l, int shell) const
2186
{
2187
  if ((shell < 0) || (shell > shape_[0]))
121,089,254✔
2188
    return INFTY;
2189

2190
  // solve |r+s*u| = r0
2191
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2192
  const double r0 = grid_[0][shell];
110,283,503✔
2193
  if (r0 == 0.0)
110,283,503✔
2194
    return INFTY;
2195
  const double p = r.dot(u);
108,189,362✔
2196
  double R = r.norm();
108,189,362✔
2197
  double D = p * p - (R - r0) * (R + r0);
108,189,362✔
2198

2199
  // Particle is already on the shell surface; avoid spurious crossing
2200
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
108,189,362✔
2201
    return INFTY;
2202

2203
  if (D >= 0.0) {
105,268,820✔
2204
    D = std::sqrt(D);
97,666,016✔
2205
    // Check -p - D first because it is always smaller as -p + D
2206
    if (-p - D > l)
97,666,016✔
2207
      return -p - D;
2208
    if (-p + D > l)
80,124,976✔
2209
      return -p + D;
48,340,405✔
2210
  }
2211

2212
  return INFTY;
2213
}
2214

2215
double SphericalMesh::find_theta_crossing(
30,044,004✔
2216
  const Position& r, const Direction& u, double l, int shell) const
2217
{
2218
  // Theta grid is [0, π], thus there is no real surface to cross
2219
  if (full_theta_ && (shape_[1] == 1))
30,044,004✔
2220
    return INFTY;
2221

2222
  shell = sanitize_theta(shell);
10,461,420✔
2223

2224
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2225
  // yields
2226
  // a*s^2 + 2*b*s + c == 0 with
2227
  // a = cos(theta)^2 - u.z * u.z
2228
  // b = r*u * cos(theta)^2 - u.z * r.z
2229
  // c = r*r * cos(theta)^2 - r.z^2
2230

2231
  const double cos_t = std::cos(grid_[1][shell]);
10,461,420✔
2232
  const bool sgn = std::signbit(cos_t);
10,461,420✔
2233
  const double cos_t_2 = cos_t * cos_t;
10,461,420✔
2234

2235
  const double a = cos_t_2 - u.z * u.z;
10,461,420✔
2236
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
10,461,420✔
2237
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
10,461,420✔
2238

2239
  // if factor of s^2 is zero, direction of flight is parallel to theta
2240
  // surface
2241
  if (std::abs(a) < FP_PRECISION) {
10,461,420✔
2242
    // if b vanishes, direction of flight is within theta surface and crossing
2243
    // is not possible
2244
    if (std::abs(b) < FP_PRECISION)
131,604!
2245
      return INFTY;
2246

2247
    const double s = -0.5 * c / b;
×
2248
    // Check if solution is in positive direction of flight and has correct
2249
    // sign
2250
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2251
      return s;
×
2252

2253
    // no crossing is possible
2254
    return INFTY;
2255
  }
2256

2257
  const double p = b / a;
10,329,816✔
2258
  double D = p * p - c / a;
10,329,816✔
2259

2260
  if (D < 0.0)
10,329,816✔
2261
    return INFTY;
2262

2263
  D = std::sqrt(D);
7,342,092✔
2264

2265
  // the solution -p-D is always smaller as -p+D : Check this one first
2266
  double s = -p - D;
7,342,092✔
2267
  // Check if solution is in positive direction of flight and has correct sign
2268
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
7,342,092✔
2269
    return s;
2270

2271
  s = -p + D;
5,901,381✔
2272
  // Check if solution is in positive direction of flight and has correct sign
2273
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
5,901,381✔
2274
    return s;
2,771,808✔
2275

2276
  return INFTY;
2277
}
2278

2279
double SphericalMesh::find_phi_crossing(
30,477,498✔
2280
  const Position& r, const Direction& u, double l, int shell) const
2281
{
2282
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2283
  if (full_phi_ && (shape_[2] == 1))
30,477,498✔
2284
    return INFTY;
2285

2286
  shell = sanitize_phi(shell);
10,894,914✔
2287

2288
  const double p0 = grid_[2][shell];
10,894,914✔
2289

2290
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2291
  // => x(s) * cos(p0) = y(s) * sin(p0)
2292
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2293
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2294

2295
  const double c0 = std::cos(p0);
10,894,914✔
2296
  const double s0 = std::sin(p0);
10,894,914✔
2297

2298
  const double denominator = (u.x * s0 - u.y * c0);
10,894,914✔
2299

2300
  // Check if direction of flight is not parallel to phi surface
2301
  if (std::abs(denominator) > FP_PRECISION) {
10,894,914✔
2302
    const double s = -(r.x * s0 - r.y * c0) / denominator;
10,831,098✔
2303
    // Check if solution is in positive direction of flight and crosses the
2304
    // correct phi surface (not -phi)
2305
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
10,831,098✔
2306
      return s;
4,794,396✔
2307
  }
2308

2309
  return INFTY;
2310
}
2311

2312
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
90,805,378✔
2313
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2314
  double l) const
2315
{
2316

2317
  if (i == 0) {
90,805,378✔
2318
    return std::min(
121,089,254✔
2319
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
60,544,627✔
2320
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
121,089,254✔
2321

2322
  } else if (i == 1) {
30,260,751✔
2323
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
15,022,002✔
2324
                      find_theta_crossing(r0, u, l, ijk[i])),
15,022,002✔
2325
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
15,022,002✔
2326
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
30,044,004✔
2327

2328
  } else {
2329
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
15,238,749✔
2330
                      find_phi_crossing(r0, u, l, ijk[i])),
15,238,749✔
2331
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
15,238,749✔
2332
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
30,477,498✔
2333
  }
2334
}
2335

2336
int SphericalMesh::set_grid()
102✔
2337
{
2338
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
102✔
2339
    static_cast<int>(grid_[1].size()) - 1,
102✔
2340
    static_cast<int>(grid_[2].size()) - 1};
102✔
2341

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

2364
    return OPENMC_E_INVALID_ARGUMENT;
×
2365
  }
2366
  if (grid_[2].back() > 2 * PI) {
102!
2367
    set_errmsg("phi-grids for "
×
2368
               "spherical meshes must end with phi <= 2*pi.");
2369
    return OPENMC_E_INVALID_ARGUMENT;
×
2370
  }
2371

2372
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
102!
2373
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
102✔
2374

2375
  double r = grid_[0].back();
102✔
2376
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
102✔
2377
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
102✔
2378

2379
  return 0;
102✔
2380
}
2381

2382
int SphericalMesh::get_index_in_direction(double r, int i) const
56,120,832✔
2383
{
2384
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
56,120,832✔
2385
}
2386

2387
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2388
  Position plot_ll, Position plot_ur) const
2389
{
2390
  fatal_error("Plot of spherical Mesh not implemented");
×
2391

2392
  // Figure out which axes lie in the plane of the plot.
2393
  array<vector<double>, 2> axis_lines;
2394
  return {axis_lines[0], axis_lines[1]};
2395
}
2396

2397
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
87✔
2398
{
2399
  write_dataset(mesh_group, "r_grid", grid_[0]);
87✔
2400
  write_dataset(mesh_group, "theta_grid", grid_[1]);
87✔
2401
  write_dataset(mesh_group, "phi_grid", grid_[2]);
87✔
2402
  write_dataset(mesh_group, "origin", origin_);
87✔
2403
}
87✔
2404

2405
double SphericalMesh::volume(const MeshIndex& ijk) const
255✔
2406
{
2407
  double r_i = grid_[0][ijk[0] - 1];
255✔
2408
  double r_o = grid_[0][ijk[0]];
255✔
2409

2410
  double theta_i = grid_[1][ijk[1] - 1];
255✔
2411
  double theta_o = grid_[1][ijk[1]];
255✔
2412

2413
  double phi_i = grid_[2][ijk[2] - 1];
255✔
2414
  double phi_o = grid_[2][ijk[2]];
255✔
2415

2416
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
510✔
2417
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
255✔
2418
}
2419

2420
//==============================================================================
2421
// Helper functions for the C API
2422
//==============================================================================
2423

2424
int check_mesh(int32_t index)
1,770✔
2425
{
2426
  if (index < 0 || index >= model::meshes.size()) {
1,770!
2427
    set_errmsg("Index in meshes array is out of bounds.");
×
2428
    return OPENMC_E_OUT_OF_BOUNDS;
×
2429
  }
2430
  return 0;
2431
}
2432

2433
template<class T>
2434
int check_mesh_type(int32_t index)
300✔
2435
{
2436
  if (int err = check_mesh(index))
300!
2437
    return err;
2438

2439
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
300!
2440
  if (!mesh) {
300!
2441
    set_errmsg("This function is not valid for input mesh.");
×
2442
    return OPENMC_E_INVALID_TYPE;
×
2443
  }
2444
  return 0;
2445
}
2446

2447
template<class T>
2448
bool is_mesh_type(int32_t index)
2449
{
2450
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2451
  return mesh;
2452
}
2453

2454
//==============================================================================
2455
// C API functions
2456
//==============================================================================
2457

2458
// Return the type of mesh as a C string
2459
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
408✔
2460
{
2461
  if (int err = check_mesh(index))
408!
2462
    return err;
2463

2464
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
408✔
2465

2466
  return 0;
408✔
2467
}
2468

2469
//! Extend the meshes array by n elements
2470
extern "C" int openmc_extend_meshes(
69✔
2471
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2472
{
2473
  if (index_start)
69!
2474
    *index_start = model::meshes.size();
69✔
2475
  std::string mesh_type;
69✔
2476

2477
  for (int i = 0; i < n; ++i) {
138✔
2478
    if (RegularMesh::mesh_type == type) {
69✔
2479
      model::meshes.push_back(make_unique<RegularMesh>());
45✔
2480
    } else if (RectilinearMesh::mesh_type == type) {
24✔
2481
      model::meshes.push_back(make_unique<RectilinearMesh>());
12✔
2482
    } else if (CylindricalMesh::mesh_type == type) {
12✔
2483
      model::meshes.push_back(make_unique<CylindricalMesh>());
6✔
2484
    } else if (SphericalMesh::mesh_type == type) {
6!
2485
      model::meshes.push_back(make_unique<SphericalMesh>());
6✔
2486
    } else {
2487
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2488
    }
2489
  }
2490
  if (index_end)
69!
2491
    *index_end = model::meshes.size() - 1;
×
2492

2493
  return 0;
69✔
2494
}
69✔
2495

2496
//! Adds a new unstructured mesh to OpenMC
2497
extern "C" int openmc_add_unstructured_mesh(
×
2498
  const char filename[], const char library[], int* id)
2499
{
2500
  std::string lib_name(library);
×
2501
  std::string mesh_file(filename);
×
2502
  bool valid_lib = false;
×
2503

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

2511
#ifdef OPENMC_LIBMESH_ENABLED
2512
  if (lib_name == LibMesh::mesh_lib_type) {
2513
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
2514
    valid_lib = true;
2515
  }
2516
#endif
2517

2518
  if (!valid_lib) {
×
2519
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2520
                           "by this build of OpenMC",
2521
      lib_name));
2522
    return OPENMC_E_INVALID_ARGUMENT;
×
2523
  }
2524

2525
  // auto-assign new ID
2526
  model::meshes.back()->set_id(-1);
2527
  *id = model::meshes.back()->id_;
2528

2529
  return 0;
2530
}
×
2531

2532
//! Return the index in the meshes array of a mesh with a given ID
2533
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
117✔
2534
{
2535
  auto pair = model::mesh_map.find(id);
117!
2536
  if (pair == model::mesh_map.end()) {
117!
2537
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2538
    return OPENMC_E_INVALID_ID;
×
2539
  }
2540
  *index = pair->second;
117✔
2541
  return 0;
117✔
2542
}
2543

2544
//! Return the ID of a mesh
2545
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
771✔
2546
{
2547
  if (int err = check_mesh(index))
771!
2548
    return err;
2549
  *id = model::meshes[index]->id_;
771✔
2550
  return 0;
771✔
2551
}
2552

2553
//! Set the ID of a mesh
2554
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
69✔
2555
{
2556
  if (int err = check_mesh(index))
69!
2557
    return err;
2558
  model::meshes[index]->id_ = id;
69✔
2559
  model::mesh_map[id] = index;
69✔
2560
  return 0;
69✔
2561
}
2562

2563
//! Get the number of elements in a mesh
2564
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
81✔
2565
{
2566
  if (int err = check_mesh(index))
81!
2567
    return err;
2568
  *n = model::meshes[index]->n_bins();
81✔
2569
  return 0;
81✔
2570
}
2571

2572
//! Get the volume of each element in the mesh
2573
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
24✔
2574
{
2575
  if (int err = check_mesh(index))
24!
2576
    return err;
2577
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
264✔
2578
    volumes[i] = model::meshes[index]->volume(i);
240✔
2579
  }
2580
  return 0;
2581
}
2582

2583
//! Get the bounding box of a mesh
2584
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
48✔
2585
{
2586
  if (int err = check_mesh(index))
48!
2587
    return err;
2588

2589
  BoundingBox bbox = model::meshes[index]->bounding_box();
48✔
2590

2591
  // set lower left corner values
2592
  ll[0] = bbox.min.x;
48✔
2593
  ll[1] = bbox.min.y;
48✔
2594
  ll[2] = bbox.min.z;
48✔
2595

2596
  // set upper right corner values
2597
  ur[0] = bbox.max.x;
48✔
2598
  ur[1] = bbox.max.y;
48✔
2599
  ur[2] = bbox.max.z;
48✔
2600
  return 0;
48✔
2601
}
2602

2603
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
57✔
2604
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2605
{
2606
  if (int err = check_mesh(index))
57!
2607
    return err;
2608

2609
  try {
57✔
2610
    model::meshes[index]->material_volumes(
57✔
2611
      nx, ny, nz, table_size, materials, volumes, bboxes);
2612
  } catch (const std::exception& e) {
3!
2613
    set_errmsg(e.what());
3✔
2614
    if (starts_with(e.what(), "Mesh")) {
3!
2615
      return OPENMC_E_GEOMETRY;
3✔
2616
    } else {
2617
      return OPENMC_E_ALLOCATE;
×
2618
    }
2619
  }
3✔
2620

2621
  return 0;
2622
}
2623

2624
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
12✔
2625
  Position width, int basis, int* pixels, int32_t* data)
2626
{
2627
  if (int err = check_mesh(index))
12!
2628
    return err;
2629
  const auto& mesh = model::meshes[index].get();
12!
2630

2631
  int pixel_width = pixels[0];
12✔
2632
  int pixel_height = pixels[1];
12✔
2633

2634
  // get pixel size
2635
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
12✔
2636
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
12✔
2637

2638
  // setup basis indices and initial position centered on pixel
2639
  int in_i, out_i;
12✔
2640
  Position xyz = origin;
12✔
2641
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
12✔
2642
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
12✔
2643
  switch (basis_enum) {
12!
2644
  case PlotBasis::xy:
2645
    in_i = 0;
2646
    out_i = 1;
2647
    break;
2648
  case PlotBasis::xz:
2649
    in_i = 0;
2650
    out_i = 2;
2651
    break;
2652
  case PlotBasis::yz:
2653
    in_i = 1;
2654
    out_i = 2;
2655
    break;
2656
  default:
×
2657
    UNREACHABLE();
×
2658
  }
2659

2660
  // set initial position
2661
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
12✔
2662
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
12✔
2663

2664
#pragma omp parallel
2665
  {
12✔
2666
    Position r = xyz;
12✔
2667

2668
#pragma omp for
2669
    for (int y = 0; y < pixel_height; y++) {
252✔
2670
      r[out_i] = xyz[out_i] - out_pixel * y;
240✔
2671
      for (int x = 0; x < pixel_width; x++) {
5,040✔
2672
        r[in_i] = xyz[in_i] + in_pixel * x;
4,800✔
2673
        data[pixel_width * y + x] = mesh->get_bin(r);
4,800✔
2674
      }
2675
    }
2676
  }
2677

2678
  return 0;
12✔
2679
}
2680

2681
//! Get the dimension of a regular mesh
2682
extern "C" int openmc_regular_mesh_get_dimension(
3✔
2683
  int32_t index, int** dims, int* n)
2684
{
2685
  if (int err = check_mesh_type<RegularMesh>(index))
3!
2686
    return err;
2687
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
3!
2688
  *dims = mesh->shape_.data();
3✔
2689
  *n = mesh->n_dimension_;
3✔
2690
  return 0;
3✔
2691
}
2692

2693
//! Set the dimension of a regular mesh
2694
extern "C" int openmc_regular_mesh_set_dimension(
51✔
2695
  int32_t index, int n, const int* dims)
2696
{
2697
  if (int err = check_mesh_type<RegularMesh>(index))
51!
2698
    return err;
2699
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
51!
2700

2701
  // Copy dimension
2702
  mesh->n_dimension_ = n;
51✔
2703
  std::copy(dims, dims + n, mesh->shape_.begin());
51✔
2704
  return 0;
51✔
2705
}
2706

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

2715
  if (m->lower_left_.empty()) {
57!
2716
    set_errmsg("Mesh parameters have not been set.");
×
2717
    return OPENMC_E_ALLOCATE;
×
2718
  }
2719

2720
  *ll = m->lower_left_.data();
57✔
2721
  *ur = m->upper_right_.data();
57✔
2722
  *width = m->width_.data();
57✔
2723
  *n = m->n_dimension_;
57✔
2724
  return 0;
57✔
2725
}
2726

2727
//! Set the regular mesh parameters
2728
extern "C" int openmc_regular_mesh_set_params(
60✔
2729
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2730
{
2731
  if (int err = check_mesh_type<RegularMesh>(index))
60!
2732
    return err;
2733
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
60!
2734

2735
  if (m->n_dimension_ == -1) {
60!
2736
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2737
    return OPENMC_E_UNASSIGNED;
×
2738
  }
2739

2740
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
60✔
2741
  if (ll && ur) {
60✔
2742
    m->lower_left_ = tensor::Tensor<double>(ll, n);
54✔
2743
    m->upper_right_ = tensor::Tensor<double>(ur, n);
54✔
2744
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
216✔
2745
  } else if (ll && width) {
6✔
2746
    m->lower_left_ = tensor::Tensor<double>(ll, n);
3✔
2747
    m->width_ = tensor::Tensor<double>(width, n);
3✔
2748
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
12✔
2749
  } else if (ur && width) {
3!
2750
    m->upper_right_ = tensor::Tensor<double>(ur, n);
3✔
2751
    m->width_ = tensor::Tensor<double>(width, n);
3✔
2752
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
12✔
2753
  } else {
2754
    set_errmsg("At least two parameters must be specified.");
×
2755
    return OPENMC_E_INVALID_ARGUMENT;
×
2756
  }
2757

2758
  // Set material volumes
2759

2760
  // TODO: incorporate this into method in RegularMesh that can be called from
2761
  // here and from constructor
2762
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
60✔
2763
  m->element_volume_ = 1.0;
60✔
2764
  for (int i = 0; i < m->n_dimension_; i++) {
240✔
2765
    m->element_volume_ *= m->width_[i];
180✔
2766
  }
2767

2768
  return 0;
2769
}
60✔
2770

2771
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2772
template<class C>
2773
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
24✔
2774
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2775
  const int nz)
2776
{
2777
  if (int err = check_mesh_type<C>(index))
24!
2778
    return err;
2779

2780
  C* m = dynamic_cast<C*>(model::meshes[index].get());
24!
2781

2782
  m->n_dimension_ = 3;
24✔
2783

2784
  m->grid_[0].reserve(nx);
24✔
2785
  m->grid_[1].reserve(ny);
24✔
2786
  m->grid_[2].reserve(nz);
24✔
2787

2788
  for (int i = 0; i < nx; i++) {
156✔
2789
    m->grid_[0].push_back(grid_x[i]);
132✔
2790
  }
2791
  for (int i = 0; i < ny; i++) {
93✔
2792
    m->grid_[1].push_back(grid_y[i]);
69✔
2793
  }
2794
  for (int i = 0; i < nz; i++) {
87✔
2795
    m->grid_[2].push_back(grid_z[i]);
63✔
2796
  }
2797

2798
  int err = m->set_grid();
24✔
2799
  return err;
24✔
2800
}
2801

2802
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2803
template<class C>
2804
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
105✔
2805
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2806
{
2807
  if (int err = check_mesh_type<C>(index))
105!
2808
    return err;
2809
  C* m = dynamic_cast<C*>(model::meshes[index].get());
105!
2810

2811
  if (m->lower_left_.empty()) {
105!
2812
    set_errmsg("Mesh parameters have not been set.");
×
2813
    return OPENMC_E_ALLOCATE;
×
2814
  }
2815

2816
  *grid_x = m->grid_[0].data();
105✔
2817
  *nx = m->grid_[0].size();
105✔
2818
  *grid_y = m->grid_[1].data();
105✔
2819
  *ny = m->grid_[1].size();
105✔
2820
  *grid_z = m->grid_[2].data();
105✔
2821
  *nz = m->grid_[2].size();
105✔
2822

2823
  return 0;
105✔
2824
}
2825

2826
//! Get the rectilinear mesh grid
2827
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
39✔
2828
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2829
{
2830
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
39✔
2831
    index, grid_x, nx, grid_y, ny, grid_z, nz);
39✔
2832
}
2833

2834
//! Set the rectilienar mesh parameters
2835
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
12✔
2836
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2837
  const double* grid_z, const int nz)
2838
{
2839
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
12✔
2840
    index, grid_x, nx, grid_y, ny, grid_z, nz);
12✔
2841
}
2842

2843
//! Get the cylindrical mesh grid
2844
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
33✔
2845
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2846
{
2847
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
33✔
2848
    index, grid_x, nx, grid_y, ny, grid_z, nz);
33✔
2849
}
2850

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

2860
//! Get the spherical mesh grid
2861
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
33✔
2862
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2863
{
2864

2865
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
33✔
2866
    index, grid_x, nx, grid_y, ny, grid_z, nz);
33✔
2867
  ;
33✔
2868
}
2869

2870
//! Set the spherical mesh parameters
2871
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
6✔
2872
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2873
  const double* grid_z, const int nz)
2874
{
2875
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
6✔
2876
    index, grid_x, nx, grid_y, ny, grid_z, nz);
6✔
2877
}
2878

NEW
2879
extern "C" int openmc_unstructured_mesh_export_hdf5(
×
2880
  int32_t index, hid_t mesh_group)
2881
{
NEW
2882
  if (!mpi::master)
×
2883
    return 0;
2884

NEW
2885
  if (H5Iget_type(mesh_group) != H5I_GROUP)
×
NEW
2886
    fatal_error(fmt::format("Not a valid group {} {}", mesh_group, static_cast<int>(H5Iget_type(mesh_group))));
×
2887

NEW
2888
  if (int err = check_mesh_type<UnstructuredMesh>(index))
×
2889
    return err;
NEW
2890
  UnstructuredMesh* m =
×
NEW
2891
    dynamic_cast<UnstructuredMesh*>(model::meshes[index].get());
×
2892

NEW
2893
  m->to_hdf5_inner(mesh_group);
×
NEW
2894
  return 0;
×
2895
}
2896

2897
#ifdef OPENMC_DAGMC_ENABLED
2898

2899
const std::string MOABMesh::mesh_lib_type = "moab";
2900

2901
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2902
{
2903
  initialize();
2904
}
2905

2906
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
2907
{
2908
  initialize();
2909
}
2910

2911
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2912
  : UnstructuredMesh()
2913
{
2914
  n_dimension_ = 3;
2915
  filename_ = filename;
2916
  set_length_multiplier(length_multiplier);
2917
  initialize();
2918
}
2919

2920
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
2921
{
2922
  mbi_ = external_mbi;
2923
  filename_ = "unknown (external file)";
2924
  this->initialize();
2925
}
2926

2927
void MOABMesh::initialize()
2928
{
2929

2930
  // Create the MOAB interface and load data from file
2931
  this->create_interface();
2932

2933
  // Initialise MOAB error code
2934
  moab::ErrorCode rval = moab::MB_SUCCESS;
2935

2936
  // Set the dimension
2937
  n_dimension_ = 3;
2938

2939
  // set member range of tetrahedral entities
2940
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2941
  if (rval != moab::MB_SUCCESS) {
2942
    fatal_error("Failed to get all tetrahedral elements");
2943
  }
2944

2945
  if (!ehs_.all_of_type(moab::MBTET)) {
2946
    warning("Non-tetrahedral elements found in unstructured "
2947
            "mesh file: " +
2948
            filename_);
2949
  }
2950

2951
  // set member range of vertices
2952
  int vertex_dim = 0;
2953
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
2954
  if (rval != moab::MB_SUCCESS) {
2955
    fatal_error("Failed to get all vertex handles");
2956
  }
2957

2958
  // make an entity set for all tetrahedra
2959
  // this is used for convenience later in output
2960
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
2961
  if (rval != moab::MB_SUCCESS) {
2962
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2963
  }
2964

2965
  rval = mbi_->add_entities(tetset_, ehs_);
2966
  if (rval != moab::MB_SUCCESS) {
2967
    fatal_error("Failed to add tetrahedra to an entity set.");
2968
  }
2969

2970
  if (length_multiplier_ > 0.0) {
2971
    // get the connectivity of all tets
2972
    moab::Range adj;
2973
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2974
    if (rval != moab::MB_SUCCESS) {
2975
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2976
    }
2977
    // scale all vertex coords by multiplier (done individually so not all
2978
    // coordinates are in memory twice at once)
2979
    for (auto vert : adj) {
2980
      // retrieve coords
2981
      std::array<double, 3> coord;
2982
      rval = mbi_->get_coords(&vert, 1, coord.data());
2983
      if (rval != moab::MB_SUCCESS) {
2984
        fatal_error("Could not get coordinates of vertex.");
2985
      }
2986
      // scale coords
2987
      for (auto& c : coord) {
2988
        c *= length_multiplier_;
2989
      }
2990
      // set new coords
2991
      rval = mbi_->set_coords(&vert, 1, coord.data());
2992
      if (rval != moab::MB_SUCCESS) {
2993
        fatal_error("Failed to set new vertex coordinates");
2994
      }
2995
    }
2996
  }
2997

2998
  // Determine bounds of mesh
2999
  this->determine_bounds();
3000
}
3001

3002
void MOABMesh::prepare_for_point_location()
3003
{
3004
  // if the KDTree has already been constructed, do nothing
3005
  if (kdtree_)
3006
    return;
3007

3008
  // build acceleration data structures
3009
  compute_barycentric_data(ehs_);
3010
  build_kdtree(ehs_);
3011
}
3012

3013
void MOABMesh::create_interface()
3014
{
3015
  // Do not create a MOAB instance if one is already in memory
3016
  if (mbi_)
3017
    return;
3018

3019
  // create MOAB instance
3020
  mbi_ = std::make_shared<moab::Core>();
3021

3022
  // load unstructured mesh file
3023
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
3024
  if (rval != moab::MB_SUCCESS) {
3025
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3026
  }
3027
}
3028

3029
void MOABMesh::build_kdtree(const moab::Range& all_tets)
3030
{
3031
  moab::Range all_tris;
3032
  int adj_dim = 2;
3033
  write_message("Getting tet adjacencies...", 7);
3034
  moab::ErrorCode rval = mbi_->get_adjacencies(
3035
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3036
  if (rval != moab::MB_SUCCESS) {
3037
    fatal_error("Failed to get adjacent triangles for tets");
3038
  }
3039

3040
  if (!all_tris.all_of_type(moab::MBTRI)) {
3041
    warning("Non-triangle elements found in tet adjacencies in "
3042
            "unstructured mesh file: " +
3043
            filename_);
3044
  }
3045

3046
  // combine into one range
3047
  moab::Range all_tets_and_tris;
3048
  all_tets_and_tris.merge(all_tets);
3049
  all_tets_and_tris.merge(all_tris);
3050

3051
  // create a kd-tree instance
3052
  write_message(
3053
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
3054
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
3055

3056
  // Determine what options to use
3057
  std::ostringstream options_stream;
3058
  if (options_.empty()) {
3059
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
3060
  } else {
3061
    options_stream << options_;
3062
  }
3063
  moab::FileOptions file_opts(options_stream.str().c_str());
3064

3065
  // Build the k-d tree
3066
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
3067
  if (rval != moab::MB_SUCCESS) {
3068
    fatal_error("Failed to construct KDTree for the "
3069
                "unstructured mesh file: " +
3070
                filename_);
3071
  }
3072
}
3073

3074
void MOABMesh::intersect_track(const moab::CartVect& start,
3075
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3076
{
3077
  hits.clear();
3078

3079
  moab::ErrorCode rval;
3080
  vector<moab::EntityHandle> tris;
3081
  // get all intersections with triangles in the tet mesh
3082
  // (distances are relative to the start point, not the previous
3083
  // intersection)
3084
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
3085
    dir.array(), start.array(), tris, hits, 0, track_len);
3086
  if (rval != moab::MB_SUCCESS) {
3087
    fatal_error(
3088
      "Failed to compute intersections on unstructured mesh: " + filename_);
3089
  }
3090

3091
  // remove duplicate intersection distances
3092
  std::unique(hits.begin(), hits.end());
3093

3094
  // sorts by first component of std::pair by default
3095
  std::sort(hits.begin(), hits.end());
3096
}
3097

3098
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3099
  vector<int>& bins, vector<double>& lengths) const
3100
{
3101
  moab::CartVect start(r0.x, r0.y, r0.z);
3102
  moab::CartVect end(r1.x, r1.y, r1.z);
3103
  moab::CartVect dir(u.x, u.y, u.z);
3104
  dir.normalize();
3105

3106
  double track_len = (end - start).length();
3107
  if (track_len == 0.0)
3108
    return;
3109

3110
  start -= TINY_BIT * dir;
3111
  end += TINY_BIT * dir;
3112

3113
  vector<double> hits;
3114
  intersect_track(start, dir, track_len, hits);
3115

3116
  bins.clear();
3117
  lengths.clear();
3118

3119
  // if there are no intersections the track may lie entirely
3120
  // within a single tet. If this is the case, apply entire
3121
  // score to that tet and return.
3122
  if (hits.size() == 0) {
3123
    Position midpoint = r0 + u * (track_len * 0.5);
3124
    int bin = this->get_bin(midpoint);
3125
    if (bin != -1) {
3126
      bins.push_back(bin);
3127
      lengths.push_back(1.0);
3128
    }
3129
    return;
3130
  }
3131

3132
  // for each segment in the set of tracks, try to look up a tet
3133
  // at the midpoint of the segment
3134
  Position current = r0;
3135
  double last_dist = 0.0;
3136
  for (const auto& hit : hits) {
3137
    // get the segment length
3138
    double segment_length = hit - last_dist;
3139
    last_dist = hit;
3140
    // find the midpoint of this segment
3141
    Position midpoint = current + u * (segment_length * 0.5);
3142
    // try to find a tet for this position
3143
    int bin = this->get_bin(midpoint);
3144

3145
    // determine the start point for this segment
3146
    current = r0 + u * hit;
3147

3148
    if (bin == -1) {
3149
      continue;
3150
    }
3151

3152
    bins.push_back(bin);
3153
    lengths.push_back(segment_length / track_len);
3154
  }
3155

3156
  // tally remaining portion of track after last hit if
3157
  // the last segment of the track is in the mesh but doesn't
3158
  // reach the other side of the tet
3159
  if (hits.back() < track_len) {
3160
    Position segment_start = r0 + u * hits.back();
3161
    double segment_length = track_len - hits.back();
3162
    Position midpoint = segment_start + u * (segment_length * 0.5);
3163
    int bin = this->get_bin(midpoint);
3164
    if (bin != -1) {
3165
      bins.push_back(bin);
3166
      lengths.push_back(segment_length / track_len);
3167
    }
3168
  }
3169
};
3170

3171
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
3172
{
3173
  moab::CartVect pos(r.x, r.y, r.z);
3174
  // find the leaf of the kd-tree for this position
3175
  moab::AdaptiveKDTreeIter kdtree_iter;
3176
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
3177
  if (rval != moab::MB_SUCCESS) {
3178
    return 0;
3179
  }
3180

3181
  // retrieve the tet elements of this leaf
3182
  moab::EntityHandle leaf = kdtree_iter.handle();
3183
  moab::Range tets;
3184
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3185
  if (rval != moab::MB_SUCCESS) {
3186
    warning("MOAB error finding tets.");
3187
  }
3188

3189
  // loop over the tets in this leaf, returning the containing tet if found
3190
  for (const auto& tet : tets) {
3191
    if (point_in_tet(pos, tet)) {
3192
      return tet;
3193
    }
3194
  }
3195

3196
  // if no tet is found, return an invalid handle
3197
  return 0;
3198
}
3199

3200
double MOABMesh::volume(int bin) const
3201
{
3202
  return tet_volume(get_ent_handle_from_bin(bin));
3203
}
3204

3205
std::string MOABMesh::library() const
3206
{
3207
  return mesh_lib_type;
3208
}
3209

3210
// Sample position within a tet for MOAB type tets
3211
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
3212
{
3213

3214
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3215

3216
  // Get vertex coordinates for MOAB tet
3217
  const moab::EntityHandle* conn1;
3218
  int conn1_size;
3219
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
3220
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
3221
    fatal_error(fmt::format(
3222
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3223
      conn1_size));
3224
  }
3225
  moab::CartVect p[4];
3226
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
3227
  if (rval != moab::MB_SUCCESS) {
3228
    fatal_error("Failed to get tet coords");
3229
  }
3230

3231
  std::array<Position, 4> tet_verts;
3232
  for (int i = 0; i < 4; i++) {
3233
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
3234
  }
3235
  // Samples position within tet using Barycentric stuff
3236
  return this->sample_tet(tet_verts, seed);
3237
}
3238

3239
double MOABMesh::tet_volume(moab::EntityHandle tet) const
3240
{
3241
  vector<moab::EntityHandle> conn;
3242
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
3243
  if (rval != moab::MB_SUCCESS) {
3244
    fatal_error("Failed to get tet connectivity");
3245
  }
3246

3247
  moab::CartVect p[4];
3248
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
3249
  if (rval != moab::MB_SUCCESS) {
3250
    fatal_error("Failed to get tet coords");
3251
  }
3252

3253
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
3254
}
3255

3256
int MOABMesh::get_bin(Position r) const
3257
{
3258
  moab::EntityHandle tet = get_tet(r);
3259
  if (tet == 0) {
3260
    return -1;
3261
  } else {
3262
    return get_bin_from_ent_handle(tet);
3263
  }
3264
}
3265

3266
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
3267
{
3268
  moab::ErrorCode rval;
3269

3270
  baryc_data_.clear();
3271
  baryc_data_.resize(tets.size());
3272

3273
  // compute the barycentric data for each tet element
3274
  // and store it as a 3x3 matrix
3275
  for (auto& tet : tets) {
3276
    vector<moab::EntityHandle> verts;
3277
    rval = mbi_->get_connectivity(&tet, 1, verts);
3278
    if (rval != moab::MB_SUCCESS) {
3279
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
3280
    }
3281

3282
    moab::CartVect p[4];
3283
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
3284
    if (rval != moab::MB_SUCCESS) {
3285
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
3286
    }
3287

3288
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
3289

3290
    // invert now to avoid this cost later
3291
    a = a.transpose().inverse();
3292
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
3293
  }
3294
}
3295

3296
bool MOABMesh::point_in_tet(
3297
  const moab::CartVect& r, moab::EntityHandle tet) const
3298
{
3299

3300
  moab::ErrorCode rval;
3301

3302
  // get tet vertices
3303
  vector<moab::EntityHandle> verts;
3304
  rval = mbi_->get_connectivity(&tet, 1, verts);
3305
  if (rval != moab::MB_SUCCESS) {
3306
    warning("Failed to get vertices of tet in umesh: " + filename_);
3307
    return false;
3308
  }
3309

3310
  // first vertex is used as a reference point for the barycentric data -
3311
  // retrieve its coordinates
3312
  moab::CartVect p_zero;
3313
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
3314
  if (rval != moab::MB_SUCCESS) {
3315
    warning("Failed to get coordinates of a vertex in "
3316
            "unstructured mesh: " +
3317
            filename_);
3318
    return false;
3319
  }
3320

3321
  // look up barycentric data
3322
  int idx = get_bin_from_ent_handle(tet);
3323
  const moab::Matrix3& a_inv = baryc_data_[idx];
3324

3325
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3326

3327
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
3328
          bary_coords[2] >= 0.0 &&
3329
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
3330
}
3331

3332
int MOABMesh::get_bin_from_index(int idx) const
3333
{
3334
  if (idx >= n_bins()) {
3335
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3336
  }
3337
  return ehs_[idx] - ehs_[0];
3338
}
3339

3340
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3341
{
3342
  int bin = get_bin(r);
3343
  *in_mesh = bin != -1;
3344
  return bin;
3345
}
3346

3347
int MOABMesh::get_index_from_bin(int bin) const
3348
{
3349
  return bin;
3350
}
3351

3352
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3353
  Position plot_ll, Position plot_ur) const
3354
{
3355
  // TODO: Implement mesh lines
3356
  return {};
3357
}
3358

3359
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
3360
{
3361
  int idx = vert - verts_[0];
3362
  if (idx >= n_vertices()) {
3363
    fatal_error(
3364
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
3365
  }
3366
  return idx;
3367
}
3368

3369
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
3370
{
3371
  int bin = eh - ehs_[0];
3372
  if (bin >= n_bins()) {
3373
    fatal_error(fmt::format("Invalid bin: {}", bin));
3374
  }
3375
  return bin;
3376
}
3377

3378
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
3379
{
3380
  if (bin >= n_bins()) {
3381
    fatal_error(fmt::format("Invalid bin index: ", bin));
3382
  }
3383
  return ehs_[0] + bin;
3384
}
3385

3386
int MOABMesh::n_bins() const
3387
{
3388
  return ehs_.size();
3389
}
3390

3391
int MOABMesh::n_surface_bins() const
3392
{
3393
  // collect all triangles in the set of tets for this mesh
3394
  moab::Range tris;
3395
  moab::ErrorCode rval;
3396
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
3397
  if (rval != moab::MB_SUCCESS) {
3398
    warning("Failed to get all triangles in the mesh instance");
3399
    return -1;
3400
  }
3401
  return 2 * tris.size();
3402
}
3403

3404
Position MOABMesh::centroid(int bin) const
3405
{
3406
  moab::ErrorCode rval;
3407

3408
  auto tet = this->get_ent_handle_from_bin(bin);
3409

3410
  // look up the tet connectivity
3411
  vector<moab::EntityHandle> conn;
3412
  rval = mbi_->get_connectivity(&tet, 1, conn);
3413
  if (rval != moab::MB_SUCCESS) {
3414
    warning("Failed to get connectivity of a mesh element.");
3415
    return {};
3416
  }
3417

3418
  // get the coordinates
3419
  vector<moab::CartVect> coords(conn.size());
3420
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3421
  if (rval != moab::MB_SUCCESS) {
3422
    warning("Failed to get the coordinates of a mesh element.");
3423
    return {};
3424
  }
3425

3426
  // compute the centroid of the element vertices
3427
  moab::CartVect centroid(0.0, 0.0, 0.0);
3428
  for (const auto& coord : coords) {
3429
    centroid += coord;
3430
  }
3431
  centroid /= double(coords.size());
3432

3433
  return {centroid[0], centroid[1], centroid[2]};
3434
}
3435

3436
int MOABMesh::n_vertices() const
3437
{
3438
  return verts_.size();
3439
}
3440

3441
Position MOABMesh::vertex(int id) const
3442
{
3443

3444
  moab::ErrorCode rval;
3445

3446
  moab::EntityHandle vert = verts_[id];
3447

3448
  moab::CartVect coords;
3449
  rval = mbi_->get_coords(&vert, 1, coords.array());
3450
  if (rval != moab::MB_SUCCESS) {
3451
    fatal_error("Failed to get the coordinates of a vertex.");
3452
  }
3453

3454
  return {coords[0], coords[1], coords[2]};
3455
}
3456

3457
std::vector<int> MOABMesh::connectivity(int bin) const
3458
{
3459
  moab::ErrorCode rval;
3460

3461
  auto tet = get_ent_handle_from_bin(bin);
3462

3463
  // look up the tet connectivity
3464
  vector<moab::EntityHandle> conn;
3465
  rval = mbi_->get_connectivity(&tet, 1, conn);
3466
  if (rval != moab::MB_SUCCESS) {
3467
    fatal_error("Failed to get connectivity of a mesh element.");
3468
    return {};
3469
  }
3470

3471
  std::vector<int> verts(4);
3472
  for (int i = 0; i < verts.size(); i++) {
3473
    verts[i] = get_vert_idx_from_handle(conn[i]);
3474
  }
3475

3476
  return verts;
3477
}
3478

3479
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3480
  std::string score) const
3481
{
3482
  moab::ErrorCode rval;
3483
  // add a tag to the mesh
3484
  // all scores are treated as a single value
3485
  // with an uncertainty
3486
  moab::Tag value_tag;
3487

3488
  // create the value tag if not present and get handle
3489
  double default_val = 0.0;
3490
  auto val_string = score + "_mean";
3491
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3492
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3493
  if (rval != moab::MB_SUCCESS) {
3494
    auto msg =
3495
      fmt::format("Could not create or retrieve the value tag for the score {}"
3496
                  " on unstructured mesh {}",
3497
        score, id_);
3498
    fatal_error(msg);
3499
  }
3500

3501
  // create the std dev tag if not present and get handle
3502
  moab::Tag error_tag;
3503
  std::string err_string = score + "_std_dev";
3504
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3505
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3506
  if (rval != moab::MB_SUCCESS) {
3507
    auto msg =
3508
      fmt::format("Could not create or retrieve the error tag for the score {}"
3509
                  " on unstructured mesh {}",
3510
        score, id_);
3511
    fatal_error(msg);
3512
  }
3513

3514
  // return the populated tag handles
3515
  return {value_tag, error_tag};
3516
}
3517

3518
void MOABMesh::add_score(const std::string& score)
3519
{
3520
  auto score_tags = get_score_tags(score);
3521
  tag_names_.push_back(score);
3522
}
3523

3524
void MOABMesh::remove_scores()
3525
{
3526
  for (const auto& name : tag_names_) {
3527
    auto value_name = name + "_mean";
3528
    moab::Tag tag;
3529
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
3530
    if (rval != moab::MB_SUCCESS)
3531
      return;
3532

3533
    rval = mbi_->tag_delete(tag);
3534
    if (rval != moab::MB_SUCCESS) {
3535
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3536
                             " on unstructured mesh {}",
3537
        name, id_);
3538
      fatal_error(msg);
3539
    }
3540

3541
    auto std_dev_name = name + "_std_dev";
3542
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3543
    if (rval != moab::MB_SUCCESS) {
3544
      auto msg =
3545
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3546
                    " on unstructured mesh {}",
3547
          name, id_);
3548
    }
3549

3550
    rval = mbi_->tag_delete(tag);
3551
    if (rval != moab::MB_SUCCESS) {
3552
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3553
                             " on unstructured mesh {}",
3554
        name, id_);
3555
      fatal_error(msg);
3556
    }
3557
  }
3558
  tag_names_.clear();
3559
}
3560

3561
void MOABMesh::set_score_data(const std::string& score,
3562
  const vector<double>& values, const vector<double>& std_dev)
3563
{
3564
  auto score_tags = this->get_score_tags(score);
3565

3566
  moab::ErrorCode rval;
3567
  // set the score value
3568
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3569
  if (rval != moab::MB_SUCCESS) {
3570
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3571
                           "on unstructured mesh {}",
3572
      score, id_);
3573
    warning(msg);
3574
  }
3575

3576
  // set the error value
3577
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3578
  if (rval != moab::MB_SUCCESS) {
3579
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3580
                           "on unstructured mesh {}",
3581
      score, id_);
3582
    warning(msg);
3583
  }
3584
}
3585

3586
void MOABMesh::write(const std::string& base_filename) const
3587
{
3588
  // add extension to the base name
3589
  auto filename = base_filename + ".vtk";
3590
  write_message(5, "Writing unstructured mesh {}...", filename);
3591
  filename = settings::path_output + filename;
3592

3593
  // write the tetrahedral elements of the mesh only
3594
  // to avoid clutter from zero-value data on other
3595
  // elements during visualization
3596
  moab::ErrorCode rval;
3597
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3598
  if (rval != moab::MB_SUCCESS) {
3599
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3600
    warning(msg);
3601
  }
3602
}
3603

3604
#endif
3605

3606
#ifdef OPENMC_LIBMESH_ENABLED
3607

3608
const std::string LibMesh::mesh_lib_type = "libmesh";
3609

3610
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
3611
{
3612
  // filename_ and length_multiplier_ will already be set by the
3613
  // UnstructuredMesh constructor
3614
  set_mesh_pointer_from_filename(filename_);
3615
  set_length_multiplier(length_multiplier_);
3616
  initialize();
3617
}
3618

3619
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
3620
{
3621
  // filename_ and length_multiplier_ will already be set by the
3622
  // UnstructuredMesh constructor
3623
  set_mesh_pointer_from_filename(filename_);
3624
  set_length_multiplier(length_multiplier_);
3625
  initialize();
3626
}
3627

3628
// create the mesh from a pointer to a libMesh Mesh
3629
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3630
{
3631
  if (!input_mesh.is_replicated()) {
3632
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3633
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3634
  }
3635

3636
  m_ = &input_mesh;
3637
  set_length_multiplier(length_multiplier);
3638
  initialize();
3639
}
3640

3641
// create the mesh from an input file
3642
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
3643
{
3644
  n_dimension_ = 3;
3645
  set_mesh_pointer_from_filename(filename);
3646
  set_length_multiplier(length_multiplier);
3647
  initialize();
3648
}
3649

3650
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3651
{
3652
  filename_ = filename;
3653
  unique_m_ =
3654
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
3655
  m_ = unique_m_.get();
3656
  m_->read(filename_);
3657
}
3658

3659
// build a libMesh equation system for storing values
3660
void LibMesh::build_eqn_sys()
3661
{
3662
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
3663
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3664
  libMesh::ExplicitSystem& eq_sys =
3665
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3666
}
3667

3668
// intialize from mesh file
3669
void LibMesh::initialize()
3670
{
3671
  if (!settings::libmesh_comm) {
3672
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3673
                "communicator.");
3674
  }
3675

3676
  // assuming that unstructured meshes used in OpenMC are 3D
3677
  n_dimension_ = 3;
3678

3679
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3680
  // Otherwise assume that it is prepared by its owning application
3681
  if (unique_m_) {
3682
    m_->prepare_for_use();
3683
  }
3684

3685
  // ensure that the loaded mesh is 3 dimensional
3686
  if (m_->mesh_dimension() != n_dimension_) {
3687
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3688
                            "mesh is not a 3D mesh.",
3689
      filename_));
3690
  }
3691

3692
  for (int i = 0; i < num_threads(); i++) {
3693
    pl_.emplace_back(m_->sub_point_locator());
3694
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3695
    pl_.back()->enable_out_of_mesh_mode();
3696
  }
3697

3698
  // store first element in the mesh to use as an offset for bin indices
3699
  auto first_elem = *m_->elements_begin();
3700
  first_element_id_ = first_elem->id();
3701

3702
  // bounding box for the mesh for quick rejection checks
3703
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3704
  libMesh::Point ll = bbox_.min();
3705
  libMesh::Point ur = bbox_.max();
3706
  if (length_multiplier_ > 0.0) {
3707
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3708
      length_multiplier_ * ll(2)};
3709
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3710
      length_multiplier_ * ur(2)};
3711
  } else {
3712
    lower_left_ = {ll(0), ll(1), ll(2)};
3713
    upper_right_ = {ur(0), ur(1), ur(2)};
3714
  }
3715
}
3716

3717
// Sample position within a tet for LibMesh type tets
3718
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
3719
{
3720
  const auto& elem = get_element_from_bin(bin);
3721
  // Get tet vertex coordinates from LibMesh
3722
  std::array<Position, 4> tet_verts;
3723
  for (int i = 0; i < elem.n_nodes(); i++) {
3724
    const auto& node_ref = elem.node_ref(i);
3725
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3726
  }
3727
  // Samples position within tet using Barycentric coordinates
3728
  Position sampled_position = this->sample_tet(tet_verts, seed);
3729
  if (length_multiplier_ > 0.0) {
3730
    return length_multiplier_ * sampled_position;
3731
  } else {
3732
    return sampled_position;
3733
  }
3734
}
3735

3736
Position LibMesh::centroid(int bin) const
3737
{
3738
  const auto& elem = this->get_element_from_bin(bin);
3739
  auto centroid = elem.vertex_average();
3740
  if (length_multiplier_ > 0.0) {
3741
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3742
  } else {
3743
    return {centroid(0), centroid(1), centroid(2)};
3744
  }
3745
}
3746

3747
int LibMesh::n_vertices() const
3748
{
3749
  return m_->n_nodes();
3750
}
3751

3752
Position LibMesh::vertex(int vertex_id) const
3753
{
3754
  const auto& node_ref = m_->node_ref(vertex_id);
3755
  if (length_multiplier_ > 0.0) {
3756
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3757
  } else {
3758
    return {node_ref(0), node_ref(1), node_ref(2)};
3759
  }
3760
}
3761

3762
std::vector<int> LibMesh::connectivity(int elem_id) const
3763
{
3764
  std::vector<int> conn;
3765
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3766
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3767
    conn.push_back(elem_ptr->node_id(i));
3768
  }
3769
  return conn;
3770
}
3771

3772
std::string LibMesh::library() const
3773
{
3774
  return mesh_lib_type;
3775
}
3776

3777
int LibMesh::n_bins() const
3778
{
3779
  return m_->n_elem();
3780
}
3781

3782
int LibMesh::n_surface_bins() const
3783
{
3784
  int n_bins = 0;
3785
  for (int i = 0; i < this->n_bins(); i++) {
3786
    const libMesh::Elem& e = get_element_from_bin(i);
3787
    n_bins += e.n_faces();
3788
    // if this is a boundary element, it will only be visited once,
3789
    // the number of surface bins is incremented to
3790
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3791
      // null neighbor pointer indicates a boundary face
3792
      if (!neighbor_ptr) {
3793
        n_bins++;
3794
      }
3795
    }
3796
  }
3797
  return n_bins;
3798
}
3799

3800
void LibMesh::add_score(const std::string& var_name)
3801
{
3802
  if (!equation_systems_) {
3803
    build_eqn_sys();
3804
  }
3805

3806
  // check if this is a new variable
3807
  std::string value_name = var_name + "_mean";
3808
  if (!variable_map_.count(value_name)) {
3809
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3810
    auto var_num =
3811
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3812
    variable_map_[value_name] = var_num;
3813
  }
3814

3815
  std::string std_dev_name = var_name + "_std_dev";
3816
  // check if this is a new variable
3817
  if (!variable_map_.count(std_dev_name)) {
3818
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3819
    auto var_num =
3820
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3821
    variable_map_[std_dev_name] = var_num;
3822
  }
3823
}
3824

3825
void LibMesh::remove_scores()
3826
{
3827
  if (equation_systems_) {
3828
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3829
    eqn_sys.clear();
3830
    variable_map_.clear();
3831
  }
3832
}
3833

3834
void LibMesh::set_score_data(const std::string& var_name,
3835
  const vector<double>& values, const vector<double>& std_dev)
3836
{
3837
  if (!equation_systems_) {
3838
    build_eqn_sys();
3839
  }
3840

3841
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3842

3843
  if (!eqn_sys.is_initialized()) {
3844
    equation_systems_->init();
3845
  }
3846

3847
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3848

3849
  // look up the value variable
3850
  std::string value_name = var_name + "_mean";
3851
  unsigned int value_num = variable_map_.at(value_name);
3852
  // look up the std dev variable
3853
  std::string std_dev_name = var_name + "_std_dev";
3854
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3855

3856
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3857
       it++) {
3858
    if (!(*it)->active()) {
3859
      continue;
3860
    }
3861

3862
    auto bin = get_bin_from_element(*it);
3863

3864
    // set value
3865
    vector<libMesh::dof_id_type> value_dof_indices;
3866
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3867
    assert(value_dof_indices.size() == 1);
3868
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3869

3870
    // set std dev
3871
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3872
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3873
    assert(std_dev_dof_indices.size() == 1);
3874
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3875
  }
3876
}
3877

3878
void LibMesh::write(const std::string& filename) const
3879
{
3880
  write_message(fmt::format(
3881
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3882
  libMesh::ExodusII_IO exo(*m_);
3883
  std::set<std::string> systems_out = {eq_system_name_};
3884
  exo.write_discontinuous_exodusII(
3885
    filename + ".e", *equation_systems_, &systems_out);
3886
}
3887

3888
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3889
  vector<int>& bins, vector<double>& lengths) const
3890
{
3891
  // TODO: Implement triangle crossings here
3892
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3893
}
3894

3895
int LibMesh::get_bin(Position r) const
3896
{
3897
  // look-up a tet using the point locator
3898
  libMesh::Point p(r.x, r.y, r.z);
3899

3900
  if (length_multiplier_ > 0.0) {
3901
    // Scale the point down
3902
    p /= length_multiplier_;
3903
  }
3904

3905
  // quick rejection check
3906
  if (!bbox_.contains_point(p)) {
3907
    return -1;
3908
  }
3909

3910
  const auto& point_locator = pl_.at(thread_num());
3911

3912
  const auto elem_ptr = (*point_locator)(p);
3913
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3914
}
3915

3916
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3917
{
3918
  int bin = elem->id() - first_element_id_;
3919
  if (bin >= n_bins() || bin < 0) {
3920
    fatal_error(fmt::format("Invalid bin: {}", bin));
3921
  }
3922
  return bin;
3923
}
3924

3925
std::pair<vector<double>, vector<double>> LibMesh::plot(
3926
  Position plot_ll, Position plot_ur) const
3927
{
3928
  return {};
3929
}
3930

3931
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3932
{
3933
  return m_->elem_ref(bin);
3934
}
3935

3936
double LibMesh::volume(int bin) const
3937
{
3938
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
3939
         length_multiplier_ * length_multiplier_;
3940
}
3941

3942
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3943
  double length_multiplier,
3944
  const std::set<libMesh::subdomain_id_type>& block_ids)
3945
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3946
    block_restrict_(!block_ids_.empty()),
3947
    num_active_(
3948
      block_restrict_
3949
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
3950
            m_->active_subdomain_set_elements_end(block_ids_))
3951
        : m_->n_active_elem())
3952
{
3953
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3954
  // contiguous in ID space, so we need to map from bin indices (defined over
3955
  // active elements) to global dof ids
3956
  bin_to_elem_map_.reserve(num_active_);
3957
  elem_to_bin_map_.resize(m_->n_elem(), -1);
3958
  auto begin = block_restrict_
3959
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
3960
                 : m_->active_elements_begin();
3961
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
3962
                             : m_->active_elements_end();
3963
  for (const auto& elem : libMesh::as_range(begin, end)) {
3964
    bin_to_elem_map_.push_back(elem->id());
3965
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3966
  }
3967
}
3968

3969
int AdaptiveLibMesh::n_bins() const
3970
{
3971
  return num_active_;
3972
}
3973

3974
void AdaptiveLibMesh::add_score(const std::string& var_name)
3975
{
3976
  warning(fmt::format(
3977
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3978
    this->id_));
3979
}
3980

3981
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3982
  const vector<double>& values, const vector<double>& std_dev)
3983
{
3984
  warning(fmt::format(
3985
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3986
    this->id_));
3987
}
3988

3989
void AdaptiveLibMesh::write(const std::string& filename) const
3990
{
3991
  warning(fmt::format(
3992
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3993
    this->id_));
3994
}
3995

3996
int AdaptiveLibMesh::get_bin(Position r) const
3997
{
3998
  // look-up a tet using the point locator
3999
  libMesh::Point p(r.x, r.y, r.z);
4000

4001
  if (length_multiplier_ > 0.0) {
4002
    // Scale the point down
4003
    p /= length_multiplier_;
4004
  }
4005

4006
  // quick rejection check
4007
  if (!bbox_.contains_point(p)) {
4008
    return -1;
4009
  }
4010

4011
  const auto& point_locator = pl_.at(thread_num());
4012

4013
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
4014
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
4015
}
4016

4017
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4018
{
4019
  int bin = elem_to_bin_map_[elem->id()];
4020
  if (bin >= n_bins() || bin < 0) {
4021
    fatal_error(fmt::format("Invalid bin: {}", bin));
4022
  }
4023
  return bin;
4024
}
4025

4026
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4027
{
4028
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4029
}
4030

4031
#endif // OPENMC_LIBMESH_ENABLED
4032

4033
//==============================================================================
4034
// Non-member functions
4035
//==============================================================================
4036

4037
void read_meshes(pugi::xml_node root)
3,333✔
4038
{
4039
  std::unordered_set<int> mesh_ids;
3,333✔
4040

4041
  for (auto node : root.children("mesh")) {
4,131✔
4042
    // Check to make sure multiple meshes in the same file don't share IDs
4043
    int id = std::stoi(get_node_value(node, "id"));
1,596✔
4044
    if (contains(mesh_ids, id)) {
1,596!
4045
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4046
                              "'{}' in the same input file",
4047
        id));
4048
    }
4049
    mesh_ids.insert(id);
798✔
4050

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

4058
    std::string mesh_type;
798✔
4059
    if (check_for_node(node, "type")) {
798✔
4060
      mesh_type = get_node_value(node, "type", true, true);
234✔
4061
    } else {
4062
      mesh_type = "regular";
564✔
4063
    }
4064

4065
    // determine the mesh library to use
4066
    std::string mesh_lib;
798✔
4067
    if (check_for_node(node, "library")) {
798!
UNCOV
4068
      mesh_lib = get_node_value(node, "library", true, true);
×
4069
    }
4070

4071
    Mesh::create(node, mesh_type, mesh_lib);
798✔
4072
  }
798✔
4073
}
3,333✔
4074

4075
void read_meshes(hid_t group)
6✔
4076
{
4077
  std::unordered_set<int> mesh_ids;
6✔
4078

4079
  std::vector<int> ids;
6✔
4080
  read_attribute(group, "ids", ids);
6✔
4081

4082
  for (auto id : ids) {
15✔
4083

4084
    // Check to make sure multiple meshes in the same file don't share IDs
4085
    if (contains(mesh_ids, id)) {
18!
4086
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4087
                              "'{}' in the same HDF5 input file",
4088
        id));
4089
    }
4090
    mesh_ids.insert(id);
9✔
4091

4092
    // If we've already read a mesh with the same ID in a *different* file,
4093
    // assume it is the same here
4094
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
9!
4095
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
9✔
4096
      continue;
9✔
4097
    }
4098

4099
    std::string name = fmt::format("mesh {}", id);
×
4100
    hid_t mesh_group = open_group(group, name.c_str());
×
4101

4102
    std::string mesh_type;
×
4103
    if (object_exists(mesh_group, "type")) {
×
4104
      read_dataset(mesh_group, "type", mesh_type);
×
4105
    } else {
4106
      mesh_type = "regular";
×
4107
    }
4108

4109
    // determine the mesh library to use
4110
    std::string mesh_lib;
×
4111
    if (object_exists(mesh_group, "library")) {
×
4112
      read_dataset(mesh_group, "library", mesh_lib);
×
4113
    }
4114

4115
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4116
  }
×
4117
}
12✔
4118

4119
void meshes_to_hdf5(hid_t group)
2,112✔
4120
{
4121
  // Write number of meshes
4122
  hid_t meshes_group = create_group(group, "meshes");
2,112✔
4123
  int32_t n_meshes = model::meshes.size();
2,112✔
4124
  write_attribute(meshes_group, "n_meshes", n_meshes);
2,112✔
4125

4126
  if (n_meshes > 0) {
2,112✔
4127
    // Write IDs of meshes
4128
    vector<int> ids;
633✔
4129
    for (const auto& m : model::meshes) {
1,449✔
4130
      m->to_hdf5(meshes_group);
816✔
4131
      ids.push_back(m->id_);
816✔
4132
    }
4133
    write_attribute(meshes_group, "ids", ids);
633✔
4134
  }
633✔
4135

4136
  close_group(meshes_group);
2,112✔
4137
}
2,112✔
4138

4139
void free_memory_mesh()
2,166✔
4140
{
4141
  model::meshes.clear();
2,166✔
4142
  model::mesh_map.clear();
2,166✔
4143
}
2,166✔
4144

4145
extern "C" int n_meshes()
84✔
4146
{
4147
  return model::meshes.size();
84✔
4148
}
4149

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