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

openmc-dev / openmc / 29043664591

09 Jul 2026 07:15PM UTC coverage: 80.499% (-0.8%) from 81.28%
29043664591

Pull #3951

github

web-flow
Merge 059d94b4a into 3cdb67e50
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16736 of 24231 branches covered (69.07%)

Branch coverage included in aggregate %.

70 of 119 new or added lines in 10 files covered. (58.82%)

787 existing lines in 49 files now uncovered.

57479 of 67963 relevant lines covered (84.57%)

17358525.61 hits per line

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

66.85
/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)
282✔
125
{
126
#if defined(__GNUC__) || defined(__clang__)
127
  // For gcc/clang, use the __atomic_compare_exchange_n intrinsic
128
  return __atomic_compare_exchange_n(
282✔
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)
7,020,288✔
146
{
147
  To out;
148
  std::memcpy(&out, &value, sizeof(To));
7,185✔
149
  return out;
150
}
151

152
inline void atomic_update_double(double* ptr, double value, bool is_min)
7,020,288✔
153
{
154
#if defined(__GNUC__) || defined(__clang__)
155
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
7,020,288✔
156
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
7,020,288✔
157
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
7,020,288✔
158
  double current = bit_cast_value<double>(current_bits);
7,020,288✔
159
  while (is_min ? (value < current) : (value > current)) {
7,020,288✔
160
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
7,185✔
161
    uint64_t expected_bits = current_bits;
7,185✔
162
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
7,185!
163
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
164
      return;
7,020,288✔
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)
3,510,144✔
191
{
192
  atomic_update_double(ptr, value, false);
1,170,048✔
193
}
1,170,048✔
194

195
inline void atomic_min_double(double* ptr, double value)
3,510,144✔
196
{
197
  atomic_update_double(ptr, value, true);
1,170,048✔
198
}
199

200
namespace detail {
201

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

206
void MaterialVolumes::add_volume(
1,652,482✔
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) {
1,652,482!
217
    // Determine slot to check, making sure it is positive
218
    int slot = (index_material + attempt) % table_size_;
1,652,482✔
219
    if (slot < 0)
1,652,482✔
220
      slot += table_size_;
1,064,572✔
221
    int32_t* slot_ptr = &this->materials(index_elem, slot);
1,652,482✔
222

223
    // Non-atomic read of current material
224
    int32_t current_val = *slot_ptr;
1,652,482✔
225

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

241
    // Slot appears to be empty; attempt to claim
242
    if (current_val == EMPTY) {
282!
243
      // Attempt compare-and-swap from EMPTY to index_material
244
      int32_t expected_val = EMPTY;
282✔
245
      bool claimed_slot =
282✔
246
        atomic_cas_int32(slot_ptr, expected_val, index_material);
282✔
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)) {
282!
251
#pragma omp atomic
252
        this->volumes(index_elem, slot) += volume;
282✔
253
        if (bbox) {
282✔
254
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
30✔
255
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
30✔
256
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
30✔
257
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
30✔
258
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
30✔
259
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
30✔
260
        }
261
        return;
282✔
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(
532✔
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) {
532✔
341
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
386✔
342
  } else if (mesh_type == RectilinearMesh::mesh_type) {
146✔
343
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
16✔
344
  } else if (mesh_type == CylindricalMesh::mesh_type) {
130✔
345
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
70✔
346
  } else if (mesh_type == SphericalMesh::mesh_type) {
60!
347
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
60✔
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;
532✔
367

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

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

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

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

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

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

400
  // Ensure no other mesh has the same ID
401
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
4!
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) {
4!
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;
4✔
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(),
8✔
421
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
10!
422

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

426
vector<double> Mesh::volumes() const
46✔
427
{
428
  vector<double> volumes(n_bins());
46✔
429
  for (int i = 0; i < n_bins(); i++) {
193,502✔
430
    volumes[i] = this->volume(i);
193,456✔
431
  }
432
  return volumes;
46✔
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,
38✔
442
  int32_t* materials, double* volumes, double* bboxes) const
443
{
444
  if (mpi::master) {
38!
445
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
38✔
446
  }
447
  write_message(7, "Number of mesh elements = {}", n_bins());
38✔
448
  write_message(7, "Number of rays (x) = {}", nx);
38✔
449
  write_message(7, "Number of rays (y) = {}", ny);
38✔
450
  write_message(7, "Number of rays (z) = {}", nz);
38✔
451
  int64_t n_total = static_cast<int64_t>(nx) * ny +
38✔
452
                    static_cast<int64_t>(ny) * nz +
38✔
453
                    static_cast<int64_t>(nx) * nz;
38✔
454
  write_message(7, "Total number of rays = {}", n_total);
38✔
455
  write_message(7, "Table size per mesh element = {}", table_size);
38✔
456

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

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

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

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

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

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

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

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

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

496
      // Determine width of rays and number of rays in other directions
497
      int ax1 = (axis + 1) % 3;
114✔
498
      int ax2 = (axis + 2) % 3;
114✔
499
      double min1 = bbox.min[ax1];
114✔
500
      double min2 = bbox.min[ax2];
114✔
501
      double d1 = width[ax1];
114✔
502
      double d2 = width[ax2];
114✔
503
      int n1 = n_rays[ax1];
114✔
504
      int n2 = n_rays[ax2];
114✔
505
      if (n1 == 0 || n2 == 0) {
114✔
506
        continue;
24✔
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;
90✔
512
      int remainder = n1 % mpi::n_procs;
90✔
513
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
90!
514
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
90!
515
      int i1_end = i1_start + n1_local;
90✔
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) {
7,040✔
520
        for (int i2 = 0; i2 < n2; ++i2) {
1,232,088✔
521
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
1,225,138✔
522
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
1,225,138✔
523

524
          p.from_source(&site);
1,225,138✔
525

526
          // Determine particle's location
527
          if (!exhaustive_find_cell(p)) {
1,225,138✔
528
            out_of_model = true;
15,972✔
529
            continue;
15,972✔
530
          }
531

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

536
          // Initialize last cells from current cell
537
          for (int j = 0; j < p.n_coord(); ++j) {
2,418,332✔
538
            p.cell_last(j) = p.coord(j).cell();
1,209,166✔
539
          }
540
          p.n_coord_last() = p.n_coord();
1,209,166✔
541

542
          while (true) {
1,920,878✔
543
            // Ray trace from r_start to r_end
544
            Position r0 = p.r();
1,565,022✔
545
            double max_distance = bbox.max[axis] - r0[axis];
1,565,022✔
546

547
            // Find the distance to the nearest boundary
548
            BoundaryInfo boundary = distance_to_boundary(p);
1,565,022✔
549

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

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

559
            // Add volumes to any mesh elements that were crossed
560
            int i_material = p.material();
1,565,022✔
561
            if (i_material != C_NONE) {
1,565,022✔
562
              i_material = model::materials[i_material]->id();
496,170✔
563
            }
564
            double cumulative_frac = 0.0;
1,565,022✔
565
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
3,217,504✔
566
              int mesh_index = bins[i_bin];
1,652,482✔
567
              double length = distance * length_fractions[i_bin];
1,652,482✔
568
              double volume = length * d1 * d2;
1,652,482✔
569

570
              if (compute_bboxes) {
1,652,482✔
571
                double axis_start = r0[axis] + distance * cumulative_frac;
1,170,048✔
572
                double axis_end = axis_start + length;
1,170,048✔
573
                cumulative_frac += length_fractions[i_bin];
1,170,048✔
574

575
                Position contrib_min = site.r;
1,170,048✔
576
                Position contrib_max = site.r;
1,170,048✔
577

578
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
1,170,048✔
579
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
1,170,048✔
580
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
1,170,048✔
581
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
1,170,048✔
582
                contrib_min[axis] = std::min(axis_start, axis_end);
1,170,048!
583
                contrib_max[axis] = std::max(axis_start, axis_end);
2,340,096!
584

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

588
                result.add_volume(
1,170,048✔
589
                  mesh_index, i_material, volume, &contrib_bbox);
590
              } else {
591
                // Add volume to result
592
                result.add_volume(mesh_index, i_material, volume);
482,434✔
593
              }
594
            }
595

596
            if (distance == max_distance)
1,565,022✔
597
              break;
598

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

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

609
            if (boundary.lattice_translation()[0] != 0 ||
355,856!
610
                boundary.lattice_translation()[1] != 0 ||
355,856!
611
                boundary.lattice_translation()[2] != 0) {
355,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()};
355,856✔
617
              p.cross_surface(*surf);
355,856✔
618
            }
619
          }
355,856✔
620
        }
621
      }
622
    }
623
  }
38✔
624

625
  // Check for errors
626
  if (out_of_model) {
38✔
627
    throw std::runtime_error("Mesh not fully contained in geometry.");
2✔
628
  } else if (result.table_full()) {
36!
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();
36✔
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;
36✔
698
#endif
699

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

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

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

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

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

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

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

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

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

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

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

764
  if (n_dimension_ > 2) {
941,032✔
765
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
938,062✔
766
  } else if (n_dimension_ > 1) {
2,970✔
767
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
2,920✔
768
  } else {
769
    return fmt::format("Mesh Index ({})", ijk[0]);
50✔
770
  }
771
}
772

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

778
Position StructuredMesh::sample_element(
256,454✔
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);
256,454✔
783
  double x_max = positive_grid_boundary(ijk, 0);
256,454✔
784

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

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

791
  return {x_min + (x_max - x_min) * prn(seed),
256,454✔
792
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
256,454✔
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
{
UNCOV
950
  write_dataset(mesh_group, "filename", filename_);
×
UNCOV
951
  write_dataset(mesh_group, "library", this->library());
×
UNCOV
952
  if (!options_.empty()) {
×
UNCOV
953
    write_attribute(mesh_group, "options", options_);
×
954
  }
955

UNCOV
956
  if (length_multiplier_ > 0.0)
×
957
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
958

959
  // write vertex coordinates
UNCOV
960
  tensor::Tensor<double> vertices(
×
UNCOV
961
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
×
UNCOV
962
  for (int i = 0; i < this->n_vertices(); i++) {
×
UNCOV
963
    auto v = this->vertex(i);
×
UNCOV
964
    vertices.slice(i) = {v.x, v.y, v.z};
×
965
  }
UNCOV
966
  write_dataset(mesh_group, "vertices", vertices);
×
967

UNCOV
968
  int num_elem_skipped = 0;
×
969

970
  // write element types and connectivity
UNCOV
971
  vector<double> volumes;
×
UNCOV
972
  tensor::Tensor<int> connectivity(
×
UNCOV
973
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
×
UNCOV
974
  tensor::Tensor<int> elem_types(
×
UNCOV
975
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
×
UNCOV
976
  for (int i = 0; i < this->n_bins(); i++) {
×
UNCOV
977
    auto conn = this->connectivity(i);
×
978

UNCOV
979
    volumes.emplace_back(this->volume(i));
×
980

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

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

UNCOV
1006
  write_dataset(mesh_group, "volumes", volumes);
×
UNCOV
1007
  write_dataset(mesh_group, "connectivity", connectivity);
×
UNCOV
1008
  write_dataset(mesh_group, "element_types", elem_types);
×
UNCOV
1009
}
×
1010

UNCOV
1011
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
×
1012
{
UNCOV
1013
  length_multiplier_ = length_multiplier;
×
UNCOV
1014
}
×
1015

UNCOV
1016
ElementType UnstructuredMesh::element_type(int bin) const
×
1017
{
UNCOV
1018
  auto conn = connectivity(bin);
×
1019

UNCOV
1020
  if (conn.size() == 4)
×
1021
    return ElementType::LINEAR_TET;
1022
  else if (conn.size() == 8)
×
1023
    return ElementType::LINEAR_HEX;
1024
  else
1025
    return ElementType::UNSUPPORTED;
×
UNCOV
1026
}
×
1027

1028
StructuredMesh::MeshIndex StructuredMesh::get_indices(
295,563,570✔
1029
  Position r, bool& in_mesh) const
1030
{
1031
  MeshIndex ijk;
295,563,570✔
1032
  in_mesh = true;
295,563,570✔
1033
  for (int i = 0; i < n_dimension_; ++i) {
1,163,899,954✔
1034
    ijk[i] = get_index_in_direction(r[i], i);
868,336,384✔
1035

1036
    if (ijk[i] < 1 || ijk[i] > shape_[i])
868,336,384✔
1037
      in_mesh = false;
18,712,970✔
1038
  }
1039
  return ijk;
295,563,570✔
1040
}
1041

1042
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
405,059,552✔
1043
{
1044
  switch (n_dimension_) {
405,059,552!
1045
  case 1:
160,110✔
1046
    return ijk[0] - 1;
160,110✔
1047
  case 2:
25,756,954✔
1048
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
25,756,954✔
1049
  case 3:
379,142,488✔
1050
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
379,142,488✔
1051
  default:
×
1052
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1053
  }
1054
}
1055

1056
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
1,407,548✔
1057
{
1058
  MeshIndex ijk;
1,407,548✔
1059
  if (n_dimension_ == 1) {
1,407,548✔
1060
    ijk[0] = bin + 1;
50✔
1061
  } else if (n_dimension_ == 2) {
1,407,498✔
1062
    ijk[0] = bin % shape_[0] + 1;
2,920✔
1063
    ijk[1] = bin / shape_[0] + 1;
2,920✔
1064
  } else if (n_dimension_ == 3) {
1,404,578!
1065
    ijk[0] = bin % shape_[0] + 1;
1,404,578✔
1066
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
1,404,578✔
1067
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
1,404,578✔
1068
  }
1069
  return ijk;
1,407,548✔
1070
}
1071

1072
int StructuredMesh::get_bin(Position r) const
77,389,768✔
1073
{
1074
  // Determine indices
1075
  bool in_mesh;
77,389,768✔
1076
  MeshIndex ijk = get_indices(r, in_mesh);
77,389,768✔
1077
  if (!in_mesh)
77,389,768✔
1078
    return -1;
1079

1080
  // Convert indices to bin
1081
  return get_bin_from_indices(ijk);
73,807,790✔
1082
}
1083

1084
int StructuredMesh::n_bins() const
196,178✔
1085
{
1086
  // Bin indices are stored as 32-bit ints in the tally system.
1087
  int64_t n = 1;
196,178✔
1088
  for (int i = 0; i < n_dimension_; ++i)
784,654✔
1089
    n *= shape_[i];
588,476✔
1090
  if (n > std::numeric_limits<int>::max()) {
196,178!
1091
    fatal_error(fmt::format(
×
1092
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1093
  }
1094
  return static_cast<int>(n);
196,178✔
1095
}
1096

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

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

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

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

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

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

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

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

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

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

1154
  return counts;
×
1155
}
×
1156

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

1170
  // Compute the length of the entire track.
1171
  double total_distance = (r1 - r0).norm();
226,249,804✔
1172
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
226,249,804✔
1173
    return;
1174

1175
  // keep a copy of the original global position to pass to get_indices,
1176
  // which performs its own transformation to local coordinates
1177
  Position global_r = r0;
216,859,818✔
1178
  Position local_r = local_coords(r0);
216,859,818✔
1179

1180
  const int n = n_dimension_;
216,859,818✔
1181

1182
  // Flag if position is inside the mesh
1183
  bool in_mesh;
1184

1185
  // Position is r = r0 + u * traveled_distance, start at r0
1186
  double traveled_distance {0.0};
216,859,818✔
1187

1188
  // Calculate index of current cell. Offset the position a tiny bit in
1189
  // direction of flight
1190
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
216,859,818✔
1191

1192
  // if track is very short, assume that it is completely inside one cell.
1193
  // Only the current cell will score and no surfaces
1194
  if (total_distance < 2 * TINY_BIT) {
216,859,818✔
1195
    if (in_mesh) {
65,766✔
1196
      tally.track(ijk, 1.0);
65,678✔
1197
    }
1198
    return;
65,766✔
1199
  }
1200

1201
  // Calculate initial distances to next surfaces in all three dimensions
1202
  std::array<MeshDistance, 3> distances;
433,588,104✔
1203
  for (int k = 0; k < n; ++k) {
849,179,124✔
1204
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
632,385,072✔
1205
  }
1206

1207
  // Loop until r = r1 is eventually reached
1208
  while (true) {
1209

1210
    if (in_mesh) {
362,140,318✔
1211

1212
      // find surface with minimal distance to current position
1213
      const auto k = std::min_element(distances.begin(), distances.end()) -
346,074,334✔
1214
                     distances.begin();
346,074,334✔
1215

1216
      // Tally track length delta since last step
1217
      tally.track(ijk,
346,074,334✔
1218
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
524,156,988✔
1219
          total_distance);
1220

1221
      // update position and leave, if we have reached end position
1222
      traveled_distance = distances[k].distance;
346,074,334✔
1223
      if (traveled_distance >= total_distance)
346,074,334✔
1224
        return;
1225

1226
      // If we have not reached r1, we have hit a surface. Tally outward
1227
      // current
1228
      tally.surface(ijk, k, distances[k].max_surface, false);
144,032,282✔
1229

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

1236
      // Check if we have left the interior of the mesh
1237
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
145,284,118✔
1238

1239
      // If we are still inside the mesh, tally inward current for the next
1240
      // cell
1241
      if (in_mesh)
5,377,618✔
1242
        tally.surface(ijk, k, !distances[k].max_surface, true);
145,088,772✔
1243

1244
    } else { // not inside mesh
1245

1246
      // For all directions outside the mesh, find the distance that we need
1247
      // to travel to reach the next surface. Use the largest distance, as
1248
      // only this will cross all outer surfaces.
1249
      int k_max {-1};
1250
      for (int k = 0; k < n; ++k) {
63,996,852✔
1251
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
47,930,868✔
1252
            (distances[k].distance > traveled_distance)) {
17,505,258✔
1253
          traveled_distance = distances[k].distance;
1254
          k_max = k;
1255
        }
1256
      }
1257
      // Assure some distance is traveled
1258
      if (k_max == -1) {
16,065,984✔
1259
        traveled_distance += TINY_BIT;
20✔
1260
      }
1261

1262
      // If r1 is not inside the mesh, exit here
1263
      if (traveled_distance >= total_distance)
16,065,984✔
1264
        return;
1265

1266
      // Calculate the new cell index and update all distances to next
1267
      // surfaces.
1268
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
1,313,984✔
1269
      for (int k = 0; k < n; ++k) {
5,218,020✔
1270
        distances[k] =
3,904,036✔
1271
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
3,904,036✔
1272
      }
1273

1274
      // If inside the mesh, Tally inward current
1275
      if (in_mesh && k_max >= 0)
1,313,984!
1276
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
139,964,472✔
1277
    }
1278
  }
1279
}
1280

1281
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
205,862,974✔
1282
  vector<int>& bins, vector<double>& lengths) const
1283
{
1284

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

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

1305
  // Perform the mesh raytrace with the helper class.
1306
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
205,862,974✔
1307
}
205,862,974✔
1308

1309
void StructuredMesh::surface_bins_crossed(
20,386,830✔
1310
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1311
{
1312

1313
  // Helper tally class.
1314
  // stores a pointer to the mesh class and a reference to the bins parameter.
1315
  // Performs the actual tally through the surface method.
1316
  struct SurfaceAggregator {
20,386,830✔
1317
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
20,386,830✔
1318
      : mesh(_mesh), bins(_bins)
20,386,830✔
1319
    {}
1320
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
10,574,398✔
1321
    {
1322
      int i_bin =
10,574,398✔
1323
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
10,574,398✔
1324
      if (max)
10,574,398✔
1325
        i_bin += 2;
5,282,080✔
1326
      if (inward)
10,574,398✔
1327
        i_bin += 1;
5,196,780✔
1328
      bins.push_back(i_bin);
10,574,398✔
1329
    }
10,574,398✔
1330
    void track(const MeshIndex& idx, double l) const {}
1331

1332
    const StructuredMesh* mesh;
1333
    vector<int>& bins;
1334
  };
1335

1336
  // Perform the mesh raytrace with the helper class.
1337
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
20,386,830✔
1338
}
20,386,830✔
1339

1340
//==============================================================================
1341
// RegularMesh implementation
1342
//==============================================================================
1343

1344
int RegularMesh::set_grid()
390✔
1345
{
1346
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
390✔
1347

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

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

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

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

1376
    // Set width and upper right coordinate
1377
    upper_right_ = lower_left_ + shape * width_;
18✔
1378

1379
  } else if (upper_right_.size() > 0) {
384!
1380

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

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

1396
    // Set width
1397
    width_ = (upper_right_ - lower_left_) / shape;
1,152✔
1398
  }
1399

1400
  // Set material volumes
1401
  volume_frac_ = 1.0 / shape.prod();
390✔
1402

1403
  element_volume_ = 1.0;
390✔
1404
  for (int i = 0; i < n_dimension_; i++) {
1,484✔
1405
    element_volume_ *= width_[i];
1,094✔
1406
  }
1407
  return 0;
1408
}
390✔
1409

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

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

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

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

1438
    width_ = get_node_tensor<double>(node, "width");
12✔
1439

1440
  } else if (check_for_node(node, "upper_right")) {
382!
1441

1442
    upper_right_ = get_node_tensor<double>(node, "upper_right");
764✔
1443

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

1448
  if (int err = set_grid()) {
388!
1449
    fatal_error(openmc_err_msg);
×
1450
  }
1451
}
388✔
1452

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

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

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

1476
  if (object_exists(group, "upper_right")) {
2!
1477

1478
    read_dataset(group, "upper_right", upper_right_);
2✔
1479

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

1484
  if (int err = set_grid()) {
2!
1485
    fatal_error(openmc_err_msg);
×
1486
  }
1487
}
2✔
1488

1489
int RegularMesh::get_index_in_direction(double r, int i) const
791,412,466✔
1490
{
1491
  return std::ceil((r - lower_left_[i]) / width_[i]);
791,412,466✔
1492
}
1493

1494
const std::string RegularMesh::mesh_type = "regular";
1495

1496
std::string RegularMesh::get_mesh_type() const
638✔
1497
{
1498
  return mesh_type;
638✔
1499
}
1500

1501
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
345,433,264✔
1502
{
1503
  return lower_left_[i] + ijk[i] * width_[i];
345,433,264✔
1504
}
1505

1506
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
332,850,004✔
1507
{
1508
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
332,850,004✔
1509
}
1510

1511
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
683,637,998✔
1512
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1513
  double l) const
1514
{
1515
  MeshDistance d;
683,637,998✔
1516
  d.next_index = ijk[i];
683,637,998✔
1517
  if (std::abs(u[i]) < FP_PRECISION)
683,637,998✔
1518
    return d;
2,781,264✔
1519

1520
  d.max_surface = (u[i] > 0);
680,856,734✔
1521
  if (d.max_surface && (ijk[i] <= shape_[i])) {
680,856,734✔
1522
    d.next_index++;
344,663,902✔
1523
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
344,663,902✔
1524
  } else if (!d.max_surface && (ijk[i] >= 1)) {
336,192,832✔
1525
    d.next_index--;
332,080,642✔
1526
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
332,080,642✔
1527
  }
1528

1529
  return d;
680,856,734✔
1530
}
1531

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

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

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

1570
  return {axis_lines[0], axis_lines[1]};
8✔
1571
}
1572

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

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

1588
  // Create array of zeros
1589
  auto cnt = tensor::zeros<double>(shape);
1,408✔
1590
  bool outside_ = false;
1591

1592
  for (int64_t i = 0; i < length; i++) {
1,395,490✔
1593
    const auto& site = bank[i];
1,394,082✔
1594

1595
    // determine scoring bin for entropy mesh
1596
    int mesh_bin = get_bin(site.r);
1,394,082✔
1597

1598
    // if outside mesh, skip particle
1599
    if (mesh_bin < 0) {
1,394,082!
1600
      outside_ = true;
×
1601
      continue;
×
1602
    }
1603

1604
    // Add to appropriate bin
1605
    cnt(mesh_bin) += site.wgt;
1,394,082✔
1606
  }
1607

1608
  // Create reduced count data
1609
  auto counts = tensor::zeros<double>(shape);
1,408✔
1610
  int total = cnt.size();
1,408✔
1611

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

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

1627
  return counts;
1,408✔
1628
}
1,408✔
1629

1630
double RegularMesh::volume(const MeshIndex& ijk) const
193,684✔
1631
{
1632
  return element_volume_;
193,684✔
1633
}
1634

1635
//==============================================================================
1636
// RectilinearMesh implementation
1637
//==============================================================================
1638

1639
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
18✔
1640
{
1641
  n_dimension_ = 3;
18✔
1642

1643
  grid_[0] = get_node_array<double>(node, "x_grid");
18✔
1644
  grid_[1] = get_node_array<double>(node, "y_grid");
18✔
1645
  grid_[2] = get_node_array<double>(node, "z_grid");
18✔
1646

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

1652
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
2✔
1653
{
1654
  n_dimension_ = 3;
2✔
1655

1656
  read_dataset(group, "x_grid", grid_[0]);
2✔
1657
  read_dataset(group, "y_grid", grid_[1]);
2✔
1658
  read_dataset(group, "z_grid", grid_[2]);
2✔
1659

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

1665
const std::string RectilinearMesh::mesh_type = "rectilinear";
1666

1667
std::string RectilinearMesh::get_mesh_type() const
48✔
1668
{
1669
  return mesh_type;
48✔
1670
}
1671

1672
double RectilinearMesh::positive_grid_boundary(
4,819,266✔
1673
  const MeshIndex& ijk, int i) const
1674
{
1675
  return grid_[i][ijk[i]];
4,819,266✔
1676
}
1677

1678
double RectilinearMesh::negative_grid_boundary(
4,679,892✔
1679
  const MeshIndex& ijk, int i) const
1680
{
1681
  return grid_[i][ijk[i] - 1];
4,679,892✔
1682
}
1683

1684
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
9,745,834✔
1685
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1686
  double l) const
1687
{
1688
  MeshDistance d;
9,745,834✔
1689
  d.next_index = ijk[i];
9,745,834✔
1690
  if (std::abs(u[i]) < FP_PRECISION)
9,745,834✔
1691
    return d;
103,968✔
1692

1693
  d.max_surface = (u[i] > 0);
9,641,866✔
1694
  if (d.max_surface && (ijk[i] <= shape_[i])) {
9,641,866✔
1695
    d.next_index++;
4,819,266✔
1696
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
4,819,266✔
1697
  } else if (!d.max_surface && (ijk[i] > 0)) {
4,822,600✔
1698
    d.next_index--;
4,679,892✔
1699
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
4,679,892✔
1700
  }
1701
  return d;
9,641,866✔
1702
}
1703

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

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

1724
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
28✔
1725
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
28✔
1726

1727
  return 0;
28✔
1728
}
1729

1730
int RectilinearMesh::get_index_in_direction(double r, int i) const
13,474,344✔
1731
{
1732
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
13,474,344✔
1733
}
1734

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

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

1756
    for (auto coord : grid_[axis]) {
20✔
1757
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
16!
1758
        lines.push_back(coord);
16✔
1759
    }
1760
  }
