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

openmc-dev / openmc / 43538648659

14 Nov 2026 01:07AM UTC coverage: 82.356% (+0.05%) from 82.304%
43538648659

push

github

web-flow
Specify temperature from a field (structured mesh only) (#3734)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

20953 of 29717 branches covered (70.51%)

Branch coverage included in aggregate %.

320 of 342 new or added lines in 15 files covered. (93.57%)

64452 of 73985 relevant lines covered (87.11%)

42544112.91 hits per line

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

72.28
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cassert>
4
#include <cmath>   // for ceil
5
#include <cstddef> // for size_t
6
#include <cstdint> // for uint64_t
7
#include <cstring> // for memcpy
8
#include <limits>
9
#include <numeric> // for accumulate
10
#include <string>
11

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

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

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

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

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

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

58
#include "openmc/xdg.h"
59

60
namespace openmc {
61

62
//==============================================================================
63
// Global variables
64
//==============================================================================
65

66
// Value used to indicate an empty slot in the hash table. We use -2 because
67
// the value -1 is used to indicate a void material.
68
constexpr int32_t EMPTY = -2;
69

70
namespace model {
71

72
std::unordered_map<int32_t, int32_t> mesh_map;
73
vector<unique_ptr<Mesh>> meshes;
74

75
} // namespace model
76

77
#ifdef OPENMC_LIBMESH_ENABLED
78
namespace settings {
79
unique_ptr<libMesh::LibMeshInit> libmesh_init;
80
const libMesh::Parallel::Communicator* libmesh_comm {nullptr};
81
} // namespace settings
82
#endif
83

84
//==============================================================================
85
// Helper functions
86
//==============================================================================
87

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

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

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

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

131
#else
132
#error "No compare-and-swap implementation available for this compiler."
133
#endif
134
}
135

136
// Helper function equivalent to std::bit_cast in C++20
137
template<typename To, typename From>
138
inline To bit_cast_value(const From& value)
28,464,336 ✔
139
{
140
  To out;
141
  std::memcpy(&out, &value, sizeof(To));
46,036 ✔
142
  return out;
143
}
144

145
inline void atomic_update_double(double* ptr, double value, bool is_min)
28,464,192 ✔
146
{
147
#if defined(__GNUC__) || defined(__clang__)
148
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
28,464,192 ✔
149
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
28,464,192 ✔
150
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
28,464,192 ✔
151
  double current = bit_cast_value<double>(current_bits);
28,464,192 ✔
152
  while (is_min ? (value < current) : (value > current)) {
28,464,336 ✔
153
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
46,036 ✔
154
    uint64_t expected_bits = current_bits;
46,036 ✔
155
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
46,036 ✔
156
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
157
      return;
28,464,192 ✔
158
    }
159
    current_bits = expected_bits;
144 ✔
160
    current = bit_cast_value<double>(current_bits);
144 ✔
161
  }
162

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

178
#else
179
#error "No compare-and-swap implementation available for this compiler."
180
#endif
181
}
182

183
inline void atomic_max_double(double* ptr, double value)
14,232,096 ✔
184
{
185
  atomic_update_double(ptr, value, false);
4,744,032 ✔
186
}
4,744,032 ✔
187

188
inline void atomic_min_double(double* ptr, double value)
14,232,096 ✔
189
{
190
  atomic_update_double(ptr, value, true);
4,744,032 ✔
191
}
192

193
namespace detail {
194

195
//==============================================================================
196
// MaterialVolumes implementation
197
//==============================================================================
198

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

208
  // Loop for linear probing
209
  for (int attempt = 0; attempt < table_size_; ++attempt) {
6,884,752 !
210
    // Determine slot to check, making sure it is positive
211
    int slot = (index_material + attempt) % table_size_;
6,884,752 ✔
212
    if (slot < 0)
6,884,752 ✔
213
      slot += table_size_;
4,443,316 ✔
214
    int32_t* slot_ptr = &this->materials(index_elem, slot);
6,884,752 ✔
215

216
    // Non-atomic read of current material
217
    int32_t current_val = *slot_ptr;
6,884,752 ✔
218

219
    // Found the desired material; accumulate volume and bbox
220
    if (current_val == index_material) {
6,884,752 ✔
221
#pragma omp atomic
2,713,202 ✔
222
      this->volumes(index_elem, slot) += volume;
6,882,425 ✔
223
      if (bbox) {
6,882,425 ✔
224
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
4,742,755 ✔
225
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
4,742,755 ✔
226
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
4,742,755 ✔
227
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
4,742,755 ✔
228
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
4,742,755 ✔
229
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
4,742,755 ✔
230
      }
231
      return;
6,882,425 ✔
232
    }
233

234
    // Slot appears to be empty; attempt to claim
235
    if (current_val == EMPTY) {
2,327 !
236
      // Attempt compare-and-swap from EMPTY to index_material
237
      int32_t expected_val = EMPTY;
2,327 ✔
238
      bool claimed_slot =
2,327 ✔
239
        atomic_cas_int32(slot_ptr, expected_val, index_material);
2,327 ✔
240

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

259
  // If table is full, set a flag that can be checked later
260
  table_full_ = true;
×
261
}
262

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

273
    // Read current material
274
    int32_t current_val = this->materials(index_elem, slot);
×
275

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

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

318
  // If table is full, set a flag that can be checked later
319
  table_full_ = true;
×
320
}
321

322
} // namespace detail
323

324
//==============================================================================
325
// Mesh implementation
326
//==============================================================================
327

328
std::string read_mesh_type(const pugi::xml_node& node)
2,769 ✔
329
{
330
  std::string mesh_type;
2,769 ✔
331
  if (check_for_node(node, "type")) {
2,769 ✔
332
    mesh_type = get_node_value(node, "type");
737 ✔
333
  } else {
334
    mesh_type = "regular";
2,032 ✔
335
  }
336
  return std::move(mesh_type);
5,538 !
337
}
2,769 ✔
338

339
std::string read_mesh_type(hid_t group)
18 ✔
340
{
341
  std::string mesh_type;
18 ✔
342
  if (object_exists(group, "type")) {
18 !
343
    read_dataset(group, "type", mesh_type);
18 ✔
344
  } else {
345
    mesh_type = "regular";
×
346
  }
347
  return std::move(mesh_type);
36 !
348
}
18 ✔
349

350
template<typename T>
351
const std::unique_ptr<Mesh>& Mesh::create(T dataset)
2,787 ✔
352
{
353
  std::string mesh_type = read_mesh_type(dataset);
2,787 ✔
354
  // Determine mesh type. Add to model vector and map
355
  if (mesh_type == RegularMesh::mesh_type) {
2,787 ✔
356
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
2,096 ✔
357
  } else if (mesh_type == RectilinearMesh::mesh_type) {
691 ✔
358
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
78 ✔
359
  } else if (mesh_type == CylindricalMesh::mesh_type) {
613 ✔
360
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
290 ✔
361
  } else if (mesh_type == SphericalMesh::mesh_type) {
323 ✔
362
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
258 ✔
363
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
65 !
364
    model::meshes.push_back(UnstructuredMesh::create(dataset));
65 ✔
365
  } else {
366
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
367
  }
368

369
  // Map ID to position in vector
370
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
2,787 ✔
371

372
  return model::meshes.back();
2,787 ✔
373
}
2,787 ✔
374

375
Mesh::Mesh(pugi::xml_node node)
2,853 ✔
376
{
377
  // Read mesh id
378
  id_ = std::stoi(get_node_value(node, "id"));
5,706 ✔
379
  if (check_for_node(node, "name"))
2,853 ✔
380
    name_ = get_node_value(node, "name");
10 ✔
381
}
2,853 ✔
382

383
Mesh::Mesh(hid_t group)
50 ✔
384
{
385
  // Read mesh ID
386
  read_attribute(group, "id", id_);
50 ✔
387

388
  // Read mesh name
389
  if (object_exists(group, "name")) {
50 !
390
    read_dataset(group, "name", name_);
×
391
  }
392
}
50 ✔
393

394
void Mesh::set_id(int32_t id)
323 ✔
395
{
396
  assert(id >= 0 || id == C_NONE);
323 !
397

398
  // Clear entry in mesh map in case one was already assigned
399
  if (id_ != C_NONE) {
323 ✔
400
    model::mesh_map.erase(id_);
16 ✔
401
    id_ = C_NONE;
16 ✔
402
  }
403

404
  // Ensure no other mesh has the same ID
405
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
323 !
406
    throw std::runtime_error {
×
407
      fmt::format("Two meshes have the same ID: {}", id)};
×
408
  }
409

410
  // If no ID is specified, auto-assign the next ID in the sequence
411
  if (id == C_NONE) {
323 ✔
412
    id = 0;
1 ✔
413
    for (const auto& m : model::meshes) {
3 ✔
414
      id = std::max(id, m->id_);
3 ✔
415
    }
416
    ++id;
1 ✔
417
  }
418

419
  // Update ID and entry in the mesh map
420
  id_ = id;
323 ✔
421

422
  // find the index of this mesh in the model::meshes vector
423
  // (search in reverse because this mesh was likely just added to the vector)
424
  auto it = std::find_if(model::meshes.rbegin(), model::meshes.rend(),
646 ✔
425
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
654 !
426

427
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
323 ✔
428
}
323 ✔
429

430
vector<double> Mesh::volumes() const
274 ✔
431
{
432
  vector<double> volumes(n_bins());
274 ✔
433
  for (int i = 0; i < n_bins(); i++) {
905,830 ✔
434
    volumes[i] = this->volume(i);
905,556 ✔
435
  }
436
  return volumes;
274 ✔
437
}
×
438

439
//! Default (Cartesian) axis labels used for surface bin labels.
440
std::array<const char*, 3> Mesh::axis_labels() const
311,456 ✔
441
{
442
  return {"x", "y", "z"};
311,456 ✔
443
}
444

445
//! Build the surface component of a mesh surface tally bin label.
446
//! surf_index: 0=out/min, 1=in/min, 2=out/max, 3=in/max
447
std::string Mesh::surface_bin_label(int surf_index) const
1,016,864 ✔
448
{
449
  auto labels = this->axis_labels();
1,016,864 ✔
450
  int dim = surf_index / 4;
1,016,864 ✔
451
  int code = surf_index % 4;
1,016,864 ✔
452
  bool incoming = (code == 1) || (code == 3);
1,016,864 ✔
453
  bool max = (code == 2) || (code == 3);
1,016,864 ✔
454
  return fmt::format(" {}, {}-{}", incoming ? "Incoming" : "Outgoing",
1,016,864 ✔
455
    labels[dim], max ? "max" : "min");
2,033,728 ✔
456
}
457

458
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
459
  int32_t* materials, double* volumes) const
460
{
461
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
462
}
×
463

464
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
169 ✔
465
  int32_t* materials, double* volumes, double* bboxes) const
466
{
467
  if (mpi::master) {
169 !
468
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
169 ✔
469
  }
470
  write_message(7, "Number of mesh elements = {}", n_bins());
169 ✔
471
  write_message(7, "Number of rays (x) = {}", nx);
169 ✔
472
  write_message(7, "Number of rays (y) = {}", ny);
169 ✔
473
  write_message(7, "Number of rays (z) = {}", nz);
169 ✔
474
  int64_t n_total = static_cast<int64_t>(nx) * ny +
169 ✔
475
                    static_cast<int64_t>(ny) * nz +
169 ✔
476
                    static_cast<int64_t>(nx) * nz;
169 ✔
477
  write_message(7, "Total number of rays = {}", n_total);
169 ✔
478
  write_message(7, "Table size per mesh element = {}", table_size);
169 ✔
479

480
  Timer timer;
169 ✔
481
  timer.start();
169 ✔
482

483
  // Create object for keeping track of materials/volumes
484
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
169 ✔
485
  bool compute_bboxes = bboxes != nullptr;
169 ✔
486

487
  // Determine bounding box
488
  auto bbox = this->bounding_box();
169 ✔
489

490
  std::array<int, 3> n_rays = {nx, ny, nz};
169 ✔
491

492
  // Determine effective width of rays
493
  Position width = bbox.max - bbox.min;
169 ✔
494
  width.x = (nx > 0) ? width.x / nx : 0.0;
169 ✔
495
  width.y = (ny > 0) ? width.y / ny : 0.0;
169 ✔
496
  width.z = (nz > 0) ? width.z / nz : 0.0;
169 ✔
497

498
#pragma omp parallel
63 ✔
499
  {
106 ✔
500
    // Preallocate vector for mesh indices and length fractions and particle
501
    vector<int> bins;
106 ✔
502
    vector<double> length_fractions;
106 ✔
503
    Particle p;
106 ✔
504

505
    SourceSite site;
106 ✔
506
    site.E = 1.0;
106 ✔
507
    site.particle = ParticleType::neutron();
106 ✔
508

509
    bool verbose = settings::verbosity >= 10;
106 ✔
510

511
    // Save the cells occupied immediately before a boundary crossing.
512
    auto save_cell_state = [&p]() {
6,374,560 ✔
513
      for (int j = 0; j < p.n_coord(); ++j) {
12,749,120 ✔
514
        p.cell_last(j) = p.coord(j).cell();
6,374,560 ✔
515
      }
516
      p.n_coord_last() = p.n_coord();
6,374,560 ✔
517
    };
6,374,666 ✔
518

519
    // Initialize cell history after locating a ray inside the model.
520
    auto initialize_cell_state = [&p, &save_cell_state]() {
4,873,432 ✔
521
      if (p.cell_born() == C_NONE)
4,873,432 !
522
        p.cell_born() = p.lowest_coord().cell();
4,873,432 ✔
523

524
      save_cell_state();
4,873,432 ✔
525
    };
4,873,538 ✔
526

527
    // Reset a failed coordinate search while preserving position and direction.
528
    auto reset_geometry_state = [&p]() {
129,824 ✔
529
      Position r = p.r();
129,824 ✔
530
      Direction u = p.u();
129,824 ✔
531
      p.init_from_r_u(r, u);
129,824 ✔
532
      p.coord(0).universe() = model::root_universe;
129,824 ✔
533
    };
129,930 ✔
534

535
    for (int axis = 0; axis < 3; ++axis) {
424 ✔
536
      // Set starting position and direction
537
      site.r = {0.0, 0.0, 0.0};
318 ✔
538
      site.r[axis] = bbox.min[axis];
318 ✔
539
      site.u = {0.0, 0.0, 0.0};
318 ✔
540
      site.u[axis] = 1.0;
318 ✔
541

542
      // Determine width of rays and number of rays in other directions
543
      int ax1 = (axis + 1) % 3;
318 ✔
544
      int ax2 = (axis + 2) % 3;
318 ✔
545
      double min1 = bbox.min[ax1];
318 ✔
546
      double min2 = bbox.min[ax2];
318 ✔
547
      double d1 = width[ax1];
318 ✔
548
      double d2 = width[ax2];
318 ✔
549
      int n1 = n_rays[ax1];
318 ✔
550
      int n2 = n_rays[ax2];
318 ✔
551
      if (n1 == 0 || n2 == 0) {
318 ✔
552
        continue;
60 ✔
553
      }
554

555
      // Divide rays in first direction over MPI processes by computing starting
556
      // and ending indices
557
      int min_work = n1 / mpi::n_procs;
258 ✔
558
      int remainder = n1 % mpi::n_procs;
258 ✔
559
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
258 !
560
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
258 !
561
      int i1_end = i1_start + n1_local;
258 ✔
562

563
      // Add the contribution from a ray segment. The positions used here are
564
      // kept separate from the particle position because the latter is moved a
565
      // tiny distance across each surface for robust geometry searches.
566
      auto add_segment = [&](const Position& r0, const Position& r1,
6,477,216 ✔
567
                           int i_material) {
568
        double distance = r1[axis] - r0[axis];
6,477,216 ✔
569
        if (distance <= 0.0)
6,477,216 !
570
          return;
571

572
        bins.clear();
6,477,216 ✔
573
        length_fractions.clear();
6,477,216 ✔
574
        this->bins_crossed(r0, r1, site.u, bins, length_fractions);
25,453,344 ✔
575

576
        double cumulative_frac = 0.0;
6,477,216 ✔
577
        for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
13,361,968 ✔
578
          int mesh_index = bins[i_bin];
6,884,752 ✔
579
          double length = distance * length_fractions[i_bin];
6,884,752 ✔
580
          double volume = length * d1 * d2;
25,860,880 ✔
581

582
          if (compute_bboxes) {
6,884,752 ✔
583
            double axis_start = r0[axis] + distance * cumulative_frac;
4,744,032 ✔
584
            double axis_end = axis_start + length;
4,744,032 ✔
585
            cumulative_frac += length_fractions[i_bin];
4,744,032 ✔
586

587
            Position contrib_min = site.r;
4,744,032 ✔
588
            Position contrib_max = site.r;
4,744,032 ✔
589

590
            contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
4,744,032 ✔
591
            contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
4,744,032 ✔
592
            contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
4,744,032 ✔
593
            contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
4,744,032 ✔
594
            contrib_min[axis] = std::min(axis_start, axis_end);
4,744,032 !
595
            contrib_max[axis] = std::max(axis_start, axis_end);
9,488,064 !
596

597
            BoundingBox contrib_bbox {contrib_min, contrib_max};
4,744,032 ✔
598
            contrib_bbox &= bbox;
4,744,032 ✔
599

600
            result.add_volume(mesh_index, i_material, volume, &contrib_bbox);
4,744,032 ✔
601
          } else {
602
            result.add_volume(mesh_index, i_material, volume);
2,140,720 ✔
603
          }
604
        }
605
      };
258 ✔
606

607
      // Loop over rays on face of bounding box
608
#pragma omp for collapse(2)
609
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
18,245 ✔
610
        for (int i2 = 0; i2 < n2; ++i2) {
3,092,880 ✔
611
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,074,893 ✔
612
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,074,893 ✔
613

614
          p.from_source(&site);
3,074,893 ✔
615

616
          // Set the physical endpoint of this ray at the far mesh face.
617
          Position r_mesh_end = site.r;
3,074,893 ✔
618
          r_mesh_end[axis] = bbox.max[axis];
3,074,893 ✔
619

620
          // Determine particle's location
621
          bool inside_model = exhaustive_find_cell(p, verbose);
3,074,893 ✔
622

623
          if (inside_model) {
3,074,893 ✔
624
            initialize_cell_state();
3,028,915 ✔
625
          } else {
626
            // Clear any partial descent into nested universes before searching
627
            // for the first root-universe boundary from undefined space.
628
            reset_geometry_state();
45,978 ✔
629
          }
630

631
          // Physical position through which volume has been accumulated. This
632
          // differs by TINY_BIT from p.r() after crossing a surface.
633
          Position r_scored = site.r;
3,074,893 ✔
634

635
          while (r_scored[axis] < r_mesh_end[axis]) {
4,038,921 !
636
            if (!inside_model) {
4,038,921 ✔
637
              // The ray is outside the model. Advance to the next surface of
638
              // any cell in the root universe, as is done for ray-traced
639
              // plots. Undefined space traversed along the way is void.
640
              Position r0 = p.r();
81,176 ✔
641
              p.advance_to_boundary_from_void();
81,176 ✔
642

643
              // If no model surface lies before the mesh edge, score the
644
              // remaining exterior interval as void and finish the ray.
645
              double distance_to_mesh_end = r_mesh_end[axis] - r0[axis];
81,176 ✔
646
              if (p.boundary().surface() == SURFACE_NONE ||
81,176 ✔
647
                  p.boundary().distance() >= distance_to_mesh_end) {
35,198 !
648
                add_segment(r_scored, r_mesh_end, MATERIAL_VOID);
45,978 ✔
649
                break;
45,978 ✔
650
              }
651

652
              // Determine the physical position of the model boundary.
653
              Position r_boundary = r0 + p.boundary().distance() * p.u();
35,198 ✔
654

655
              // Score the exterior interval and record its physical endpoint.
656
              add_segment(r_scored, r_boundary, MATERIAL_VOID);
35,198 ✔
657
              r_scored = r_boundary;
35,198 ✔
658

659
              // Check whether advancing through the surface entered the model.
660
              inside_model = exhaustive_find_cell(p, verbose);
35,198 ✔
661
              if (inside_model) {
35,198 ✔
662
                initialize_cell_state();
16,998 ✔
663
              } else {
664
                // Clear any partial coordinate search before looking for the
665
                // next surface from undefined space.
666
                reset_geometry_state();
18,200 ✔
667
              }
668
              continue;
35,198 ✔
669
            }
35,198 ✔
670

671
            // Find the distance to the nearest boundary
672
            BoundaryInfo boundary = distance_to_boundary(p);
3,957,745 ✔
673

674
            // Convert the material index to a user-facing ID
675
            int i_material = p.material();
3,957,745 ✔
676
            if (i_material != C_NONE) {
3,957,745 ✔
677
              i_material = model::materials[i_material]->id();
1,289,431 ✔
678
            }
679

680
            // If no model boundary lies before the mesh edge, score the
681
            // remaining material interval and finish the ray.
682
            double distance_to_mesh_end = r_mesh_end[axis] - p.r()[axis];
3,957,745 ✔
683
            if (boundary.distance() >= distance_to_mesh_end) {
3,957,745 ✔
684
              add_segment(r_scored, r_mesh_end, i_material);
3,028,915 ✔
685
              break;
686
            }
687

688
            // Determine the physical position of the model boundary.
689
            Position r_boundary = p.r() + boundary.distance() * p.u();
928,830 ✔
690

691
            // Score the material interval and record its physical endpoint.
692
            add_segment(r_scored, r_boundary, i_material);
928,830 ✔
693
            r_scored = r_boundary;
928,830 ✔
694

695
            // Cross the next geometric surface. The small forward movement
696
            // and neighbor-list search mirror Ray::trace, allowing a failed
697
            // search to mean that the ray has left the model rather than that
698
            // a transport particle has been lost.
699
            save_cell_state();
928,830 ✔
700

701
            // Move just beyond the surface to make the next search robust.
702
            p.move_distance(boundary.distance() + TINY_BIT);
928,830 ✔
703

704
            // Set surface that particle is on and adjust coordinate levels
705
            p.surface() = boundary.surface();
928,830 ✔
706
            p.n_coord() = boundary.coord_level();
928,830 ✔
707

708
            // Update the geometry state according to the boundary type.
709
            if (boundary.lattice_translation()[0] != 0 ||
928,830 !
710
                boundary.lattice_translation()[1] != 0 ||
928,830 !
711
                boundary.lattice_translation()[2] != 0) {
928,830 !
712
              // Particle crosses lattice boundary
713
              cross_lattice(p, boundary, verbose);
×
714
              inside_model = true;
715
            } else {
716
              // Search for the cell on the opposite side of a surface.
717
              inside_model = neighbor_list_find_cell(p, verbose);
928,830 ✔
718
            }
719

720
            // Treat a failed cell search as a transition to exterior void.
721
            if (!inside_model) {
928,830 ✔
722
              // Reset the geometry state so the next iteration can search for
723
              // another disjoint portion of the model.
724
              reset_geometry_state();
16,998 ✔
725
            }
726
          }
727
        }
728
      }
729
    }