1761

1762
  return {axis_lines[0], axis_lines[1]};
4✔
1763
}
1764

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

1772
double RectilinearMesh::volume(const MeshIndex& ijk) const
24✔
1773
{
1774
  double vol {1.0};
24✔
1775

1776
  for (int i = 0; i < n_dimension_; i++) {
96✔
1777
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
72✔
1778
  }
1779
  return vol;
24✔
1780
}
1781

1782
//==============================================================================
1783
// CylindricalMesh implementation
1784
//==============================================================================
1785

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

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

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

1808
  if (int err = set_grid()) {
2!
1809
    fatal_error(openmc_err_msg);
×
1810
  }
1811
}
2✔
1812

1813
const std::string CylindricalMesh::mesh_type = "cylindrical";
1814

1815
std::string CylindricalMesh::get_mesh_type() const
88✔
1816
{
1817
  return mesh_type;
88✔
1818
}
1819

1820
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
8,678,562✔
1821
  Position r, bool& in_mesh) const
1822
{
1823
  r = local_coords(r);
8,678,562✔
1824

1825
  Position mapped_r;
8,678,562✔
1826
  mapped_r[0] = std::hypot(r.x, r.y);
8,678,562✔
1827
  mapped_r[2] = r[2];
8,678,562✔
1828

1829
  if (mapped_r[0] < FP_PRECISION) {
8,678,562!
1830
    mapped_r[1] = 0.0;
1831
  } else {
1832
    mapped_r[1] = std::atan2(r.y, r.x);
8,678,562✔
1833
    if (mapped_r[1] < 0)
8,678,562✔
1834
      mapped_r[1] += 2 * M_PI;
4,340,884✔
1835
  }
1836

1837
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
8,678,562✔
1838

1839
  idx[1] = sanitize_phi(idx[1]);
8,678,562✔
1840

1841
  return idx;
8,678,562✔
1842
}
1843

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