730
  }
106 ✔
731

732
  // Check for errors
733
  if (result.table_full()) {
169 !
734
    throw std::runtime_error("Maximum number of materials for mesh material "
×
735
                             "volume calculation insufficient.");
×
736
  }
737

738
  // Compute time for raytracing
739
  double t_raytrace = timer.elapsed();
169 ✔
740

741
#ifdef OPENMC_MPI
742
  // Combine results from multiple MPI processes
743
  if (mpi::n_procs > 1) {
42 !
744
    int total = this->n_bins() * table_size;
745
    int total_bbox = total * 6;
746
    if (mpi::master) {
×
747
      // Allocate temporary buffer for receiving data
748
      vector<int32_t> mats(total);
749
      vector<double> vols(total);
×
750
      vector<double> recv_bboxes;
×
751
      if (compute_bboxes) {
×
752
        recv_bboxes.resize(total_bbox);
×
753
      }
754

755
      for (int i = 1; i < mpi::n_procs; ++i) {
×
756
        // Receive material indices and volumes from process i
757
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
758
          MPI_STATUS_IGNORE);
759
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
760
          MPI_STATUS_IGNORE);
761
        if (compute_bboxes) {
×
762
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
763
            mpi::intracomm, MPI_STATUS_IGNORE);
764
        }
765

766
        // Combine with existing results; we can call thread unsafe version of
767
        // add_volume because each thread is operating on a different element
768
#pragma omp for
769
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
770
          for (int k = 0; k < table_size; ++k) {
×
771
            int index = index_elem * table_size + k;
772
            if (mats[index] != EMPTY) {
×
773
              if (compute_bboxes) {
×
774
                int bbox_index = index * 6;
775
                BoundingBox slot_bbox {
776
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
777
                    recv_bboxes[bbox_index + 2]},
778
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
779
                    recv_bboxes[bbox_index + 5]}};
×
780
                result.add_volume_unsafe(
781
                  index_elem, mats[index], vols[index], &slot_bbox);
×
782
              } else {
783
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
784
              }
785
            }
786
          }
787
        }
788
      }
789
    } else {
790
      // Send material indices and volumes to process 0
791
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
792
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
793
      if (compute_bboxes) {
×
794
        MPI_Send(bboxes, total_bbox, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
795
      }
796
    }
797
  }
798

799
  // Report time for MPI communication
800
  double t_mpi = timer.elapsed() - t_raytrace;
42 ✔
801
#else
802
  double t_mpi = 0.0;
105 ✔
803
#endif
804

805
  // Normalize based on known volumes of elements
806
  for (int i = 0; i < this->n_bins(); ++i) {
1,892 ✔
807
    // Estimated total volume in element i
808
    double volume = 0.0;
809
    for (int j = 0; j < table_size; ++j) {
11,507 ✔
810
      volume += result.volumes(i, j);
9,784 ✔
811
    }
812
    // Renormalize volumes based on known volume of element i
813
    double norm = this->volume(i) / volume;
1,723 ✔
814
    for (int j = 0; j < table_size; ++j) {
11,507 ✔
815
      result.volumes(i, j) *= norm;
9,784 ✔
816
    }
817
  }
818

819
  // Get total time and normalization time
820
  timer.stop();
169 ✔
821
  double t_total = timer.elapsed();
169 ✔
822
  double t_norm = t_total - t_raytrace - t_mpi;
169 ✔
823

824
  // Show timing statistics
825
  if (settings::verbosity < 7 || !mpi::master)
169 !
826
    return;
40 ✔
827
  header("Timing Statistics", 7);
129 ✔
828
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
129 ✔
829
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
129 ✔
830
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
129 ✔
831
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
129 ✔
832
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
258 ✔
833
    n_total / t_raytrace);
129 ✔
834
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
210 ✔
835
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
129 ✔
836
  std::fflush(stdout);
129 ✔
837
}
838

839
void Mesh::to_hdf5(hid_t group) const
2,767 ✔
840
{
841
  // Create group for mesh
842
  std::string group_name = fmt::format("mesh {}", id_);
2,767 ✔
843
  hid_t mesh_group = create_group(group, group_name.c_str());
2,767 ✔
844

845
  // Write mesh type
846
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,767 ✔
847

848
  // Write mesh ID
849
  write_attribute(mesh_group, "id", id_);
2,767 ✔
850

851
  // Write mesh name
852
  write_dataset(mesh_group, "name", name_);
2,767 ✔
853

854
  // Write mesh data
855
  this->to_hdf5_inner(mesh_group);
2,767 ✔
856

857
  // Close group
858
  close_group(mesh_group);
2,767 ✔
859
}
2,767 ✔
860

861
//==============================================================================
862
// Structured Mesh implementation
863
//==============================================================================
864

865
std::string StructuredMesh::bin_label(int bin) const
3,910,352 ✔
866
{
867
  MeshIndex ijk = get_indices_from_bin(bin);
3,910,352 ✔
868

869
  if (n_dimension_ > 2) {
3,910,352 ✔
870
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
3,898,184 ✔
871
  } else if (n_dimension_ > 1) {
12,168 ✔
872
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
11,904 ✔
873
  } else {
874
    return fmt::format("Mesh Index ({})", ijk[0]);
264 ✔
875
  }
876
}
877

878
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,515 ✔
879
{
880
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,515 ✔
881
}
882

883
Position StructuredMesh::sample_element(
1,045,247 ✔
884
  const MeshIndex& ijk, uint64_t* seed) const