1850
  double phi_min = this->phi(ijk[1] - 1);
16,020✔
1851
  double phi_max = this->phi(ijk[1]);
16,020✔
1852

1853
  double z_min = this->z(ijk[2] - 1);
16,020✔
1854
  double z_max = this->z(ijk[2]);
16,020✔
1855

1856
  double r_min_sq = r_min * r_min;
16,020✔
1857
  double r_max_sq = r_max * r_max;
16,020✔
1858
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
16,020✔
1859
  double phi = uniform_distribution(phi_min, phi_max, seed);
16,020✔
1860
  double z = uniform_distribution(z_min, z_max, seed);
16,020✔
1861

1862
  double x = r * std::cos(phi);
16,020✔
1863
  double y = r * std::sin(phi);
16,020✔
1864

1865
  return origin_ + Position(x, y, z);
16,020✔
1866
}
1867

1868
double CylindricalMesh::find_r_crossing(
25,924,668✔
1869
  const Position& r, const Direction& u, double l, int shell) const
1870
{
1871

1872
  if ((shell < 0) || (shell > shape_[0]))
25,924,668!
1873
    return INFTY;
1874

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

1879
  const double r0 = grid_[0][shell];
22,667,610✔
1880
  if (r0 == 0.0)
22,667,610✔
1881
    return INFTY;
1882

1883
  const double denominator = u.x * u.x + u.y * u.y;
21,370,142✔
1884

1885
  // Direction of flight is in z-direction. Will never intersect r.
1886
  if (std::abs(denominator) < FP_PRECISION)
21,370,142✔
1887
    return INFTY;
1888

1889
  // inverse of dominator to help the compiler to speed things up
1890
  const double inv_denominator = 1.0 / denominator;
21,359,422✔
1891

1892
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
21,359,422✔
1893
  double R = std::sqrt(r.x * r.x + r.y * r.y);
21,359,422✔
1894
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
21,359,422✔
1895

1896
  if (D < 0.0)
21,359,422✔
1897
    return INFTY;
1898

1899
  D = std::sqrt(D);
19,589,218✔
1900

1901
  // Particle is already on the shell surface; avoid spurious crossing
1902
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
19,589,218✔
1903
    return INFTY;
1904

1905
  // Check -p - D first because it is always smaller as -p + D
1906
  if (-p - D > l)
18,383,150✔
1907
    return -p - D;
1908
  if (-p + D > l)
14,709,044✔
1909
    return -p + D;
9,104,954✔
1910

1911
  return INFTY;
1912
}
1913

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

1921
  shell = sanitize_phi(shell);
7,994,676✔
1922

1923
  const double p0 = grid_[1][shell];
7,994,676✔
1924

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

1930
  const double c0 = std::cos(p0);
7,994,676✔
1931
  const double s0 = std::sin(p0);
7,994,676✔
1932

1933
  const double denominator = (u.x * s0 - u.y * c0);
7,994,676✔
1934

1935
  // Check if direction of flight is not parallel to phi surface
1936
  if (std::abs(denominator) > FP_PRECISION) {
7,994,676✔
1937
    const double s = -(r.x * s0 - r.y * c0) / denominator;
7,947,268✔
1938
    // Check if solution is in positive direction of flight and crosses the
1939
    // correct phi surface (not -phi)
1940
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
7,947,268✔
1941
      return s;
3,676,338✔
1942
  }
1943

1944
  return INFTY;
1945
}
1946

1947
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
6,671,954✔
1948
  const Position& r, const Direction& u, double l, int shell) const
1949
{
1950
  MeshDistance d;
6,671,954✔
1951
  d.next_index = shell;
6,671,954✔
1952

1953
  // Direction of flight is within xy-plane. Will never intersect z.
1954
  if (std::abs(u.z) < FP_PRECISION)
6,671,954✔
1955
    return d;
203,312✔
1956

1957
  d.max_surface = (u.z > 0.0);
6,468,642✔
1958
  if (d.max_surface && (shell <= shape_[2])) {
6,468,642✔
1959
    d.next_index += 1;
3,068,344✔
1960
    d.distance = (grid_[2][shell] - r.z) / u.z;
3,068,344✔
1961
  } else if (!d.max_surface && (shell > 0)) {
3,400,298✔
1962
    d.next_index -= 1;
3,062,950✔
1963
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
3,062,950✔
1964
  }
1965
  return d;
6,468,642✔
1966
}
1967

1968
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
26,403,052✔
1969
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1970
  double l) const
1971
{
1972
  if (i == 0) {
26,403,052✔
1973

1974
    return std::min(
25,924,668✔
1975
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
12,962,334✔
1976
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
25,924,668✔
1977

1978
  } else if (i == 1) {
13,440,718✔
1979

1980
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
6,768,764✔
1981
                      find_phi_crossing(r0, u, l, ijk[i])),
6,768,764✔
1982
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
6,768,764✔
1983
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
13,537,528✔
1984

1985
  } else {
1986
    return find_z_crossing(r0, u, l, ijk[i]);
6,671,954✔
1987
  }
1988
}
1989

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

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

2023
    return OPENMC_E_INVALID_ARGUMENT;
×
2024
  }
2025

2026
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
78!
2027

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

2033
  return 0;
78✔
2034
}
2035

2036
int CylindricalMesh::get_index_in_direction(double r, int i) const
26,035,686✔
2037
{
2038
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
26,035,686✔
2039
}
2040

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

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

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

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

2064
  double phi_i = grid_[1][ijk[1] - 1];
144✔
2065
  double phi_o = grid_[1][ijk[1]];
144✔
2066

2067
  double z_i = grid_[2][ijk[2] - 1];
144✔
2068
  double z_o = grid_[2][ijk[2]];
144✔
2069

2070
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
144✔
2071
}
2072

2073
//==============================================================================
2074
// SphericalMesh implementation
2075
//==============================================================================
2076

2077
SphericalMesh::SphericalMesh(pugi::xml_node node)
62✔
2078
  : PeriodicStructuredMesh {node}
62✔
2079
{
2080
  n_dimension_ = 3;
62✔
2081

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

2087
  if (int err = set_grid()) {
62!
2088
    fatal_error(openmc_err_msg);
×
2089
  }
2090
}
62✔
2091

2092
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
2✔
2093
{
2094
  n_dimension_ = 3;
2✔
2095

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

2101
  if (int err = set_grid()) {
2!
2102
    fatal_error(openmc_err_msg);
×
2103
  }
2104
}
2✔
2105

2106
const std::string SphericalMesh::mesh_type = "spherical";
2107

2108
std::string SphericalMesh::get_mesh_type() const
70✔
2109
{
2110
  return mesh_type;
70✔
2111
}
2112

2113
StructuredMesh::MeshIndex SphericalMesh::get_indices(
12,471,296✔
2114
  Position r, bool& in_mesh) const
2115
{
2116
  r = local_coords(r);
12,471,296✔
2117

2118
  Position mapped_r;
12,471,296✔
2119
  mapped_r[0] = r.norm();
12,471,296✔
2120

2121
  if (mapped_r[0] < FP_PRECISION) {
12,471,296!
2122
    mapped_r[1] = 0.0;
2123
    mapped_r[2] = 0.0;
2124
  } else {
2125
    mapped_r[1] = std::acos(r.z / mapped_r.x);
12,471,296✔
2126
    mapped_r[2] = std::atan2(r.y, r.x);
12,471,296✔
2127
    if (mapped_r[2] < 0)
12,471,296✔
2128
      mapped_r[2] += 2 * M_PI;
6,230,670✔
2129
  }
2130

2131
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
12,471,296✔
2132

2133
  idx[1] = sanitize_theta(idx[1]);
12,471,296✔
2134
  idx[2] = sanitize_phi(idx[2]);
12,471,296✔
2135

2136
  return idx;
12,471,296✔
2137
}
2138

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

2145
  double theta_min = this->theta(ijk[1] - 1);
20✔
2146
  double theta_max = this->theta(ijk[1]);
20✔
2147

2148
  double phi_min = this->phi(ijk[2] - 1);
20✔
2149
  double phi_max = this->phi(ijk[2]);
20✔
2150

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

2160
  double x = r * std::cos(phi) * sin_theta;
20✔
2161
  double y = r * std::sin(phi) * sin_theta;
20✔
2162
  double z = r * cos_theta;
20✔
2163

2164
  return origin_ + Position(x, y, z);
20✔
2165
}
2166

2167
double SphericalMesh::find_r_crossing(
80,721,344✔
2168
  const Position& r, const Direction& u, double l, int shell) const
2169
{
2170
  if ((shell < 0) || (shell > shape_[0]))
80,721,344✔
2171
    return INFTY;
2172

2173
  // solve |r+s*u| = r0
2174
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2175
  const double r0 = grid_[0][shell];
73,517,510✔
2176
  if (r0 == 0.0)
73,517,510✔
2177
    return INFTY;
2178
  const double p = r.dot(u);
72,121,416✔
2179
  double R = r.norm();
72,121,416✔
2180
  double D = p * p - (R - r0) * (R + r0);
72,121,416✔
2181

2182
  // Particle is already on the shell surface; avoid spurious crossing
2183
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
72,121,416✔
2184
    return INFTY;
2185

2186
  if (D >= 0.0) {
70,174,388✔
2187
    D = std::sqrt(D);
65,105,852✔
2188
    // Check -p - D first because it is always smaller as -p + D
2189
    if (-p - D > l)
65,105,852✔
2190
      return -p - D;
2191
    if (-p + D > l)
53,413,204✔
2192
      return -p + D;
32,224,524✔
2193
  }
2194

2195
  return INFTY;
2196
}
2197

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

2205
  shell = sanitize_theta(shell);
6,974,280✔
2206

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

2214
  const double cos_t = std::cos(grid_[1][shell]);
6,974,280✔
2215
  const bool sgn = std::signbit(cos_t);
6,974,280✔
2216
  const double cos_t_2 = cos_t * cos_t;
6,974,280✔
2217

2218
  const double a = cos_t_2 - u.z * u.z;
6,974,280✔
2219
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
6,974,280✔
2220
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
6,974,280✔
2221

2222
  // if factor of s^2 is zero, direction of flight is parallel to theta
2223
  // surface
2224
  if (std::abs(a) < FP_PRECISION) {
6,974,280✔
2225
    // if b vanishes, direction of flight is within theta surface and crossing
2226
    // is not possible
2227
    if (std::abs(b) < FP_PRECISION)
87,736!
2228
      return INFTY;
2229

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

2236
    // no crossing is possible
2237
    return INFTY;
2238
  }
2239

2240
  const double p = b / a;
6,886,544✔
2241
  double D = p * p - c / a;
6,886,544✔
2242

2243
  if (D < 0.0)
6,886,544✔
2244
    return INFTY;
2245

2246
  D = std::sqrt(D);
4,894,728✔
2247

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

2254
  s = -p + D;
3,934,254✔
2255
  // Check if solution is in positive direction of flight and has correct sign
2256
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
3,934,254✔
2257
    return s;
1,847,872✔
2258

2259
  return INFTY;
2260
}
2261

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

2269
  shell = sanitize_phi(shell);
7,263,276✔
2270

2271
  const double p0 = grid_[2][shell];
7,263,276✔
2272

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

2278
  const double c0 = std::cos(p0);
7,263,276✔
2279
  const double s0 = std::sin(p0);
7,263,276✔
2280

2281
  const double denominator = (u.x * s0 - u.y * c0);
7,263,276✔
2282

2283
  // Check if direction of flight is not parallel to phi surface
2284
  if (std::abs(denominator) > FP_PRECISION) {
7,263,276✔
2285
    const double s = -(r.x * s0 - r.y * c0) / denominator;
7,220,732✔
2286
    // Check if solution is in positive direction of flight and crosses the
2287
    // correct phi surface (not -phi)
2288
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
7,220,732✔
2289
      return s;
3,196,264✔
2290
  }
2291

2292
  return INFTY;
2293
}
2294

2295
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
60,534,506✔
2296
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2297
  double l) const
2298
{
2299

2300
  if (i == 0) {
60,534,506✔
2301
    return std::min(
80,721,344✔
2302
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
40,360,672✔
2303
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
80,721,344✔
2304

2305
  } else if (i == 1) {
20,173,834✔
2306
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
10,014,668✔
2307
                      find_theta_crossing(r0, u, l, ijk[i])),
10,014,668✔
2308
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
10,014,668✔
2309
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
20,029,336✔
2310

2311
  } else {
2312
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
10,159,166✔
2313
                      find_phi_crossing(r0, u, l, ijk[i])),
10,159,166✔
2314
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
10,159,166✔
2315
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
20,318,332✔
2316
  }
2317
}
2318

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

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

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

2355
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
68!
2356
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
68✔
2357

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

2362
  return 0;
68✔
2363
}
2364

2365
int SphericalMesh::get_index_in_direction(double r, int i) const
37,413,888✔
2366
{
2367
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
37,413,888✔
2368
}
2369

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

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

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

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

2393
  double theta_i = grid_[1][ijk[1] - 1];
170✔
2394
  double theta_o = grid_[1][ijk[1]];
170✔
2395

2396
  double phi_i = grid_[2][ijk[2] - 1];
170✔
2397
  double phi_o = grid_[2][ijk[2]];
170✔
2398

2399
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
340✔
2400
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
170✔
2401
}
2402

2403
//==============================================================================
2404
// Helper functions for the C API
2405
//==============================================================================
2406

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