885
{
886
  // lookup the lower/upper bounds for the mesh element
887
  double x_min = negative_grid_boundary(ijk, 0);
1,045,247 ✔
888
  double x_max = positive_grid_boundary(ijk, 0);
1,045,247 ✔
889

890
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,045,247 !
891
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,045,247 !
892

893
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,045,247 !
894
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,045,247 !
895

896
  return {x_min + (x_max - x_min) * prn(seed),
1,045,247 ✔
897
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,045,247 ✔
898
}
899

900
//==============================================================================
901
// Unstructured Mesh implementation
902
//==============================================================================
903

904
std::string read_mesh_interface(const pugi::xml_node& node)
65 ✔
905
{
906
  std::string mesh_interface;
65 !
907
  if (check_for_node(node, "interface")) {
65 !
908
    mesh_interface = get_node_value(node, "interface");
40 !
909
  } else {
910
    mesh_interface = "native";
25 !
911
  }
912
  return std::move(mesh_interface);
130 !
913
}
65 ✔
914

915
std::string read_mesh_interface(hid_t group)
×
916
{
917
  std::string mesh_interface;
×
918
  if (object_exists(group, "interface")) {
×
919
    read_dataset(group, "interface", mesh_interface);
×
920
  } else {
921
    mesh_interface = "native";
×
922
  }
923
  return std::move(mesh_interface);
×
924
}
×
925

926
std::string read_mesh_library(const pugi::xml_node& node)
65 ✔
927
{
928
  std::string mesh_library;
65 !
929
  if (check_for_node(node, "library")) {
65 !
930
    mesh_library = get_node_value(node, "library");
65 !
931
  } else {
932
    mesh_library = "moab";
×
933
  }
934
  return std::move(mesh_library);
130 !
935
}
65 ✔
936

937
std::string read_mesh_library(hid_t group)
×
938
{
939
  std::string mesh_library;
×
940
  if (object_exists(group, "library")) {
×
941
    read_dataset(group, "library", mesh_library);
×
942
  } else {
943
    mesh_library = "moab";
×
944
  }
945
  return std::move(mesh_library);
×
946
}
×
947

948
template<typename T>
949
std::unique_ptr<UnstructuredMesh> UnstructuredMesh::create(T dataset)
65 ✔
950
{
951
  std::string mesh_interface = read_mesh_interface(dataset);
65 ✔
952
  std::string mesh_library = read_mesh_library(dataset);
65 !
953

954
  if (mesh_interface == "xdg") {
65 ✔
955
#ifdef OPENMC_XDG_ENABLED
956
    return make_unique<XDGMesh>(dataset);
40 ✔
957
#else
958
    fatal_error(fmt::format(
×
959
      "XDG unstructured mesh interface with library '{}' is not enabled in "
960
      "this build of OpenMC.",
961
      mesh_library));
962
#endif
963
  }
964

965
  if (mesh_interface != "native") {
25 !
966
    fatal_error(fmt::format(
×
967
      "Unrecognized unstructured mesh interface '{}'.", mesh_interface));
968
  }
969

970
#ifdef OPENMC_DAGMC_ENABLED
971
  if (mesh_library == MOABMesh::mesh_lib_type) {
25 ✔
972
    return make_unique<MOABMesh>(dataset);
15 ✔
973
  }
974
#endif
975

976
#ifdef OPENMC_LIBMESH_ENABLED
977
  if (mesh_library == LibMesh::mesh_lib_type) {
10 !
978
    return make_unique<LibMesh>(dataset);
10 ✔
979
  }
980
#endif
981

982
  fatal_error(fmt::format("Native unstructured mesh library '{}' is not "
×
983
                          "enabled in this build of OpenMC.",
984
    mesh_library));
985
}
65 ✔
986

987
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
69 !
988
{
989
  n_dimension_ = 3;
69 ✔
990

991
  // check if a length unit multiplier was specified
992
  if (check_for_node(node, "length_multiplier")) {
69 !
993
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
994
  }
995

996
  // get the filename of the unstructured mesh to load
997
  if (check_for_node(node, "filename")) {
69 !
998
    filename_ = get_node_value(node, "filename");
69 !
999
    if (!file_exists(filename_)) {
69 !
1000
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
1001
    }
1002
  } else {
1003
    fatal_error(fmt::format(
×
1004
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
1005
  }
1006

1007
  if (check_for_node(node, "options")) {
69 !
1008
    options_ = get_node_value(node, "options");
20 !
1009
  }
1010

1011
  // check if mesh tally data should be written with
1012
  // statepoint files
1013
  if (check_for_node(node, "output")) {
69 !
1014
    output_ = get_node_value_bool(node, "output");
×
1015
  }
1016
}
69 ✔
1017

1018
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
1019
{
1020
  n_dimension_ = 3;
×
1021

1022
  // check the mesh type
1023
  if (object_exists(group, "type")) {
×
1024
    std::string temp;
×
1025
    read_dataset(group, "type", temp);
×
1026
    if (temp != mesh_type) {
×
1027
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
1028
    }
1029
  }
×
1030

1031
  // check if a length unit multiplier was specified
1032
  if (object_exists(group, "length_multiplier")) {
×
1033
    read_dataset(group, "length_multiplier", length_multiplier_);
×
1034
  }
1035

1036
  // get the filename of the unstructured mesh to load
1037
  if (object_exists(group, "filename")) {
×
1038
    read_dataset(group, "filename", filename_);
×
1039
    if (!file_exists(filename_)) {
×
1040
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
1041
    }
1042
  } else {
1043
    fatal_error(fmt::format(
×
1044
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
1045
  }
1046

1047
  if (attribute_exists(group, "options")) {
×
1048
    read_attribute(group, "options", options_);
×
1049
  }
1050

1051
  // check if mesh tally data should be written with
1052
  // statepoint files
1053
  if (attribute_exists(group, "output")) {
×
1054
    read_attribute(group, "output", output_);
×
1055
  }
1056
}
×
1057

NEW
1058
MeshCrossing UnstructuredMesh::next_mesh_crossing(
×
1059
  int current_bin, Position r, Direction u) const
1060
{
NEW
1061
  fatal_error("Not implemented");
×
1062
  return {INFTY, C_NONE};
1063
}
1064

1065
void UnstructuredMesh::determine_bounds()
17 ✔
1066
{
1067
  double xmin = INFTY;
17 ✔
1068
  double ymin = INFTY;
17 ✔
1069
  double zmin = INFTY;
17 ✔
1070
  double xmax = -INFTY;
17 ✔
1071
  double ymax = -INFTY;
17 ✔
1072
  double zmax = -INFTY;
17 ✔
1073
  int n = this->n_vertices();
17 ✔
1074
  for (int i = 0; i < n; ++i) {
37,311 ✔
1075
    auto v = this->vertex(i);
37,294 ✔
1076
    xmin = std::min(v.x, xmin);
37,294 ✔
1077
    ymin = std::min(v.y, ymin);
37,294 ✔
1078
    zmin = std::min(v.z, zmin);
37,294 ✔
1079
    xmax = std::max(v.x, xmax);
37,294 ✔
1080
    ymax = std::max(v.y, ymax);
37,294 ✔
1081
    zmax = std::max(v.z, zmax);
53,291 ✔
1082
  }
1083
  lower_left_ = {xmin, ymin, zmin};
17 ✔
1084
  upper_right_ = {xmax, ymax, zmax};
17 ✔
1085
}
17 ✔
1086

1087
const std::string UnstructuredMesh::mesh_type = "unstructured";
1088

1089
std::string UnstructuredMesh::get_mesh_type() const
72 ✔
1090
{
1091
  return mesh_type;
72 ✔
1092
}
1093

1094
void UnstructuredMesh::surface_bins_crossed(
×
1095
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1096
{
1097
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
1098
}
1099

1100
std::string UnstructuredMesh::bin_label(int bin) const
521,304 ✔
1101
{
1102
  return fmt::format("Mesh Index ({})", bin);
521,304 ✔
1103
};
1104

1105
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
68 ✔
1106
{
1107
  write_dataset(mesh_group, "filename", filename_);
68 !
1108
  write_dataset(mesh_group, "library", this->library());
68 !
1109
  if (interface_ != "native") {
68 ✔
1110
    write_dataset(mesh_group, "interface", interface_);
80 !
1111
  }
1112
  if (!options_.empty()) {
68 ✔
1113
    write_attribute(mesh_group, "options", options_);
20 ✔
1114
  }
1115

1116
  if (length_multiplier_ > 0.0)
68 ✔
1117
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
2 ✔
1118

1119
  // write vertex coordinates
1120
  tensor::Tensor<double> vertices(
68 ✔
1121
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
68 ✔
1122
  for (int i = 0; i < this->n_vertices(); i++) {
150,179 !
1123
    auto v = this->vertex(i);
150,111 !
1124
    vertices.slice(i) = {v.x, v.y, v.z};
300,222 !
1125
  }
1126
  write_dataset(mesh_group, "vertices", vertices);
68 !
1127

1128
  int num_elem_skipped = 0;
68 ✔
1129

1130
  // write element types and connectivity
1131
  vector<double> volumes;
68 !
1132
  tensor::Tensor<int> connectivity(
68 ✔
1133
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
68 !
1134
  tensor::Tensor<int> elem_types(
68 ✔
1135
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
68 !
1136
  for (int i = 0; i < this->n_bins(); i++) {
737,372 !
1137
    auto conn = this->connectivity(i);
737,304 !
1138

1139
    volumes.emplace_back(this->volume(i));
737,304 !
1140

1141
    // write linear tet element
1142
    if (conn.size() == 4) {
737,304 ✔
1143
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
731,304 !
1144
      connectivity.slice(i) = {
731,304 !
1145
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
1,462,608 !
1146
      // write linear hex element
1147
    } else if (conn.size() == 8) {
6,000 !
1148
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
6,000 !
1149
      connectivity.slice(i) = {
6,000 !
1150
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
12,000 !
1151
    } else {
1152
      num_elem_skipped++;
×
1153
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
1154
      connectivity.slice(i) = -1;
×
1155
    }
1156
  }
737,304 ✔
1157
  // warn users that some elements were skipped
1158
  if (num_elem_skipped > 0) {
68 !
1159
    warning(fmt::format("The connectivity of {} elements "
×
1160
                        "on mesh {} were not written "
1161
                        "because they are not of type linear tet/hex.",
1162
      num_elem_skipped, this->id_));
×
1163
  }
1164

1165
  write_dataset(mesh_group, "volumes", volumes);
68 !
1166
  write_dataset(mesh_group, "connectivity", connectivity);
68 !
1167
  write_dataset(mesh_group, "element_types", elem_types);
68 !
1168
}
204 ✔
1169

1170
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
16 ✔
1171
{
1172
  length_multiplier_ = length_multiplier;
16 ✔
1173
}
16 ✔
1174

1175
ElementType UnstructuredMesh::element_type(int bin) const
144,000 ✔
1176
{
1177
  auto conn = connectivity(bin);
144,000 ✔
1178

1179
  if (conn.size() == 4)
144,000 !
1180
    return ElementType::LINEAR_TET;
1181
  else if (conn.size() == 8)
×
1182
    return ElementType::LINEAR_HEX;
1183
  else
1184
    return ElementType::UNSUPPORTED;
×
1185
}
144,000 ✔
1186

1187
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,367,534,682 ✔
1188
  Position r, bool& in_mesh) const
1189
{
1190
  MeshIndex ijk;
1,367,534,682 ✔
1191
  in_mesh = true;
1,367,534,682 ✔
1192
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647 ✔
1193
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647 ✔
1194

1195
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647 ✔
1196
      in_mesh = false;
88,502,828 ✔
1197
  }
1198
  return ijk;
1,367,534,682 ✔
1199
}
1200

1201
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,879,569,661 ✔
1202
{
1203
  switch (n_dimension_) {
1,879,569,661 !
1204
  case 1:
599,696 ✔
1205
    return ijk[0] - 1;
599,696 ✔
1206
  case 2:
135,704,717 ✔
1207
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
135,704,717 ✔
1208
  case 3:
1,743,265,248 ✔
1209
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,743,265,248 ✔
1210
  default:
×
1211
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1212
  }
1213
}
1214

1215
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
5,928,638 ✔
1216
{
1217
  MeshIndex ijk;
5,928,638 ✔
1218
  if (n_dimension_ == 1) {
5,928,638 ✔
1219
    ijk[0] = bin + 1;
264 ✔
1220
  } else if (n_dimension_ == 2) {
5,928,374 ✔
1221
    ijk[0] = bin % shape_[0] + 1;
11,904 ✔
1222
    ijk[1] = bin / shape_[0] + 1;
11,904 ✔
1223
  } else if (n_dimension_ == 3) {
5,916,470 !
1224
    ijk[0] = bin % shape_[0] + 1;
5,916,470 ✔
1225
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
5,916,470 ✔
1226
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
5,916,470 ✔
1227
  }
1228
  return ijk;
5,928,638 ✔
1229
}
1230

1231
int StructuredMesh::get_bin(Position r) const
449,175,628 ✔
1232
{
1233
  // Determine indices
1234
  bool in_mesh;
449,175,628 ✔
1235
  MeshIndex ijk = get_indices(r, in_mesh);
449,175,628 ✔
1236
  if (!in_mesh)
449,175,628 ✔
1237
    return -1;
1238

1239
  // Convert indices to bin
1240
  return get_bin_from_indices(ijk);
432,488,302 ✔
1241
}
1242

1243
int StructuredMesh::n_bins() const
919,128 ✔
1244
{
1245
  // Bin indices are stored as 32-bit ints in the tally system.
1246
  int64_t n = 1;
919,128 ✔
1247
  for (int i = 0; i < n_dimension_; ++i)
3,676,140 ✔
1248
    n *= shape_[i];
2,757,012 ✔
1249
  if (n > std::numeric_limits<int>::max()) {
919,128 !
1250
    fatal_error(fmt::format(
×
1251
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1252
  }
1253
  return static_cast<int>(n);
919,128 ✔
1254
}
1255

1256
int StructuredMesh::n_surface_bins() const
308 ✔
1257
{
1258
  // Surface bin indices are stored as 32-bit ints in the tally system.
1259
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
308 ✔
1260
  if (n > std::numeric_limits<int>::max()) {
308 !
1261
    fatal_error(fmt::format(
×
1262
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1263
  }
1264
  return static_cast<int>(n);
308 ✔
1265
}
1266

1267
tensor::Tensor<double> StructuredMesh::count_sites(
×
1268
  const SourceSite* bank, int64_t length, bool* outside) const
1269
{
1270
  // Determine shape of array for counts
1271
  std::size_t m = this->n_bins();
×
1272
  vector<std::size_t> shape = {m};
×
1273

1274
  // Create array of zeros
1275
  auto cnt = tensor::zeros<double>(shape);
×
1276
  bool outside_ = false;
1277

1278
  for (int64_t i = 0; i < length; i++) {
×
1279
    const auto& site = bank[i];
×
1280

1281
    // determine scoring bin for entropy mesh
1282
    int mesh_bin = get_bin(site.r);
×
1283

1284
    // if outside mesh, skip particle
1285
    if (mesh_bin < 0) {
×
1286
      outside_ = true;
×
1287
      continue;
×
1288
    }
1289

1290
    // Add to appropriate bin
1291
    cnt(mesh_bin) += site.wgt;
×
1292
  }
1293

1294
  // Create reduced count data
1295
  auto counts = tensor::zeros<double>(shape);
×
1296
  int total = cnt.size();
×
1297

1298
#ifdef OPENMC_MPI
1299
  // collect values from all processors
1300
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
×
1301

1302
  // Check if there were sites outside the mesh for any processor
1303
  if (outside) {
×
1304
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1305
  }
1306
#else
1307
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1308
  if (outside)
×
1309
    *outside = outside_;
1310
#endif
1311

1312
  return counts;
×
1313
}
×
1314

1315
// raytrace through the mesh. The template class T will do the tallying.
1316
// A modern optimizing compiler can recognize the noop method of T and
1317
// eliminate that call entirely.
1318
template<class T>
1319
void StructuredMesh::raytrace_mesh(
904,720,125 ✔
1320
  Position r0, Position r1, const Direction& u, T tally) const
1321
{
1322
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1323
  // enable/disable tally calls for now, T template type needs to provide both
1324
  // surface and track methods, which might be empty. modern optimizing
1325
  // compilers will (hopefully) eliminate the complete code (including
1326
  // calculation of parameters) but for the future: be explicit
1327

1328
  // Compute the length of the entire track.
1329
  double total_distance = (r1 - r0).norm();
904,720,125 ✔
1330
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
904,720,125 ✔
1331
    return;
1332

1333
  // keep a copy of the original global position to pass to get_indices,
1334
  // which performs its own transformation to local coordinates
1335
  Position global_r = r0;
904,714,021 ✔
1336
  Position local_r = local_coords(r0);
904,714,021 ✔
1337

1338
  const int n = n_dimension_;
904,714,021 ✔
1339

1340
  // Flag if position is inside the mesh
1341
  bool in_mesh;
1342

1343
  // Position is r = r0 + u * traveled_distance, start at r0
1344
  double traveled_distance {0.0};
904,714,021 ✔
1345

1346
  // Calculate index of current cell. Offset the position a tiny bit in
1347
  // direction of flight
1348
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
904,714,021 ✔
1349

1350
  // if track is very short, assume that it is completely inside one cell.
1351
  // Only the current cell will score and no surfaces
1352
  if (total_distance < 2 * TINY_BIT) {
904,714,021 ✔
1353
    if (in_mesh) {
518,851 ✔
1354
      tally.track(ijk, 1.0);
518,499 ✔
1355
    }
1356
    return;
518,851 ✔
1357
  }
1358

1359
  // Calculate initial distances to next surfaces in all three dimensions
1360
  std::array<MeshDistance, 3> distances;
1,808,390,340 ✔
1361
  for (int k = 0; k < n; ++k) {
2,147,483,647 ✔
1362
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647 ✔
1363
  }
1364

1365
  // Loop until r = r1 is eventually reached
1366
  while (true) {
1367

1368
    if (in_mesh) {
1,570,684,190 ✔
1369

1370
      // find surface with minimal distance to current position
1371
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,504,473,672 ✔
1372
                     distances.begin();
1,504,473,672 ✔
1373

1374
      // Tally track length delta since last step
1375
      tally.track(ijk,
1,504,473,672 ✔
1376
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647 ✔
1377
          total_distance);
1378

1379
      // update position and leave, if we have reached end position
1380
      traveled_distance = distances[k].distance;
1,504,473,672 ✔
1381
      if (traveled_distance >= total_distance)
1,504,473,672 ✔
1382
        return;
1383

1384
      // If we have not reached r1, we have hit a surface. Tally outward
1385
      // current
1386
      tally.surface(ijk, k, distances[k].max_surface, false);
661,478,493 ✔
1387

1388
      // Update cell and calculate distance to next surface in k-direction.
1389
      // The two other directions are still valid!
1390
      ijk[k] = distances[k].next_index;
661,478,493 ✔
1391
      distances[k] =
661,478,493 ✔
1392
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
661,478,493 ✔
1393

1394
      // Check if we have left the interior of the mesh
1395
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
666,707,243 ✔
1396

1397
      // If we are still inside the mesh, tally inward current for the next
1398
      // cell
1399
      if (in_mesh)
21,445,672 ✔
1400
        tally.surface(ijk, k, !distances[k].max_surface, true);
665,465,292 ✔
1401

1402
    } else { // not inside mesh
1403

1404
      // For all directions outside the mesh, find the distance that we need
1405
      // to travel to reach the next surface. Use the largest distance, as
1406
      // only this will cross all outer surfaces.
1407
      int k_max {-1};
1408
      for (int k = 0; k < n; ++k) {
263,820,344 ✔
1409
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
197,609,826 ✔
1410
            (distances[k].distance > traveled_distance)) {
75,005,317 ✔
1411
          traveled_distance = distances[k].distance;
1412
          k_max = k;
1413
        }
1414
      }
1415
      // Assure some distance is traveled
1416
      if (k_max == -1) {
66,210,518 !
1417
        traveled_distance += TINY_BIT;
×
1418
      }
1419

1420
      // If r1 is not inside the mesh, exit here
1421
      if (traveled_distance >= total_distance)
66,210,518 ✔
1422
        return;
1423

1424
      // Calculate the new cell index and update all distances to next
1425
      // surfaces.
1426
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
5,010,527 ✔
1427
      for (int k = 0; k < n; ++k) {
19,892,388 ✔
1428
        distances[k] =
14,881,861 ✔
1429
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
14,881,861 ✔
1430
      }
1431

1432
      // If inside the mesh, Tally inward current
1433
      if (in_mesh && k_max >= 0)
5,010,527 !
1434
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
645,025,836 ✔
1435
    }
1436
  }
1437
}
1438

1439
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
823,185,301 ✔
1440
  vector<int>& bins, vector<double>& lengths) const
1441
{
1442

1443
  // Helper tally class.
1444
  // stores a pointer to the mesh class and references to bins and lengths
1445
  // parameters. Performs the actual tally through the track method.
1446
  struct TrackAggregator {
823,185,301 ✔
1447
    TrackAggregator(
823,185,301 ✔
1448
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1449
      : mesh(_mesh), bins(_bins), lengths(_lengths)
823,185,301 ✔
1450
    {}
1451
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1452
    void track(const MeshIndex& ijk, double l) const
1,403,213,075 ✔
1453
    {
1454
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,403,213,075 ✔
1455
      lengths.push_back(l);
1,403,213,075 ✔
1456
    }
1,403,213,075 ✔
1457

1458
    const StructuredMesh* mesh;
1459
    vector<int>& bins;
1460
    vector<double>& lengths;
1461
  };
1462

1463
  // Perform the mesh raytrace with the helper class.
1464
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
823,185,301 ✔
1465
}
823,185,301 ✔
1466

1467
void StructuredMesh::surface_bins_crossed(
81,534,824 ✔
1468
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1469
{
1470

1471
  // Helper tally class.
1472
  // stores a pointer to the mesh class and a reference to the bins parameter.
1473
  // Performs the actual tally through the surface method.
1474
  struct SurfaceAggregator {
81,534,824 ✔
1475
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
81,534,824 ✔
1476
      : mesh(_mesh), bins(_bins)
81,534,824 ✔
1477
    {}
1478
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
42,168,904 ✔
1479
    {
1480
      int i_bin =
42,168,904 ✔
1481
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
42,168,904 ✔
1482
      if (max)
42,168,904 ✔
1483
        i_bin += 2;
21,062,952 ✔
1484
      if (inward)
42,168,904 ✔
1485
        i_bin += 1;
20,723,232 ✔
1486
      bins.push_back(i_bin);
42,168,904 ✔
1487
    }
42,168,904 ✔
1488
    void track(const MeshIndex& idx, double l) const {}
1489

1490
    const StructuredMesh* mesh;
1491
    vector<int>& bins;
1492
  };
1493

1494
  // Perform the mesh raytrace with the helper class.
1495
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
81,534,824 ✔
1496
}
81,534,824 ✔
1497

1498
MeshCrossing StructuredMesh::next_mesh_crossing(
5,031,014 ✔
1499
  int current_bin, Position r, Direction u) const
1500
{
1501
  bool in_mesh;
5,031,014 ✔
1502
  MeshIndex ijk = get_indices(r + TINY_BIT * u, in_mesh);
5,031,014 ✔
1503

1504
  if (current_bin != C_NONE) {
5,031,014 ✔
1505
    if (!in_mesh)
3,092,773 !
NEW
1506
      return {0.0, C_NONE};
×
1507
  } else if (in_mesh) {
1,938,241 ✔
1508
    return {0.0, get_bin_from_indices(ijk)};
8 ✔
1509
  }
1510

1511
  const bool started_in_mesh = in_mesh;
5,031,006 ✔
1512
  Position local_r = local_coords(r);
5,031,006 ✔
1513
  std::array<MeshDistance, 3> distances;
10,062,012 ✔
1514
  for (int k = 0; k < n_dimension_; ++k)
20,124,024 ✔
1515
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
15,093,018 ✔
1516

1517
  double distance;
5,031,006 ✔
1518
  if (in_mesh) {
5,031,006 ✔
1519
    auto first = distances.begin();
3,092,773 !
1520
    auto last = first + n_dimension_;
3,092,773 ✔
1521
    distance = std::min_element(first, last)->distance;
6,185,546 !
1522
  } else {
1523
    // For a Cartesian mesh, the latest entry among the out-of-range
1524
    // directions is the point at which the ray first enters the mesh.
1525
    distance = 0.0;
1,938,233 ✔
1526
    for (int k = 0; k < n_dimension_; ++k) {
7,752,932 ✔
1527
      if (ijk[k] < 1 || ijk[k] > shape_[k])
5,814,699 ✔
1528
        distance = std::max(distance, distances[k].distance);
6,477,446 ✔
1529
    }
1530
  }
1531

1532
  if (distance >= INFTY)
5,031,006 ✔
1533
    return {INFTY, C_NONE};
1,427,514 ✔
1534

1535
  MeshIndex next_ijk = get_indices(r + (distance + TINY_BIT) * u, in_mesh);
3,603,492 ✔
1536
  if (!in_mesh)
3,603,492 ✔
1537
    return {started_in_mesh ? distance : INFTY, C_NONE};
3,454,522 ✔
1538

1539
  return {distance, get_bin_from_indices(next_ijk)};
1,699,372 ✔
1540
}
1541

1542
//==============================================================================
1543
// RegularMesh implementation
1544
//==============================================================================
1545

1546
int RegularMesh::set_grid()
2,144 ✔
1547
{
1548
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,144 ✔
1549

1550
  // Check that dimensions are all greater than zero
1551
  if ((shape <= 0).any()) {
6,432 !
1552
    set_errmsg("All entries for a regular mesh dimensions "
×
1553
               "must be positive.");
1554
    return OPENMC_E_INVALID_ARGUMENT;
1555
  }
1556

1557
  // Make sure lower_left and dimension match
1558
  if (lower_left_.size() != n_dimension_) {
2,144 !
1559
    set_errmsg("Number of entries in lower_left must be the same "
×
1560
               "as the regular mesh dimensions.");
1561
    return OPENMC_E_INVALID_ARGUMENT;
1562
  }
1563
  if (width_.size() > 0) {
2,144 ✔
1564

1565
    // Check to ensure width has same dimensions
1566
    if (width_.size() != n_dimension_) {
31 !
1567
      set_errmsg("Number of entries on width must be the same as "
×
1568
                 "the regular mesh dimensions.");
1569
      return OPENMC_E_INVALID_ARGUMENT;
1570
    }
1571

1572
    // Check for negative widths
1573
    if ((width_ < 0.0).any()) {
93 !
1574
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1575
      return OPENMC_E_INVALID_ARGUMENT;
1576
    }
1577

1578
    // Set width and upper right coordinate
1579
    upper_right_ = lower_left_ + shape * width_;
93 ✔
1580

1581
  } else if (upper_right_.size() > 0) {
2,113 !
1582

1583
    // Check to ensure upper_right_ has same dimensions
1584
    if (upper_right_.size() != n_dimension_) {
2,113 !
1585
      set_errmsg("Number of entries on upper_right must be the "
×
1586
                 "same as the regular mesh dimensions.");
1587
      return OPENMC_E_INVALID_ARGUMENT;
1588
    }
1589

1590
    // Check that upper-right is above lower-left
1591
    if ((upper_right_ < lower_left_).any()) {
6,339 !
1592
      set_errmsg(
×
1593
        "The upper_right coordinates of a regular mesh must be greater than "
1594
        "the lower_left coordinates.");
1595
      return OPENMC_E_INVALID_ARGUMENT;
1596
    }
1597

1598
    // Set width
1599
    width_ = (upper_right_ - lower_left_) / shape;
6,339 ✔
1600
  }
1601

1602
  // Set material volumes
1603
  volume_frac_ = 1.0 / shape.prod();
2,144 ✔
1604

1605
  element_volume_ = 1.0;
2,144 ✔
1606
  for (int i = 0; i < n_dimension_; i++) {
8,126 ✔
1607
    element_volume_ *= width_[i];
5,982 ✔
1608
  }
1609
  return 0;
1610
}
2,144 ✔
1611

1612
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,118 ✔
1613
{
1614
  // Determine number of dimensions for mesh
1615
  if (!check_for_node(node, "dimension")) {
2,118 !
1616
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1617
  }
1618

1619
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,118 ✔
1620
  int n = n_dimension_ = shape.size();
2,118 !
1621
  if (n != 1 && n != 2 && n != 3) {
2,118 !
1622
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1623
  }
1624
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,118 ✔
1625

1626
  // Check for lower-left coordinates
1627
  if (check_for_node(node, "lower_left")) {
2,118 !
1628
    // Read mesh lower-left corner location
1629
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,118 ✔
1630
  } else {
1631
    fatal_error("Must specify <lower_left> on a mesh.");
×
1632
  }
1633

1634
  if (check_for_node(node, "width")) {
2,118 ✔
1635
    // Make sure one of upper-right or width were specified
1636
    if (check_for_node(node, "upper_right")) {
31 !
1637
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1638
    }
1639

1640
    width_ = get_node_tensor<double>(node, "width");
62 ✔
1641

1642
  } else if (check_for_node(node, "upper_right")) {
2,087 !
1643

1644
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,174 ✔
1645

1646
  } else {
1647
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1648
  }
1649

1650
  if (set_grid()) {
2,118 !
1651
    fatal_error(get_errmsg());
×
1652
  }
1653
}
2,118 ✔
1654

1655
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
26 ✔
1656
{
1657
  // Determine number of dimensions for mesh
1658
  if (!object_exists(group, "dimension")) {
26 !
1659
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1660
  }
1661

1662
  tensor::Tensor<int> shape;
26 ✔
1663
  read_dataset(group, "dimension", shape);
26 ✔
1664
  int n = n_dimension_ = shape.size();
26 !
1665
  if (n != 1 && n != 2 && n != 3) {
26 !
1666
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1667
  }
1668
  std::copy(shape.begin(), shape.end(), shape_.begin());
26 ✔
1669

1670
  // Check for lower-left coordinates
1671
  if (object_exists(group, "lower_left")) {
26 !
1672
    // Read mesh lower-left corner location
1673
    read_dataset(group, "lower_left", lower_left_);
26 ✔
1674
  } else {
1675
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1676
  }
1677

1678
  if (object_exists(group, "upper_right")) {
26 !
1679

1680
    read_dataset(group, "upper_right", upper_right_);
26 ✔
1681

1682
  } else {
1683
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1684
  }
1685

1686
  if (set_grid()) {
26 !
1687
    fatal_error(get_errmsg());
×
1688
  }
1689
}
26 ✔
1690

1691
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647 ✔
1692
{
1693
  if (r <= lower_left_[i])
2,147,483,647 ✔
1694
    return r == lower_left_[i] ? 1 : 0;
17,093,103 ✔
1695
  if (r >= upper_right_[i])
2,147,483,647 ✔
1696
    return r == upper_right_[i] ? shape_[i] : shape_[i] + 1;
15,407,685 ✔
1697

1698
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647 ✔
1699
}
1700

1701
const std::string RegularMesh::mesh_type = "regular";
1702

1703
std::string RegularMesh::get_mesh_type() const
3,212 ✔
1704
{
1705
  return mesh_type;
3,212 ✔
1706
}
1707

1708
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,476,726,850 ✔
1709
{
1710
  return lower_left_[i] + ijk[i] * width_[i];
1,476,726,850 ✔
1711
}
1712

1713
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,425,922,145 ✔
1714
{
1715
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,425,922,145 ✔
1716
}
1717

1718
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647 ✔
1719
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1720
  double l) const
1721
{
1722
  MeshDistance d;
2,147,483,647 ✔
1723
  d.next_index = ijk[i];
2,147,483,647 ✔
1724
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647 ✔
1725
    return d;
11,709,444 ✔
1726

1727
  d.max_surface = (u[i] > 0);
2,147,483,647 ✔
1728
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647 ✔
1729
    d.next_index++;
1,473,591,109 ✔
1730
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,473,591,109 ✔
1731
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,444,221,710 ✔
1732
    d.next_index--;
1,422,786,404 ✔
1733
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,422,786,404 ✔
1734
  }
1735

1736
  return d;
2,147,483,647 ✔
1737
}
1738

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

1761
  // Get the coordinates of the mesh lines along both of the axes.
1762
  array<vector<double>, 2> axis_lines;
1763
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
48 ✔
1764
    int axis = axes[i_ax];
32 !
1765
    if (axis == -1)
32 !
1766
      continue;
×
1767
    auto& lines {axis_lines[i_ax]};
32 ✔
1768

1769
    double coord = lower_left_[axis];
32 ✔
1770
    for (int i = 0; i < shape_[axis] + 1; ++i) {
208 ✔
1771
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
176 !
1772
        lines.push_back(coord);
176 ✔
1773
      coord += width_[axis];
176 ✔
1774
    }
1775
  }
1776

1777
  return {axis_lines[0], axis_lines[1]};
32 ✔
1778
}
1779

1780
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,067 ✔
1781
{
1782
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,067 ✔
1783
  write_dataset(mesh_group, "lower_left", lower_left_);
2,067 ✔
1784
  write_dataset(mesh_group, "upper_right", upper_right_);
2,067 ✔
1785
  write_dataset(mesh_group, "width", width_);
2,067 ✔
1786
}
2,067 ✔
1787

1788
tensor::Tensor<double> RegularMesh::count_sites(
5,670 ✔
1789
  const SourceSite* bank, int64_t length, bool* outside) const
1790
{
1791
  // Determine shape of array for counts
1792
  std::size_t m = this->n_bins();
5,670 ✔
1793
  vector<std::size_t> shape = {m};
5,670 ✔
1794

1795
  // Create array of zeros
1796
  auto cnt = tensor::zeros<double>(shape);
5,670 ✔
1797
  bool outside_ = false;
1,446 ✔
1798

1799
  for (int64_t i = 0; i < length; i++) {
5,581,998 ✔
1800
    const auto& site = bank[i];
5,576,328 ✔
1801

1802
    // determine scoring bin for entropy mesh
1803
    int mesh_bin = get_bin(site.r);
5,576,328 ✔
1804

1805
    // if outside mesh, skip particle
1806
    if (mesh_bin < 0) {
5,576,328 !
1807
      outside_ = true;
×
1808
      continue;
×
1809
    }
1810

1811
    // Add to appropriate bin
1812
    cnt(mesh_bin) += site.wgt;
5,576,328 ✔
1813
  }
1814

1815
  // Create reduced count data
1816
  auto counts = tensor::zeros<double>(shape);
5,670 ✔
1817
  int total = cnt.size();
5,670 ✔
1818

1819
#ifdef OPENMC_MPI
1820
  // collect values from all processors
1821
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
1,446 ✔
1822

1823
  // Check if there were sites outside the mesh for any processor
1824
  if (outside) {
1,446 !
1825
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1,446 ✔
1826
  }
1827
#else
1828
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,224 ✔
1829
  if (outside)
4,224 !
1830
    *outside = outside_;
4,224 ✔
1831
#endif
1832

1833
  return counts;
5,670 ✔
1834
}
5,670 ✔
1835

1836
double RegularMesh::volume(const MeshIndex& ijk) const
907,527 ✔
1837
{
1838
  return element_volume_;
907,527 ✔
1839
}
1840

1841
//==============================================================================
1842
// RectilinearMesh implementation
1843
//==============================================================================
1844

1845
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
102 ✔
1846
{
1847
  n_dimension_ = 3;
102 ✔
1848

1849
  grid_[0] = get_node_array<double>(node, "x_grid");
102 ✔
1850
  grid_[1] = get_node_array<double>(node, "y_grid");
102 ✔
1851
  grid_[2] = get_node_array<double>(node, "z_grid");
102 ✔
1852

1853
  if (set_grid()) {
102 !
1854
    fatal_error(get_errmsg());
×
1855
  }
1856
}
102 ✔
1857

1858
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
8 ✔
1859
{
1860
  n_dimension_ = 3;
8 ✔
1861

1862
  read_dataset(group, "x_grid", grid_[0]);
8 ✔
1863
  read_dataset(group, "y_grid", grid_[1]);
8 ✔
1864
  read_dataset(group, "z_grid", grid_[2]);
8 ✔
1865

1866
  if (set_grid()) {
8 !
1867
    fatal_error(get_errmsg());
×
1868
  }
1869
}
8 ✔
1870

1871
const std::string RectilinearMesh::mesh_type = "rectilinear";
1872

1873
std::string RectilinearMesh::get_mesh_type() const
232 ✔
1874
{
1875
  return mesh_type;
232 ✔
1876
}
1877

1878
double RectilinearMesh::positive_grid_boundary(
19,069,960 ✔
1879
  const MeshIndex& ijk, int i) const
1880
{
1881
  return grid_[i][ijk[i]];
19,069,960 ✔
1882
}
1883

1884
double RectilinearMesh::negative_grid_boundary(
18,519,792 ✔
1885
  const MeshIndex& ijk, int i) const
1886
{
1887
  return grid_[i][ijk[i] - 1];
18,519,792 ✔
1888
}
1889

1890
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
38,529,320 ✔
1891
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1892
  double l) const
1893
{
1894
  MeshDistance d;
38,529,320 ✔
1895
  d.next_index = ijk[i];
38,529,320 ✔
1896
  if (std::abs(u[i]) < FP_PRECISION)
38,529,320 ✔
1897
    return d;
415,896 ✔
1898

1899
  d.max_surface = (u[i] > 0);
38,113,424 ✔
1900
  if (d.max_surface && (ijk[i] <= shape_[i])) {
38,113,424 ✔
1901
    d.next_index++;
19,069,960 ✔
1902
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
19,069,960 ✔
1903
  } else if (!d.max_surface && (ijk[i] > 0)) {
19,043,464 ✔
1904
    d.next_index--;
18,519,792 ✔
1905
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
18,519,792 ✔
1906
  }
1907
  return d;
38,113,424 ✔
1908
}
1909

1910
int RectilinearMesh::set_grid()
166 ✔
1911
{
1912
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
166 ✔
1913
    static_cast<int>(grid_[1].size()) - 1,
166 ✔
1914
    static_cast<int>(grid_[2].size()) - 1};
166 ✔
1915

1916
  for (const auto& g : grid_) {
664 ✔
1917
    if (g.size() < 2) {
498 !
1918
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1919
                 "must each have at least 2 points");
1920
      return OPENMC_E_INVALID_ARGUMENT;
×
1921
    }
1922
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
498 !
1923
        g.end()) {
498 !
1924
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1925
                 "rectilinear meshes must be sorted and unique.");
1926
      return OPENMC_E_INVALID_ARGUMENT;
×
1927
    }
1928
  }
1929

1930
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
166 ✔
1931
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
166 ✔
1932

1933
  return 0;
166 ✔
1934
}
1935

1936
int RectilinearMesh::get_index_in_direction(double r, int i) const
53,484,376 ✔
1937
{
1938
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
53,484,376 ✔
1939
}
1940

1941
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
8 ✔
1942
  Position plot_ll, Position plot_ur) const
1943
{
1944
  // Figure out which axes lie in the plane of the plot.
1945
  array<int, 2> axes {-1, -1};
8 ✔
1946
  if (plot_ur.z == plot_ll.z) {
8 !
1947
    axes = {0, 1};
×
1948
  } else if (plot_ur.y == plot_ll.y) {
8 !
1949
    axes = {0, 2};
8 ✔
1950
  } else if (plot_ur.x == plot_ll.x) {
×
1951
    axes = {1, 2};
×
1952
  } else {
1953
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1954
  }
1955

1956
  // Get the coordinates of the mesh lines along both of the axes.
1957
  array<vector<double>, 2> axis_lines;
1958
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
24 ✔
1959
    int axis = axes[i_ax];
16 ✔
1960
    vector<double>& lines {axis_lines[i_ax]};
16 ✔
1961

1962
    for (auto coord : grid_[axis]) {
80 ✔
1963
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
64 !
1964
        lines.push_back(coord);
64 ✔
1965
    }
1966
  }
1967

1968
  return {axis_lines[0], axis_lines[1]};
16 ✔
1969
}
1970

1971
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
96 ✔
1972
{
1973
  write_dataset(mesh_group, "x_grid", grid_[0]);
96 ✔
1974
  write_dataset(mesh_group, "y_grid", grid_[1]);
96 ✔
1975
  write_dataset(mesh_group, "z_grid", grid_[2]);
96 ✔
1976
}
96 ✔
1977

1978
double RectilinearMesh::volume(const MeshIndex& ijk) const
96 ✔
1979
{
1980
  double vol {1.0};
96 ✔
1981

1982
  for (int i = 0; i < n_dimension_; i++) {
384 ✔
1983
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
288 ✔
1984
  }
1985
  return vol;
96 ✔
1986
}
1987

1988
//==============================================================================
1989
// CylindricalMesh implementation
1990
//==============================================================================
1991

1992
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
298 ✔
1993
  : PeriodicStructuredMesh {node}
298 ✔
1994
{
1995
  n_dimension_ = 3;
298 ✔
1996
  grid_[0] = get_node_array<double>(node, "r_grid");
298 ✔
1997
  grid_[1] = get_node_array<double>(node, "phi_grid");
298 ✔
1998
  grid_[2] = get_node_array<double>(node, "z_grid");
298 ✔
1999
  origin_ = get_node_position(node, "origin");
298 ✔
2000

2001
  if (set_grid()) {
298 !
2002
    fatal_error(get_errmsg());
×
2003
  }
2004
}
298 ✔
2005

2006
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
8 ✔
2007
{
2008
  n_dimension_ = 3;
8 ✔
2009
  read_dataset(group, "r_grid", grid_[0]);
8 ✔
2010
  read_dataset(group, "phi_grid", grid_[1]);
8 ✔
2011
  read_dataset(group, "z_grid", grid_[2]);
8 ✔
2012
  read_dataset(group, "origin", origin_);
8 ✔
2013

2014
  if (set_grid()) {
8 !
2015
    fatal_error(get_errmsg());
×
2016
  }
2017
}
8 ✔
2018

2019
const std::string CylindricalMesh::mesh_type = "cylindrical";
2020

2021
std::string CylindricalMesh::get_mesh_type() const
376 ✔
2022
{
2023
  return mesh_type;
376 ✔
2024
}
2025

2026
std::array<const char*, 3> CylindricalMesh::axis_labels() const
470,208 ✔
2027
{
2028
  return {"r", "phi", "z"};
470,208 ✔
2029
}
2030

2031
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
34,667,408 ✔
2032
  Position r, bool& in_mesh) const
2033
{
2034
  r = local_coords(r);
34,667,408 ✔
2035

2036
  Position mapped_r;
34,667,408 ✔
2037
  mapped_r[0] = std::hypot(r.x, r.y);
34,667,408 ✔
2038
  mapped_r[2] = r[2];
34,667,408 ✔
2039

2040
  if (mapped_r[0] < FP_PRECISION) {
34,667,408 !
2041
    mapped_r[1] = 0.0;
2042
  } else {
2043
    mapped_r[1] = std::atan2(r.y, r.x);
34,667,408 ✔
2044
    if (mapped_r[1] < 0)
34,667,408 ✔
2045
      mapped_r[1] += 2 * PI;
17,348,768 ✔
2046
  }
2047

2048
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
34,667,408 ✔
2049

2050
  idx[1] = sanitize_phi(idx[1]);
34,667,408 ✔
2051

2052
  return idx;
34,667,408 ✔
2053
}
2054

2055
Position CylindricalMesh::sample_element(
64,080 ✔
2056
  const MeshIndex& ijk, uint64_t* seed) const
2057
{
2058
  double r_min = this->r(ijk[0] - 1);
64,080 ✔
2059
  double r_max = this->r(ijk[0]);
64,080 ✔
2060

2061
  double phi_min = this->phi(ijk[1] - 1);
64,080 ✔
2062
  double phi_max = this->phi(ijk[1]);
64,080 ✔
2063

2064
  double z_min = this->z(ijk[2] - 1);
64,080 ✔
2065
  double z_max = this->z(ijk[2]);
64,080 ✔
2066

2067
  double r_min_sq = r_min * r_min;
64,080 ✔
2068
  double r_max_sq = r_max * r_max;
64,080 ✔
2069
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
64,080 ✔
2070
  double phi = uniform_distribution(phi_min, phi_max, seed);
64,080 ✔
2071
  double z = uniform_distribution(z_min, z_max, seed);
64,080 ✔
2072

2073
  double x = r * std::cos(phi);
64,080 ✔
2074
  double y = r * std::sin(phi);
64,080 ✔
2075

2076
  return origin_ + Position(x, y, z);
64,080 ✔
2077
}
2078

2079
double CylindricalMesh::find_r_crossing(
103,575,718 ✔
2080
  const Position& r, const Direction& u, double l, int shell) const
2081
{
2082

2083
  if ((shell < 0) || (shell > shape_[0]))
103,575,718 !
2084
    return INFTY;
2085

2086
  // solve r.x^2 + r.y^2 == r0^2
2087
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
2088
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
2089

2090
  const double r0 = grid_[0][shell];
90,585,440 ✔
2091
  if (r0 == 0.0)
90,585,440 ✔
2092
    return INFTY;
2093

2094
  const double denominator = u.x * u.x + u.y * u.y;
85,395,896 ✔
2095

2096
  // Direction of flight is in z-direction. Will never intersect r.
2097
  if (std::abs(denominator) < FP_PRECISION)
85,395,896 ✔
2098
    return INFTY;
2099

2100
  // inverse of dominator to help the compiler to speed things up
2101
  const double inv_denominator = 1.0 / denominator;
85,353,016 ✔
2102

2103
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
85,353,016 ✔
2104
  double R = std::sqrt(r.x * r.x + r.y * r.y);
85,353,016 ✔
2105
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
85,353,016 ✔
2106

2107
  if (D < 0.0)
85,353,016 ✔
2108
    return INFTY;
2109

2110
  D = std::sqrt(D);
78,290,760 ✔
2111

2112
  // Particle is already on the shell surface; avoid spurious crossing
2113
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
78,290,760 ✔
2114
    return INFTY;
2115

2116
  // Check -p - D first because it is always smaller as -p + D
2117
  if (-p - D > l)
73,466,488 ✔
2118
    return -p - D;
2119
  if (-p + D > l)
58,782,657 ✔
2120
    return -p + D;
36,396,293 ✔
2121

2122
  return INFTY;
2123
}
2124

2125
double CylindricalMesh::find_phi_crossing(
54,034,160 ✔
2126
  const Position& r, const Direction& u, double l, int shell) const
2127
{
2128
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2129
  if (full_phi_ && (shape_[1] == 1))
54,034,160 ✔
2130
    return INFTY;
2131

2132
  shell = sanitize_phi(shell);
31,862,736 ✔
2133

2134
  const double p0 = grid_[1][shell];
31,862,736 ✔
2135

2136
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2137
  // => x(s) * cos(p0) = y(s) * sin(p0)
2138
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2139
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2140

2141
  const double c0 = std::cos(p0);
31,862,736 ✔
2142
  const double s0 = std::sin(p0);
31,862,736 ✔
2143

2144
  const double denominator = (u.x * s0 - u.y * c0);
31,862,736 ✔
2145

2146
  // Check if direction of flight is not parallel to phi surface
2147
  if (std::abs(denominator) > FP_PRECISION) {
31,862,736 ✔
2148
    const double s = -(r.x * s0 - r.y * c0) / denominator;
31,673,104 ✔
2149
    // Check if solution is in positive direction of flight and crosses the
2150
    // correct phi surface (not -phi)
2151
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
31,673,104 ✔
2152
      return s;
14,653,256 ✔
2153
  }
2154

2155
  return INFTY;
2156
}
2157

2158
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
26,632,880 ✔
2159
  const Position& r, const Direction& u, double l, int shell) const