2416
template<class T>
2417
int check_mesh_type(int32_t index)
200✔
2418
{
2419
  if (int err = check_mesh(index))
200!
2420
    return err;
2421

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

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

2437
//==============================================================================
2438
// C API functions
2439
//==============================================================================
2440

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

2447
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
272✔
2448

2449
  return 0;
272✔
2450
}
2451

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

2460
  for (int i = 0; i < n; ++i) {
92✔
2461
    if (RegularMesh::mesh_type == type) {
46✔
2462
      model::meshes.push_back(make_unique<RegularMesh>());
30✔
2463
    } else if (RectilinearMesh::mesh_type == type) {
16✔
2464
      model::meshes.push_back(make_unique<RectilinearMesh>());
8✔
2465
    } else if (CylindricalMesh::mesh_type == type) {
8✔
2466
      model::meshes.push_back(make_unique<CylindricalMesh>());
4✔
2467
    } else if (SphericalMesh::mesh_type == type) {
4!
2468
      model::meshes.push_back(make_unique<SphericalMesh>());
4✔
2469
    } else {
2470
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2471
    }
2472
  }
2473
  if (index_end)
46!
2474
    *index_end = model::meshes.size() - 1;
×
2475

2476
  return 0;
46✔
2477
}
46✔
2478

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

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

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

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

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

2512
  return 0;
2513
}
×
2514

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

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

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

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

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

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

2572
  BoundingBox bbox = model::meshes[index]->bounding_box();
32✔
2573

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

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

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

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

2604
  return 0;
2605
}
2606

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

2614
  int pixel_width = pixels[0];
8✔
2615
  int pixel_height = pixels[1];
8✔
2616

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

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

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

2647
#pragma omp parallel
2648
  {
8✔
2649
    Position r = xyz;
8✔
2650

2651
#pragma omp for
2652
    for (int y = 0; y < pixel_height; y++) {
168✔
2653
      r[out_i] = xyz[out_i] - out_pixel * y;
160✔
2654
      for (int x = 0; x < pixel_width; x++) {
3,360✔
2655
        r[in_i] = xyz[in_i] + in_pixel * x;
3,200✔
2656
        data[pixel_width * y + x] = mesh->get_bin(r);
3,200✔
2657
      }
2658
    }
2659
  }
2660

2661
  return 0;
8✔
2662
}
2663

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

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

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

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

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

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

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

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

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

2741
  // Set material volumes
2742

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

2751
  return 0;
2752
}
40✔
2753

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

2763
  C* m = dynamic_cast<C*>(model::meshes[index].get());
16!
2764

2765
  m->n_dimension_ = 3;
16✔
2766

2767
  m->grid_[0].reserve(nx);
16✔
2768
  m->grid_[1].reserve(ny);
16✔
2769
  m->grid_[2].reserve(nz);
16✔
2770

2771
  for (int i = 0; i < nx; i++) {
104✔
2772
    m->grid_[0].push_back(grid_x[i]);
88✔
2773
  }
2774
  for (int i = 0; i < ny; i++) {
62✔
2775
    m->grid_[1].push_back(grid_y[i]);
46✔
2776
  }
2777
  for (int i = 0; i < nz; i++) {
58✔
2778
    m->grid_[2].push_back(grid_z[i]);
42✔
2779
  }
2780

2781
  int err = m->set_grid();
16✔
2782
  return err;
16✔
2783
}
2784

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

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

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

2806
  return 0;
70✔
2807
}
2808

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

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

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

2834
//! Set the cylindrical mesh parameters
2835
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
4✔
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<CylindricalMesh>(
4✔
2840
    index, grid_x, nx, grid_y, ny, grid_z, nz);
4✔
2841
}
2842

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

2848
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
22✔
2849
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2850
  ;
22✔
2851
}
2852

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

NEW
2862
extern "C" int openmc_unstructured_mesh_export_hdf5(
×
2863
  int32_t index, hid_t mesh_group)
2864
{
NEW
2865
  if (!mpi::master)
×
2866
    return 0;
2867

NEW
2868
  if (H5Iis_valid(mesh_group) <= 0)
×
NEW
2869
    fatal_error("Not a valid group");
×
NEW
2870
  if (H5Iget_type(mesh_group) != H5I_GROUP)
×
NEW
2871
    fatal_error("Not a valid group");
×
2872

NEW
2873
  if (int err = check_mesh_type<UnstructuredMesh>(index))
×
2874
    return err;
NEW
2875
  UnstructuredMesh* m =
×
NEW
2876
    dynamic_cast<UnstructuredMesh*>(model::meshes[index].get());
×
2877

NEW
2878
  m->to_hdf5_inner(mesh_group);
×
NEW
2879
  return 0;
×
2880
}
2881

2882
#ifdef OPENMC_DAGMC_ENABLED
2883

2884
const std::string MOABMesh::mesh_lib_type = "moab";
2885

2886
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2887
{
2888
  initialize();
2889
}
2890

2891
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
2892
{
2893
  initialize();
2894
}
2895

2896
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2897
  : UnstructuredMesh()
2898
{
2899
  n_dimension_ = 3;
2900
  filename_ = filename;
2901
  set_length_multiplier(length_multiplier);
2902
  initialize();
2903
}
2904

2905
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
2906
{
2907
  mbi_ = external_mbi;
2908
  filename_ = "unknown (external file)";
2909
  this->initialize();
2910
}
2911

2912
void MOABMesh::initialize()
2913
{
2914

2915
  // Create the MOAB interface and load data from file
2916
  this->create_interface();
2917

2918
  // Initialise MOAB error code
2919
  moab::ErrorCode rval = moab::MB_SUCCESS;
2920

2921
  // Set the dimension
2922
  n_dimension_ = 3;
2923

2924
  // set member range of tetrahedral entities
2925
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2926
  if (rval != moab::MB_SUCCESS) {
2927
    fatal_error("Failed to get all tetrahedral elements");
2928
  }
2929

2930
  if (!ehs_.all_of_type(moab::MBTET)) {
2931
    warning("Non-tetrahedral elements found in unstructured "
2932
            "mesh file: " +
2933
            filename_);
2934
  }
2935

2936
  // set member range of vertices
2937
  int vertex_dim = 0;
2938
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
2939
  if (rval != moab::MB_SUCCESS) {
2940
    fatal_error("Failed to get all vertex handles");
2941
  }
2942

2943
  // make an entity set for all tetrahedra
2944
  // this is used for convenience later in output
2945
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
2946
  if (rval != moab::MB_SUCCESS) {
2947
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2948
  }
2949

2950
  rval = mbi_->add_entities(tetset_, ehs_);
2951
  if (rval != moab::MB_SUCCESS) {
2952
    fatal_error("Failed to add tetrahedra to an entity set.");
2953
  }
2954

2955
  if (length_multiplier_ > 0.0) {
2956
    // get the connectivity of all tets
2957
    moab::Range adj;
2958
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2959
    if (rval != moab::MB_SUCCESS) {
2960
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2961
    }
2962
    // scale all vertex coords by multiplier (done individually so not all
2963
    // coordinates are in memory twice at once)
2964
    for (auto vert : adj) {
2965
      // retrieve coords
2966
      std::array<double, 3> coord;
2967
      rval = mbi_->get_coords(&vert, 1, coord.data());
2968
      if (rval != moab::MB_SUCCESS) {
2969
        fatal_error("Could not get coordinates of vertex.");
2970
      }
2971
      // scale coords
2972
      for (auto& c : coord) {
2973
        c *= length_multiplier_;
2974
      }
2975
      // set new coords
2976
      rval = mbi_->set_coords(&vert, 1, coord.data());
2977
      if (rval != moab::MB_SUCCESS) {
2978
        fatal_error("Failed to set new vertex coordinates");
2979
      }
2980
    }
2981
  }
2982

2983
  // Determine bounds of mesh
2984
  this->determine_bounds();
2985
}
2986

2987
void MOABMesh::prepare_for_point_location()
2988
{
2989
  // if the KDTree has already been constructed, do nothing
2990
  if (kdtree_)
2991
    return;
2992

2993
  // build acceleration data structures
2994
  compute_barycentric_data(ehs_);
2995
  build_kdtree(ehs_);
2996
}
2997

2998
void MOABMesh::create_interface()
2999
{
3000
  // Do not create a MOAB instance if one is already in memory
3001
  if (mbi_)
3002
    return;
3003

3004
  // create MOAB instance
3005
  mbi_ = std::make_shared<moab::Core>();
3006

3007
  // load unstructured mesh file
3008
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
3009
  if (rval != moab::MB_SUCCESS) {
3010
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3011
  }
3012
}
3013