2160
{
2161
  MeshDistance d;
26,632,880 ✔
2162
  d.next_index = shell;
26,632,880 ✔
2163

2164
  // Direction of flight is within xy-plane. Will never intersect z.
2165
  if (std::abs(u.z) < FP_PRECISION)
26,632,880 ✔
2166
    return d;
813,248 ✔
2167

2168
  d.max_surface = (u.z > 0.0);
25,819,632 ✔
2169
  if (d.max_surface && (shell <= shape_[2])) {
25,819,632 ✔
2170
    d.next_index += 1;
12,250,888 ✔
2171
    d.distance = (grid_[2][shell] - r.z) / u.z;
12,250,888 ✔
2172
  } else if (!d.max_surface && (shell > 0)) {
13,568,744 ✔
2173
    d.next_index -= 1;
12,226,344 ✔
2174
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
12,226,344 ✔
2175
  }
2176
  return d;
25,819,632 ✔
2177
}
2178

2179
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
105,437,819 ✔
2180
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2181
  double l) const
2182
{
2183
  if (i == 0) {
105,437,819 ✔
2184

2185
    return std::min(
103,575,718 ✔
2186
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
51,787,859 ✔
2187
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
103,575,718 ✔
2188

2189
  } else if (i == 1) {
53,649,960 ✔
2190

2191
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
27,017,080 ✔
2192
                      find_phi_crossing(r0, u, l, ijk[i])),
27,017,080 ✔
2193
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
27,017,080 ✔
2194
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
54,034,160 ✔
2195

2196
  } else {
2197
    return find_z_crossing(r0, u, l, ijk[i]);
26,632,880 ✔
2198
  }
2199
}
2200

2201
int CylindricalMesh::set_grid()
370 ✔
2202
{
2203
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
370 ✔
2204
    static_cast<int>(grid_[1].size()) - 1,
370 ✔
2205
    static_cast<int>(grid_[2].size()) - 1};
370 ✔
2206

2207
  for (const auto& g : grid_) {
1,480 ✔
2208
    if (g.size() < 2) {
1,110 !
2209
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2210
                 "must each have at least 2 points");
2211
      return OPENMC_E_INVALID_ARGUMENT;
×
2212
    }
2213
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,110 !
2214
        g.end()) {
1,110 !
2215
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2216
                 "cylindrical meshes must be sorted and unique.");
2217
      return OPENMC_E_INVALID_ARGUMENT;
×
2218
    }
2219
  }
2220
  if (grid_[0].front() < 0.0) {
370 !
2221
    set_errmsg("r-grid for "
×
2222
               "cylindrical meshes must start at r >= 0.");
2223
    return OPENMC_E_INVALID_ARGUMENT;
×
2224
  }
2225
  if (grid_[1].front() < 0.0) {
370 !
2226
    set_errmsg("phi-grid for "
×
2227
               "cylindrical meshes must start at phi >= 0.");
2228
    return OPENMC_E_INVALID_ARGUMENT;
×
2229
  }
2230
  if (grid_[1].back() > 2.0 * PI) {
370 !
2231
    set_errmsg("phi-grids for "
×
2232
               "cylindrical meshes must end with theta <= 2*pi.");
2233

2234
    return OPENMC_E_INVALID_ARGUMENT;
×
2235
  }
2236

2237
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
370 !
2238

2239
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
370 ✔
2240
    origin_[2] + grid_[2].front()};
370 ✔
2241
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
370 ✔
2242
    origin_[2] + grid_[2].back()};
370 ✔
2243

2244
  return 0;
370 ✔
2245
}
2246

2247
int CylindricalMesh::get_index_in_direction(double r, int i) const
104,002,224 ✔
2248
{
2249
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
104,002,224 ✔
2250
}
2251

2252
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2253
  Position plot_ll, Position plot_ur) const
2254
{
2255
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2256

2257
  // Figure out which axes lie in the plane of the plot.
2258
  array<vector<double>, 2> axis_lines;
2259
  return {axis_lines[0], axis_lines[1]};
2260
}
2261

2262
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
288 ✔
2263
{
2264
  write_dataset(mesh_group, "r_grid", grid_[0]);
288 ✔
2265
  write_dataset(mesh_group, "phi_grid", grid_[1]);
288 ✔
2266
  write_dataset(mesh_group, "z_grid", grid_[2]);
288 ✔
2267
  write_dataset(mesh_group, "origin", origin_);
288 ✔
2268
}
288 ✔
2269

2270
double CylindricalMesh::volume(const MeshIndex& ijk) const
576 ✔
2271
{
2272
  double r_i = grid_[0][ijk[0] - 1];
576 ✔
2273
  double r_o = grid_[0][ijk[0]];
576 ✔
2274

2275
  double phi_i = grid_[1][ijk[1] - 1];
576 ✔
2276
  double phi_o = grid_[1][ijk[1]];
576 ✔
2277

2278
  double z_i = grid_[2][ijk[2] - 1];
576 ✔
2279
  double z_o = grid_[2][ijk[2]];
576 ✔
2280

2281
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
576 ✔
2282
}
2283

2284
//==============================================================================
2285
// SphericalMesh implementation
2286
//==============================================================================
2287

2288
SphericalMesh::SphericalMesh(pugi::xml_node node)
266 ✔
2289
  : PeriodicStructuredMesh {node}
266 ✔
2290
{
2291
  n_dimension_ = 3;
266 ✔
2292

2293
  grid_[0] = get_node_array<double>(node, "r_grid");
266 ✔
2294
  grid_[1] = get_node_array<double>(node, "theta_grid");
266 ✔
2295
  grid_[2] = get_node_array<double>(node, "phi_grid");
266 ✔
2296
  origin_ = get_node_position(node, "origin");
266 ✔
2297

2298
  if (set_grid()) {
266 !
2299
    fatal_error(get_errmsg());
×
2300
  }
2301
}
266 ✔
2302

2303
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
8 ✔
2304
{
2305
  n_dimension_ = 3;
8 ✔
2306

2307
  read_dataset(group, "r_grid", grid_[0]);
8 ✔
2308
  read_dataset(group, "theta_grid", grid_[1]);
8 ✔
2309
  read_dataset(group, "phi_grid", grid_[2]);
8 ✔
2310
  read_dataset(group, "origin", origin_);
8 ✔
2311

2312
  if (set_grid()) {
8 !
2313
    fatal_error(get_errmsg());
×
2314
  }
2315
}
8 ✔
2316

2317
const std::string SphericalMesh::mesh_type = "spherical";
2318

2319
std::string SphericalMesh::get_mesh_type() const
304 ✔
2320
{
2321
  return mesh_type;
304 ✔
2322
}
2323

2324
std::array<const char*, 3> SphericalMesh::axis_labels() const
235,200 ✔
2325
{
2326
  return {"r", "theta", "phi"};
235,200 ✔
2327
}
2328

2329
StructuredMesh::MeshIndex SphericalMesh::get_indices(
49,838,688 ✔
2330
  Position r, bool& in_mesh) const
2331
{
2332
  r = local_coords(r);
49,838,688 ✔
2333

2334
  Position mapped_r;
49,838,688 ✔
2335
  mapped_r[0] = r.norm();
49,838,688 ✔
2336

2337
  if (mapped_r[0] < FP_PRECISION) {
49,838,688 !
2338
    mapped_r[1] = 0.0;
2339
    mapped_r[2] = 0.0;
2340
  } else {
2341
    mapped_r[1] = std::acos(r.z / mapped_r.x);
49,838,688 ✔
2342
    mapped_r[2] = std::atan2(r.y, r.x);
49,838,688 ✔
2343
    if (mapped_r[2] < 0)
49,838,688 ✔
2344
      mapped_r[2] += 2 * PI;
24,908,400 ✔
2345
  }
2346

2347
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
49,838,688 ✔
2348

2349
  idx[1] = sanitize_theta(idx[1]);
49,838,688 ✔
2350
  idx[2] = sanitize_phi(idx[2]);
49,838,688 ✔
2351

2352
  return idx;
49,838,688 ✔
2353
}
2354

2355
Position SphericalMesh::sample_element(
80 ✔
2356
  const MeshIndex& ijk, uint64_t* seed) const
2357
{
2358
  double r_min = this->r(ijk[0] - 1);
80 ✔
2359
  double r_max = this->r(ijk[0]);
80 ✔
2360

2361
  double theta_min = this->theta(ijk[1] - 1);
80 ✔
2362
  double theta_max = this->theta(ijk[1]);
80 ✔
2363

2364
  double phi_min = this->phi(ijk[2] - 1);
80 ✔
2365
  double phi_max = this->phi(ijk[2]);
80 ✔
2366

2367
  double cos_theta =
80 ✔
2368
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
80 ✔
2369
  double sin_theta = std::sin(std::acos(cos_theta));
80 ✔
2370
  double phi = uniform_distribution(phi_min, phi_max, seed);
80 ✔
2371
  double r_min_cub = std::pow(r_min, 3);
80 ✔
2372
  double r_max_cub = std::pow(r_max, 3);
80 ✔
2373
  // might be faster to do rejection here?
2374
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
80 ✔
2375

2376
  double x = r * std::cos(phi) * sin_theta;
80 ✔
2377
  double y = r * std::sin(phi) * sin_theta;
80 ✔
2378
  double z = r * cos_theta;
80 ✔
2379

2380
  return origin_ + Position(x, y, z);
80 ✔
2381
}
2382

2383
double SphericalMesh::find_r_crossing(
322,799,102 ✔
2384
  const Position& r, const Direction& u, double l, int shell) const
2385
{
2386
  if ((shell < 0) || (shell > shape_[0]))
322,799,102 ✔
2387
    return INFTY;
2388

2389
  // solve |r+s*u| = r0
2390
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2391
  const double r0 = grid_[0][shell];
294,026,830 ✔
2392
  if (r0 == 0.0)
294,026,830 ✔
2393
    return INFTY;
2394
  const double p = r.dot(u);
288,442,350 ✔
2395
  double R = r.norm();
288,442,350 ✔
2396
  double D = p * p - (R - r0) * (R + r0);
288,442,350 ✔
2397

2398
  // Particle is already on the shell surface; avoid spurious crossing
2399
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
288,442,350 ✔
2400
    return INFTY;
2401

2402
  if (D >= 0.0) {
280,654,238 ✔
2403
    D = std::sqrt(D);
260,408,982 ✔
2404
    // Check -p - D first because it is always smaller as -p + D
2405
    if (-p - D > l)
260,408,982 ✔
2406
      return -p - D;
2407
    if (-p + D > l)
213,639,506 ✔
2408
      return -p + D;
128,898,023 ✔
2409
  }
2410

2411
  return INFTY;
2412
}
2413

2414
double SphericalMesh::find_theta_crossing(
80,018,896 ✔
2415
  const Position& r, const Direction& u, double l, int shell) const
2416
{
2417
  // Theta grid is [0, π], thus there is no real surface to cross
2418
  if (full_theta_ && (shape_[1] == 1))
80,018,896 ✔
2419
    return INFTY;
2420

2421
  shell = sanitize_theta(shell);
27,798,656 ✔
2422

2423
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2424
  // yields
2425
  // a*s^2 + 2*b*s + c == 0 with
2426
  // a = cos(theta)^2 - u.z * u.z
2427
  // b = r*u * cos(theta)^2 - u.z * r.z
2428
  // c = r*r * cos(theta)^2 - r.z^2
2429

2430
  const double cos_t = std::cos(grid_[1][shell]);
27,798,656 ✔
2431
  const bool sgn = std::signbit(cos_t);
27,798,656 ✔
2432
  const double cos_t_2 = cos_t * cos_t;
27,798,656 ✔
2433

2434
  const double a = cos_t_2 - u.z * u.z;
27,798,656 ✔
2435
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
27,798,656 ✔
2436
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
27,798,656 ✔
2437

2438
  // if factor of s^2 is zero, direction of flight is parallel to theta
2439
  // surface
2440
  if (std::abs(a) < FP_PRECISION) {
27,798,656 ✔
2441
    // if b vanishes, direction of flight is within theta surface and crossing
2442
    // is not possible
2443
    if (std::abs(b) < FP_PRECISION)
350,944 !
2444
      return INFTY;
2445

2446
    const double s = -0.5 * c / b;
×
2447
    // Check if solution is in positive direction of flight and has correct
2448
    // sign
2449
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2450
      return s;
×
2451

2452
    // no crossing is possible
2453
    return INFTY;
2454
  }
2455

2456
  const double p = b / a;
27,447,712 ✔
2457
  double D = p * p - c / a;
27,447,712 ✔
2458

2459
  if (D < 0.0)
27,447,712 ✔
2460
    return INFTY;
2461

2462
  D = std::sqrt(D);
19,507,968 ✔
2463

2464
  // the solution -p-D is always smaller as -p+D : Check this one first
2465
  double s = -p - D;
19,507,968 ✔
2466
  // Check if solution is in positive direction of flight and has correct sign
2467
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
19,507,968 ✔
2468
    return s;
2469

2470
  s = -p + D;
15,683,208 ✔
2471
  // Check if solution is in positive direction of flight and has correct sign
2472
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
15,683,208 ✔
2473
    return s;
7,365,712 ✔
2474

2475
  return INFTY;
2476
}
2477

2478
double SphericalMesh::find_phi_crossing(
81,163,568 ✔
2479
  const Position& r, const Direction& u, double l, int shell) const
2480
{
2481
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2482
  if (full_phi_ && (shape_[2] == 1))
81,163,568 ✔
2483
    return INFTY;
2484

2485
  shell = sanitize_phi(shell);
28,943,328 ✔
2486

2487
  const double p0 = grid_[2][shell];
28,943,328 ✔
2488

2489
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2490
  // => x(s) * cos(p0) = y(s) * sin(p0)
2491
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2492
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2493

2494
  const double c0 = std::cos(p0);
28,943,328 ✔
2495
  const double s0 = std::sin(p0);
28,943,328 ✔
2496

2497
  const double denominator = (u.x * s0 - u.y * c0);
28,943,328 ✔
2498

2499
  // Check if direction of flight is not parallel to phi surface
2500
  if (std::abs(denominator) > FP_PRECISION) {
28,943,328 ✔
2501
    const double s = -(r.x * s0 - r.y * c0) / denominator;
28,773,152 ✔
2502
    // Check if solution is in positive direction of flight and crosses the
2503
    // correct phi surface (not -phi)
2504
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
28,773,152 ✔
2505
      return s;
12,736,320 ✔
2506
  }
2507

2508
  return INFTY;
2509
}
2510

2511
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
241,990,783 ✔
2512
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2513
  double l) const
2514
{
2515

2516
  if (i == 0) {
241,990,783 ✔
2517
    return std::min(
322,799,102 ✔
2518
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
161,399,551 ✔
2519
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
322,799,102 ✔
2520

2521
  } else if (i == 1) {
80,591,232 ✔
2522
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
40,009,448 ✔
2523
                      find_theta_crossing(r0, u, l, ijk[i])),
40,009,448 ✔
2524
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
40,009,448 ✔
2525
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
80,018,896 ✔
2526

2527
  } else {
2528
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
40,581,784 ✔
2529
                      find_phi_crossing(r0, u, l, ijk[i])),
40,581,784 ✔
2530
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
40,581,784 ✔
2531
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
81,163,568 ✔
2532
  }
2533
}
2534

2535
int SphericalMesh::set_grid()
338 ✔
2536
{
2537
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
338 ✔
2538
    static_cast<int>(grid_[1].size()) - 1,
338 ✔
2539
    static_cast<int>(grid_[2].size()) - 1};
338 ✔
2540

2541
  for (const auto& g : grid_) {
1,352 ✔
2542
    if (g.size() < 2) {
1,014 !
2543
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2544
                 "must each have at least 2 points");
2545
      return OPENMC_E_INVALID_ARGUMENT;
×
2546
    }
2547
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,014 !
2548
        g.end()) {
1,014 !
2549
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2550
                 "spherical meshes must be sorted and unique.");
2551
      return OPENMC_E_INVALID_ARGUMENT;
×
2552
    }
2553
    if (g.front() < 0.0) {
1,014 !
2554
      set_errmsg("r-, theta-, and phi- grids for "
×
2555
                 "spherical meshes must start at v >= 0.");
2556
      return OPENMC_E_INVALID_ARGUMENT;
×
2557
    }
2558
  }
2559
  if (grid_[1].back() > PI) {
338 !
2560
    set_errmsg("theta-grids for "
×
2561
               "spherical meshes must end with theta <= pi.");
2562

2563
    return OPENMC_E_INVALID_ARGUMENT;
×
2564
  }
2565
  if (grid_[2].back() > 2 * PI) {
338 !
2566
    set_errmsg("phi-grids for "
×
2567
               "spherical meshes must end with phi <= 2*pi.");
2568
    return OPENMC_E_INVALID_ARGUMENT;
×
2569
  }
2570

2571
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
338 !
2572
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
338 ✔
2573

2574
  double r = grid_[0].back();
338 ✔
2575
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
338 ✔
2576
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
338 ✔
2577

2578
  return 0;
338 ✔
2579
}
2580

2581
int SphericalMesh::get_index_in_direction(double r, int i) const
149,516,064 ✔
2582
{
2583
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
149,516,064 ✔
2584
}
2585

2586
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2587
  Position plot_ll, Position plot_ur) const
2588
{
2589
  fatal_error("Plot of spherical Mesh not implemented");
×
2590

2591
  // Figure out which axes lie in the plane of the plot.
2592
  array<vector<double>, 2> axis_lines;
2593
  return {axis_lines[0], axis_lines[1]};
2594
}
2595

2596
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
248 ✔
2597
{
2598
  write_dataset(mesh_group, "r_grid", grid_[0]);
248 ✔
2599
  write_dataset(mesh_group, "theta_grid", grid_[1]);
248 ✔
2600
  write_dataset(mesh_group, "phi_grid", grid_[2]);
248 ✔
2601
  write_dataset(mesh_group, "origin", origin_);
248 ✔
2602
}
248 ✔
2603

2604
double SphericalMesh::volume(const MeshIndex& ijk) const
680 ✔
2605
{
2606
  double r_i = grid_[0][ijk[0] - 1];
680 ✔
2607
  double r_o = grid_[0][ijk[0]];
680 ✔
2608

2609
  double theta_i = grid_[1][ijk[1] - 1];
680 ✔
2610
  double theta_o = grid_[1][ijk[1]];
680 ✔
2611

2612
  double phi_i = grid_[2][ijk[2] - 1];
680 ✔
2613
  double phi_o = grid_[2][ijk[2]];
680 ✔
2614

2615
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,360 ✔
2616
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
680 ✔
2617
}
2618

2619
//==============================================================================
2620
// Helper functions for the C API
2621
//==============================================================================
2622

2623
int check_mesh(int32_t index)
6,516 ✔
2624
{
2625
  if (index < 0 || index >= model::meshes.size()) {
6,516 !
2626
    set_errmsg("Index in meshes array is out of bounds.");
×
2627
    return OPENMC_E_OUT_OF_BOUNDS;
×
2628
  }
2629
  return 0;
2630
}
2631

2632
template<class T>
2633
int check_mesh_type(int32_t index)
1,064 ✔
2634
{
2635
  if (int err = check_mesh(index))
1,064 !
2636
    return err;
2637

2638
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,064 !
2639
  if (!mesh) {
1,064 !
2640
    set_errmsg("This function is not valid for input mesh.");
×
2641
    return OPENMC_E_INVALID_TYPE;
×
2642
  }
2643
  return 0;
2644
}
2645

2646
template<class T>
2647
bool is_mesh_type(int32_t index)
2648
{
2649
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2650
  return mesh;
2651
}
2652

2653
//==============================================================================
2654
// C API functions
2655
//==============================================================================
2656

2657
// Return the type of mesh as a C string
2658
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,429 ✔
2659
{
2660
  if (int err = check_mesh(index))
1,429 !
2661
    return err;
2662

2663
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,429 ✔
2664

2665
  return 0;
1,429 ✔
2666
}
2667

2668
//! Extend the meshes array by n elements
2669
extern "C" int openmc_extend_meshes(
304 ✔
2670
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2671
{
2672
  if (index_start)
304 !
2673
    *index_start = model::meshes.size();
304 ✔
2674
  std::string mesh_type;
304 ✔
2675

2676
  for (int i = 0; i < n; ++i) {
608 ✔
2677
    if (RegularMesh::mesh_type == type) {
304 ✔
2678
      model::meshes.push_back(make_unique<RegularMesh>());
184 ✔
2679
    } else if (RectilinearMesh::mesh_type == type) {
120 ✔
2680
      model::meshes.push_back(make_unique<RectilinearMesh>());
56 ✔
2681
    } else if (CylindricalMesh::mesh_type == type) {
64 ✔
2682
      model::meshes.push_back(make_unique<CylindricalMesh>());
32 ✔
2683
    } else if (SphericalMesh::mesh_type == type) {
32 !
2684
      model::meshes.push_back(make_unique<SphericalMesh>());
32 ✔
2685
    } else {
2686
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2687
    }
2688
  }
2689
  if (index_end)
304 !
2690
    *index_end = model::meshes.size() - 1;
×
2691

2692
  return 0;
304 ✔
2693
}
304 ✔
2694

2695
//! Adds a new unstructured mesh to OpenMC with all supported properties
2696
extern "C" int openmc_add_unstructured_mesh(const char filename[],
2 ✔
2697
  const char library[], double length_multiplier, const char options[],
2698
  int32_t id, int32_t* index)
2699
{
2700
  std::string lib_name(library);
2 ✔
2701
  std::string mesh_file(filename);
2 !
2702
  std::string mesh_options(options ? options : "");
4 !
2703
  bool valid_lib = false;
2 ✔
2704

2705
#ifdef OPENMC_DAGMC_ENABLED
2706
  if (lib_name == MOABMesh::mesh_lib_type) {
2 ✔
2707
    model::meshes.push_back(
1 ✔
2708
      make_unique<MOABMesh>(mesh_file, length_multiplier, mesh_options));
2 ✔
2709
    valid_lib = true;
1 ✔
2710
  }
2711
#endif
2712

2713
#ifdef OPENMC_LIBMESH_ENABLED
2714
  if (lib_name == LibMesh::mesh_lib_type) {
2 ✔
2715
    model::meshes.push_back(
1 ✔
2716
      make_unique<LibMesh>(mesh_file, length_multiplier, mesh_options));
2 ✔
2717
    valid_lib = true;
1 ✔
2718
  }
2719
#endif
2720

2721
  if (!valid_lib) {
2 !
2722
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2723
                           "by this build of OpenMC",
2724
      lib_name));
2725
    return OPENMC_E_INVALID_ARGUMENT;
×
2726
  }
2727

2728
  model::meshes.back()->set_id(id);
2 ✔
2729
  *index = model::meshes.size() - 1;
2 ✔
2730

2731
  return 0;
2 ✔
2732
}
2 ✔
2733

2734
//! Return the index in the meshes array of a mesh with a given ID
2735
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
476 ✔
2736
{
2737
  auto pair = model::mesh_map.find(id);
476 ✔
2738
  if (pair == model::mesh_map.end()) {
476 ✔
2739
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
144 ✔
2740
    return OPENMC_E_INVALID_ID;
72 ✔
2741
  }
2742
  *index = pair->second;
404 ✔
2743
  return 0;
404 ✔
2744
}
2745