3014
void MOABMesh::build_kdtree(const moab::Range& all_tets)
3015
{
3016
  moab::Range all_tris;
3017
  int adj_dim = 2;
3018
  write_message("Getting tet adjacencies...", 7);
3019
  moab::ErrorCode rval = mbi_->get_adjacencies(
3020
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3021
  if (rval != moab::MB_SUCCESS) {
3022
    fatal_error("Failed to get adjacent triangles for tets");
3023
  }
3024

3025
  if (!all_tris.all_of_type(moab::MBTRI)) {
3026
    warning("Non-triangle elements found in tet adjacencies in "
3027
            "unstructured mesh file: " +
3028
            filename_);
3029
  }
3030

3031
  // combine into one range
3032
  moab::Range all_tets_and_tris;
3033
  all_tets_and_tris.merge(all_tets);
3034
  all_tets_and_tris.merge(all_tris);
3035

3036
  // create a kd-tree instance
3037
  write_message(
3038
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
3039
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
3040

3041
  // Determine what options to use
3042
  std::ostringstream options_stream;
3043
  if (options_.empty()) {
3044
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
3045
  } else {
3046
    options_stream << options_;
3047
  }
3048
  moab::FileOptions file_opts(options_stream.str().c_str());
3049

3050
  // Build the k-d tree
3051
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
3052
  if (rval != moab::MB_SUCCESS) {
3053
    fatal_error("Failed to construct KDTree for the "
3054
                "unstructured mesh file: " +
3055
                filename_);
3056
  }
3057
}
3058

3059
void MOABMesh::intersect_track(const moab::CartVect& start,
3060
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3061
{
3062
  hits.clear();
3063

3064
  moab::ErrorCode rval;
3065
  vector<moab::EntityHandle> tris;
3066
  // get all intersections with triangles in the tet mesh
3067
  // (distances are relative to the start point, not the previous
3068
  // intersection)
3069
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
3070
    dir.array(), start.array(), tris, hits, 0, track_len);
3071
  if (rval != moab::MB_SUCCESS) {
3072
    fatal_error(
3073
      "Failed to compute intersections on unstructured mesh: " + filename_);
3074
  }
3075

3076
  // remove duplicate intersection distances
3077
  std::unique(hits.begin(), hits.end());
3078

3079
  // sorts by first component of std::pair by default
3080
  std::sort(hits.begin(), hits.end());
3081
}
3082

3083
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3084
  vector<int>& bins, vector<double>& lengths) const
3085
{
3086
  moab::CartVect start(r0.x, r0.y, r0.z);
3087
  moab::CartVect end(r1.x, r1.y, r1.z);
3088
  moab::CartVect dir(u.x, u.y, u.z);
3089
  dir.normalize();
3090

3091
  double track_len = (end - start).length();
3092
  if (track_len == 0.0)
3093
    return;
3094

3095
  start -= TINY_BIT * dir;
3096
  end += TINY_BIT * dir;
3097

3098
  vector<double> hits;
3099
  intersect_track(start, dir, track_len, hits);
3100

3101
  bins.clear();
3102
  lengths.clear();
3103

3104
  // if there are no intersections the track may lie entirely
3105
  // within a single tet. If this is the case, apply entire
3106
  // score to that tet and return.
3107
  if (hits.size() == 0) {
3108
    Position midpoint = r0 + u * (track_len * 0.5);
3109
    int bin = this->get_bin(midpoint);
3110
    if (bin != -1) {
3111
      bins.push_back(bin);
3112
      lengths.push_back(1.0);
3113
    }
3114
    return;
3115
  }
3116

3117
  // for each segment in the set of tracks, try to look up a tet
3118
  // at the midpoint of the segment
3119
  Position current = r0;
3120
  double last_dist = 0.0;
3121
  for (const auto& hit : hits) {
3122
    // get the segment length
3123
    double segment_length = hit - last_dist;
3124
    last_dist = hit;
3125
    // find the midpoint of this segment
3126
    Position midpoint = current + u * (segment_length * 0.5);
3127
    // try to find a tet for this position
3128
    int bin = this->get_bin(midpoint);
3129

3130
    // determine the start point for this segment
3131
    current = r0 + u * hit;
3132

3133
    if (bin == -1) {
3134
      continue;
3135
    }
3136

3137
    bins.push_back(bin);
3138
    lengths.push_back(segment_length / track_len);
3139
  }
3140

3141
  // tally remaining portion of track after last hit if
3142
  // the last segment of the track is in the mesh but doesn't
3143
  // reach the other side of the tet
3144
  if (hits.back() < track_len) {
3145
    Position segment_start = r0 + u * hits.back();
3146
    double segment_length = track_len - hits.back();
3147
    Position midpoint = segment_start + u * (segment_length * 0.5);
3148
    int bin = this->get_bin(midpoint);
3149
    if (bin != -1) {
3150
      bins.push_back(bin);
3151
      lengths.push_back(segment_length / track_len);
3152
    }
3153
  }
3154
};
3155

3156
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
3157
{
3158
  moab::CartVect pos(r.x, r.y, r.z);
3159
  // find the leaf of the kd-tree for this position
3160
  moab::AdaptiveKDTreeIter kdtree_iter;
3161
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
3162
  if (rval != moab::MB_SUCCESS) {
3163
    return 0;
3164
  }
3165

3166
  // retrieve the tet elements of this leaf
3167
  moab::EntityHandle leaf = kdtree_iter.handle();
3168
  moab::Range tets;
3169
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3170
  if (rval != moab::MB_SUCCESS) {
3171
    warning("MOAB error finding tets.");
3172
  }
3173

3174
  // loop over the tets in this leaf, returning the containing tet if found
3175
  for (const auto& tet : tets) {
3176
    if (point_in_tet(pos, tet)) {
3177
      return tet;
3178
    }
3179
  }
3180

3181
  // if no tet is found, return an invalid handle
3182
  return 0;
3183
}
3184

3185
double MOABMesh::volume(int bin) const
3186
{
3187
  return tet_volume(get_ent_handle_from_bin(bin));
3188
}
3189

3190
std::string MOABMesh::library() const
3191
{
3192
  return mesh_lib_type;
3193
}
3194

3195
// Sample position within a tet for MOAB type tets
3196
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
3197
{
3198

3199
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3200

3201
  // Get vertex coordinates for MOAB tet
3202
  const moab::EntityHandle* conn1;
3203
  int conn1_size;
3204
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
3205
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
3206
    fatal_error(fmt::format(
3207
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3208
      conn1_size));
3209
  }
3210
  moab::CartVect p[4];
3211
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
3212
  if (rval != moab::MB_SUCCESS) {
3213
    fatal_error("Failed to get tet coords");
3214
  }
3215

3216
  std::array<Position, 4> tet_verts;
3217
  for (int i = 0; i < 4; i++) {
3218
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
3219
  }
3220
  // Samples position within tet using Barycentric stuff
3221
  return this->sample_tet(tet_verts, seed);
3222
}
3223

3224
double MOABMesh::tet_volume(moab::EntityHandle tet) const
3225
{
3226
  vector<moab::EntityHandle> conn;
3227
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
3228
  if (rval != moab::MB_SUCCESS) {
3229
    fatal_error("Failed to get tet connectivity");
3230
  }
3231

3232
  moab::CartVect p[4];
3233
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
3234
  if (rval != moab::MB_SUCCESS) {
3235
    fatal_error("Failed to get tet coords");
3236
  }
3237

3238
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
3239
}
3240

3241
int MOABMesh::get_bin(Position r) const
3242
{
3243
  moab::EntityHandle tet = get_tet(r);
3244
  if (tet == 0) {
3245
    return -1;
3246
  } else {
3247
    return get_bin_from_ent_handle(tet);
3248
  }
3249
}
3250

3251
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
3252
{
3253
  moab::ErrorCode rval;
3254

3255
  baryc_data_.clear();
3256
  baryc_data_.resize(tets.size());
3257

3258
  // compute the barycentric data for each tet element
3259
  // and store it as a 3x3 matrix
3260
  for (auto& tet : tets) {
3261
    vector<moab::EntityHandle> verts;
3262
    rval = mbi_->get_connectivity(&tet, 1, verts);
3263
    if (rval != moab::MB_SUCCESS) {
3264
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
3265
    }
3266

3267
    moab::CartVect p[4];
3268
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
3269
    if (rval != moab::MB_SUCCESS) {
3270
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
3271
    }
3272

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

3275
    // invert now to avoid this cost later
3276
    a = a.transpose().inverse();
3277
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
3278
  }
3279
}
3280

3281
bool MOABMesh::point_in_tet(
3282
  const moab::CartVect& r, moab::EntityHandle tet) const
3283
{
3284

3285
  moab::ErrorCode rval;
3286

3287
  // get tet vertices
3288
  vector<moab::EntityHandle> verts;
3289
  rval = mbi_->get_connectivity(&tet, 1, verts);
3290
  if (rval != moab::MB_SUCCESS) {
3291
    warning("Failed to get vertices of tet in umesh: " + filename_);
3292
    return false;
3293
  }
3294

3295
  // first vertex is used as a reference point for the barycentric data -
3296
  // retrieve its coordinates
3297
  moab::CartVect p_zero;
3298
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
3299
  if (rval != moab::MB_SUCCESS) {
3300
    warning("Failed to get coordinates of a vertex in "
3301
            "unstructured mesh: " +
3302
            filename_);
3303
    return false;
3304
  }
3305

3306
  // look up barycentric data
3307
  int idx = get_bin_from_ent_handle(tet);
3308
  const moab::Matrix3& a_inv = baryc_data_[idx];
3309

3310
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3311

3312
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
3313
          bary_coords[2] >= 0.0 &&
3314
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
3315
}
3316

3317
int MOABMesh::get_bin_from_index(int idx) const
3318
{
3319
  if (idx >= n_bins()) {
3320
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3321
  }
3322
  return ehs_[idx] - ehs_[0];
3323
}
3324

3325
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3326
{
3327
  int bin = get_bin(r);
3328
  *in_mesh = bin != -1;
3329
  return bin;
3330
}
3331

3332
int MOABMesh::get_index_from_bin(int bin) const
3333
{
3334
  return bin;
3335
}
3336

3337
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3338
  Position plot_ll, Position plot_ur) const
3339
{
3340
  // TODO: Implement mesh lines
3341
  return {};
3342
}
3343

3344
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
3345
{
3346
  int idx = vert - verts_[0];
3347
  if (idx >= n_vertices()) {
3348
    fatal_error(
3349
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
3350
  }
3351
  return idx;
3352
}
3353

3354
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
3355
{
3356
  int bin = eh - ehs_[0];
3357
  if (bin >= n_bins()) {
3358
    fatal_error(fmt::format("Invalid bin: {}", bin));
3359
  }
3360
  return bin;
3361
}
3362

3363
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
3364
{
3365
  if (bin >= n_bins()) {
3366
    fatal_error(fmt::format("Invalid bin index: ", bin));
3367
  }
3368
  return ehs_[0] + bin;
3369
}
3370

3371
int MOABMesh::n_bins() const
3372
{
3373
  return ehs_.size();
3374
}
3375

3376
int MOABMesh::n_surface_bins() const
3377
{
3378
  // collect all triangles in the set of tets for this mesh
3379
  moab::Range tris;
3380
  moab::ErrorCode rval;
3381
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
3382
  if (rval != moab::MB_SUCCESS) {
3383
    warning("Failed to get all triangles in the mesh instance");
3384
    return -1;
3385
  }
3386
  return 2 * tris.size();
3387
}
3388

3389
Position MOABMesh::centroid(int bin) const
3390
{
3391
  moab::ErrorCode rval;
3392

3393
  auto tet = this->get_ent_handle_from_bin(bin);
3394

3395
  // look up the tet connectivity
3396
  vector<moab::EntityHandle> conn;
3397
  rval = mbi_->get_connectivity(&tet, 1, conn);
3398
  if (rval != moab::MB_SUCCESS) {
3399
    warning("Failed to get connectivity of a mesh element.");
3400
    return {};
3401
  }
3402

3403
  // get the coordinates
3404
  vector<moab::CartVect> coords(conn.size());
3405
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3406
  if (rval != moab::MB_SUCCESS) {
3407
    warning("Failed to get the coordinates of a mesh element.");
3408
    return {};
3409
  }
3410

3411
  // compute the centroid of the element vertices
3412
  moab::CartVect centroid(0.0, 0.0, 0.0);
3413
  for (const auto& coord : coords) {
3414
    centroid += coord;
3415
  }
3416
  centroid /= double(coords.size());
3417

3418
  return {centroid[0], centroid[1], centroid[2]};
3419
}
3420

3421
int MOABMesh::n_vertices() const
3422
{
3423
  return verts_.size();
3424
}
3425

3426
Position MOABMesh::vertex(int id) const
3427
{
3428

3429
  moab::ErrorCode rval;
3430

3431
  moab::EntityHandle vert = verts_[id];
3432

3433
  moab::CartVect coords;
3434
  rval = mbi_->get_coords(&vert, 1, coords.array());
3435
  if (rval != moab::MB_SUCCESS) {
3436
    fatal_error("Failed to get the coordinates of a vertex.");
3437
  }
3438

3439
  return {coords[0], coords[1], coords[2]};
3440
}
3441

3442
std::vector<int> MOABMesh::connectivity(int bin) const
3443
{
3444
  moab::ErrorCode rval;
3445

3446
  auto tet = get_ent_handle_from_bin(bin);
3447

3448
  // look up the tet connectivity
3449
  vector<moab::EntityHandle> conn;
3450
  rval = mbi_->get_connectivity(&tet, 1, conn);
3451
  if (rval != moab::MB_SUCCESS) {
3452
    fatal_error("Failed to get connectivity of a mesh element.");
3453
    return {};
3454
  }
3455

3456
  std::vector<int> verts(4);
3457
  for (int i = 0; i < verts.size(); i++) {
3458
    verts[i] = get_vert_idx_from_handle(conn[i]);
3459
  }
3460

3461
  return verts;
3462
}
3463

3464
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3465
  std::string score) const