2746
//! Return the ID of a mesh
2747
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,673 ✔
2748
{
2749
  if (int err = check_mesh(index))
2,673 !
2750
    return err;
2751
  *id = model::meshes[index]->id_;
2,673 ✔
2752
  return 0;
2,673 ✔
2753
}
2754

2755
//! Set the ID of a mesh
2756
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
304 ✔
2757
{
2758
  if (int err = check_mesh(index))
304 !
2759
    return err;
2760
  model::meshes[index]->set_id(id);
304 ✔
2761
  return 0;
304 ✔
2762
}
2763

2764
//! Return the name of a mesh
2765
extern "C" int openmc_mesh_get_name(int32_t index, const char** name)
40 ✔
2766
{
2767
  if (int err = check_mesh(index))
40 !
2768
    return err;
2769
  *name = model::meshes[index]->name().c_str();
40 ✔
2770
  return 0;
40 ✔
2771
}
2772

2773
//! Set the name of a mesh
2774
extern "C" int openmc_mesh_set_name(int32_t index, const char* name)
82 ✔
2775
{
2776
  if (int err = check_mesh(index))
82 !
2777
    return err;
2778
  model::meshes[index]->set_name(name);
164 ✔
2779
  return 0;
82 ✔
2780
}
2781

2782
//! Get the number of elements in a mesh
2783
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
433 ✔
2784
{
2785
  if (int err = check_mesh(index))
433 !
2786
    return err;
2787
  *n = model::meshes[index]->n_bins();
433 ✔
2788
  return 0;
433 ✔
2789
}
2790

2791
//! Get the volume of each element in the mesh
2792
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
64 ✔
2793
{
2794
  if (int err = check_mesh(index))
64 !
2795
    return err;
2796
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
704 ✔
2797
    volumes[i] = model::meshes[index]->volume(i);
640 ✔
2798
  }
2799
  return 0;
2800
}
2801

2802
//! Get the bounding box of a mesh
2803
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
130 ✔
2804
{
2805
  if (int err = check_mesh(index))
130 !
2806
    return err;
2807

2808
  BoundingBox bbox = model::meshes[index]->bounding_box();
130 ✔
2809

2810
  // set lower left corner values
2811
  ll[0] = bbox.min.x;
130 ✔
2812
  ll[1] = bbox.min.y;
130 ✔
2813
  ll[2] = bbox.min.z;
130 ✔
2814

2815
  // set upper right corner values
2816
  ur[0] = bbox.max.x;
130 ✔
2817
  ur[1] = bbox.max.y;
130 ✔
2818
  ur[2] = bbox.max.z;
130 ✔
2819
  return 0;
130 ✔
2820
}
2821

2822
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
169 ✔
2823
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2824
{
2825
  if (int err = check_mesh(index))
169 !
2826
    return err;
2827

2828
  try {
169 ✔
2829
    model::meshes[index]->material_volumes(
169 ✔
2830
      nx, ny, nz, table_size, materials, volumes, bboxes);
2831
  } catch (const std::exception& e) {
×
2832
    set_errmsg(e.what());
×
2833
    if (starts_with(e.what(), "Mesh")) {
×
2834
      return OPENMC_E_GEOMETRY;
2835
    } else {
2836
      return OPENMC_E_ALLOCATE;
×
2837
    }
2838
  }
×
2839

2840
  return 0;
2841
}
2842

2843
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
32 ✔
2844
  Position width, int basis, int* pixels, int32_t* data)
2845
{
2846
  if (int err = check_mesh(index))
32 !
2847
    return err;
2848
  const auto& mesh = model::meshes[index].get();
32 !
2849

2850
  int pixel_width = pixels[0];
32 ✔
2851
  int pixel_height = pixels[1];
32 ✔
2852

2853
  // get pixel size
2854
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
32 ✔
2855
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
32 ✔
2856

2857
  // setup basis indices and initial position centered on pixel
2858
  int in_i, out_i;
32 ✔
2859
  Position xyz = origin;
32 ✔
2860
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
32 ✔
2861
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
32 ✔
2862
  switch (basis_enum) {
32 !
2863
  case PlotBasis::xy:
2864
    in_i = 0;
2865
    out_i = 1;
2866
    break;
2867
  case PlotBasis::xz:
2868
    in_i = 0;
2869
    out_i = 2;
2870
    break;
2871
  case PlotBasis::yz:
2872
    in_i = 1;
2873
    out_i = 2;
2874
    break;
2875
  default:
×
2876
    UNREACHABLE();
×
2877
  }
2878

2879
  // set initial position
2880
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
32 ✔
2881
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
32 ✔
2882

2883
#pragma omp parallel
12 ✔
2884
  {
20 ✔
2885
    Position r = xyz;
20 ✔
2886

2887
#pragma omp for
2888
    for (int y = 0; y < pixel_height; y++) {
420 ✔
2889
      r[out_i] = xyz[out_i] - out_pixel * y;
400 ✔
2890
      for (int x = 0; x < pixel_width; x++) {
8,400 ✔
2891
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000 ✔
2892
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000 ✔
2893
      }
2894
    }
2895
  }
2896

2897
  return 0;
32 ✔
2898
}
2899

2900
//! Get the dimension of a regular mesh
2901
extern "C" int openmc_regular_mesh_get_dimension(
16 ✔
2902
  int32_t index, int** dims, int* n)
2903
{
2904
  if (int err = check_mesh_type<RegularMesh>(index))
16 !
2905
    return err;
2906
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
16 !
2907
  *dims = mesh->shape_.data();
16 ✔
2908
  *n = mesh->n_dimension_;
16 ✔
2909
  return 0;
16 ✔
2910
}
2911

2912
//! Set the dimension of a regular mesh
2913
extern "C" int openmc_regular_mesh_set_dimension(
200 ✔
2914
  int32_t index, int n, const int* dims)
2915
{
2916
  if (int err = check_mesh_type<RegularMesh>(index))
200 !
2917
    return err;
2918
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
200 !
2919

2920
  // Copy dimension
2921
  mesh->n_dimension_ = n;
200 ✔
2922
  std::copy(dims, dims + n, mesh->shape_.begin());
200 ✔
2923
  return 0;
200 ✔
2924
}
2925

2926
//! Get the regular mesh parameters
2927
extern "C" int openmc_regular_mesh_get_params(
168 ✔
2928
  int32_t index, double** ll, double** ur, double** width, int* n)
2929
{
2930
  if (int err = check_mesh_type<RegularMesh>(index))
168 !
2931
    return err;
2932
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
168 !
2933

2934
  if (m->lower_left_.empty()) {
168 !
2935
    set_errmsg("Mesh parameters have not been set.");
×
2936
    return OPENMC_E_ALLOCATE;
×
2937
  }
2938

2939
  *ll = m->lower_left_.data();
168 ✔
2940
  *ur = m->upper_right_.data();
168 ✔
2941
  *width = m->width_.data();
168 ✔
2942
  *n = m->n_dimension_;
168 ✔
2943
  return 0;
168 ✔
2944
}
2945

2946
//! Set the regular mesh parameters
2947
extern "C" int openmc_regular_mesh_set_params(
224 ✔
2948
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2949
{
2950
  if (int err = check_mesh_type<RegularMesh>(index))
224 !
2951
    return err;
2952
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
224 !
2953

2954
  if (m->n_dimension_ == -1) {
224 !
2955
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2956
    return OPENMC_E_UNASSIGNED;
×
2957
  }
2958

2959
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
224 ✔
2960
  if (ll && ur) {
224 ✔
2961
    m->lower_left_ = tensor::Tensor<double>(ll, n);
208 ✔
2962
    m->upper_right_ = tensor::Tensor<double>(ur, n);
208 ✔
2963
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
832 ✔
2964
  } else if (ll && width) {
16 ✔
2965
    m->lower_left_ = tensor::Tensor<double>(ll, n);
8 ✔
2966
    m->width_ = tensor::Tensor<double>(width, n);
8 ✔
2967
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
32 ✔
2968
  } else if (ur && width) {
8 !
2969
    m->upper_right_ = tensor::Tensor<double>(ur, n);
8 ✔
2970
    m->width_ = tensor::Tensor<double>(width, n);
8 ✔
2971
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
32 ✔
2972
  } else {
2973
    set_errmsg("At least two parameters must be specified.");
×
2974
    return OPENMC_E_INVALID_ARGUMENT;
2975
  }
2976

2977
  // Set material volumes
2978

2979
  // TODO: incorporate this into method in RegularMesh that can be called from
2980
  // here and from constructor
2981
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
224 ✔
2982
  m->element_volume_ = 1.0;
224 ✔
2983
  for (int i = 0; i < m->n_dimension_; i++) {
880 ✔
2984
    m->element_volume_ *= m->width_[i];
656 ✔
2985
  }
2986

2987
  return 0;
2988
}
224 ✔
2989

2990
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2991
template<class C>
2992
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
120 ✔
2993
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2994
  const int nz)
2995
{
2996
  if (int err = check_mesh_type<C>(index))
120 !
2997
    return err;
2998

2999
  C* m = dynamic_cast<C*>(model::meshes[index].get());
120 !
3000

3001
  m->n_dimension_ = 3;
120 ✔
3002

3003
  m->grid_[0].reserve(nx);
120 ✔
3004
  m->grid_[1].reserve(ny);
120 ✔
3005
  m->grid_[2].reserve(nz);
120 ✔
3006

3007
  for (int i = 0; i < nx; i++) {
832 ✔
3008
    m->grid_[0].push_back(grid_x[i]);
712 ✔
3009
  }
3010
  for (int i = 0; i < ny; i++) {
528 ✔
3011
    m->grid_[1].push_back(grid_y[i]);
408 ✔
3012
  }
3013
  for (int i = 0; i < nz; i++) {
488 ✔
3014
    m->grid_[2].push_back(grid_z[i]);
368 ✔
3015
  }
3016

3017
  int err = m->set_grid();
120 ✔
3018
  return err;
120 ✔
3019
}
3020

3021
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
3022
template<class C>
3023
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
336 ✔
3024
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3025
{
3026
  if (int err = check_mesh_type<C>(index))
336 !
3027
    return err;
3028
  C* m = dynamic_cast<C*>(model::meshes[index].get());
336 !
3029

3030
  if (m->lower_left_.empty()) {
336 !
3031
    set_errmsg("Mesh parameters have not been set.");
×
3032
    return OPENMC_E_ALLOCATE;
×
3033
  }
3034

3035
  *grid_x = m->grid_[0].data();
336 ✔
3036
  *nx = m->grid_[0].size();
336 ✔
3037
  *grid_y = m->grid_[1].data();
336 ✔
3038
  *ny = m->grid_[1].size();
336 ✔
3039
  *grid_z = m->grid_[2].data();
336 ✔
3040
  *nz = m->grid_[2].size();
336 ✔
3041

3042
  return 0;
336 ✔
3043
}
3044

3045
//! Get the rectilinear mesh grid
3046
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
128 ✔
3047
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3048
{
3049
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
128 ✔
3050
    index, grid_x, nx, grid_y, ny, grid_z, nz);
128 ✔
3051
}
3052

3053
//! Set the rectilienar mesh parameters
3054
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
56 ✔
3055
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3056
  const double* grid_z, const int nz)
3057
{
3058
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
56 ✔
3059
    index, grid_x, nx, grid_y, ny, grid_z, nz);
56 ✔
3060
}
3061

3062
//! Get the cylindrical mesh grid
3063
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
104 ✔
3064
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3065
{
3066
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
104 ✔
3067
    index, grid_x, nx, grid_y, ny, grid_z, nz);
104 ✔
3068
}
3069

3070
//! Set the cylindrical mesh parameters
3071
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
32 ✔
3072
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3073
  const double* grid_z, const int nz)
3074
{
3075
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
32 ✔
3076
    index, grid_x, nx, grid_y, ny, grid_z, nz);
32 ✔
3077
}
3078

3079
//! Get the spherical mesh grid
3080
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
104 ✔
3081
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3082
{
3083

3084
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
104 ✔
3085
    index, grid_x, nx, grid_y, ny, grid_z, nz);
104 ✔
3086
  ;
104 ✔
3087
}
3088

3089
//! Set the spherical mesh parameters
3090
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
32 ✔
3091
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3092
  const double* grid_z, const int nz)
3093
{
3094
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
32 ✔
3095
    index, grid_x, nx, grid_y, ny, grid_z, nz);
32 ✔
3096
}
3097

3098
template<class T>
3099
int openmc_periodic_mesh_get_origin_impl(int32_t index, double origin[3])
32 ✔
3100
{
3101
  if (int err = check_mesh(index))
32 !
3102
    return err;
3103
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
32 !
3104
  if (!mesh) {
32 !
3105
    set_errmsg("This mesh is not of the expected type.");
×
3106
    return OPENMC_E_INVALID_TYPE;
×
3107
  }
3108
  const auto& mesh_origin = mesh->origin();
32 ✔
3109
  origin[0] = mesh_origin.x;
32 ✔
3110
  origin[1] = mesh_origin.y;
32 ✔
3111
  origin[2] = mesh_origin.z;
32 ✔
3112
  return 0;
32 ✔
3113
}
3114

3115
template<class T>
3116
int openmc_periodic_mesh_set_origin_impl(int32_t index, const double origin[3])
64 ✔
3117
{
3118
  if (int err = check_mesh(index))
64 !
3119
    return err;
3120
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
64 !
3121
  if (!mesh) {
64 !
3122
    set_errmsg("This mesh is not of the expected type.");
×
3123
    return OPENMC_E_INVALID_TYPE;
×
3124
  }
3125
  return mesh->set_origin({origin[0], origin[1], origin[2]});
64 ✔
3126
}
3127

3128
extern "C" int openmc_cylindrical_mesh_get_origin(
16 ✔
3129
  int32_t index, double origin[3])
3130
{
3131
  return openmc_periodic_mesh_get_origin_impl<CylindricalMesh>(index, origin);
16 ✔
3132
}
3133

3134
extern "C" int openmc_cylindrical_mesh_set_origin(
32 ✔
3135
  int32_t index, const double origin[3])
3136
{
3137
  return openmc_periodic_mesh_set_origin_impl<CylindricalMesh>(index, origin);
32 ✔
3138
}
3139

3140
extern "C" int openmc_spherical_mesh_get_origin(int32_t index, double origin[3])
16 ✔
3141
{
3142
  return openmc_periodic_mesh_get_origin_impl<SphericalMesh>(index, origin);
16 ✔
3143
}
3144

3145
extern "C" int openmc_spherical_mesh_set_origin(
32 ✔
3146
  int32_t index, const double origin[3])
3147
{
3148
  return openmc_periodic_mesh_set_origin_impl<SphericalMesh>(index, origin);
32 ✔
3149
}
3150

3151
#ifdef OPENMC_DAGMC_ENABLED
3152

3153
const std::string MOABMesh::mesh_lib_type = "moab";
3154

3155
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
15 ✔
3156
{
3157
  initialize();
15 ✔
3158
}
15 !
3159

3160
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
3161
{
3162
  initialize();
×
3163
}
×
3164

3165
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier,
1 ✔
3166
  const std::string& options)
1 ✔
3167
  : UnstructuredMesh()
1 ✔
3168
{
3169
  n_dimension_ = 3;
1 ✔
3170
  filename_ = filename;
1 ✔
3171
  options_ = options;
1 ✔
3172
  set_length_multiplier(length_multiplier);
1 ✔
3173
  initialize();
1 ✔
3174
}
1 !
3175

3176
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1 ✔
3177
{
3178
  mbi_ = external_mbi;
1 ✔
3179
  filename_ = "unknown (external file)";
1 ✔
3180
  this->initialize();
1 ✔
3181
}
1 !
3182

3183
void MOABMesh::initialize()
17 ✔
3184
{
3185
  // Create the MOAB interface and load data from file
3186
  this->create_interface();
17 ✔
3187

3188
  // Initialise MOAB error code
3189
  moab::ErrorCode rval = moab::MB_SUCCESS;
17 ✔
3190

3191
  // Set the dimension
3192
  n_dimension_ = 3;
17 ✔
3193

3194
  // set member range of tetrahedral entities
3195
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
17 ✔
3196
  if (rval != moab::MB_SUCCESS) {
17 !
3197
    fatal_error("Failed to get all tetrahedral elements");
3198
  }
3199

3200
  if (!ehs_.all_of_type(moab::MBTET)) {
17 !
3201
    warning("Non-tetrahedral elements found in unstructured "
×
3202
            "mesh file: " +
3203
            filename_);
3204
  }
3205

3206
  // set member range of vertices
3207
  int vertex_dim = 0;
17 ✔
3208
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
17 ✔
3209
  if (rval != moab::MB_SUCCESS) {
17 !
3210
    fatal_error("Failed to get all vertex handles");
3211
  }
3212

3213
  // make an entity set for all tetrahedra
3214
  // this is used for convenience later in output
3215
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
17 ✔
3216
  if (rval != moab::MB_SUCCESS) {
17 !
3217
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3218
  }
3219

3220
  rval = mbi_->add_entities(tetset_, ehs_);
17 ✔
3221
  if (rval != moab::MB_SUCCESS) {
17 !
3222
    fatal_error("Failed to add tetrahedra to an entity set.");
3223
  }
3224

3225
  if (length_multiplier_ > 0.0) {
17 ✔
3226
    // get the connectivity of all tets
3227
    moab::Range adj;
1 ✔
3228
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
1 ✔
3229
    if (rval != moab::MB_SUCCESS) {
1 !
3230
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3231
    }
3232
    // scale all vertex coords by multiplier (done individually so not all
3233
    // coordinates are in memory twice at once)
3234
    for (auto vert : adj) {
2,333 ✔
3235
      // retrieve coords
3236
      std::array<double, 3> coord;
2,331 ✔
3237
      rval = mbi_->get_coords(&vert, 1, coord.data());
2,331 ✔
3238
      if (rval != moab::MB_SUCCESS) {
2,331 !
3239
        fatal_error("Could not get coordinates of vertex.");
3240
      }
3241
      // scale coords
3242
      for (auto& c : coord) {
9,324 ✔
3243
        c *= length_multiplier_;
6,993 ✔
3244
      }
3245
      // set new coords
3246
      rval = mbi_->set_coords(&vert, 1, coord.data());
2,331 ✔
3247
      if (rval != moab::MB_SUCCESS) {
2,331 !
3248
        fatal_error("Failed to set new vertex coordinates");
3249
      }
3250
    }
3251
  }
1 ✔
3252

3253
  // Determine bounds of mesh
3254
  this->determine_bounds();
17 ✔
3255
}
17 ✔
3256

3257
void MOABMesh::prepare_for_point_location()
14 ✔
3258
{
3259
  // if the KDTree has already been constructed, do nothing
3260
  if (kdtree_)
14 !
3261
    return;
3262

3263
  // build acceleration data structures
3264
  compute_barycentric_data(ehs_);
14 ✔
3265
  build_kdtree(ehs_);
14 ✔
3266
}
3267

3268
void MOABMesh::create_interface()
17 ✔
3269
{
3270
  // Do not create a MOAB instance if one is already in memory
3271
  if (mbi_)
17 ✔
3272
    return;
3273

3274
  // create MOAB instance
3275
  mbi_ = std::make_shared<moab::Core>();
16 !
3276

3277
  // load unstructured mesh file
3278
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
16 ✔
3279
  if (rval != moab::MB_SUCCESS) {
16 !
3280
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3281
  }
3282
}
3283