3466
{
3467
  moab::ErrorCode rval;
3468
  // add a tag to the mesh
3469
  // all scores are treated as a single value
3470
  // with an uncertainty
3471
  moab::Tag value_tag;
3472

3473
  // create the value tag if not present and get handle
3474
  double default_val = 0.0;
3475
  auto val_string = score + "_mean";
3476
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3477
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3478
  if (rval != moab::MB_SUCCESS) {
3479
    auto msg =
3480
      fmt::format("Could not create or retrieve the value tag for the score {}"
3481
                  " on unstructured mesh {}",
3482
        score, id_);
3483
    fatal_error(msg);
3484
  }
3485

3486
  // create the std dev tag if not present and get handle
3487
  moab::Tag error_tag;
3488
  std::string err_string = score + "_std_dev";
3489
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3490
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3491
  if (rval != moab::MB_SUCCESS) {
3492
    auto msg =
3493
      fmt::format("Could not create or retrieve the error tag for the score {}"
3494
                  " on unstructured mesh {}",
3495
        score, id_);
3496
    fatal_error(msg);
3497
  }
3498

3499
  // return the populated tag handles
3500
  return {value_tag, error_tag};
3501
}
3502

3503
void MOABMesh::add_score(const std::string& score)
3504
{
3505
  auto score_tags = get_score_tags(score);
3506
  tag_names_.push_back(score);
3507
}
3508

3509
void MOABMesh::remove_scores()
3510
{
3511
  for (const auto& name : tag_names_) {
3512
    auto value_name = name + "_mean";
3513
    moab::Tag tag;
3514
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
3515
    if (rval != moab::MB_SUCCESS)
3516
      return;
3517

3518
    rval = mbi_->tag_delete(tag);
3519
    if (rval != moab::MB_SUCCESS) {
3520
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3521
                             " on unstructured mesh {}",
3522
        name, id_);
3523
      fatal_error(msg);
3524
    }
3525

3526
    auto std_dev_name = name + "_std_dev";
3527
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3528
    if (rval != moab::MB_SUCCESS) {
3529
      auto msg =
3530
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3531
                    " on unstructured mesh {}",
3532
          name, id_);
3533
    }
3534

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

3546
void MOABMesh::set_score_data(const std::string& score,
3547
  const vector<double>& values, const vector<double>& std_dev)
3548
{
3549
  auto score_tags = this->get_score_tags(score);
3550

3551
  moab::ErrorCode rval;
3552
  // set the score value
3553
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3554
  if (rval != moab::MB_SUCCESS) {
3555
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3556
                           "on unstructured mesh {}",
3557
      score, id_);
3558
    warning(msg);
3559
  }
3560

3561
  // set the error value
3562
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3563
  if (rval != moab::MB_SUCCESS) {
3564
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3565
                           "on unstructured mesh {}",
3566
      score, id_);
3567
    warning(msg);
3568
  }
3569
}
3570

3571
void MOABMesh::write(const std::string& base_filename) const
3572
{
3573
  // add extension to the base name
3574
  auto filename = base_filename + ".vtk";
3575
  write_message(5, "Writing unstructured mesh {}...", filename);
3576
  filename = settings::path_output + filename;
3577

3578
  // write the tetrahedral elements of the mesh only
3579
  // to avoid clutter from zero-value data on other
3580
  // elements during visualization
3581
  moab::ErrorCode rval;
3582
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3583
  if (rval != moab::MB_SUCCESS) {
3584
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3585
    warning(msg);
3586
  }
3587
}
3588

3589
#endif
3590

3591
#ifdef OPENMC_LIBMESH_ENABLED
3592

3593
const std::string LibMesh::mesh_lib_type = "libmesh";
3594

3595
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
3596
{
3597
  // filename_ and length_multiplier_ will already be set by the
3598
  // UnstructuredMesh constructor
3599
  set_mesh_pointer_from_filename(filename_);
3600
  set_length_multiplier(length_multiplier_);
3601
  initialize();
3602
}
3603

3604
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
3605
{
3606
  // filename_ and length_multiplier_ will already be set by the
3607
  // UnstructuredMesh constructor
3608
  set_mesh_pointer_from_filename(filename_);
3609
  set_length_multiplier(length_multiplier_);
3610
  initialize();
3611
}
3612

3613
// create the mesh from a pointer to a libMesh Mesh
3614
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3615
{
3616
  if (!input_mesh.is_replicated()) {
3617
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3618
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3619
  }
3620

3621
  m_ = &input_mesh;
3622
  set_length_multiplier(length_multiplier);
3623
  initialize();
3624
}
3625

3626
// create the mesh from an input file
3627
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
3628
{
3629
  n_dimension_ = 3;
3630
  set_mesh_pointer_from_filename(filename);
3631
  set_length_multiplier(length_multiplier);
3632
  initialize();
3633
}
3634

3635
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3636
{
3637
  filename_ = filename;
3638
  unique_m_ =
3639
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
3640
  m_ = unique_m_.get();
3641
  m_->read(filename_);
3642
}
3643

3644
// build a libMesh equation system for storing values
3645
void LibMesh::build_eqn_sys()
3646
{
3647
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
3648
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3649
  libMesh::ExplicitSystem& eq_sys =
3650
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3651
}
3652

3653
// intialize from mesh file
3654
void LibMesh::initialize()
3655
{
3656
  if (!settings::libmesh_comm) {
3657
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3658
                "communicator.");
3659
  }
3660

3661
  // assuming that unstructured meshes used in OpenMC are 3D
3662
  n_dimension_ = 3;
3663

3664
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3665
  // Otherwise assume that it is prepared by its owning application
3666
  if (unique_m_) {
3667
    m_->prepare_for_use();
3668
  }
3669

3670
  // ensure that the loaded mesh is 3 dimensional
3671
  if (m_->mesh_dimension() != n_dimension_) {
3672
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3673
                            "mesh is not a 3D mesh.",
3674
      filename_));
3675
  }
3676

3677
  for (int i = 0; i < num_threads(); i++) {
3678
    pl_.emplace_back(m_->sub_point_locator());
3679
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3680
    pl_.back()->enable_out_of_mesh_mode();
3681
  }
3682

3683
  // store first element in the mesh to use as an offset for bin indices
3684
  auto first_elem = *m_->elements_begin();
3685
  first_element_id_ = first_elem->id();
3686

3687
  // bounding box for the mesh for quick rejection checks
3688
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3689
  libMesh::Point ll = bbox_.min();
3690
  libMesh::Point ur = bbox_.max();
3691
  if (length_multiplier_ > 0.0) {
3692
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3693
      length_multiplier_ * ll(2)};
3694
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3695
      length_multiplier_ * ur(2)};
3696
  } else {
3697
    lower_left_ = {ll(0), ll(1), ll(2)};
3698
    upper_right_ = {ur(0), ur(1), ur(2)};
3699
  }
3700
}
3701

3702
// Sample position within a tet for LibMesh type tets
3703
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
3704
{
3705
  const auto& elem = get_element_from_bin(bin);
3706
  // Get tet vertex coordinates from LibMesh
3707
  std::array<Position, 4> tet_verts;
3708
  for (int i = 0; i < elem.n_nodes(); i++) {
3709
    const auto& node_ref = elem.node_ref(i);
3710
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3711
  }
3712
  // Samples position within tet using Barycentric coordinates
3713
  Position sampled_position = this->sample_tet(tet_verts, seed);
3714
  if (length_multiplier_ > 0.0) {
3715
    return length_multiplier_ * sampled_position;
3716
  } else {
3717
    return sampled_position;
3718
  }
3719
}
3720

3721
Position LibMesh::centroid(int bin) const
3722
{
3723
  const auto& elem = this->get_element_from_bin(bin);
3724
  auto centroid = elem.vertex_average();
3725
  if (length_multiplier_ > 0.0) {
3726
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3727
  } else {
3728
    return {centroid(0), centroid(1), centroid(2)};
3729
  }
3730
}
3731

3732
int LibMesh::n_vertices() const
3733
{
3734
  return m_->n_nodes();
3735
}
3736

3737
Position LibMesh::vertex(int vertex_id) const
3738
{
3739
  const auto& node_ref = m_->node_ref(vertex_id);
3740
  if (length_multiplier_ > 0.0) {
3741
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3742
  } else {
3743
    return {node_ref(0), node_ref(1), node_ref(2)};
3744
  }
3745
}
3746

3747
std::vector<int> LibMesh::connectivity(int elem_id) const
3748
{
3749
  std::vector<int> conn;
3750
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3751
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3752
    conn.push_back(elem_ptr->node_id(i));
3753
  }
3754
  return conn;
3755
}
3756

3757
std::string LibMesh::library() const
3758
{
3759
  return mesh_lib_type;
3760
}
3761

3762
int LibMesh::n_bins() const
3763
{
3764
  return m_->n_elem();
3765
}
3766

3767
int LibMesh::n_surface_bins() const
3768
{
3769
  int n_bins = 0;
3770
  for (int i = 0; i < this->n_bins(); i++) {
3771
    const libMesh::Elem& e = get_element_from_bin(i);
3772
    n_bins += e.n_faces();
3773
    // if this is a boundary element, it will only be visited once,
3774
    // the number of surface bins is incremented to
3775
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3776
      // null neighbor pointer indicates a boundary face
3777
      if (!neighbor_ptr) {
3778
        n_bins++;
3779
      }
3780
    }
3781
  }