3284
void MOABMesh::build_kdtree(const moab::Range& all_tets)
14 ✔
3285
{
3286
  moab::Range all_tris;
14 ✔
3287
  int adj_dim = 2;
14 ✔
3288
  write_message("Getting tet adjacencies...", 7);
14 ✔
3289
  moab::ErrorCode rval = mbi_->get_adjacencies(
14 ✔
3290
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3291
  if (rval != moab::MB_SUCCESS) {
14 !
3292
    fatal_error("Failed to get adjacent triangles for tets");
3293
  }
3294

3295
  if (!all_tris.all_of_type(moab::MBTRI)) {
14 !
3296
    warning("Non-triangle elements found in tet adjacencies in "
×
3297
            "unstructured mesh file: " +
3298
            filename_);
×
3299
  }
3300

3301
  // combine into one range
3302
  moab::Range all_tets_and_tris;
14 ✔
3303
  all_tets_and_tris.merge(all_tets);
14 ✔
3304
  all_tets_and_tris.merge(all_tris);
14 ✔
3305

3306
  // create a kd-tree instance
3307
  write_message(
14 ✔
3308
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
14 ✔
3309
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
14 ✔
3310

3311
  // Determine what options to use
3312
  std::ostringstream options_stream;
14 ✔
3313
  if (options_.empty()) {
14 ✔
3314
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
6 ✔
3315
  } else {
3316
    options_stream << options_;
8 ✔
3317
  }
3318
  moab::FileOptions file_opts(options_stream.str().c_str());
14 ✔
3319

3320
  // Build the k-d tree
3321
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
14 ✔
3322
  if (rval != moab::MB_SUCCESS) {
14 !
3323
    fatal_error("Failed to construct KDTree for the "
3324
                "unstructured mesh file: " +
3325
                filename_);
×
3326
  }
3327
}
14 ✔
3328

3329
void MOABMesh::intersect_track(const moab::CartVect& start,
860,084 ✔
3330
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3331
{
3332
  hits.clear();
860,084 !
3333

3334
  moab::ErrorCode rval;
860,084 ✔
3335
  vector<moab::EntityHandle> tris;
860,084 ✔
3336
  // get all intersections with triangles in the tet mesh
3337
  // (distances are relative to the start point, not the previous
3338
  // intersection)
3339
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
860,084 ✔
3340
    dir.array(), start.array(), tris, hits, 0, track_len);
3341
  if (rval != moab::MB_SUCCESS) {
860,084 !
3342
    fatal_error(
3343
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3344
  }
3345

3346
  // remove duplicate intersection distances
3347
  std::unique(hits.begin(), hits.end());
860,084 ✔
3348

3349
  // sorts by first component of std::pair by default
3350
  std::sort(hits.begin(), hits.end());
860,084 ✔
3351
}
860,084 ✔
3352

3353
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
860,084 ✔
3354
  vector<int>& bins, vector<double>& lengths) const
3355
{
3356
  moab::CartVect start(r0.x, r0.y, r0.z);
860,084 ✔
3357
  moab::CartVect end(r1.x, r1.y, r1.z);
860,084 ✔
3358
  moab::CartVect dir(u.x, u.y, u.z);
860,084 ✔
3359
  dir.normalize();
860,084 ✔
3360

3361
  double track_len = (end - start).length();
860,084 ✔
3362
  if (track_len == 0.0)
860,084 !
3363
    return;
394,352 ✔
3364

3365
  start -= TINY_BIT * dir;
860,084 ✔
3366
  end += TINY_BIT * dir;
860,084 ✔
3367

3368
  vector<double> hits;
860,084 ✔
3369
  intersect_track(start, dir, track_len, hits);
860,084 ✔
3370

3371
  bins.clear();
860,084 !
3372
  lengths.clear();
860,084 !
3373

3374
  // if there are no intersections the track may lie entirely
3375
  // within a single tet. If this is the case, apply entire
3376
  // score to that tet and return.
3377
  if (hits.size() == 0) {
860,084 ✔
3378
    Position midpoint = r0 + u * (track_len * 0.5);
394,352 ✔
3379
    int bin = this->get_bin(midpoint);
394,352 ✔
3380
    if (bin != -1) {
394,352 ✔
3381
      bins.push_back(bin);
137,549 ✔
3382
      lengths.push_back(1.0);
137,549 ✔
3383
    }
3384
    return;
394,352 ✔
3385
  }
3386

3387
  // for each segment in the set of tracks, try to look up a tet
3388
  // at the midpoint of the segment
3389
  Position current = r0;
3390
  double last_dist = 0.0;
3391
  for (const auto& hit : hits) {
2,979,423 ✔
3392
    // get the segment length
3393
    double segment_length = hit - last_dist;
2,513,691 ✔
3394
    last_dist = hit;
2,513,691 ✔
3395
    // find the midpoint of this segment
3396
    Position midpoint = current + u * (segment_length * 0.5);
2,513,691 ✔
3397
    // try to find a tet for this position
3398
    int bin = this->get_bin(midpoint);
2,513,691 ✔
3399

3400
    // determine the start point for this segment
3401
    current = r0 + u * hit;
2,513,691 ✔
3402

3403
    if (bin == -1) {
2,513,691 ✔
3404
      continue;
12,468 ✔
3405
    }
3406

3407
    bins.push_back(bin);
2,501,223 ✔
3408
    lengths.push_back(segment_length / track_len);
2,501,223 ✔
3409
  }
3410

3411
  // tally remaining portion of track after last hit if
3412
  // the last segment of the track is in the mesh but doesn't
3413
  // reach the other side of the tet
3414
  if (hits.back() < track_len) {
465,732 !
3415
    Position segment_start = r0 + u * hits.back();
465,732 ✔
3416
    double segment_length = track_len - hits.back();
465,732 ✔
3417
    Position midpoint = segment_start + u * (segment_length * 0.5);
465,732 ✔
3418
    int bin = this->get_bin(midpoint);
465,732 ✔
3419
    if (bin != -1) {
465,732 ✔
3420
      bins.push_back(bin);
427,179 ✔
3421
      lengths.push_back(segment_length / track_len);
427,179 ✔
3422
    }
3423
  }
3424
};
860,084 ✔
3425

3426
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
4,006,322 ✔
3427
{
3428
  moab::CartVect pos(r.x, r.y, r.z);
4,006,322 ✔
3429
  // find the leaf of the kd-tree for this position
3430
  moab::AdaptiveKDTreeIter kdtree_iter;
4,006,322 ✔
3431
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
4,006,322 ✔
3432
  if (rval != moab::MB_SUCCESS) {
4,006,322 ✔
3433
    return 0;
3434
  }
3435

3436
  // retrieve the tet elements of this leaf
3437
  moab::EntityHandle leaf = kdtree_iter.handle();
3,429,493 ✔
3438
  moab::Range tets;
3,429,493 ✔
3439
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3,429,493 ✔
3440
  if (rval != moab::MB_SUCCESS) {
3,429,493 !
3441
    warning("MOAB error finding tets.");
×
3442
  }
3443

3444
  // loop over the tets in this leaf, returning the containing tet if found
3445
  for (const auto& tet : tets) {
98,661,514 ✔
3446
    if (point_in_tet(pos, tet)) {
98,659,828 ✔
3447
      return tet;
3,427,807 ✔
3448
    }
3449
  }
3450

3451
  // if no tet is found, return an invalid handle
3452
  return 0;
1,686 ✔
3453
}
8,012,644 ✔
3454

3455
double MOABMesh::volume(int bin) const
203,880 ✔
3456
{
3457
  return tet_volume(get_ent_handle_from_bin(bin));
203,880 ✔
3458
}
3459

3460
std::string MOABMesh::library() const
29 ✔
3461
{
3462
  return mesh_lib_type;
29 ✔
3463
}
3464

3465
// Sample position within a tet for MOAB type tets
3466
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410 ✔
3467
{
3468
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410 ✔
3469

3470
  // Get vertex coordinates for MOAB tet
3471
  const moab::EntityHandle* conn1;
200,410 ✔
3472
  int conn1_size;
200,410 ✔
3473
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410 ✔
3474
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410 !
3475
    fatal_error(fmt::format(
3476
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3477
      conn1_size));
3478
  }
3479
  moab::CartVect p[4];
200,410 ✔
3480
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410 ✔
3481
  if (rval != moab::MB_SUCCESS) {
200,410 !
3482
    fatal_error("Failed to get tet coords");
3483
  }
3484

3485
  // Samples position within tet using Barycentric stuff
3486
  return this->sample_tet<moab::CartVect>({p, 4}, seed);
200,410 ✔
3487
}
3488

3489
double MOABMesh::tet_volume(moab::EntityHandle tet) const
203,880 ✔
3490
{
3491
  vector<moab::EntityHandle> conn;
203,880 ✔
3492
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
203,880 ✔
3493
  if (rval != moab::MB_SUCCESS) {
203,880 !
3494
    fatal_error("Failed to get tet connectivity");
3495
  }
3496

3497
  moab::CartVect p[4];
203,880 ✔
3498
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
203,880 ✔
3499
  if (rval != moab::MB_SUCCESS) {
203,880 !
3500
    fatal_error("Failed to get tet coords");
3501
  }
3502

3503
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
203,880 ✔
3504
}
203,880 ✔
3505

3506
int MOABMesh::get_bin(Position r) const
4,006,322 ✔
3507
{
3508
  moab::EntityHandle tet = get_tet(r);
4,006,322 ✔
3509
  if (tet == 0) {
4,006,322 ✔
3510
    return -1;
3511
  } else {
3512
    return get_bin_from_ent_handle(tet);
3,427,807 ✔
3513
  }
3514
}
3515

3516
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
14 ✔
3517
{
3518
  moab::ErrorCode rval;
14 ✔
3519

3520
  baryc_data_.clear();
14 !
3521
  baryc_data_.resize(tets.size());
14 ✔
3522

3523
  // compute the barycentric data for each tet element
3524
  // and store it as a 3x3 matrix
3525
  for (auto& tet : tets) {
155,894 ✔
3526
    vector<moab::EntityHandle> verts;
155,880 ✔
3527
    rval = mbi_->get_connectivity(&tet, 1, verts);
155,880 ✔
3528
    if (rval != moab::MB_SUCCESS) {
155,880 !
3529
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3530
    }
3531

3532
    moab::CartVect p[4];
155,880 ✔
3533
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
155,880 ✔
3534
    if (rval != moab::MB_SUCCESS) {
155,880 !
3535
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3536
    }
3537

3538
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
155,880 ✔
3539

3540
    // invert now to avoid this cost later
3541
    a = a.transpose().inverse();
155,880 ✔
3542
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
155,880 ✔
3543
  }
155,880 ✔
3544
}
14 ✔
3545

3546
bool MOABMesh::point_in_tet(
98,659,828 ✔
3547
  const moab::CartVect& r, moab::EntityHandle tet) const
3548
{
3549

3550
  moab::ErrorCode rval;
98,659,828 ✔
3551

3552
  // get tet vertices
3553
  vector<moab::EntityHandle> verts;
98,659,828 ✔
3554
  rval = mbi_->get_connectivity(&tet, 1, verts);
98,659,828 ✔
3555
  if (rval != moab::MB_SUCCESS) {
98,659,828 !
3556
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3557
    return false;
3558
  }
3559

3560
  // first vertex is used as a reference point for the barycentric data -
3561
  // retrieve its coordinates
3562
  moab::CartVect p_zero;
98,659,828 ✔
3563
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
98,659,828 ✔
3564
  if (rval != moab::MB_SUCCESS) {
98,659,828 !
3565
    warning("Failed to get coordinates of a vertex in "
×
3566
            "unstructured mesh: " +
3567
            filename_);
×
3568
    return false;
3569
  }
3570

3571
  // look up barycentric data
3572
  int idx = get_bin_from_ent_handle(tet);
98,659,828 ✔
3573
  const moab::Matrix3& a_inv = baryc_data_[idx];
98,659,828 ✔
3574

3575
  moab::CartVect bary_coords = a_inv * (r - p_zero);
98,659,828 ✔
3576

3577
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
62,713,089 ✔
3578
          bary_coords[2] >= 0.0 &&
124,669,028 ✔
3579
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
10,749,159 ✔
3580
}
98,659,828 ✔
3581

3582
int MOABMesh::get_bin_from_index(int idx) const
3583
{
3584
  if (idx >= n_bins()) {
×
3585
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3586
  }
3587
  return ehs_[idx] - ehs_[0];
3588
}
3589

3590
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3591
{
3592
  int bin = get_bin(r);
3593
  *in_mesh = bin != -1;
3594
  return bin;
3595
}
3596

3597
int MOABMesh::get_index_from_bin(int bin) const
3598
{
3599
  return bin;
3600
}
3601

3602
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3603
  Position plot_ll, Position plot_ur) const
3604
{
3605
  // TODO: Implement mesh lines
3606
  return {};
3607
}
3608

3609
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
911,520 ✔
3610
{
3611
  int idx = vert - verts_[0];
911,520 ✔
3612
  if (idx >= n_vertices()) {
911,520 !
3613
    fatal_error(
3614
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3615
  }
3616
  return idx;
911,520 ✔
3617
}
3618

3619
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
102,243,515 ✔
3620
{
3621
  int bin = eh - ehs_[0];
102,243,515 ✔
3622
  if (bin >= n_bins()) {
102,243,515 !
3623
    fatal_error(fmt::format("Invalid bin: {}", bin));
3624
  }
3625
  return bin;
102,243,515 ✔
3626
}
3627

3628
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
632,170 ✔
3629
{
3630
  if (bin >= n_bins()) {
632,170 !
3631
    fatal_error(fmt::format("Invalid bin index: ", bin));
3632
  }
3633
  return ehs_[0] + bin;
632,170 ✔
3634
}
3635

3636
int MOABMesh::n_bins() const
103,103,640 ✔
3637
{
3638
  return ehs_.size();
103,103,640 ✔
3639
}
3640

3641
int MOABMesh::n_surface_bins() const
3642
{
3643
  // collect all triangles in the set of tets for this mesh
3644
  moab::Range tris;
×
3645
  moab::ErrorCode rval;
3646
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3647
  if (rval != moab::MB_SUCCESS) {
×
3648
    warning("Failed to get all triangles in the mesh instance");
×
3649
    return -1;
3650
  }
3651
  return 2 * tris.size();
×
3652
}
3653

3654
Position MOABMesh::centroid(int bin) const
3655
{
3656
  moab::ErrorCode rval;
3657

3658
  auto tet = this->get_ent_handle_from_bin(bin);
3659

3660
  // look up the tet connectivity
3661
  vector<moab::EntityHandle> conn;
×
3662
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3663
  if (rval != moab::MB_SUCCESS) {
×
3664
    warning("Failed to get connectivity of a mesh element.");
×
3665
    return {};
3666
  }
3667

3668
  // get the coordinates
3669
  vector<moab::CartVect> coords(conn.size());
×
3670
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3671
  if (rval != moab::MB_SUCCESS) {
×
3672
    warning("Failed to get the coordinates of a mesh element.");
×
3673
    return {};
3674
  }
3675

3676
  // compute the centroid of the element vertices
3677
  moab::CartVect centroid(0.0, 0.0, 0.0);
3678
  for (const auto& coord : coords) {
×
3679
    centroid += coord;
3680
  }
3681
  centroid /= double(coords.size());
3682

3683
  return {centroid[0], centroid[1], centroid[2]};
3684
}
3685

3686
int MOABMesh::n_vertices() const
948,865 ✔
3687
{
3688
  return verts_.size();
948,865 ✔
3689
}
3690

3691
Position MOABMesh::vertex(int id) const
74,588 ✔
3692
{
3693

3694
  moab::ErrorCode rval;
74,588 ✔
3695

3696
  moab::EntityHandle vert = verts_[id];
74,588 ✔
3697

3698
  moab::CartVect coords;
74,588 ✔
3699
  rval = mbi_->get_coords(&vert, 1, coords.array());
74,588 ✔
3700
  if (rval != moab::MB_SUCCESS) {
74,588 !
3701
    fatal_error("Failed to get the coordinates of a vertex.");
3702
  }
3703

3704
  return {coords[0], coords[1], coords[2]};
74,588 ✔
3705
}
3706

3707
std::vector<int> MOABMesh::connectivity(int bin) const
227,880 ✔
3708
{
3709
  moab::ErrorCode rval;
227,880 ✔
3710

3711
  auto tet = get_ent_handle_from_bin(bin);
227,880 ✔
3712

3713
  // look up the tet connectivity
3714
  vector<moab::EntityHandle> conn;
227,880 ✔
3715
  rval = mbi_->get_connectivity(&tet, 1, conn);
227,880 ✔
3716
  if (rval != moab::MB_SUCCESS) {
227,880 !
3717
    fatal_error("Failed to get connectivity of a mesh element.");
3718
    return {};
3719
  }
3720

3721
  std::vector<int> verts(4);
227,880 ✔
3722
  for (int i = 0; i < verts.size(); i++) {
1,139,400 ✔
3723
    verts[i] = get_vert_idx_from_handle(conn[i]);
911,520 ✔
3724
  }
3725

3726
  return verts;
227,880 ✔
3727
}
227,880 ✔
3728

3729
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3730
  std::string score) const
3731
{
3732
  moab::ErrorCode rval;
3733
  // add a tag to the mesh
3734
  // all scores are treated as a single value
3735
  // with an uncertainty
3736
  moab::Tag value_tag;
3737

3738
  // create the value tag if not present and get handle
3739
  double default_val = 0.0;
3740
  auto val_string = score + "_mean";
3741
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3742
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3743
  if (rval != moab::MB_SUCCESS) {
×
3744
    auto msg =
3745
      fmt::format("Could not create or retrieve the value tag for the score {}"
3746
                  " on unstructured mesh {}",
3747
        score, id_);
3748
    fatal_error(msg);
3749
  }
3750

3751
  // create the std dev tag if not present and get handle
3752
  moab::Tag error_tag;
3753
  std::string err_string = score + "_std_dev";
×
3754
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3755
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3756
  if (rval != moab::MB_SUCCESS) {
×
3757
    auto msg =
3758
      fmt::format("Could not create or retrieve the error tag for the score {}"
3759
                  " on unstructured mesh {}",
3760
        score, id_);
3761
    fatal_error(msg);
3762
  }
3763

3764
  // return the populated tag handles
3765
  return {value_tag, error_tag};
3766
}
3767

3768
void MOABMesh::add_score(const std::string& score)
3769
{
3770
  auto score_tags = get_score_tags(score);
×
3771
  tag_names_.push_back(score);
3772
}
3773

3774
void MOABMesh::remove_scores()
3775
{
3776
  for (const auto& name : tag_names_) {
×
3777
    auto value_name = name + "_mean";
3778
    moab::Tag tag;
3779
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3780
    if (rval != moab::MB_SUCCESS)
×
3781
      return;
3782

3783
    rval = mbi_->tag_delete(tag);
×
3784
    if (rval != moab::MB_SUCCESS) {
×
3785
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3786
                             " on unstructured mesh {}",
3787
        name, id_);
3788
      fatal_error(msg);
3789
    }
3790

3791
    auto std_dev_name = name + "_std_dev";
×
3792
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3793
    if (rval != moab::MB_SUCCESS) {
×
3794
      auto msg =
3795
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3796
                    " on unstructured mesh {}",
3797
          name, id_);
3798
    }
3799

3800
    rval = mbi_->tag_delete(tag);
×
3801
    if (rval != moab::MB_SUCCESS) {
×
3802
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3803
                             " on unstructured mesh {}",
3804
        name, id_);
3805
      fatal_error(msg);
3806
    }
3807
  }
3808
  tag_names_.clear();
3809
}
3810

3811
void MOABMesh::set_score_data(const std::string& score,
3812
  const vector<double>& values, const vector<double>& std_dev)
3813
{
3814
  auto score_tags = this->get_score_tags(score);
×
3815

3816
  moab::ErrorCode rval;
3817
  // set the score value
3818
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3819
  if (rval != moab::MB_SUCCESS) {
×
3820
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3821
                           "on unstructured mesh {}",
3822
      score, id_);
3823
    warning(msg);
×
3824
  }
3825

3826
  // set the error value
3827
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3828
  if (rval != moab::MB_SUCCESS) {
×
3829
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3830
                           "on unstructured mesh {}",
3831
      score, id_);
3832
    warning(msg);
×
3833
  }
3834
}
3835