3782
  return n_bins;
3783
}
3784

3785
void LibMesh::add_score(const std::string& var_name)
3786
{
3787
  if (!equation_systems_) {
3788
    build_eqn_sys();
3789
  }
3790

3791
  // check if this is a new variable
3792
  std::string value_name = var_name + "_mean";
3793
  if (!variable_map_.count(value_name)) {
3794
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3795
    auto var_num =
3796
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3797
    variable_map_[value_name] = var_num;
3798
  }
3799

3800
  std::string std_dev_name = var_name + "_std_dev";
3801
  // check if this is a new variable
3802
  if (!variable_map_.count(std_dev_name)) {
3803
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3804
    auto var_num =
3805
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3806
    variable_map_[std_dev_name] = var_num;
3807
  }
3808
}
3809

3810
void LibMesh::remove_scores()
3811
{
3812
  if (equation_systems_) {
3813
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3814
    eqn_sys.clear();
3815
    variable_map_.clear();
3816
  }
3817
}
3818

3819
void LibMesh::set_score_data(const std::string& var_name,
3820
  const vector<double>& values, const vector<double>& std_dev)
3821
{
3822
  if (!equation_systems_) {
3823
    build_eqn_sys();
3824
  }
3825

3826
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3827

3828
  if (!eqn_sys.is_initialized()) {
3829
    equation_systems_->init();
3830
  }
3831

3832
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3833

3834
  // look up the value variable
3835
  std::string value_name = var_name + "_mean";
3836
  unsigned int value_num = variable_map_.at(value_name);
3837
  // look up the std dev variable
3838
  std::string std_dev_name = var_name + "_std_dev";
3839
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3840

3841
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3842
       it++) {
3843
    if (!(*it)->active()) {
3844
      continue;
3845
    }
3846

3847
    auto bin = get_bin_from_element(*it);
3848

3849
    // set value
3850
    vector<libMesh::dof_id_type> value_dof_indices;
3851
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3852
    assert(value_dof_indices.size() == 1);
3853
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3854

3855
    // set std dev
3856
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3857
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3858
    assert(std_dev_dof_indices.size() == 1);
3859
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3860
  }
3861
}
3862

3863
void LibMesh::write(const std::string& filename) const
3864
{
3865
  write_message(fmt::format(
3866
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3867
  libMesh::ExodusII_IO exo(*m_);
3868
  std::set<std::string> systems_out = {eq_system_name_};
3869
  exo.write_discontinuous_exodusII(
3870
    filename + ".e", *equation_systems_, &systems_out);
3871
}
3872

3873
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3874
  vector<int>& bins, vector<double>& lengths) const
3875
{
3876
  // TODO: Implement triangle crossings here
3877
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3878
}
3879

3880
int LibMesh::get_bin(Position r) const
3881
{
3882
  // look-up a tet using the point locator
3883
  libMesh::Point p(r.x, r.y, r.z);
3884

3885
  if (length_multiplier_ > 0.0) {
3886
    // Scale the point down
3887
    p /= length_multiplier_;
3888
  }
3889

3890
  // quick rejection check
3891
  if (!bbox_.contains_point(p)) {
3892
    return -1;
3893
  }
3894

3895
  const auto& point_locator = pl_.at(thread_num());
3896

3897
  const auto elem_ptr = (*point_locator)(p);
3898
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3899
}
3900

3901
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3902
{
3903
  int bin = elem->id() - first_element_id_;
3904
  if (bin >= n_bins() || bin < 0) {
3905
    fatal_error(fmt::format("Invalid bin: {}", bin));
3906
  }
3907
  return bin;
3908
}
3909

3910
std::pair<vector<double>, vector<double>> LibMesh::plot(
3911
  Position plot_ll, Position plot_ur) const
3912
{
3913
  return {};
3914
}
3915

3916
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3917
{
3918
  return m_->elem_ref(bin);
3919
}
3920

3921
double LibMesh::volume(int bin) const
3922
{
3923
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
3924
         length_multiplier_ * length_multiplier_;
3925
}
3926

3927
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3928
  double length_multiplier,
3929
  const std::set<libMesh::subdomain_id_type>& block_ids)
3930
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3931
    block_restrict_(!block_ids_.empty()),
3932
    num_active_(
3933
      block_restrict_
3934
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
3935
            m_->active_subdomain_set_elements_end(block_ids_))
3936
        : m_->n_active_elem())
3937
{
3938
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3939
  // contiguous in ID space, so we need to map from bin indices (defined over
3940
  // active elements) to global dof ids
3941
  bin_to_elem_map_.reserve(num_active_);
3942
  elem_to_bin_map_.resize(m_->n_elem(), -1);
3943
  auto begin = block_restrict_
3944
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
3945
                 : m_->active_elements_begin();
3946
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
3947
                             : m_->active_elements_end();
3948
  for (const auto& elem : libMesh::as_range(begin, end)) {
3949
    bin_to_elem_map_.push_back(elem->id());
3950
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3951
  }
3952
}
3953

3954
int AdaptiveLibMesh::n_bins() const
3955
{
3956
  return num_active_;
3957
}
3958

3959
void AdaptiveLibMesh::add_score(const std::string& var_name)
3960
{
3961
  warning(fmt::format(
3962
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3963
    this->id_));
3964
}
3965

3966
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3967
  const vector<double>& values, const vector<double>& std_dev)
3968
{
3969
  warning(fmt::format(
3970
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3971
    this->id_));
3972
}
3973

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

3981
int AdaptiveLibMesh::get_bin(Position r) const
3982
{
3983
  // look-up a tet using the point locator
3984
  libMesh::Point p(r.x, r.y, r.z);
3985

3986
  if (length_multiplier_ > 0.0) {
3987
    // Scale the point down
3988
    p /= length_multiplier_;
3989
  }
3990

3991
  // quick rejection check
3992
  if (!bbox_.contains_point(p)) {
3993
    return -1;
3994
  }
3995

3996
  const auto& point_locator = pl_.at(thread_num());
3997

3998
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
3999
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
4000
}
4001

4002
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4003
{
4004
  int bin = elem_to_bin_map_[elem->id()];
4005
  if (bin >= n_bins() || bin < 0) {
4006
    fatal_error(fmt::format("Invalid bin: {}", bin));
4007
  }
4008
  return bin;
4009
}
4010

4011
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4012
{
4013
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4014
}
4015

4016
#endif // OPENMC_LIBMESH_ENABLED
4017

4018
//==============================================================================
4019
// Non-member functions
4020
//==============================================================================
4021

4022
void read_meshes(pugi::xml_node root)
2,222✔
4023
{
4024
  std::unordered_set<int> mesh_ids;
2,222✔
4025

4026
  for (auto node : root.children("mesh")) {
2,754✔
4027
    // Check to make sure multiple meshes in the same file don't share IDs
4028
    int id = std::stoi(get_node_value(node, "id"));
1,064✔
4029
    if (contains(mesh_ids, id)) {
1,064!
4030
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4031
                              "'{}' in the same input file",
4032
        id));
4033
    }
4034
    mesh_ids.insert(id);
532✔
4035

4036
    // If we've already read a mesh with the same ID in a *different* file,
4037
    // assume it is the same here
4038
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
532!
4039
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4040
      continue;
×
4041
    }
4042

4043
    std::string mesh_type;
532✔
4044
    if (check_for_node(node, "type")) {
532✔
4045
      mesh_type = get_node_value(node, "type", true, true);
156✔
4046
    } else {
4047
      mesh_type = "regular";
376✔
4048
    }
4049

4050
    // determine the mesh library to use
4051
    std::string mesh_lib;
532✔
4052
    if (check_for_node(node, "library")) {
532!
UNCOV
4053
      mesh_lib = get_node_value(node, "library", true, true);
×
4054
    }
4055

4056
    Mesh::create(node, mesh_type, mesh_lib);
532✔
4057
  }
532✔
4058
}
2,222✔
4059

4060
void read_meshes(hid_t group)
4✔
4061
{
4062
  std::unordered_set<int> mesh_ids;
4✔
4063

4064
  std::vector<int> ids;
4✔
4065
  read_attribute(group, "ids", ids);
4✔
4066

4067
  for (auto id : ids) {
10✔
4068

4069
    // Check to make sure multiple meshes in the same file don't share IDs
4070
    if (contains(mesh_ids, id)) {
12!
4071
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4072
                              "'{}' in the same HDF5 input file",
4073
        id));
4074
    }
4075
    mesh_ids.insert(id);
6✔
4076

4077
    // If we've already read a mesh with the same ID in a *different* file,
4078
    // assume it is the same here
4079
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
6!
4080
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
6✔
4081
      continue;
6✔
4082
    }
4083

4084
    std::string name = fmt::format("mesh {}", id);
×
4085
    hid_t mesh_group = open_group(group, name.c_str());
×
4086

4087
    std::string mesh_type;
×
4088
    if (object_exists(mesh_group, "type")) {
×
4089
      read_dataset(mesh_group, "type", mesh_type);
×
4090
    } else {
4091
      mesh_type = "regular";
×
4092
    }
4093

4094
    // determine the mesh library to use
4095
    std::string mesh_lib;
×
4096
    if (object_exists(mesh_group, "library")) {
×
4097
      read_dataset(mesh_group, "library", mesh_lib);
×
4098
    }
4099

4100
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4101
  }
×
4102
}
8✔
4103

4104
void meshes_to_hdf5(hid_t group)
1,408✔
4105
{
4106
  // Write number of meshes
4107
  hid_t meshes_group = create_group(group, "meshes");
1,408✔
4108
  int32_t n_meshes = model::meshes.size();
1,408✔
4109
  write_attribute(meshes_group, "n_meshes", n_meshes);
1,408✔
4110

4111
  if (n_meshes > 0) {
1,408✔
4112
    // Write IDs of meshes
4113
    vector<int> ids;
422✔
4114
    for (const auto& m : model::meshes) {
966✔
4115
      m->to_hdf5(meshes_group);
544✔
4116
      ids.push_back(m->id_);
544✔
4117
    }
4118
    write_attribute(meshes_group, "ids", ids);
422✔
4119
  }
422✔
4120

4121
  close_group(meshes_group);
1,408✔
4122
}
1,408✔
4123

4124
void free_memory_mesh()
1,444✔
4125
{
4126
  model::meshes.clear();
1,444✔
4127
  model::mesh_map.clear();
1,444✔
4128
}
1,444✔
4129

4130
extern "C" int n_meshes()
56✔
4131
{
4132
  return model::meshes.size();
56✔
4133
}
4134

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