3836
void MOABMesh::write(const std::string& base_filename) const
3837
{
3838
  // add extension to the base name
3839
  auto filename = base_filename + ".vtk";
3840
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3841
  filename = settings::path_output + filename;
×
3842

3843
  // write the tetrahedral elements of the mesh only
3844
  // to avoid clutter from zero-value data on other
3845
  // elements during visualization
3846
  moab::ErrorCode rval;
3847
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3848
  if (rval != moab::MB_SUCCESS) {
×
3849
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3850
    warning(msg);
×
3851
  }
3852
}
3853

3854
#endif
3855

3856
#ifdef OPENMC_LIBMESH_ENABLED
3857

3858
const std::string LibMesh::mesh_lib_type = "libmesh";
3859

3860
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
10 ✔
3861
{
3862
  // filename_ and length_multiplier_ will already be set by the
3863
  // UnstructuredMesh constructor
3864
  set_mesh_pointer_from_filename(filename_);
10 ✔
3865
  set_length_multiplier(length_multiplier_);
10 ✔
3866
  initialize();
10 ✔
3867
}
10 ✔
3868

3869
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3870
{
3871
  // filename_ and length_multiplier_ will already be set by the
3872
  // UnstructuredMesh constructor
3873
  set_mesh_pointer_from_filename(filename_);
×
3874
  set_length_multiplier(length_multiplier_);
×
3875
  initialize();
×
3876
}
3877

3878
// create the mesh from a pointer to a libMesh Mesh
3879
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3880
{
3881
  if (!input_mesh.is_replicated()) {
×
3882
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3883
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3884
  }
3885

3886
  m_ = &input_mesh;
3887
  set_length_multiplier(length_multiplier);
×
3888
  initialize();
×
3889
}
3890

3891
// create the mesh from an input file
3892
LibMesh::LibMesh(const std::string& filename, double length_multiplier,
1 ✔
3893
  const std::string& options)
1 ✔
3894
{
3895
  n_dimension_ = 3;
1 ✔
3896
  options_ = options;
1 ✔
3897
  set_mesh_pointer_from_filename(filename);
1 ✔
3898
  set_length_multiplier(length_multiplier);
1 ✔
3899
  initialize();
1 ✔
3900
}
1 ✔
3901

3902
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
11 ✔
3903
{
3904
  filename_ = filename;
11 ✔
3905
  unique_m_ =
11 ✔
3906
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
11 ✔
3907
  m_ = unique_m_.get();
11 ✔
3908
  m_->read(filename_);
11 ✔
3909
}
11 ✔
3910

3911
// build a libMesh equation system for storing values
3912
void LibMesh::build_eqn_sys()
6 ✔
3913
{
3914
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
6 ✔
3915
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
6 ✔
3916
  libMesh::ExplicitSystem& eq_sys =
6 ✔
3917
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
6 ✔
3918
}
6 ✔
3919

3920
// intialize from mesh file
3921
void LibMesh::initialize()
11 ✔
3922
{
3923
  if (!settings::libmesh_comm) {
11 !
3924
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3925
                "communicator.");
3926
  }
3927

3928
  // assuming that unstructured meshes used in OpenMC are 3D
3929
  n_dimension_ = 3;
11 ✔
3930

3931
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3932
  // Otherwise assume that it is prepared by its owning application
3933
  if (unique_m_) {
11 !
3934
    m_->prepare_for_use();
11 ✔
3935
  }
3936

3937
  // ensure that the loaded mesh is 3 dimensional
3938
  if (m_->mesh_dimension() != n_dimension_) {
11 !
3939
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3940
                            "mesh is not a 3D mesh.",
3941
      filename_));
3942
  }
3943

3944
  for (int i = 0; i < num_threads(); i++) {
22 ✔
3945
    pl_.emplace_back(m_->sub_point_locator());
11 ✔
3946
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
11 ✔
3947
    pl_.back()->enable_out_of_mesh_mode();
11 ✔
3948
  }
3949

3950
  // store first element in the mesh to use as an offset for bin indices
3951
  auto first_elem = *m_->elements_begin();
22 ✔
3952
  first_element_id_ = first_elem->id();
11 ✔
3953

3954
  // bounding box for the mesh for quick rejection checks
3955
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
11 ✔
3956
  libMesh::Point ll = bbox_.min();
11 ✔
3957
  libMesh::Point ur = bbox_.max();
11 ✔
3958
  if (length_multiplier_ > 0.0) {
11 ✔
3959
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
2 ✔
3960
      length_multiplier_ * ll(2)};
1 ✔
3961
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
1 ✔
3962
      length_multiplier_ * ur(2)};
1 ✔
3963
  } else {
3964
    lower_left_ = {ll(0), ll(1), ll(2)};
10 ✔
3965
    upper_right_ = {ur(0), ur(1), ur(2)};
10 ✔
3966
  }
3967
}
11 ✔
3968

3969
// Sample position within a tet for LibMesh type tets
3970
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410 ✔
3971
{
3972
  const auto& elem = get_element_from_bin(bin);
200,410 ✔
3973
  // Get tet vertex coordinates from LibMesh
3974
  std::array<Position, 4> tet_verts;
200,410 ✔
3975
  for (int i = 0; i < elem.n_nodes(); i++) {
1,002,050 ✔
3976
    const auto& node_ref = elem.node_ref(i);
801,640 ✔
3977
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
801,640 ✔
3978
  }
3979
  // Samples position within tet using Barycentric coordinates
3980
  Position sampled_position =
200,410 ✔
3981
    this->sample_tet<Position>({tet_verts.begin(), tet_verts.end()}, seed);
200,410 ✔
3982
  if (length_multiplier_ > 0.0) {
200,410 !
3983
    return length_multiplier_ * sampled_position;
3984
  } else {
3985
    return sampled_position;
200,410 ✔
3986
  }
3987
}
3988

3989
Position LibMesh::centroid(int bin) const
3990
{
3991
  const auto& elem = this->get_element_from_bin(bin);
3992
  auto centroid = elem.vertex_average();
3993
  if (length_multiplier_ > 0.0) {
×
3994
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3995
  } else {
3996
    return {centroid(0), centroid(1), centroid(2)};
3997
  }
3998
}
3999

4000
int LibMesh::n_vertices() const
23,655 ✔
4001
{
4002
  return m_->n_nodes();
23,655 ✔
4003
}
4004

4005
Position LibMesh::vertex(int vertex_id) const
23,633 ✔
4006
{
4007
  const auto& node_ref = m_->node_ref(vertex_id);
23,633 ✔
4008
  if (length_multiplier_ > 0.0) {
23,633 ✔
4009
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
2,331 ✔
4010
  } else {
4011
    return {node_ref(0), node_ref(1), node_ref(2)};
21,302 ✔
4012
  }
4013
}
4014

4015
std::vector<int> LibMesh::connectivity(int elem_id) const
145,928 ✔
4016
{
4017
  std::vector<int> conn;
145,928 ✔
4018
  const auto* elem_ptr = m_->elem_ptr(elem_id);
145,928 ✔
4019
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
737,640 ✔
4020
    conn.push_back(elem_ptr->node_id(i));
591,712 ✔
4021
  }
4022
  return conn;
145,928 ✔
4023
}
4024

4025
std::string LibMesh::library() const
17 ✔
4026
{
4027
  return mesh_lib_type;
17 ✔
4028
}
4029

4030
int LibMesh::n_bins() const
611,912 ✔
4031
{
4032
  return m_->n_elem();
611,912 ✔
4033
}
4034

4035
int LibMesh::n_surface_bins() const
4036
{
4037
  int n_bins = 0;
4038
  for (int i = 0; i < this->n_bins(); i++) {
×
4039
    const libMesh::Elem& e = get_element_from_bin(i);
4040
    n_bins += e.n_faces();
4041
    // if this is a boundary element, it will only be visited once,
4042
    // the number of surface bins is incremented to
4043
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
4044
      // null neighbor pointer indicates a boundary face
4045
      if (!neighbor_ptr) {
×
4046
        n_bins++;
4047
      }
4048
    }
4049
  }
4050
  return n_bins;
4051
}
4052

4053
void LibMesh::add_score(const std::string& var_name)
6 ✔
4054
{
4055
  if (!equation_systems_) {
6 !
4056
    build_eqn_sys();
6 ✔
4057
  }
4058

4059
  // check if this is a new variable
4060
  std::string value_name = var_name + "_mean";
6 ✔
4061
  if (!variable_map_.count(value_name)) {
6 ✔
4062
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
6 ✔
4063
    auto var_num =
6 ✔
4064
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
6 ✔
4065
    variable_map_[value_name] = var_num;
6 ✔
4066
  }
4067

4068
  std::string std_dev_name = var_name + "_std_dev";
6 ✔
4069
  // check if this is a new variable
4070
  if (!variable_map_.count(std_dev_name)) {
6 ✔
4071
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
6 ✔
4072
    auto var_num =
6 ✔
4073
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
6 ✔
4074
    variable_map_[std_dev_name] = var_num;
6 ✔
4075
  }
4076
}
6 ✔
4077

4078
void LibMesh::remove_scores()
6 ✔
4079
{
4080
  if (equation_systems_) {
6 !
4081
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
6 ✔
4082
    eqn_sys.clear();
6 ✔
4083
    variable_map_.clear();
6 ✔
4084
  }
4085
}
6 ✔
4086

4087
void LibMesh::set_score_data(const std::string& var_name,
6 ✔
4088
  const vector<double>& values, const vector<double>& std_dev)
4089
{
4090
  if (!equation_systems_) {
6 !
4091
    build_eqn_sys();
4092
  }
4093

4094
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
6 ✔
4095

4096
  if (!eqn_sys.is_initialized()) {
6 !
4097
    equation_systems_->init();
6 ✔
4098
  }
4099

4100
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
6 ✔
4101

4102
  // look up the value variable
4103
  std::string value_name = var_name + "_mean";
6 ✔
4104
  unsigned int value_num = variable_map_.at(value_name);
6 ✔
4105
  // look up the std dev variable
4106
  std::string std_dev_name = var_name + "_std_dev";
6 ✔
4107
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
6 ✔
4108

4109
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
99,874 ✔
4110
       it++) {
4111
    if (!(*it)->active()) {
49,928 !
4112
      continue;
4113
    }
4114

4115
    auto bin = get_bin_from_element(*it);
49,928 ✔
4116

4117
    // set value
4118
    vector<libMesh::dof_id_type> value_dof_indices;
49,928 ✔
4119
    dof_map.dof_indices(*it, value_dof_indices, value_num);
49,928 ✔
4120
    assert(value_dof_indices.size() == 1);
49,928 ✔
4121
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
49,928 ✔
4122

4123
    // set std dev
4124
    vector<libMesh::dof_id_type> std_dev_dof_indices;
49,928 ✔
4125
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
49,928 ✔
4126
    assert(std_dev_dof_indices.size() == 1);
49,928 ✔
4127
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
49,928 ✔
4128
  }
49,934 ✔
4129
}
6 ✔
4130

4131
void LibMesh::write(const std::string& filename) const
6 ✔
4132
{
4133
  // A serial libMesh communicator considers every OpenMC rank to be its
4134
  // processor 0. Restrict the non-collective write to the OpenMC master in
4135
  // that case. With a parallel communicator, all ranks must participate in
4136
  // libMesh's solution assembly.
4137
  if (settings::libmesh_comm->size() == 1 && !mpi::master) {
6 !
4138
    return;
4139
  }
4140

4141
  write_message(fmt::format(
6 ✔
4142
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
6 ✔
4143
  libMesh::ExodusII_IO exo(*m_);
6 ✔
4144
  std::set<std::string> systems_out = {eq_system_name_};
12 !
4145
  exo.write_discontinuous_exodusII(
6 ✔
4146
    filename + ".e", *equation_systems_, &systems_out);
12 ✔
4147
}
6 ✔
4148

4149
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
4150
  vector<int>& bins, vector<double>& lengths) const
4151
{
4152
  // TODO: Implement triangle crossings here
4153
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
4154
}
4155

4156
int LibMesh::get_bin(Position r) const
686,684 ✔
4157
{
4158
  // look-up a tet using the point locator
4159
  libMesh::Point p(r.x, r.y, r.z);
686,684 !
4160

4161
  if (length_multiplier_ > 0.0) {
686,684 !
4162
    // Scale the point down
4163
    p /= length_multiplier_;
686,684 ✔
4164
  }
4165

4166
  // quick rejection check
4167
  if (!bbox_.contains_point(p)) {
686,684 ✔
4168
    return -1;
4169
  }
4170

4171
  const auto& point_locator = pl_.at(thread_num());
416,322 ✔
4172

4173
  const auto elem_ptr = (*point_locator)(p);
416,322 ✔
4174
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
416,322 ✔
4175
}
686,684 ✔
4176

4177
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
465,921 ✔
4178
{
4179
  int bin = elem->id() - first_element_id_;
465,921 ✔
4180
  if (bin >= n_bins() || bin < 0) {
465,921 !
4181
    fatal_error(fmt::format("Invalid bin: {}", bin));
4182
  }
4183
  return bin;
465,921 ✔
4184
}
4185

4186
std::pair<vector<double>, vector<double>> LibMesh::plot(
4187
  Position plot_ll, Position plot_ur) const
4188
{
4189
  return {};
4190
}
4191

4192
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
372,266 ✔
4193
{
4194
  return m_->elem_ref(bin);
372,266 ✔
4195
}
4196

4197
double LibMesh::volume(int bin) const
171,856 ✔
4198
{
4199
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
171,856 ✔
4200
         length_multiplier_ * length_multiplier_;
171,856 ✔
4201
}
4202

4203
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4204
  double length_multiplier,
4205
  const std::set<libMesh::subdomain_id_type>& block_ids)
4206
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4207
    block_restrict_(!block_ids_.empty()),
×
4208
    num_active_(
×
4209
      block_restrict_
4210
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
4211
            m_->active_subdomain_set_elements_end(block_ids_))
×
4212
        : m_->n_active_elem())
×
4213
{
4214
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4215
  // contiguous in ID space, so we need to map from bin indices (defined over
4216
  // active elements) to global dof ids
4217
  bin_to_elem_map_.reserve(num_active_);
×
4218
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
4219
  auto begin = block_restrict_
4220
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
4221
                 : m_->active_elements_begin();
×
4222
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
4223
                             : m_->active_elements_end();
×
4224
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
4225
    bin_to_elem_map_.push_back(elem->id());
×
4226
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
4227
  }
4228
}
4229

4230
int AdaptiveLibMesh::n_bins() const
4231
{
4232
  return num_active_;
4233
}
4234

4235
void AdaptiveLibMesh::add_score(const std::string& var_name)
4236
{
4237
  warning(fmt::format(
×
4238
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4239
    this->id_));
4240
}
4241

4242
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4243
  const vector<double>& values, const vector<double>& std_dev)
4244
{
4245
  warning(fmt::format(
×
4246
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4247
    this->id_));
4248
}
4249

4250
void AdaptiveLibMesh::write(const std::string& filename) const
4251
{
4252
  warning(fmt::format(
×
4253
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4254
    this->id_));
4255
}
4256

4257
int AdaptiveLibMesh::get_bin(Position r) const
4258
{
4259
  // look-up a tet using the point locator
4260
  libMesh::Point p(r.x, r.y, r.z);
×
4261

4262
  if (length_multiplier_ > 0.0) {
×
4263
    // Scale the point down
4264
    p /= length_multiplier_;
4265
  }
4266

4267
  // quick rejection check
4268
  if (!bbox_.contains_point(p)) {
×
4269
    return -1;
4270
  }
4271

4272
  const auto& point_locator = pl_.at(thread_num());
×
4273

4274
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4275
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4276
}
4277

4278
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4279
{
4280
  int bin = elem_to_bin_map_[elem->id()];
4281
  if (bin >= n_bins() || bin < 0) {
×
4282
    fatal_error(fmt::format("Invalid bin: {}", bin));
4283
  }
4284
  return bin;
4285
}
4286

4287
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4288
{
4289
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4290
}
4291

4292
#endif // OPENMC_LIBMESH_ENABLED
4293

4294
//==============================================================================
4295
// Non-member functions
4296
//==============================================================================
4297

4298
void read_meshes(pugi::xml_node root)
11,104 ✔
4299
{
4300
  std::unordered_set<int> mesh_ids;
11,104 ✔
4301

4302
  for (auto node : root.children("mesh")) {
13,873 ✔
4303
    // Check to make sure multiple meshes in the same file don't share IDs
4304
    int id = std::stoi(get_node_value(node, "id"));
5,538 ✔
4305
    if (contains(mesh_ids, id)) {
5,538 !
4306
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4307
                              "'{}' in the same input file",
4308
        id));
4309
    }
4310
    mesh_ids.insert(id);
2,769 ✔
4311

4312
    // If we've already read a mesh with the same ID in a *different* file,
4313
    // assume it is the same here
4314
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,769 !
4315
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4316
      continue;
×
4317
    }
4318

4319
    std::string mesh_type;
2,769 ✔
4320
    if (check_for_node(node, "type")) {
2,769 ✔
4321
      mesh_type = get_node_value(node, "type", true, true);
737 ✔
4322
    } else {
4323
      // legacy support: older versions of XML do not specify a type,
4324
      // so assume a regular mesh
4325
      mesh_type = "regular";
2,032 ✔
4326
    }
4327

4328
    Mesh::create(node);
2,769 ✔
4329
  }
2,769 ✔
4330
}
11,104 ✔
4331

4332
void read_meshes(hid_t group)
34 ✔
4333
{
4334
  std::unordered_set<int> mesh_ids;
34 ✔
4335

4336
  std::vector<int> ids;
34 ✔
4337
  read_attribute(group, "ids", ids);
34 ✔
4338

4339
  for (auto id : ids) {
76 ✔
4340

4341
    // Check to make sure multiple meshes in the same file don't share IDs
4342
    if (contains(mesh_ids, id)) {
84 !
4343
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4344
                              "'{}' in the same HDF5 input file",
4345
        id));
4346
    }
4347
    mesh_ids.insert(id);
42 ✔
4348

4349
    // If we've already read a mesh with the same ID in a *different* file,
4350
    // assume it is the same here
4351
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
42 ✔
4352
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
24 ✔
4353
      continue;
24 ✔
4354
    }
4355

4356
    std::string name = fmt::format("mesh {}", id);
18 ✔
4357
    hid_t mesh_group = open_group(group, name.c_str());
18 ✔
4358

4359
    std::string mesh_type;
18 ✔
4360
    if (object_exists(mesh_group, "type")) {
18 !
4361
      read_dataset(mesh_group, "type", mesh_type);
18 ✔
4362
    } else {
4363
      // legacy support: older versions of HDF5 do not specify a type,
4364
      // so assume a regular mesh
4365
      mesh_type = "regular";
×
4366
    }
4367

4368
    Mesh::create(mesh_group);
18 ✔
4369
  }
18 ✔
4370
}
68 ✔
4371

4372
void meshes_to_hdf5(hid_t group)
6,251 ✔
4373
{
4374
  // Write number of meshes
4375
  hid_t meshes_group = create_group(group, "meshes");
6,251 ✔
4376
  int32_t n_meshes = model::meshes.size();
6,251 ✔
4377
  write_attribute(meshes_group, "n_meshes", n_meshes);
6,251 ✔
4378

4379
  if (n_meshes > 0) {
6,251 ✔
4380
    // Write IDs of meshes
4381
    vector<int> ids;
2,006 ✔
4382
    for (const auto& m : model::meshes) {
4,594 ✔
4383
      m->to_hdf5(meshes_group);
2,588 ✔
4384
      ids.push_back(m->id_);
2,588 ✔
4385
    }
4386
    write_attribute(meshes_group, "ids", ids);
2,006 ✔
4387
  }
2,006 ✔
4388

4389
  close_group(meshes_group);
6,251 ✔
4390
}
6,251 ✔
4391

4392
void free_memory_mesh()
7,200 ✔
4393
{
4394
  model::meshes.clear();
7,200 ✔
4395
  model::mesh_map.clear();
7,200 ✔
4396
}
7,200 ✔
4397

4398
extern "C" int n_meshes()
272 ✔
4399
{
4400
  return model::meshes.size();
272 ✔
4401
}
4402

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

© 2026 Coveralls, Inc