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

openmc-dev / openmc / 22072323215

16 Feb 2026 05:32PM UTC coverage: 81.601% (-0.1%) from 81.721%
22072323215

Pull #3809

github

web-flow
Merge 067469002 into c6ef84d1d
Pull Request #3809: Implement tally filter for filtering by reaction

17039 of 23686 branches covered (71.94%)

Branch coverage included in aggregate %.

79 of 81 new or added lines in 6 files covered. (97.53%)

300 existing lines in 24 files now uncovered.

56231 of 66105 relevant lines covered (85.06%)

41986437.76 hits per line

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

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

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

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

19
#include "xtensor/xadapt.hpp"
20
#include "xtensor/xbuilder.hpp"
21
#include "xtensor/xeval.hpp"
22
#include "xtensor/xmath.hpp"
23
#include "xtensor/xsort.hpp"
24
#include "xtensor/xtensor.hpp"
25
#include "xtensor/xview.hpp"
26
#include <fmt/core.h> // for fmt
27

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

52
#ifdef OPENMC_LIBMESH_ENABLED
53
#include "libmesh/mesh_modification.h"
54
#include "libmesh/mesh_tools.h"
55
#include "libmesh/numeric_vector.h"
56
#include "libmesh/replicated_mesh.h"
57
#endif
58

59
#ifdef OPENMC_DAGMC_ENABLED
60
#include "moab/FileOptions.hpp"
61
#endif
62

63
namespace openmc {
64

65
//==============================================================================
66
// Global variables
67
//==============================================================================
68

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

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

79
namespace model {
80

81
std::unordered_map<int32_t, int32_t> mesh_map;
82
vector<unique_ptr<Mesh>> meshes;
83

84
} // namespace model
85

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

93
//==============================================================================
94
// Helper functions
95
//==============================================================================
96

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

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

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

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

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

145
// Helper function equivalent to std::bit_cast in C++20
146
template<typename To, typename From>
147
inline To bit_cast_value(const From& value)
29,857,248✔
148
{
149
  To out;
150
  std::memcpy(&out, &value, sizeof(To));
29,857,248✔
151
  return out;
29,857,248✔
152
}
153

154
inline void atomic_update_double(double* ptr, double value, bool is_min)
29,831,184✔
155
{
156
#if defined(__GNUC__) || defined(__clang__)
157
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
158
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
29,831,184✔
159
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
29,831,184✔
160
  double current = bit_cast_value<double>(current_bits);
29,831,184✔
161
  while (is_min ? (value < current) : (value > current)) {
29,831,335✔
162
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
25,913✔
163
    uint64_t expected_bits = current_bits;
25,913✔
164
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
25,913✔
165
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
166
      return;
25,762✔
167
    }
168
    current_bits = expected_bits;
151✔
169
    current = bit_cast_value<double>(current_bits);
151✔
170
  }
171

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

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

192
inline void atomic_max_double(double* ptr, double value)
14,915,592✔
193
{
194
  atomic_update_double(ptr, value, false);
14,915,592✔
195
}
14,915,592✔
196

197
inline void atomic_min_double(double* ptr, double value)
14,915,592✔
198
{
199
  atomic_update_double(ptr, value, true);
14,915,592✔
200
}
14,915,592✔
201

202
namespace detail {
203

204
//==============================================================================
205
// MaterialVolumes implementation
206
//==============================================================================
207

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

217
  // Loop for linear probing
218
  for (int attempt = 0; attempt < table_size_; ++attempt) {
7,184,505!
219
    // Determine slot to check, making sure it is positive
220
    int slot = (index_material + attempt) % table_size_;
7,184,505✔
221
    if (slot < 0)
7,184,505✔
222
      slot += table_size_;
4,756,362✔
223
    int32_t* slot_ptr = &this->materials(index_elem, slot);
7,184,505✔
224

225
    // Non-atomic read of current material
226
    int32_t current_val = *slot_ptr;
7,184,505✔
227

228
    // Found the desired material; accumulate volume and bbox
229
    if (current_val == index_material) {
7,184,505✔
230
#pragma omp atomic
3,997,047✔
231
      this->volumes(index_elem, slot) += volume;
7,141,574✔
232
      if (bbox) {
7,141,574✔
233
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
4,971,761✔
234
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
4,971,761✔
235
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
4,971,761✔
236
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
4,971,761✔
237
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
4,971,761✔
238
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
4,971,761✔
239
      }
240
      return;
7,141,574✔
241
    }
242

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

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

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

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

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

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

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

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

331
} // namespace detail
332

333
//==============================================================================
334
// Mesh implementation
335
//==============================================================================
336

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

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

370
  return model::meshes.back();
2,372✔
371
}
372

373
Mesh::Mesh(pugi::xml_node node)
2,408✔
374
{
375
  // Read mesh id
376
  id_ = std::stoi(get_node_value(node, "id"));
2,408✔
377
  if (check_for_node(node, "name"))
2,408✔
378
    name_ = get_node_value(node, "name");
12✔
379
}
2,408✔
380

381
Mesh::Mesh(hid_t group)
36✔
382
{
383
  // Read mesh ID
384
  read_attribute(group, "id", id_);
36✔
385

386
  // Read mesh name
387
  if (object_exists(group, "name")) {
36!
388
    read_dataset(group, "name", name_);
×
389
  }
390
}
36✔
391

392
void Mesh::set_id(int32_t id)
18✔
393
{
394
  assert(id >= 0 || id == C_NONE);
14!
395

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

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

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

417
  // Update ID and entry in the mesh map
418
  id_ = id;
18✔
419

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

425
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
18✔
426
}
18✔
427

428
vector<double> Mesh::volumes() const
198✔
429
{
430
  vector<double> volumes(n_bins());
198✔
431
  for (int i = 0; i < n_bins(); i++) {
905,247✔
432
    volumes[i] = this->volume(i);
905,049✔
433
  }
434
  return volumes;
198✔
435
}
×
436

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

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

459
  Timer timer;
153✔
460
  timer.start();
153✔
461

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

466
  // Determine bounding box
467
  auto bbox = this->bounding_box();
153✔
468

469
  std::array<int, 3> n_rays = {nx, ny, nz};
153✔
470

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

477
  // Set flag for mesh being contained within model
478
  bool out_of_model = false;
153✔
479

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

487
    SourceSite site;
68✔
488
    site.E = 1.0;
68✔
489
    site.particle = ParticleType::neutron();
68✔
490

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

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

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

519
      // Loop over rays on face of bounding box
520
#pragma omp for collapse(2)
521
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
12,640✔
522
        for (int i2 = 0; i2 < n2; ++i2) {
2,382,672✔
523
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
2,370,188✔
524
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
2,370,188✔
525

526
          p.from_source(&site);
2,370,188✔
527

528
          // Determine particle's location
529
          if (!exhaustive_find_cell(p)) {
2,370,188✔
530
            out_of_model = true;
31,944✔
531
            continue;
31,944✔
532
          }
533

534
          // Set birth cell attribute
535
          if (p.cell_born() == C_NONE)
2,338,244!
536
            p.cell_born() = p.lowest_coord().cell();
2,338,244✔
537

538
          // Initialize last cells from current cell
539
          for (int j = 0; j < p.n_coord(); ++j) {
4,676,488✔
540
            p.cell_last(j) = p.coord(j).cell();
2,338,244✔
541
          }
542
          p.n_coord_last() = p.n_coord();
2,338,244✔
543

544
          while (true) {
545
            // Ray trace from r_start to r_end
546
            Position r0 = p.r();
2,976,628✔
547
            double max_distance = bbox.max[axis] - r0[axis];
2,976,628✔
548

549
            // Find the distance to the nearest boundary
550
            BoundaryInfo boundary = distance_to_boundary(p);
2,976,628✔
551

552
            // Advance particle forward
553
            double distance = std::min(boundary.distance(), max_distance);
2,976,628✔
554
            p.move_distance(distance);
2,976,628✔
555

556
            // Determine what mesh elements were crossed by particle
557
            bins.clear();
2,976,628✔
558
            length_fractions.clear();
2,976,628✔
559
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
2,976,628✔
560

561
            // Add volumes to any mesh elements that were crossed
562
            int i_material = p.material();
2,976,628✔
563
            if (i_material != C_NONE) {
2,976,628✔
564
              i_material = model::materials[i_material]->id();
865,648✔
565
            }
566
            double cumulative_frac = 0.0;
2,976,628✔
567
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
6,128,176✔
568
              int mesh_index = bins[i_bin];
3,151,548✔
569
              double length = distance * length_fractions[i_bin];
3,151,548✔
570
              double volume = length * d1 * d2;
3,151,548✔
571

572
              if (compute_bboxes) {
3,151,548✔
573
                double axis_start = r0[axis] + distance * cumulative_frac;
2,186,680✔
574
                double axis_end = axis_start + length;
2,186,680✔
575
                cumulative_frac += length_fractions[i_bin];
2,186,680✔
576

577
                Position contrib_min = site.r;
2,186,680✔
578
                Position contrib_max = site.r;
2,186,680✔
579

580
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,186,680✔
581
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,186,680✔
582
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,186,680✔
583
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,186,680✔
584
                contrib_min[axis] = std::min(axis_start, axis_end);
2,186,680✔
585
                contrib_max[axis] = std::max(axis_start, axis_end);
2,186,680✔
586

587
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,186,680✔
588
                contrib_bbox &= bbox;
2,186,680✔
589

590
                result.add_volume(
2,186,680✔
591
                  mesh_index, i_material, volume, &contrib_bbox);
592
              } else {
593
                // Add volume to result
594
                result.add_volume(mesh_index, i_material, volume);
964,868✔
595
              }
596
            }
597

598
            if (distance == max_distance)
2,976,628✔
599
              break;
2,338,244✔
600

601
            // cross next geometric surface
602
            for (int j = 0; j < p.n_coord(); ++j) {
1,276,768✔
603
              p.cell_last(j) = p.coord(j).cell();
638,384✔
604
            }
605
            p.n_coord_last() = p.n_coord();
638,384✔
606

607
            // Set surface that particle is on and adjust coordinate levels
608
            p.surface() = boundary.surface();
638,384✔
609
            p.n_coord() = boundary.coord_level();
638,384✔
610

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

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

635
  // Compute time for raytracing
636
  double t_raytrace = timer.elapsed();
144✔
637

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

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

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

696
  // Report time for MPI communication
697
  double t_mpi = timer.elapsed() - t_raytrace;
48✔
698
#else
699
  double t_mpi = 0.0;
96✔
700
#endif
701

702
  // Normalize based on known volumes of elements
703
  for (int i = 0; i < this->n_bins(); ++i) {
873✔
704
    // Estimated total volume in element i
705
    double volume = 0.0;
729✔
706
    for (int j = 0; j < table_size; ++j) {
6,669✔
707
      volume += result.volumes(i, j);
5,940✔
708
    }
709
    // Renormalize volumes based on known volume of element i
710
    double norm = this->volume(i) / volume;
729✔
711
    for (int j = 0; j < table_size; ++j) {
6,669✔
712
      result.volumes(i, j) *= norm;
5,940✔
713
    }
714
  }
715

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

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

736
void Mesh::to_hdf5(hid_t group) const
2,359✔
737
{
738
  // Create group for mesh
739
  std::string group_name = fmt::format("mesh {}", id_);
4,172✔
740
  hid_t mesh_group = create_group(group, group_name.c_str());
2,359✔
741

742
  // Write mesh type
743
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,359✔
744

745
  // Write mesh ID
746
  write_attribute(mesh_group, "id", id_);
2,359✔
747

748
  // Write mesh name
749
  write_dataset(mesh_group, "name", name_);
2,359✔
750

751
  // Write mesh data
752
  this->to_hdf5_inner(mesh_group);
2,359✔
753

754
  // Close group
755
  close_group(mesh_group);
2,359✔
756
}
2,359✔
757

758
//==============================================================================
759
// Structured Mesh implementation
760
//==============================================================================
761

762
std::string StructuredMesh::bin_label(int bin) const
4,192,849✔
763
{
764
  MeshIndex ijk = get_indices_from_bin(bin);
4,192,849✔
765

766
  if (n_dimension_ > 2) {
4,192,849✔
767
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
8,359,616✔
768
  } else if (n_dimension_ > 1) {
13,041✔
769
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
25,632✔
770
  } else {
771
    return fmt::format("Mesh Index ({})", ijk[0]);
450✔
772
  }
773
}
774

775
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,044✔
776
{
777
  // because method is const, shape_ is const as well and can't be adapted
778
  auto tmp_shape = shape_;
2,044✔
779
  return xt::adapt(tmp_shape, {n_dimension_});
4,088✔
780
}
781

782
Position StructuredMesh::sample_element(
1,172,677✔
783
  const MeshIndex& ijk, uint64_t* seed) const
784
{
785
  // lookup the lower/upper bounds for the mesh element
786
  double x_min = negative_grid_boundary(ijk, 0);
1,172,677✔
787
  double x_max = positive_grid_boundary(ijk, 0);
1,172,677✔
788

789
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,172,677!
790
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,172,677!
791

792
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,172,677!
793
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,172,677!
794

795
  return {x_min + (x_max - x_min) * prn(seed),
1,172,677✔
796
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,172,677✔
797
}
798

799
//==============================================================================
800
// Unstructured Mesh implementation
801
//==============================================================================
802

803
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
23✔
804
{
805
  n_dimension_ = 3;
23✔
806

807
  // check the mesh type
808
  if (check_for_node(node, "type")) {
23!
809
    auto temp = get_node_value(node, "type", true, true);
23!
810
    if (temp != mesh_type) {
23!
811
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
812
    }
813
  }
23✔
814

815
  // check if a length unit multiplier was specified
816
  if (check_for_node(node, "length_multiplier")) {
23!
817
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
818
  }
819

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

831
  if (check_for_node(node, "options")) {
23!
UNCOV
832
    options_ = get_node_value(node, "options");
×
833
  }
834

835
  // check if mesh tally data should be written with
836
  // statepoint files
837
  if (check_for_node(node, "output")) {
23!
838
    output_ = get_node_value_bool(node, "output");
×
839
  }
840
}
23✔
841

842
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
843
{
844
  n_dimension_ = 3;
×
845

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

855
  // check if a length unit multiplier was specified
856
  if (object_exists(group, "length_multiplier")) {
×
857
    read_dataset(group, "length_multiplier", length_multiplier_);
×
858
  }
859

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

871
  if (attribute_exists(group, "options")) {
×
872
    read_attribute(group, "options", options_);
×
873
  }
874

875
  // check if mesh tally data should be written with
876
  // statepoint files
877
  if (attribute_exists(group, "output")) {
×
878
    read_attribute(group, "output", output_);
×
879
  }
880
}
×
881

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

904
Position UnstructuredMesh::sample_tet(
400,820✔
905
  std::array<Position, 4> coords, uint64_t* seed) const
906
{
907
  // Uniform distribution
908
  double s = prn(seed);
400,820✔
909
  double t = prn(seed);
400,820✔
910
  double u = prn(seed);
400,820✔
911

912
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
913
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
914
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
915
  if (s + t > 1) {
400,820✔
916
    s = 1.0 - s;
200,080✔
917
    t = 1.0 - t;
200,080✔
918
  }
919
  if (s + t + u > 1) {
400,820✔
920
    if (t + u > 1) {
267,326✔
921
      double old_t = t;
133,906✔
922
      t = 1.0 - u;
133,906✔
923
      u = 1.0 - s - old_t;
133,906✔
924
    } else if (t + u <= 1) {
133,420!
925
      double old_s = s;
133,420✔
926
      s = 1.0 - t - u;
133,420✔
927
      u = old_s + t + u - 1;
133,420✔
928
    }
929
  }
930
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
801,640✔
931
         u * (coords[3] - coords[0]) + coords[0];
1,202,460✔
932
}
933

934
const std::string UnstructuredMesh::mesh_type = "unstructured";
935

936
std::string UnstructuredMesh::get_mesh_type() const
18✔
937
{
938
  return mesh_type;
18✔
939
}
940

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

947
std::string UnstructuredMesh::bin_label(int bin) const
97,856✔
948
{
949
  return fmt::format("Mesh Index ({})", bin);
97,856!
950
};
951

952
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
18✔
953
{
954
  write_dataset(mesh_group, "filename", filename_);
18!
955
  write_dataset(mesh_group, "library", this->library());
18!
956
  if (!options_.empty()) {
18!
UNCOV
957
    write_attribute(mesh_group, "options", options_);
×
958
  }
959

960
  if (length_multiplier_ > 0.0)
18!
961
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
962

963
  // write vertex coordinates
964
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
18!
965
  for (int i = 0; i < this->n_vertices(); i++) {
39,960!
966
    auto v = this->vertex(i);
39,942!
967
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
39,942!
968
  }
969
  write_dataset(mesh_group, "vertices", vertices);
18!
970

971
  int num_elem_skipped = 0;
18✔
972

973
  // write element types and connectivity
974
  vector<double> volumes;
18✔
975
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
18!
976
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
18!
977
  for (int i = 0; i < this->n_bins(); i++) {
193,874!
978
    auto conn = this->connectivity(i);
193,856!
979

980
    volumes.emplace_back(this->volume(i));
193,856!
981

982
    // write linear tet element
983
    if (conn.size() == 4) {
193,856✔
984
      xt::view(elem_types, i, xt::all()) =
383,712!
985
        static_cast<int>(ElementType::LINEAR_TET);
383,712!
986
      xt::view(connectivity, i, xt::all()) =
383,712!
987
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
575,568!
988
      // write linear hex element
989
    } else if (conn.size() == 8) {
2,000!
990
      xt::view(elem_types, i, xt::all()) =
4,000!
991
        static_cast<int>(ElementType::LINEAR_HEX);
4,000!
992
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000!
993
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000!
994
    } else {
995
      num_elem_skipped++;
×
996
      xt::view(elem_types, i, xt::all()) =
×
997
        static_cast<int>(ElementType::UNSUPPORTED);
×
998
      xt::view(connectivity, i, xt::all()) = -1;
×
999
    }
1000
  }
193,856✔
1001

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

1010
  write_dataset(mesh_group, "volumes", volumes);
18!
1011
  write_dataset(mesh_group, "connectivity", connectivity);
18!
1012
  write_dataset(mesh_group, "element_types", elem_types);
18!
1013
}
18✔
1014

1015
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
1016
{
1017
  length_multiplier_ = length_multiplier;
23✔
1018
}
23✔
1019

1020
ElementType UnstructuredMesh::element_type(int bin) const
72,000✔
1021
{
1022
  auto conn = connectivity(bin);
72,000!
1023

1024
  if (conn.size() == 4)
72,000!
1025
    return ElementType::LINEAR_TET;
72,000✔
1026
  else if (conn.size() == 8)
×
1027
    return ElementType::LINEAR_HEX;
×
1028
  else
1029
    return ElementType::UNSUPPORTED;
×
1030
}
72,000✔
1031

1032
StructuredMesh::MeshIndex StructuredMesh::get_indices(
960,374,630✔
1033
  Position r, bool& in_mesh) const
1034
{
1035
  MeshIndex ijk;
1036
  in_mesh = true;
960,374,630✔
1037
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1038
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1039

1040
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1041
      in_mesh = false;
83,197,650✔
1042
  }
1043
  return ijk;
960,374,630✔
1044
}
1045

1046
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,417,039,198✔
1047
{
1048
  switch (n_dimension_) {
1,417,039,198!
1049
  case 1:
720,495✔
1050
    return ijk[0] - 1;
720,495✔
1051
  case 2:
111,579,732✔
1052
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
111,579,732✔
1053
  case 3:
1,304,738,971✔
1054
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,304,738,971✔
1055
  default:
×
1056
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1057
  }
1058
}
1059

1060
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
6,345,284✔
1061
{
1062
  MeshIndex ijk;
1063
  if (n_dimension_ == 1) {
6,345,284✔
1064
    ijk[0] = bin + 1;
225✔
1065
  } else if (n_dimension_ == 2) {
6,345,059✔
1066
    ijk[0] = bin % shape_[0] + 1;
12,816✔
1067
    ijk[1] = bin / shape_[0] + 1;
12,816✔
1068
  } else if (n_dimension_ == 3) {
6,332,243!
1069
    ijk[0] = bin % shape_[0] + 1;
6,332,243✔
1070
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
6,332,243✔
1071
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
6,332,243✔
1072
  }
1073
  return ijk;
6,345,284✔
1074
}
1075

1076
int StructuredMesh::get_bin(Position r) const
201,068,628✔
1077
{
1078
  // Determine indices
1079
  bool in_mesh;
1080
  MeshIndex ijk = get_indices(r, in_mesh);
201,068,628✔
1081
  if (!in_mesh)
201,068,628✔
1082
    return -1;
16,965,058✔
1083

1084
  // Convert indices to bin
1085
  return get_bin_from_indices(ijk);
184,103,570✔
1086
}
1087

1088
int StructuredMesh::n_bins() const
916,890✔
1089
{
1090
  return std::accumulate(
916,890✔
1091
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,833,780✔
1092
}
1093

1094
int StructuredMesh::n_surface_bins() const
300✔
1095
{
1096
  return 4 * n_dimension_ * n_bins();
300✔
1097
}
1098

1099
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
1100
  const SourceSite* bank, int64_t length, bool* outside) const
1101
{
1102
  // Determine shape of array for counts
1103
  std::size_t m = this->n_bins();
×
1104
  vector<std::size_t> shape = {m};
×
1105

1106
  // Create array of zeros
1107
  xt::xarray<double> cnt {shape, 0.0};
×
1108
  bool outside_ = false;
×
1109

1110
  for (int64_t i = 0; i < length; i++) {
×
1111
    const auto& site = bank[i];
×
1112

1113
    // determine scoring bin for entropy mesh
1114
    int mesh_bin = get_bin(site.r);
×
1115

1116
    // if outside mesh, skip particle
1117
    if (mesh_bin < 0) {
×
1118
      outside_ = true;
×
1119
      continue;
×
1120
    }
1121

1122
    // Add to appropriate bin
1123
    cnt(mesh_bin) += site.wgt;
×
1124
  }
1125

1126
  // Create copy of count data. Since ownership will be acquired by xtensor,
1127
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
1128
  // warnings.
1129
  int total = cnt.size();
×
1130
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
1131

1132
#ifdef OPENMC_MPI
1133
  // collect values from all processors
1134
  MPI_Reduce(
×
1135
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
1136

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

1147
  // Adapt reduced values in array back into an xarray
1148
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
1149
  xt::xarray<double> counts = arr;
×
1150

1151
  return counts;
×
1152
}
×
1153

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

1167
  // Compute the length of the entire track.
1168
  double total_distance = (r1 - r0).norm();
763,360,721✔
1169
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
763,360,721✔
1170
    return;
9,890,589✔
1171

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

1177
  const int n = n_dimension_;
753,470,132✔
1178

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

1182
  // Position is r = r0 + u * traveled_distance, start at r0
1183
  double traveled_distance {0.0};
753,470,132✔
1184

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

1189
  // if track is very short, assume that it is completely inside one cell.
1190
  // Only the current cell will score and no surfaces
1191
  if (total_distance < 2 * TINY_BIT) {
753,470,132✔
1192
    if (in_mesh) {
271,341✔
1193
      tally.track(ijk, 1.0);
270,837✔
1194
    }
1195
    return;
271,341✔
1196
  }
1197

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

1204
  // Loop until r = r1 is eventually reached
1205
  while (true) {
616,549,518✔
1206

1207
    if (in_mesh) {
1,369,748,309✔
1208

1209
      // find surface with minimal distance to current position
1210
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,299,661,916✔
1211
                     distances.begin();
1,299,661,916✔
1212

1213
      // Tally track length delta since last step
1214
      tally.track(ijk,
1,299,661,916✔
1215
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,299,661,916✔
1216
          total_distance);
1217

1218
      // update position and leave, if we have reached end position
1219
      traveled_distance = distances[k].distance;
1,299,661,916✔
1220
      if (traveled_distance >= total_distance)
1,299,661,916✔
1221
        return;
688,948,268✔
1222

1223
      // If we have not reached r1, we have hit a surface. Tally outward
1224
      // current
1225
      tally.surface(ijk, k, distances[k].max_surface, false);
610,713,648✔
1226

1227
      // Update cell and calculate distance to next surface in k-direction.
1228
      // The two other directions are still valid!
1229
      ijk[k] = distances[k].next_index;
610,713,648✔
1230
      distances[k] =
610,713,648✔
1231
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
610,713,648✔
1232

1233
      // Check if we have left the interior of the mesh
1234
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
610,713,648✔
1235

1236
      // If we are still inside the mesh, tally inward current for the next
1237
      // cell
1238
      if (in_mesh)
610,713,648✔
1239
        tally.surface(ijk, k, !distances[k].max_surface, true);
599,843,457✔
1240

1241
    } else { // not inside mesh
1242

1243
      // For all directions outside the mesh, find the distance that we need
1244
      // to travel to reach the next surface. Use the largest distance, as
1245
      // only this will cross all outer surfaces.
1246
      int k_max {-1};
70,086,393✔
1247
      for (int k = 0; k < n; ++k) {
279,163,818✔
1248
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
285,640,551✔
1249
            (distances[k].distance > traveled_distance)) {
76,563,126✔
1250
          traveled_distance = distances[k].distance;
72,536,238✔
1251
          k_max = k;
72,536,238✔
1252
        }
1253
      }
1254
      // Assure some distance is traveled
1255
      if (k_max == -1) {
70,086,393✔
1256
        traveled_distance += TINY_BIT;
90✔
1257
      }
1258

1259
      // If r1 is not inside the mesh, exit here
1260
      if (traveled_distance >= total_distance)
70,086,393✔
1261
        return;
64,250,523✔
1262

1263
      // Calculate the new cell index and update all distances to next
1264
      // surfaces.
1265
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
5,835,870✔
1266
      for (int k = 0; k < n; ++k) {
23,172,858✔
1267
        distances[k] =
17,336,988✔
1268
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
17,336,988✔
1269
      }
1270

1271
      // If inside the mesh, Tally inward current
1272
      if (in_mesh && k_max >= 0)
5,835,870!
1273
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
5,503,104✔
1274
    }
1275
  }
1276
}
1277

1278
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
671,619,986✔
1279
  vector<int>& bins, vector<double>& lengths) const
1280
{
1281

1282
  // Helper tally class.
1283
  // stores a pointer to the mesh class and references to bins and lengths
1284
  // parameters. Performs the actual tally through the track method.
1285
  struct TrackAggregator {
1286
    TrackAggregator(
671,619,986✔
1287
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1288
      : mesh(_mesh), bins(_bins), lengths(_lengths)
671,619,986✔
1289
    {}
671,619,986✔
1290
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1,168,475,418✔
1291
    void track(const MeshIndex& ijk, double l) const
1,185,350,837✔
1292
    {
1293
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,185,350,837✔
1294
      lengths.push_back(l);
1,185,350,837✔
1295
    }
1,185,350,837✔
1296

1297
    const StructuredMesh* mesh;
1298
    vector<int>& bins;
1299
    vector<double>& lengths;
1300
  };
1301

1302
  // Perform the mesh raytrace with the helper class.
1303
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
671,619,986✔
1304
}
671,619,986✔
1305

1306
void StructuredMesh::surface_bins_crossed(
91,740,735✔
1307
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1308
{
1309

1310
  // Helper tally class.
1311
  // stores a pointer to the mesh class and a reference to the bins parameter.
1312
  // Performs the actual tally through the surface method.
1313
  struct SurfaceAggregator {
1314
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
91,740,735✔
1315
      : mesh(_mesh), bins(_bins)
91,740,735✔
1316
    {}
91,740,735✔
1317
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
47,584,791✔
1318
    {
1319
      int i_bin =
1320
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
47,584,791✔
1321
      if (max)
47,584,791✔
1322
        i_bin += 2;
23,769,360✔
1323
      if (inward)
47,584,791✔
1324
        i_bin += 1;
23,385,510✔
1325
      bins.push_back(i_bin);
47,584,791✔
1326
    }
47,584,791✔
1327
    void track(const MeshIndex& idx, double l) const {}
114,581,916✔
1328

1329
    const StructuredMesh* mesh;
1330
    vector<int>& bins;
1331
  };
1332

1333
  // Perform the mesh raytrace with the helper class.
1334
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
91,740,735✔
1335
}
91,740,735✔
1336

1337
//==============================================================================
1338
// RegularMesh implementation
1339
//==============================================================================
1340

1341
int RegularMesh::set_grid()
1,686✔
1342
{
1343
  auto shape = xt::adapt(shape_, {n_dimension_});
1,686✔
1344

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

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

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

1367
    // Check for negative widths
1368
    if (xt::any(width_ < 0.0)) {
36!
1369
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1370
      return OPENMC_E_INVALID_ARGUMENT;
×
1371
    }
1372

1373
    // Set width and upper right coordinate
1374
    upper_right_ = xt::eval(lower_left_ + shape * width_);
36✔
1375

1376
  } else if (upper_right_.size() > 0) {
1,650!
1377

1378
    // Check to ensure upper_right_ has same dimensions
1379
    if (upper_right_.size() != n_dimension_) {
1,650!
1380
      set_errmsg("Number of entries on upper_right must be the "
×
1381
                 "same as the regular mesh dimensions.");
1382
      return OPENMC_E_INVALID_ARGUMENT;
×
1383
    }
1384

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

1393
    // Set width
1394
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1,650✔
1395
  }
1396

1397
  // Set material volumes
1398
  volume_frac_ = 1.0 / xt::prod(shape)();
1,686✔
1399

1400
  element_volume_ = 1.0;
1,686✔
1401
  for (int i = 0; i < n_dimension_; i++) {
6,306✔
1402
    element_volume_ *= width_[i];
4,620✔
1403
  }
1404
  return 0;
1,686✔
1405
}
1,686✔
1406

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

1414
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
1,677✔
1415
  int n = n_dimension_ = shape.size();
1,677✔
1416
  if (n != 1 && n != 2 && n != 3) {
1,677!
1417
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1418
  }
1419
  std::copy(shape.begin(), shape.end(), shape_.begin());
1,677✔
1420

1421
  // Check for lower-left coordinates
1422
  if (check_for_node(node, "lower_left")) {
1,677!
1423
    // Read mesh lower-left corner location
1424
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1,677✔
1425
  } else {
1426
    fatal_error("Must specify <lower_left> on a mesh.");
×
1427
  }
1428

1429
  if (check_for_node(node, "width")) {
1,677✔
1430
    // Make sure one of upper-right or width were specified
1431
    if (check_for_node(node, "upper_right")) {
36!
1432
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1433
    }
1434

1435
    width_ = get_node_xarray<double>(node, "width");
36✔
1436

1437
  } else if (check_for_node(node, "upper_right")) {
1,641!
1438

1439
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1,641✔
1440

1441
  } else {
1442
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1443
  }
1444

1445
  if (int err = set_grid()) {
1,677!
1446
    fatal_error(openmc_err_msg);
×
1447
  }
1448
}
1,677✔
1449

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

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

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

1473
  if (object_exists(group, "upper_right")) {
9!
1474

1475
    read_dataset(group, "upper_right", upper_right_);
9✔
1476

1477
  } else {
1478
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1479
  }
1480

1481
  if (int err = set_grid()) {
9!
1482
    fatal_error(openmc_err_msg);
×
1483
  }
1484
}
9✔
1485

1486
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1487
{
1488
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1489
}
1490

1491
const std::string RegularMesh::mesh_type = "regular";
1492

1493
std::string RegularMesh::get_mesh_type() const
2,611✔
1494
{
1495
  return mesh_type;
2,611✔
1496
}
1497

1498
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,205,268,675✔
1499
{
1500
  return lower_left_[i] + ijk[i] * width_[i];
1,205,268,675✔
1501
}
1502

1503
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,148,711,102✔
1504
{
1505
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,148,711,102✔
1506
}
1507

1508
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1509
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1510
  double l) const
1511
{
1512
  MeshDistance d;
2,147,483,647✔
1513
  d.next_index = ijk[i];
2,147,483,647✔
1514
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1515
    return d;
11,136,786✔
1516

1517
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1518
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1519
    d.next_index++;
1,201,750,644✔
1520
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,201,750,644✔
1521
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,162,389,920✔
1522
    d.next_index--;
1,145,193,071✔
1523
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,145,193,071✔
1524
  }
1525

1526
  return d;
2,147,483,647✔
1527
}
1528

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

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

1559
    double coord = lower_left_[axis];
36✔
1560
    for (int i = 0; i < shape_[axis] + 1; ++i) {
234✔
1561
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
198!
1562
        lines.push_back(coord);
198✔
1563
      coord += width_[axis];
198✔
1564
    }
1565
  }
1566

1567
  return {axis_lines[0], axis_lines[1]};
36✔
1568
}
18✔
1569

1570
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1,684✔
1571
{
1572
  write_dataset(mesh_group, "dimension", get_x_shape());
1,684✔
1573
  write_dataset(mesh_group, "lower_left", lower_left_);
1,684✔
1574
  write_dataset(mesh_group, "upper_right", upper_right_);
1,684✔
1575
  write_dataset(mesh_group, "width", width_);
1,684✔
1576
}
1,684✔
1577

1578
xt::xtensor<double, 1> RegularMesh::count_sites(
6,393✔
1579
  const SourceSite* bank, int64_t length, bool* outside) const
1580
{
1581
  // Determine shape of array for counts
1582
  std::size_t m = this->n_bins();
6,393✔
1583
  vector<std::size_t> shape = {m};
6,393✔
1584

1585
  // Create array of zeros
1586
  xt::xarray<double> cnt {shape, 0.0};
6,393✔
1587
  bool outside_ = false;
6,393✔
1588

1589
  for (int64_t i = 0; i < length; i++) {
6,279,762✔
1590
    const auto& site = bank[i];
6,273,369✔
1591

1592
    // determine scoring bin for entropy mesh
1593
    int mesh_bin = get_bin(site.r);
6,273,369✔
1594

1595
    // if outside mesh, skip particle
1596
    if (mesh_bin < 0) {
6,273,369!
1597
      outside_ = true;
×
1598
      continue;
×
1599
    }
1600

1601
    // Add to appropriate bin
1602
    cnt(mesh_bin) += site.wgt;
6,273,369✔
1603
  }
1604

1605
  // Create copy of count data. Since ownership will be acquired by xtensor,
1606
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
1607
  // warnings.
1608
  int total = cnt.size();
6,393✔
1609
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
6,393✔
1610

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

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

1626
  // Adapt reduced values in array back into an xarray
1627
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
6,393✔
1628
  xt::xarray<double> counts = arr;
6,393✔
1629

1630
  return counts;
12,786✔
1631
}
6,393✔
1632

1633
double RegularMesh::volume(const MeshIndex& ijk) const
906,057✔
1634
{
1635
  return element_volume_;
906,057✔
1636
}
1637

1638
//==============================================================================
1639
// RectilinearMesh implementation
1640
//==============================================================================
1641

1642
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
99✔
1643
{
1644
  n_dimension_ = 3;
99✔
1645

1646
  grid_[0] = get_node_array<double>(node, "x_grid");
99✔
1647
  grid_[1] = get_node_array<double>(node, "y_grid");
99✔
1648
  grid_[2] = get_node_array<double>(node, "z_grid");
99✔
1649

1650
  if (int err = set_grid()) {
99!
1651
    fatal_error(openmc_err_msg);
×
1652
  }
1653
}
99✔
1654

1655
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
9✔
1656
{
1657
  n_dimension_ = 3;
9✔
1658

1659
  read_dataset(group, "x_grid", grid_[0]);
9✔
1660
  read_dataset(group, "y_grid", grid_[1]);
9✔
1661
  read_dataset(group, "z_grid", grid_[2]);
9✔
1662

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

1668
const std::string RectilinearMesh::mesh_type = "rectilinear";
1669

1670
std::string RectilinearMesh::get_mesh_type() const
225✔
1671
{
1672
  return mesh_type;
225✔
1673
}
1674

1675
double RectilinearMesh::positive_grid_boundary(
21,686,697✔
1676
  const MeshIndex& ijk, int i) const
1677
{
1678
  return grid_[i][ijk[i]];
21,686,697✔
1679
}
1680

1681
double RectilinearMesh::negative_grid_boundary(
21,059,514✔
1682
  const MeshIndex& ijk, int i) const
1683
{
1684
  return grid_[i][ijk[i] - 1];
21,059,514✔
1685
}
1686

1687
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
43,856,253✔
1688
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1689
  double l) const
1690
{
1691
  MeshDistance d;
43,856,253✔
1692
  d.next_index = ijk[i];
43,856,253✔
1693
  if (std::abs(u[i]) < FP_PRECISION)
43,856,253✔
1694
    return d;
467,856✔
1695

1696
  d.max_surface = (u[i] > 0);
43,388,397✔
1697
  if (d.max_surface && (ijk[i] <= shape_[i])) {
43,388,397✔
1698
    d.next_index++;
21,686,697✔
1699
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
21,686,697✔
1700
  } else if (!d.max_surface && (ijk[i] > 0)) {
21,701,700✔
1701
    d.next_index--;
21,059,514✔
1702
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
21,059,514✔
1703
  }
1704
  return d;
43,388,397✔
1705
}
1706

1707
int RectilinearMesh::set_grid()
144✔
1708
{
1709
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
144✔
1710
    static_cast<int>(grid_[1].size()) - 1,
144✔
1711
    static_cast<int>(grid_[2].size()) - 1};
144✔
1712

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

1727
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
144✔
1728
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
144✔
1729

1730
  return 0;
144✔
1731
}
1732

1733
int RectilinearMesh::get_index_in_direction(double r, int i) const
60,634,548✔
1734
{
1735
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
60,634,548✔
1736
}
1737

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

1753
  // Get the coordinates of the mesh lines along both of the axes.
1754
  array<vector<double>, 2> axis_lines;
9✔
1755
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
27✔
1756
    int axis = axes[i_ax];
18✔
1757
    vector<double>& lines {axis_lines[i_ax]};
18✔
1758

1759
    for (auto coord : grid_[axis]) {
90✔
1760
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
72!
1761
        lines.push_back(coord);
72✔
1762
    }
1763
  }
1764

1765
  return {axis_lines[0], axis_lines[1]};
18✔
1766
}
9✔
1767

1768
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
90✔
1769
{
1770
  write_dataset(mesh_group, "x_grid", grid_[0]);
90✔
1771
  write_dataset(mesh_group, "y_grid", grid_[1]);
90✔
1772
  write_dataset(mesh_group, "z_grid", grid_[2]);
90✔
1773
}
90✔
1774

1775
double RectilinearMesh::volume(const MeshIndex& ijk) const
108✔
1776
{
1777
  double vol {1.0};
108✔
1778

1779
  for (int i = 0; i < n_dimension_; i++) {
432✔
1780
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
324✔
1781
  }
1782
  return vol;
108✔
1783
}
1784

1785
//==============================================================================
1786
// CylindricalMesh implementation
1787
//==============================================================================
1788

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

1798
  if (int err = set_grid()) {
327!
1799
    fatal_error(openmc_err_msg);
×
1800
  }
1801
}
327✔
1802

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

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

1816
const std::string CylindricalMesh::mesh_type = "cylindrical";
1817

1818
std::string CylindricalMesh::get_mesh_type() const
396✔
1819
{
1820
  return mesh_type;
396✔
1821
}
1822

1823
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
39,053,529✔
1824
  Position r, bool& in_mesh) const
1825
{
1826
  r = local_coords(r);
39,053,529✔
1827

1828
  Position mapped_r;
39,053,529✔
1829
  mapped_r[0] = std::hypot(r.x, r.y);
39,053,529✔
1830
  mapped_r[2] = r[2];
39,053,529✔
1831

1832
  if (mapped_r[0] < FP_PRECISION) {
39,053,529!
1833
    mapped_r[1] = 0.0;
×
1834
  } else {
1835
    mapped_r[1] = std::atan2(r.y, r.x);
39,053,529✔
1836
    if (mapped_r[1] < 0)
39,053,529✔
1837
      mapped_r[1] += 2 * M_PI;
19,533,978✔
1838
  }
1839

1840
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
39,053,529✔
1841

1842
  idx[1] = sanitize_phi(idx[1]);
39,053,529✔
1843

1844
  return idx;
39,053,529✔
1845
}
1846

1847
Position CylindricalMesh::sample_element(
72,090✔
1848
  const MeshIndex& ijk, uint64_t* seed) const
1849
{
1850
  double r_min = this->r(ijk[0] - 1);
72,090✔
1851
  double r_max = this->r(ijk[0]);
72,090✔
1852

1853
  double phi_min = this->phi(ijk[1] - 1);
72,090✔
1854
  double phi_max = this->phi(ijk[1]);
72,090✔
1855

1856
  double z_min = this->z(ijk[2] - 1);
72,090✔
1857
  double z_max = this->z(ijk[2]);
72,090✔
1858

1859
  double r_min_sq = r_min * r_min;
72,090✔
1860
  double r_max_sq = r_max * r_max;
72,090✔
1861
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
72,090✔
1862
  double phi = uniform_distribution(phi_min, phi_max, seed);
72,090✔
1863
  double z = uniform_distribution(z_min, z_max, seed);
72,090✔
1864

1865
  double x = r * std::cos(phi);
72,090✔
1866
  double y = r * std::sin(phi);
72,090✔
1867

1868
  return origin_ + Position(x, y, z);
72,090✔
1869
}
1870

1871
double CylindricalMesh::find_r_crossing(
116,662,234✔
1872
  const Position& r, const Direction& u, double l, int shell) const
1873
{
1874

1875
  if ((shell < 0) || (shell > shape_[0]))
116,662,234!
1876
    return INFTY;
14,656,806✔
1877

1878
  // solve r.x^2 + r.y^2 == r0^2
1879
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1880
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1881

1882
  const double r0 = grid_[0][shell];
102,005,428✔
1883
  if (r0 == 0.0)
102,005,428✔
1884
    return INFTY;
5,838,606✔
1885

1886
  const double denominator = u.x * u.x + u.y * u.y;
96,166,822✔
1887

1888
  // Direction of flight is in z-direction. Will never intersect r.
1889
  if (std::abs(denominator) < FP_PRECISION)
96,166,822✔
1890
    return INFTY;
48,240✔
1891

1892
  // inverse of dominator to help the compiler to speed things up
1893
  const double inv_denominator = 1.0 / denominator;
96,118,582✔
1894

1895
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
96,118,582✔
1896
  double R = std::sqrt(r.x * r.x + r.y * r.y);
96,118,582✔
1897
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
96,118,582✔
1898

1899
  if (D < 0.0)
96,118,582✔
1900
    return INFTY;
7,965,918✔
1901

1902
  D = std::sqrt(D);
88,152,664✔
1903

1904
  // Particle is already on the shell surface; avoid spurious crossing
1905
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
88,152,664✔
1906
    return INFTY;
5,427,306✔
1907

1908
  // Check -p - D first because it is always smaller as -p + D
1909
  if (-p - D > l)
82,725,358✔
1910
    return -p - D;
16,533,669✔
1911
  if (-p + D > l)
66,191,689✔
1912
    return -p + D;
40,972,862✔
1913

1914
  return INFTY;
25,218,827✔
1915
}
1916

1917
double CylindricalMesh::find_phi_crossing(
60,918,876✔
1918
  const Position& r, const Direction& u, double l, int shell) const
1919
{
1920
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1921
  if (full_phi_ && (shape_[1] == 1))
60,918,876✔
1922
    return INFTY;
24,942,834✔
1923

1924
  shell = sanitize_phi(shell);
35,976,042✔
1925

1926
  const double p0 = grid_[1][shell];
35,976,042✔
1927

1928
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1929
  // => x(s) * cos(p0) = y(s) * sin(p0)
1930
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1931
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1932

1933
  const double c0 = std::cos(p0);
35,976,042✔
1934
  const double s0 = std::sin(p0);
35,976,042✔
1935

1936
  const double denominator = (u.x * s0 - u.y * c0);
35,976,042✔
1937

1938
  // Check if direction of flight is not parallel to phi surface
1939
  if (std::abs(denominator) > FP_PRECISION) {
35,976,042✔
1940
    const double s = -(r.x * s0 - r.y * c0) / denominator;
35,762,706✔
1941
    // Check if solution is in positive direction of flight and crosses the
1942
    // correct phi surface (not -phi)
1943
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
35,762,706✔
1944
      return s;
16,543,521✔
1945
  }
1946

1947
  return INFTY;
19,432,521✔
1948
}
1949

1950
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
30,023,793✔
1951
  const Position& r, const Direction& u, double l, int shell) const
1952
{
1953
  MeshDistance d;
30,023,793✔
1954
  d.next_index = shell;
30,023,793✔
1955

1956
  // Direction of flight is within xy-plane. Will never intersect z.
1957
  if (std::abs(u.z) < FP_PRECISION)
30,023,793✔
1958
    return d;
914,904✔
1959

1960
  d.max_surface = (u.z > 0.0);
29,108,889✔
1961
  if (d.max_surface && (shell <= shape_[2])) {
29,108,889✔
1962
    d.next_index += 1;
13,807,548✔
1963
    d.distance = (grid_[2][shell] - r.z) / u.z;
13,807,548✔
1964
  } else if (!d.max_surface && (shell > 0)) {
15,301,341✔
1965
    d.next_index -= 1;
13,783,275✔
1966
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
13,783,275✔
1967
  }
1968
  return d;
29,108,889✔
1969
}
1970

1971
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
118,814,348✔
1972
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1973
  double l) const
1974
{
1975
  if (i == 0) {
118,814,348✔
1976

1977
    return std::min(
58,331,117✔
1978
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
58,331,117✔
1979
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
116,662,234✔
1980

1981
  } else if (i == 1) {
60,483,231✔
1982

1983
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
30,459,438✔
1984
                      find_phi_crossing(r0, u, l, ijk[i])),
30,459,438✔
1985
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
30,459,438✔
1986
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
60,918,876✔
1987

1988
  } else {
1989
    return find_z_crossing(r0, u, l, ijk[i]);
30,023,793✔
1990
  }
1991
}
1992

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

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

2026
    return OPENMC_E_INVALID_ARGUMENT;
×
2027
  }
2028

2029
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
354!
2030

2031
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
708✔
2032
    origin_[2] + grid_[2].front()};
708✔
2033
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
708✔
2034
    origin_[2] + grid_[2].back()};
708✔
2035

2036
  return 0;
354✔
2037
}
2038

2039
int CylindricalMesh::get_index_in_direction(double r, int i) const
117,160,587✔
2040
{
2041
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
117,160,587✔
2042
}
2043

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

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

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

2062
double CylindricalMesh::volume(const MeshIndex& ijk) const
648✔
2063
{
2064
  double r_i = grid_[0][ijk[0] - 1];
648✔
2065
  double r_o = grid_[0][ijk[0]];
648✔
2066

2067
  double phi_i = grid_[1][ijk[1] - 1];
648✔
2068
  double phi_o = grid_[1][ijk[1]];
648✔
2069

2070
  double z_i = grid_[2][ijk[2] - 1];
648✔
2071
  double z_o = grid_[2][ijk[2]];
648✔
2072

2073
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
648✔
2074
}
2075

2076
//==============================================================================
2077
// SphericalMesh implementation
2078
//==============================================================================
2079

2080
SphericalMesh::SphericalMesh(pugi::xml_node node)
282✔
2081
  : PeriodicStructuredMesh {node}
282✔
2082
{
2083
  n_dimension_ = 3;
282✔
2084

2085
  grid_[0] = get_node_array<double>(node, "r_grid");
282✔
2086
  grid_[1] = get_node_array<double>(node, "theta_grid");
282✔
2087
  grid_[2] = get_node_array<double>(node, "phi_grid");
282✔
2088
  origin_ = get_node_position(node, "origin");
282✔
2089

2090
  if (int err = set_grid()) {
282!
2091
    fatal_error(openmc_err_msg);
×
2092
  }
2093
}
282✔
2094

2095
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
9✔
2096
{
2097
  n_dimension_ = 3;
9✔
2098

2099
  read_dataset(group, "r_grid", grid_[0]);
9✔
2100
  read_dataset(group, "theta_grid", grid_[1]);
9✔
2101
  read_dataset(group, "phi_grid", grid_[2]);
9✔
2102
  read_dataset(group, "origin", origin_);
9✔
2103

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

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

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

2116
StructuredMesh::MeshIndex SphericalMesh::get_indices(
56,120,832✔
2117
  Position r, bool& in_mesh) const
2118
{
2119
  r = local_coords(r);
56,120,832✔
2120

2121
  Position mapped_r;
56,120,832✔
2122
  mapped_r[0] = r.norm();
56,120,832✔
2123

2124
  if (mapped_r[0] < FP_PRECISION) {
56,120,832!
2125
    mapped_r[1] = 0.0;
×
2126
    mapped_r[2] = 0.0;
×
2127
  } else {
2128
    mapped_r[1] = std::acos(r.z / mapped_r.x);
56,120,832✔
2129
    mapped_r[2] = std::atan2(r.y, r.x);
56,120,832✔
2130
    if (mapped_r[2] < 0)
56,120,832✔
2131
      mapped_r[2] += 2 * M_PI;
28,038,015✔
2132
  }
2133

2134
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
56,120,832✔
2135

2136
  idx[1] = sanitize_theta(idx[1]);
56,120,832✔
2137
  idx[2] = sanitize_phi(idx[2]);
56,120,832✔
2138

2139
  return idx;
56,120,832✔
2140
}
2141

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

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

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

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

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

2167
  return origin_ + Position(x, y, z);
90✔
2168
}
2169

2170
double SphericalMesh::find_r_crossing(
363,303,952✔
2171
  const Position& r, const Direction& u, double l, int shell) const
2172
{
2173
  if ((shell < 0) || (shell > shape_[0]))
363,303,952✔
2174
    return INFTY;
32,417,253✔
2175

2176
  // solve |r+s*u| = r0
2177
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2178
  const double r0 = grid_[0][shell];
330,886,699✔
2179
  if (r0 == 0.0)
330,886,699✔
2180
    return INFTY;
6,282,423✔
2181
  const double p = r.dot(u);
324,604,276✔
2182
  double R = r.norm();
324,604,276✔
2183
  double D = p * p - (R - r0) * (R + r0);
324,604,276✔
2184

2185
  // Particle is already on the shell surface; avoid spurious crossing
2186
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
324,604,276✔
2187
    return INFTY;
8,761,626✔
2188

2189
  if (D >= 0.0) {
315,842,650✔
2190
    D = std::sqrt(D);
293,034,238✔
2191
    // Check -p - D first because it is always smaller as -p + D
2192
    if (-p - D > l)
293,034,238✔
2193
      return -p - D;
52,633,460✔
2194
    if (-p + D > l)
240,400,778✔
2195
      return -p + D;
145,039,310✔
2196
  }
2197

2198
  return INFTY;
118,169,880✔
2199
}
2200

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

2208
  shell = sanitize_theta(shell);
31,384,260✔
2209

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

2217
  const double cos_t = std::cos(grid_[1][shell]);
31,384,260✔
2218
  const bool sgn = std::signbit(cos_t);
31,384,260✔
2219
  const double cos_t_2 = cos_t * cos_t;
31,384,260✔
2220

2221
  const double a = cos_t_2 - u.z * u.z;
31,384,260✔
2222
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
31,384,260✔
2223
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
31,384,260✔
2224

2225
  // if factor of s^2 is zero, direction of flight is parallel to theta
2226
  // surface
2227
  if (std::abs(a) < FP_PRECISION) {
31,384,260✔
2228
    // if b vanishes, direction of flight is within theta surface and crossing
2229
    // is not possible
2230
    if (std::abs(b) < FP_PRECISION)
394,812!
2231
      return INFTY;
394,812✔
2232

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

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

2243
  const double p = b / a;
30,989,448✔
2244
  double D = p * p - c / a;
30,989,448✔
2245

2246
  if (D < 0.0)
30,989,448✔
2247
    return INFTY;
8,963,172✔
2248

2249
  D = std::sqrt(D);
22,026,276✔
2250

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

2257
  s = -p + D;
17,704,143✔
2258
  // Check if solution is in positive direction of flight and has correct sign
2259
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
17,704,143✔
2260
    return s;
8,315,424✔
2261

2262
  return INFTY;
9,388,719✔
2263
}
2264

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

2272
  shell = sanitize_phi(shell);
32,684,742✔
2273

2274
  const double p0 = grid_[2][shell];
32,684,742✔
2275

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

2281
  const double c0 = std::cos(p0);
32,684,742✔
2282
  const double s0 = std::sin(p0);
32,684,742✔
2283

2284
  const double denominator = (u.x * s0 - u.y * c0);
32,684,742✔
2285

2286
  // Check if direction of flight is not parallel to phi surface
2287
  if (std::abs(denominator) > FP_PRECISION) {
32,684,742✔
2288
    const double s = -(r.x * s0 - r.y * c0) / denominator;
32,493,294✔
2289
    // Check if solution is in positive direction of flight and crosses the
2290
    // correct phi surface (not -phi)
2291
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
32,493,294✔
2292
      return s;
14,383,188✔
2293
  }
2294

2295
  return INFTY;
18,301,554✔
2296
}
2297

2298
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
272,434,229✔
2299
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2300
  double l) const
2301
{
2302

2303
  if (i == 0) {
272,434,229✔
2304
    return std::min(
181,651,976✔
2305
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
181,651,976✔
2306
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
363,303,952✔
2307

2308
  } else if (i == 1) {
90,782,253✔
2309
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
45,066,006✔
2310
                      find_theta_crossing(r0, u, l, ijk[i])),
45,066,006✔
2311
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
45,066,006✔
2312
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
90,132,012✔
2313

2314
  } else {
2315
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
45,716,247✔
2316
                      find_phi_crossing(r0, u, l, ijk[i])),
45,716,247✔
2317
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
45,716,247✔
2318
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
91,432,494✔
2319
  }
2320
}
2321

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

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

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

2358
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
309!
2359
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
309✔
2360

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

2365
  return 0;
309✔
2366
}
2367

2368
int SphericalMesh::get_index_in_direction(double r, int i) const
168,362,496✔
2369
{
2370
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
168,362,496✔
2371
}
2372

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

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

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

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

2396
  double theta_i = grid_[1][ijk[1] - 1];
765✔
2397
  double theta_o = grid_[1][ijk[1]];
765✔
2398

2399
  double phi_i = grid_[2][ijk[2] - 1];
765✔
2400
  double phi_o = grid_[2][ijk[2]];
765✔
2401

2402
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
765✔
2403
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
765✔
2404
}
2405

2406
//==============================================================================
2407
// Helper functions for the C API
2408
//==============================================================================
2409

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

2419
template<class T>
2420
int check_mesh_type(int32_t index)
900✔
2421
{
2422
  if (int err = check_mesh(index))
900!
2423
    return err;
×
2424

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

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

2440
//==============================================================================
2441
// C API functions
2442
//==============================================================================
2443

2444
// Return the type of mesh as a C string
2445
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,206✔
2446
{
2447
  if (int err = check_mesh(index))
1,206!
2448
    return err;
×
2449

2450
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,206✔
2451

2452
  return 0;
1,206✔
2453
}
2454

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

2463
  for (int i = 0; i < n; ++i) {
414✔
2464
    if (RegularMesh::mesh_type == type) {
207✔
2465
      model::meshes.push_back(make_unique<RegularMesh>());
135✔
2466
    } else if (RectilinearMesh::mesh_type == type) {
72✔
2467
      model::meshes.push_back(make_unique<RectilinearMesh>());
36✔
2468
    } else if (CylindricalMesh::mesh_type == type) {
36✔
2469
      model::meshes.push_back(make_unique<CylindricalMesh>());
18✔
2470
    } else if (SphericalMesh::mesh_type == type) {
18!
2471
      model::meshes.push_back(make_unique<SphericalMesh>());
18✔
2472
    } else {
2473
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2474
    }
2475
  }
2476
  if (index_end)
207!
2477
    *index_end = model::meshes.size() - 1;
×
2478

2479
  return 0;
207✔
2480
}
207✔
2481

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

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

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

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

2511
  // auto-assign new ID
2512
  model::meshes.back()->set_id(-1);
×
2513
  *id = model::meshes.back()->id_;
×
2514

2515
  return 0;
×
2516
}
×
2517

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

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

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

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

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

2569
//! Get the bounding box of a mesh
2570
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
126✔
2571
{
2572
  if (int err = check_mesh(index))
126!
2573
    return err;
×
2574

2575
  BoundingBox bbox = model::meshes[index]->bounding_box();
126✔
2576

2577
  // set lower left corner values
2578
  ll[0] = bbox.min.x;
126✔
2579
  ll[1] = bbox.min.y;
126✔
2580
  ll[2] = bbox.min.z;
126✔
2581

2582
  // set upper right corner values
2583
  ur[0] = bbox.max.x;
126✔
2584
  ur[1] = bbox.max.y;
126✔
2585
  ur[2] = bbox.max.z;
126✔
2586
  return 0;
126✔
2587
}
2588

2589
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
153✔
2590
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2591
{
2592
  if (int err = check_mesh(index))
153!
2593
    return err;
×
2594

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

2607
  return 0;
144✔
2608
}
2609

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

2617
  int pixel_width = pixels[0];
36✔
2618
  int pixel_height = pixels[1];
36✔
2619

2620
  // get pixel size
2621
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
36✔
2622
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
36✔
2623

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

2646
  // set initial position
2647
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
36✔
2648
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
36✔
2649

2650
#pragma omp parallel
20✔
2651
  {
2652
    Position r = xyz;
16✔
2653

2654
#pragma omp for
2655
    for (int y = 0; y < pixel_height; y++) {
336✔
2656
      r[out_i] = xyz[out_i] - out_pixel * y;
320✔
2657
      for (int x = 0; x < pixel_width; x++) {
6,720✔
2658
        r[in_i] = xyz[in_i] + in_pixel * x;
6,400✔
2659
        data[pixel_width * y + x] = mesh->get_bin(r);
6,400✔
2660
      }
2661
    }
2662
  }
2663

2664
  return 0;
36✔
2665
}
2666

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

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

2687
  // Copy dimension
2688
  mesh->n_dimension_ = n;
153✔
2689
  std::copy(dims, dims + n, mesh->shape_.begin());
153✔
2690
  return 0;
153✔
2691
}
2692

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

2701
  if (m->lower_left_.dimension() == 0) {
171!
2702
    set_errmsg("Mesh parameters have not been set.");
×
2703
    return OPENMC_E_ALLOCATE;
×
2704
  }
2705

2706
  *ll = m->lower_left_.data();
171✔
2707
  *ur = m->upper_right_.data();
171✔
2708
  *width = m->width_.data();
171✔
2709
  *n = m->n_dimension_;
171✔
2710
  return 0;
171✔
2711
}
2712

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

2721
  if (m->n_dimension_ == -1) {
180!
2722
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2723
    return OPENMC_E_UNASSIGNED;
×
2724
  }
2725

2726
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
180✔
2727
  if (ll && ur) {
180✔
2728
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
162✔
2729
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
162✔
2730
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
162✔
2731
  } else if (ll && width) {
18!
2732
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
9✔
2733
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
9✔
2734
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
9✔
2735
  } else if (ur && width) {
9!
2736
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
9✔
2737
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
9✔
2738
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
9✔
2739
  } else {
2740
    set_errmsg("At least two parameters must be specified.");
×
2741
    return OPENMC_E_INVALID_ARGUMENT;
×
2742
  }
2743

2744
  // Set material volumes
2745

2746
  // TODO: incorporate this into method in RegularMesh that can be called from
2747
  // here and from constructor
2748
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
180✔
2749
  m->element_volume_ = 1.0;
180✔
2750
  for (int i = 0; i < m->n_dimension_; i++) {
720✔
2751
    m->element_volume_ *= m->width_[i];
540✔
2752
  }
2753

2754
  return 0;
180✔
2755
}
180✔
2756

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

2766
  C* m = dynamic_cast<C*>(model::meshes[index].get());
72!
2767

2768
  m->n_dimension_ = 3;
72✔
2769

2770
  m->grid_[0].reserve(nx);
72✔
2771
  m->grid_[1].reserve(ny);
72✔
2772
  m->grid_[2].reserve(nz);
72✔
2773

2774
  for (int i = 0; i < nx; i++) {
468✔
2775
    m->grid_[0].push_back(grid_x[i]);
396✔
2776
  }
2777
  for (int i = 0; i < ny; i++) {
279✔
2778
    m->grid_[1].push_back(grid_y[i]);
207✔
2779
  }
2780
  for (int i = 0; i < nz; i++) {
261✔
2781
    m->grid_[2].push_back(grid_z[i]);
189✔
2782
  }
2783

2784
  int err = m->set_grid();
72✔
2785
  return err;
72✔
2786
}
2787

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

2797
  if (m->lower_left_.dimension() == 0) {
315!
2798
    set_errmsg("Mesh parameters have not been set.");
×
2799
    return OPENMC_E_ALLOCATE;
×
2800
  }
2801

2802
  *grid_x = m->grid_[0].data();
315✔
2803
  *nx = m->grid_[0].size();
315✔
2804
  *grid_y = m->grid_[1].data();
315✔
2805
  *ny = m->grid_[1].size();
315✔
2806
  *grid_z = m->grid_[2].data();
315✔
2807
  *nz = m->grid_[2].size();
315✔
2808

2809
  return 0;
315✔
2810
}
2811

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

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

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

2837
//! Set the cylindrical mesh parameters
2838
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
18✔
2839
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2840
  const double* grid_z, const int nz)
2841
{
2842
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
18✔
2843
    index, grid_x, nx, grid_y, ny, grid_z, nz);
18✔
2844
}
2845

2846
//! Get the spherical mesh grid
2847
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
99✔
2848
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2849
{
2850

2851
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
99✔
2852
    index, grid_x, nx, grid_y, ny, grid_z, nz);
99✔
2853
  ;
2854
}
2855

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

2865
#ifdef OPENMC_DAGMC_ENABLED
2866

2867
const std::string MOABMesh::mesh_lib_type = "moab";
2868

2869
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2870
{
2871
  initialize();
2872
}
2873

2874
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
2875
{
2876
  initialize();
2877
}
2878

2879
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2880
  : UnstructuredMesh()
2881
{
2882
  n_dimension_ = 3;
2883
  filename_ = filename;
2884
  set_length_multiplier(length_multiplier);
2885
  initialize();
2886
}
2887

2888
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
2889
{
2890
  mbi_ = external_mbi;
2891
  filename_ = "unknown (external file)";
2892
  this->initialize();
2893
}
2894

2895
void MOABMesh::initialize()
2896
{
2897

2898
  // Create the MOAB interface and load data from file
2899
  this->create_interface();
2900

2901
  // Initialise MOAB error code
2902
  moab::ErrorCode rval = moab::MB_SUCCESS;
2903

2904
  // Set the dimension
2905
  n_dimension_ = 3;
2906

2907
  // set member range of tetrahedral entities
2908
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2909
  if (rval != moab::MB_SUCCESS) {
2910
    fatal_error("Failed to get all tetrahedral elements");
2911
  }
2912

2913
  if (!ehs_.all_of_type(moab::MBTET)) {
2914
    warning("Non-tetrahedral elements found in unstructured "
2915
            "mesh file: " +
2916
            filename_);
2917
  }
2918

2919
  // set member range of vertices
2920
  int vertex_dim = 0;
2921
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
2922
  if (rval != moab::MB_SUCCESS) {
2923
    fatal_error("Failed to get all vertex handles");
2924
  }
2925

2926
  // make an entity set for all tetrahedra
2927
  // this is used for convenience later in output
2928
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
2929
  if (rval != moab::MB_SUCCESS) {
2930
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2931
  }
2932

2933
  rval = mbi_->add_entities(tetset_, ehs_);
2934
  if (rval != moab::MB_SUCCESS) {
2935
    fatal_error("Failed to add tetrahedra to an entity set.");
2936
  }
2937

2938
  if (length_multiplier_ > 0.0) {
2939
    // get the connectivity of all tets
2940
    moab::Range adj;
2941
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2942
    if (rval != moab::MB_SUCCESS) {
2943
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2944
    }
2945
    // scale all vertex coords by multiplier (done individually so not all
2946
    // coordinates are in memory twice at once)
2947
    for (auto vert : adj) {
2948
      // retrieve coords
2949
      std::array<double, 3> coord;
2950
      rval = mbi_->get_coords(&vert, 1, coord.data());
2951
      if (rval != moab::MB_SUCCESS) {
2952
        fatal_error("Could not get coordinates of vertex.");
2953
      }
2954
      // scale coords
2955
      for (auto& c : coord) {
2956
        c *= length_multiplier_;
2957
      }
2958
      // set new coords
2959
      rval = mbi_->set_coords(&vert, 1, coord.data());
2960
      if (rval != moab::MB_SUCCESS) {
2961
        fatal_error("Failed to set new vertex coordinates");
2962
      }
2963
    }
2964
  }
2965

2966
  // Determine bounds of mesh
2967
  this->determine_bounds();
2968
}
2969

2970
void MOABMesh::prepare_for_point_location()
2971
{
2972
  // if the KDTree has already been constructed, do nothing
2973
  if (kdtree_)
2974
    return;
2975

2976
  // build acceleration data structures
2977
  compute_barycentric_data(ehs_);
2978
  build_kdtree(ehs_);
2979
}
2980

2981
void MOABMesh::create_interface()
2982
{
2983
  // Do not create a MOAB instance if one is already in memory
2984
  if (mbi_)
2985
    return;
2986

2987
  // create MOAB instance
2988
  mbi_ = std::make_shared<moab::Core>();
2989

2990
  // load unstructured mesh file
2991
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
2992
  if (rval != moab::MB_SUCCESS) {
2993
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2994
  }
2995
}
2996

2997
void MOABMesh::build_kdtree(const moab::Range& all_tets)
2998
{
2999
  moab::Range all_tris;
3000
  int adj_dim = 2;
3001
  write_message("Getting tet adjacencies...", 7);
3002
  moab::ErrorCode rval = mbi_->get_adjacencies(
3003
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3004
  if (rval != moab::MB_SUCCESS) {
3005
    fatal_error("Failed to get adjacent triangles for tets");
3006
  }
3007

3008
  if (!all_tris.all_of_type(moab::MBTRI)) {
3009
    warning("Non-triangle elements found in tet adjacencies in "
3010
            "unstructured mesh file: " +
3011
            filename_);
3012
  }
3013

3014
  // combine into one range
3015
  moab::Range all_tets_and_tris;
3016
  all_tets_and_tris.merge(all_tets);
3017
  all_tets_and_tris.merge(all_tris);
3018

3019
  // create a kd-tree instance
3020
  write_message(
3021
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
3022
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
3023

3024
  // Determine what options to use
3025
  std::ostringstream options_stream;
3026
  if (options_.empty()) {
3027
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
3028
  } else {
3029
    options_stream << options_;
3030
  }
3031
  moab::FileOptions file_opts(options_stream.str().c_str());
3032

3033
  // Build the k-d tree
3034
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
3035
  if (rval != moab::MB_SUCCESS) {
3036
    fatal_error("Failed to construct KDTree for the "
3037
                "unstructured mesh file: " +
3038
                filename_);
3039
  }
3040
}
3041

3042
void MOABMesh::intersect_track(const moab::CartVect& start,
3043
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3044
{
3045
  hits.clear();
3046

3047
  moab::ErrorCode rval;
3048
  vector<moab::EntityHandle> tris;
3049
  // get all intersections with triangles in the tet mesh
3050
  // (distances are relative to the start point, not the previous
3051
  // intersection)
3052
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
3053
    dir.array(), start.array(), tris, hits, 0, track_len);
3054
  if (rval != moab::MB_SUCCESS) {
3055
    fatal_error(
3056
      "Failed to compute intersections on unstructured mesh: " + filename_);
3057
  }
3058

3059
  // remove duplicate intersection distances
3060
  std::unique(hits.begin(), hits.end());
3061

3062
  // sorts by first component of std::pair by default
3063
  std::sort(hits.begin(), hits.end());
3064
}
3065

3066
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3067
  vector<int>& bins, vector<double>& lengths) const
3068
{
3069
  moab::CartVect start(r0.x, r0.y, r0.z);
3070
  moab::CartVect end(r1.x, r1.y, r1.z);
3071
  moab::CartVect dir(u.x, u.y, u.z);
3072
  dir.normalize();
3073

3074
  double track_len = (end - start).length();
3075
  if (track_len == 0.0)
3076
    return;
3077

3078
  start -= TINY_BIT * dir;
3079
  end += TINY_BIT * dir;
3080

3081
  vector<double> hits;
3082
  intersect_track(start, dir, track_len, hits);
3083

3084
  bins.clear();
3085
  lengths.clear();
3086

3087
  // if there are no intersections the track may lie entirely
3088
  // within a single tet. If this is the case, apply entire
3089
  // score to that tet and return.
3090
  if (hits.size() == 0) {
3091
    Position midpoint = r0 + u * (track_len * 0.5);
3092
    int bin = this->get_bin(midpoint);
3093
    if (bin != -1) {
3094
      bins.push_back(bin);
3095
      lengths.push_back(1.0);
3096
    }
3097
    return;
3098
  }
3099

3100
  // for each segment in the set of tracks, try to look up a tet
3101
  // at the midpoint of the segment
3102
  Position current = r0;
3103
  double last_dist = 0.0;
3104
  for (const auto& hit : hits) {
3105
    // get the segment length
3106
    double segment_length = hit - last_dist;
3107
    last_dist = hit;
3108
    // find the midpoint of this segment
3109
    Position midpoint = current + u * (segment_length * 0.5);
3110
    // try to find a tet for this position
3111
    int bin = this->get_bin(midpoint);
3112

3113
    // determine the start point for this segment
3114
    current = r0 + u * hit;
3115

3116
    if (bin == -1) {
3117
      continue;
3118
    }
3119

3120
    bins.push_back(bin);
3121
    lengths.push_back(segment_length / track_len);
3122
  }
3123

3124
  // tally remaining portion of track after last hit if
3125
  // the last segment of the track is in the mesh but doesn't
3126
  // reach the other side of the tet
3127
  if (hits.back() < track_len) {
3128
    Position segment_start = r0 + u * hits.back();
3129
    double segment_length = track_len - hits.back();
3130
    Position midpoint = segment_start + u * (segment_length * 0.5);
3131
    int bin = this->get_bin(midpoint);
3132
    if (bin != -1) {
3133
      bins.push_back(bin);
3134
      lengths.push_back(segment_length / track_len);
3135
    }
3136
  }
3137
};
3138

3139
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
3140
{
3141
  moab::CartVect pos(r.x, r.y, r.z);
3142
  // find the leaf of the kd-tree for this position
3143
  moab::AdaptiveKDTreeIter kdtree_iter;
3144
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
3145
  if (rval != moab::MB_SUCCESS) {
3146
    return 0;
3147
  }
3148

3149
  // retrieve the tet elements of this leaf
3150
  moab::EntityHandle leaf = kdtree_iter.handle();
3151
  moab::Range tets;
3152
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3153
  if (rval != moab::MB_SUCCESS) {
3154
    warning("MOAB error finding tets.");
3155
  }
3156

3157
  // loop over the tets in this leaf, returning the containing tet if found
3158
  for (const auto& tet : tets) {
3159
    if (point_in_tet(pos, tet)) {
3160
      return tet;
3161
    }
3162
  }
3163

3164
  // if no tet is found, return an invalid handle
3165
  return 0;
3166
}
3167

3168
double MOABMesh::volume(int bin) const
3169
{
3170
  return tet_volume(get_ent_handle_from_bin(bin));
3171
}
3172

3173
std::string MOABMesh::library() const
3174
{
3175
  return mesh_lib_type;
3176
}
3177

3178
// Sample position within a tet for MOAB type tets
3179
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
3180
{
3181

3182
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3183

3184
  // Get vertex coordinates for MOAB tet
3185
  const moab::EntityHandle* conn1;
3186
  int conn1_size;
3187
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
3188
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
3189
    fatal_error(fmt::format(
3190
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3191
      conn1_size));
3192
  }
3193
  moab::CartVect p[4];
3194
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
3195
  if (rval != moab::MB_SUCCESS) {
3196
    fatal_error("Failed to get tet coords");
3197
  }
3198

3199
  std::array<Position, 4> tet_verts;
3200
  for (int i = 0; i < 4; i++) {
3201
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
3202
  }
3203
  // Samples position within tet using Barycentric stuff
3204
  return this->sample_tet(tet_verts, seed);
3205
}
3206

3207
double MOABMesh::tet_volume(moab::EntityHandle tet) const
3208
{
3209
  vector<moab::EntityHandle> conn;
3210
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
3211
  if (rval != moab::MB_SUCCESS) {
3212
    fatal_error("Failed to get tet connectivity");
3213
  }
3214

3215
  moab::CartVect p[4];
3216
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
3217
  if (rval != moab::MB_SUCCESS) {
3218
    fatal_error("Failed to get tet coords");
3219
  }
3220

3221
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
3222
}
3223

3224
int MOABMesh::get_bin(Position r) const
3225
{
3226
  moab::EntityHandle tet = get_tet(r);
3227
  if (tet == 0) {
3228
    return -1;
3229
  } else {
3230
    return get_bin_from_ent_handle(tet);
3231
  }
3232
}
3233

3234
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
3235
{
3236
  moab::ErrorCode rval;
3237

3238
  baryc_data_.clear();
3239
  baryc_data_.resize(tets.size());
3240

3241
  // compute the barycentric data for each tet element
3242
  // and store it as a 3x3 matrix
3243
  for (auto& tet : tets) {
3244
    vector<moab::EntityHandle> verts;
3245
    rval = mbi_->get_connectivity(&tet, 1, verts);
3246
    if (rval != moab::MB_SUCCESS) {
3247
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
3248
    }
3249

3250
    moab::CartVect p[4];
3251
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
3252
    if (rval != moab::MB_SUCCESS) {
3253
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
3254
    }
3255

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

3258
    // invert now to avoid this cost later
3259
    a = a.transpose().inverse();
3260
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
3261
  }
3262
}
3263

3264
bool MOABMesh::point_in_tet(
3265
  const moab::CartVect& r, moab::EntityHandle tet) const
3266
{
3267

3268
  moab::ErrorCode rval;
3269

3270
  // get tet vertices
3271
  vector<moab::EntityHandle> verts;
3272
  rval = mbi_->get_connectivity(&tet, 1, verts);
3273
  if (rval != moab::MB_SUCCESS) {
3274
    warning("Failed to get vertices of tet in umesh: " + filename_);
3275
    return false;
3276
  }
3277

3278
  // first vertex is used as a reference point for the barycentric data -
3279
  // retrieve its coordinates
3280
  moab::CartVect p_zero;
3281
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
3282
  if (rval != moab::MB_SUCCESS) {
3283
    warning("Failed to get coordinates of a vertex in "
3284
            "unstructured mesh: " +
3285
            filename_);
3286
    return false;
3287
  }
3288

3289
  // look up barycentric data
3290
  int idx = get_bin_from_ent_handle(tet);
3291
  const moab::Matrix3& a_inv = baryc_data_[idx];
3292

3293
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3294

3295
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
3296
          bary_coords[2] >= 0.0 &&
3297
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
3298
}
3299

3300
int MOABMesh::get_bin_from_index(int idx) const
3301
{
3302
  if (idx >= n_bins()) {
3303
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3304
  }
3305
  return ehs_[idx] - ehs_[0];
3306
}
3307

3308
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3309
{
3310
  int bin = get_bin(r);
3311
  *in_mesh = bin != -1;
3312
  return bin;
3313
}
3314

3315
int MOABMesh::get_index_from_bin(int bin) const
3316
{
3317
  return bin;
3318
}
3319

3320
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3321
  Position plot_ll, Position plot_ur) const
3322
{
3323
  // TODO: Implement mesh lines
3324
  return {};
3325
}
3326

3327
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
3328
{
3329
  int idx = vert - verts_[0];
3330
  if (idx >= n_vertices()) {
3331
    fatal_error(
3332
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
3333
  }
3334
  return idx;
3335
}
3336

3337
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
3338
{
3339
  int bin = eh - ehs_[0];
3340
  if (bin >= n_bins()) {
3341
    fatal_error(fmt::format("Invalid bin: {}", bin));
3342
  }
3343
  return bin;
3344
}
3345

3346
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
3347
{
3348
  if (bin >= n_bins()) {
3349
    fatal_error(fmt::format("Invalid bin index: ", bin));
3350
  }
3351
  return ehs_[0] + bin;
3352
}
3353

3354
int MOABMesh::n_bins() const
3355
{
3356
  return ehs_.size();
3357
}
3358

3359
int MOABMesh::n_surface_bins() const
3360
{
3361
  // collect all triangles in the set of tets for this mesh
3362
  moab::Range tris;
3363
  moab::ErrorCode rval;
3364
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
3365
  if (rval != moab::MB_SUCCESS) {
3366
    warning("Failed to get all triangles in the mesh instance");
3367
    return -1;
3368
  }
3369
  return 2 * tris.size();
3370
}
3371

3372
Position MOABMesh::centroid(int bin) const
3373
{
3374
  moab::ErrorCode rval;
3375

3376
  auto tet = this->get_ent_handle_from_bin(bin);
3377

3378
  // look up the tet connectivity
3379
  vector<moab::EntityHandle> conn;
3380
  rval = mbi_->get_connectivity(&tet, 1, conn);
3381
  if (rval != moab::MB_SUCCESS) {
3382
    warning("Failed to get connectivity of a mesh element.");
3383
    return {};
3384
  }
3385

3386
  // get the coordinates
3387
  vector<moab::CartVect> coords(conn.size());
3388
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3389
  if (rval != moab::MB_SUCCESS) {
3390
    warning("Failed to get the coordinates of a mesh element.");
3391
    return {};
3392
  }
3393

3394
  // compute the centroid of the element vertices
3395
  moab::CartVect centroid(0.0, 0.0, 0.0);
3396
  for (const auto& coord : coords) {
3397
    centroid += coord;
3398
  }
3399
  centroid /= double(coords.size());
3400

3401
  return {centroid[0], centroid[1], centroid[2]};
3402
}
3403

3404
int MOABMesh::n_vertices() const
3405
{
3406
  return verts_.size();
3407
}
3408

3409
Position MOABMesh::vertex(int id) const
3410
{
3411

3412
  moab::ErrorCode rval;
3413

3414
  moab::EntityHandle vert = verts_[id];
3415

3416
  moab::CartVect coords;
3417
  rval = mbi_->get_coords(&vert, 1, coords.array());
3418
  if (rval != moab::MB_SUCCESS) {
3419
    fatal_error("Failed to get the coordinates of a vertex.");
3420
  }
3421

3422
  return {coords[0], coords[1], coords[2]};
3423
}
3424

3425
std::vector<int> MOABMesh::connectivity(int bin) const
3426
{
3427
  moab::ErrorCode rval;
3428

3429
  auto tet = get_ent_handle_from_bin(bin);
3430

3431
  // look up the tet connectivity
3432
  vector<moab::EntityHandle> conn;
3433
  rval = mbi_->get_connectivity(&tet, 1, conn);
3434
  if (rval != moab::MB_SUCCESS) {
3435
    fatal_error("Failed to get connectivity of a mesh element.");
3436
    return {};
3437
  }
3438

3439
  std::vector<int> verts(4);
3440
  for (int i = 0; i < verts.size(); i++) {
3441
    verts[i] = get_vert_idx_from_handle(conn[i]);
3442
  }
3443

3444
  return verts;
3445
}
3446

3447
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3448
  std::string score) const
3449
{
3450
  moab::ErrorCode rval;
3451
  // add a tag to the mesh
3452
  // all scores are treated as a single value
3453
  // with an uncertainty
3454
  moab::Tag value_tag;
3455

3456
  // create the value tag if not present and get handle
3457
  double default_val = 0.0;
3458
  auto val_string = score + "_mean";
3459
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3460
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3461
  if (rval != moab::MB_SUCCESS) {
3462
    auto msg =
3463
      fmt::format("Could not create or retrieve the value tag for the score {}"
3464
                  " on unstructured mesh {}",
3465
        score, id_);
3466
    fatal_error(msg);
3467
  }
3468

3469
  // create the std dev tag if not present and get handle
3470
  moab::Tag error_tag;
3471
  std::string err_string = score + "_std_dev";
3472
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3473
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3474
  if (rval != moab::MB_SUCCESS) {
3475
    auto msg =
3476
      fmt::format("Could not create or retrieve the error tag for the score {}"
3477
                  " on unstructured mesh {}",
3478
        score, id_);
3479
    fatal_error(msg);
3480
  }
3481

3482
  // return the populated tag handles
3483
  return {value_tag, error_tag};
3484
}
3485

3486
void MOABMesh::add_score(const std::string& score)
3487
{
3488
  auto score_tags = get_score_tags(score);
3489
  tag_names_.push_back(score);
3490
}
3491

3492
void MOABMesh::remove_scores()
3493
{
3494
  for (const auto& name : tag_names_) {
3495
    auto value_name = name + "_mean";
3496
    moab::Tag tag;
3497
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
3498
    if (rval != moab::MB_SUCCESS)
3499
      return;
3500

3501
    rval = mbi_->tag_delete(tag);
3502
    if (rval != moab::MB_SUCCESS) {
3503
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3504
                             " on unstructured mesh {}",
3505
        name, id_);
3506
      fatal_error(msg);
3507
    }
3508

3509
    auto std_dev_name = name + "_std_dev";
3510
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3511
    if (rval != moab::MB_SUCCESS) {
3512
      auto msg =
3513
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3514
                    " on unstructured mesh {}",
3515
          name, id_);
3516
    }
3517

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

3529
void MOABMesh::set_score_data(const std::string& score,
3530
  const vector<double>& values, const vector<double>& std_dev)
3531
{
3532
  auto score_tags = this->get_score_tags(score);
3533

3534
  moab::ErrorCode rval;
3535
  // set the score value
3536
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3537
  if (rval != moab::MB_SUCCESS) {
3538
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3539
                           "on unstructured mesh {}",
3540
      score, id_);
3541
    warning(msg);
3542
  }
3543

3544
  // set the error value
3545
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3546
  if (rval != moab::MB_SUCCESS) {
3547
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3548
                           "on unstructured mesh {}",
3549
      score, id_);
3550
    warning(msg);
3551
  }
3552
}
3553

3554
void MOABMesh::write(const std::string& base_filename) const
3555
{
3556
  // add extension to the base name
3557
  auto filename = base_filename + ".vtk";
3558
  write_message(5, "Writing unstructured mesh {}...", filename);
3559
  filename = settings::path_output + filename;
3560

3561
  // write the tetrahedral elements of the mesh only
3562
  // to avoid clutter from zero-value data on other
3563
  // elements during visualization
3564
  moab::ErrorCode rval;
3565
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3566
  if (rval != moab::MB_SUCCESS) {
3567
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3568
    warning(msg);
3569
  }
3570
}
3571

3572
#endif
3573

3574
#ifdef OPENMC_LIBMESH_ENABLED
3575

3576
const std::string LibMesh::mesh_lib_type = "libmesh";
3577

3578
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
3579
{
3580
  // filename_ and length_multiplier_ will already be set by the
3581
  // UnstructuredMesh constructor
3582
  set_mesh_pointer_from_filename(filename_);
23✔
3583
  set_length_multiplier(length_multiplier_);
23✔
3584
  initialize();
23✔
3585
}
23✔
3586

3587
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3588
{
3589
  // filename_ and length_multiplier_ will already be set by the
3590
  // UnstructuredMesh constructor
3591
  set_mesh_pointer_from_filename(filename_);
×
3592
  set_length_multiplier(length_multiplier_);
×
3593
  initialize();
×
3594
}
3595

3596
// create the mesh from a pointer to a libMesh Mesh
3597
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3598
{
3599
  if (!input_mesh.is_replicated()) {
×
3600
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3601
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3602
  }
3603

3604
  m_ = &input_mesh;
3605
  set_length_multiplier(length_multiplier);
×
3606
  initialize();
×
3607
}
3608

3609
// create the mesh from an input file
3610
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3611
{
3612
  n_dimension_ = 3;
3613
  set_mesh_pointer_from_filename(filename);
×
3614
  set_length_multiplier(length_multiplier);
×
3615
  initialize();
×
3616
}
3617

3618
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23✔
3619
{
3620
  filename_ = filename;
23✔
3621
  unique_m_ =
3622
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23✔
3623
  m_ = unique_m_.get();
23✔
3624
  m_->read(filename_);
23✔
3625
}
23✔
3626

3627
// build a libMesh equation system for storing values
3628
void LibMesh::build_eqn_sys()
15✔
3629
{
3630
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
30✔
3631
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15✔
3632
  libMesh::ExplicitSystem& eq_sys =
3633
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15✔
3634
}
15✔
3635

3636
// intialize from mesh file
3637
void LibMesh::initialize()
23✔
3638
{
3639
  if (!settings::libmesh_comm) {
23!
3640
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3641
                "communicator.");
3642
  }
3643

3644
  // assuming that unstructured meshes used in OpenMC are 3D
3645
  n_dimension_ = 3;
23✔
3646

3647
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3648
  // Otherwise assume that it is prepared by its owning application
3649
  if (unique_m_) {
23!
3650
    m_->prepare_for_use();
23✔
3651
  }
3652

3653
  // ensure that the loaded mesh is 3 dimensional
3654
  if (m_->mesh_dimension() != n_dimension_) {
23!
3655
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3656
                            "mesh is not a 3D mesh.",
3657
      filename_));
3658
  }
3659

3660
  for (int i = 0; i < num_threads(); i++) {
69✔
3661
    pl_.emplace_back(m_->sub_point_locator());
46✔
3662
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3663
    pl_.back()->enable_out_of_mesh_mode();
46✔
3664
  }
3665

3666
  // store first element in the mesh to use as an offset for bin indices
3667
  auto first_elem = *m_->elements_begin();
23✔
3668
  first_element_id_ = first_elem->id();
23✔
3669

3670
  // bounding box for the mesh for quick rejection checks
3671
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23✔
3672
  libMesh::Point ll = bbox_.min();
23✔
3673
  libMesh::Point ur = bbox_.max();
23✔
3674
  if (length_multiplier_ > 0.0) {
23!
3675
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3676
      length_multiplier_ * ll(2)};
×
3677
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3678
      length_multiplier_ * ur(2)};
×
3679
  } else {
3680
    lower_left_ = {ll(0), ll(1), ll(2)};
23✔
3681
    upper_right_ = {ur(0), ur(1), ur(2)};
23✔
3682
  }
3683
}
23✔
3684

3685
// Sample position within a tet for LibMesh type tets
3686
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3687
{
3688
  const auto& elem = get_element_from_bin(bin);
400,820✔
3689
  // Get tet vertex coordinates from LibMesh
3690
  std::array<Position, 4> tet_verts;
400,820✔
3691
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3692
    auto node_ref = elem.node_ref(i);
1,603,280✔
3693
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3694
  }
1,603,280✔
3695
  // Samples position within tet using Barycentric coordinates
3696
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3697
  if (length_multiplier_ > 0.0) {
400,820!
3698
    return length_multiplier_ * sampled_position;
×
3699
  } else {
3700
    return sampled_position;
400,820✔
3701
  }
3702
}
3703

3704
Position LibMesh::centroid(int bin) const
3705
{
3706
  const auto& elem = this->get_element_from_bin(bin);
×
3707
  auto centroid = elem.vertex_average();
×
3708
  if (length_multiplier_ > 0.0) {
×
3709
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
×
3710
  } else {
3711
    return {centroid(0), centroid(1), centroid(2)};
3712
  }
3713
}
3714

3715
int LibMesh::n_vertices() const
39,978✔
3716
{
3717
  return m_->n_nodes();
39,978✔
3718
}
3719

3720
Position LibMesh::vertex(int vertex_id) const
39,942✔
3721
{
3722
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3723
  if (length_multiplier_ > 0.0) {
39,942!
3724
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3725
  } else {
3726
    return {node_ref(0), node_ref(1), node_ref(2)};
39,942✔
3727
  }
3728
}
39,942✔
3729

3730
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
3731
{
3732
  std::vector<int> conn;
265,856✔
3733
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
3734
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
3735
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
3736
  }
3737
  return conn;
265,856✔
3738
}
3739

3740
std::string LibMesh::library() const
33✔
3741
{
3742
  return mesh_lib_type;
33✔
3743
}
3744

3745
int LibMesh::n_bins() const
1,784,287✔
3746
{
3747
  return m_->n_elem();
1,784,287✔
3748
}
3749

3750
int LibMesh::n_surface_bins() const
3751
{
3752
  int n_bins = 0;
3753
  for (int i = 0; i < this->n_bins(); i++) {
×
3754
    const libMesh::Elem& e = get_element_from_bin(i);
3755
    n_bins += e.n_faces();
3756
    // if this is a boundary element, it will only be visited once,
3757
    // the number of surface bins is incremented to
3758
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3759
      // null neighbor pointer indicates a boundary face
3760
      if (!neighbor_ptr) {
×
3761
        n_bins++;
3762
      }
3763
    }
3764
  }
3765
  return n_bins;
3766
}
3767

3768
void LibMesh::add_score(const std::string& var_name)
15✔
3769
{
3770
  if (!equation_systems_) {
15!
3771
    build_eqn_sys();
15✔
3772
  }
3773

3774
  // check if this is a new variable
3775
  std::string value_name = var_name + "_mean";
15✔
3776
  if (!variable_map_.count(value_name)) {
15!
3777
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3778
    auto var_num =
3779
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3780
    variable_map_[value_name] = var_num;
15✔
3781
  }
3782

3783
  std::string std_dev_name = var_name + "_std_dev";
15✔
3784
  // check if this is a new variable
3785
  if (!variable_map_.count(std_dev_name)) {
15!
3786
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3787
    auto var_num =
3788
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3789
    variable_map_[std_dev_name] = var_num;
15✔
3790
  }
3791
}
15✔
3792

3793
void LibMesh::remove_scores()
15✔
3794
{
3795
  if (equation_systems_) {
15!
3796
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3797
    eqn_sys.clear();
15✔
3798
    variable_map_.clear();
15✔
3799
  }
3800
}
15✔
3801

3802
void LibMesh::set_score_data(const std::string& var_name,
15✔
3803
  const vector<double>& values, const vector<double>& std_dev)
3804
{
3805
  if (!equation_systems_) {
15!
3806
    build_eqn_sys();
×
3807
  }
3808

3809
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3810

3811
  if (!eqn_sys.is_initialized()) {
15!
3812
    equation_systems_->init();
15✔
3813
  }
3814

3815
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3816

3817
  // look up the value variable
3818
  std::string value_name = var_name + "_mean";
15✔
3819
  unsigned int value_num = variable_map_.at(value_name);
15✔
3820
  // look up the std dev variable
3821
  std::string std_dev_name = var_name + "_std_dev";
15✔
3822
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15✔
3823

3824
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
97,871✔
3825
       it++) {
3826
    if (!(*it)->active()) {
97,856!
3827
      continue;
3828
    }
3829

3830
    auto bin = get_bin_from_element(*it);
97,856✔
3831

3832
    // set value
3833
    vector<libMesh::dof_id_type> value_dof_indices;
97,856✔
3834
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856✔
3835
    assert(value_dof_indices.size() == 1);
3836
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856✔
3837

3838
    // set std dev
3839
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
3840
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
3841
    assert(std_dev_dof_indices.size() == 1);
3842
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
3843
  }
97,871✔
3844
}
15✔
3845

3846
void LibMesh::write(const std::string& filename) const
15✔
3847
{
3848
  write_message(fmt::format(
15✔
3849
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15✔
3850
  libMesh::ExodusII_IO exo(*m_);
15✔
3851
  std::set<std::string> systems_out = {eq_system_name_};
45✔
3852
  exo.write_discontinuous_exodusII(
15✔
3853
    filename + ".e", *equation_systems_, &systems_out);
30✔
3854
}
15✔
3855

3856
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3857
  vector<int>& bins, vector<double>& lengths) const
3858
{
3859
  // TODO: Implement triangle crossings here
3860
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3861
}
3862

3863
int LibMesh::get_bin(Position r) const
2,340,484✔
3864
{
3865
  // look-up a tet using the point locator
3866
  libMesh::Point p(r.x, r.y, r.z);
2,340,484✔
3867

3868
  if (length_multiplier_ > 0.0) {
2,340,484!
3869
    // Scale the point down
3870
    p /= length_multiplier_;
3871
  }
3872

3873
  // quick rejection check
3874
  if (!bbox_.contains_point(p)) {
2,340,484✔
3875
    return -1;
918,796✔
3876
  }
3877

3878
  const auto& point_locator = pl_.at(thread_num());
1,421,688✔
3879

3880
  const auto elem_ptr = (*point_locator)(p);
1,421,688✔
3881
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,688✔
3882
}
2,340,484✔
3883

3884
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,314✔
3885
{
3886
  int bin = elem->id() - first_element_id_;
1,518,314✔
3887
  if (bin >= n_bins() || bin < 0) {
1,518,314!
3888
    fatal_error(fmt::format("Invalid bin: {}", bin));
3889
  }
3890
  return bin;
1,518,314✔
3891
}
3892

3893
std::pair<vector<double>, vector<double>> LibMesh::plot(
3894
  Position plot_ll, Position plot_ur) const
3895
{
3896
  return {};
3897
}
3898

3899
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3900
{
3901
  return m_->elem_ref(bin);
765,460✔
3902
}
3903

3904
double LibMesh::volume(int bin) const
364,640✔
3905
{
3906
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
364,640✔
3907
         length_multiplier_ * length_multiplier_;
364,640✔
3908
}
3909

3910
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3911
  double length_multiplier,
3912
  const std::set<libMesh::subdomain_id_type>& block_ids)
3913
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3914
    block_restrict_(!block_ids_.empty()),
3915
    num_active_(
3916
      block_restrict_
×
3917
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
3918
            m_->active_subdomain_set_elements_end(block_ids_))
×
3919
        : m_->n_active_elem())
×
3920
{
3921
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3922
  // contiguous in ID space, so we need to map from bin indices (defined over
3923
  // active elements) to global dof ids
3924
  bin_to_elem_map_.reserve(num_active_);
×
3925
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3926
  auto begin = block_restrict_
3927
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
3928
                 : m_->active_elements_begin();
×
3929
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
3930
                             : m_->active_elements_end();
×
3931
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
3932
    bin_to_elem_map_.push_back(elem->id());
×
3933
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3934
  }
3935
}
3936

3937
int AdaptiveLibMesh::n_bins() const
3938
{
3939
  return num_active_;
3940
}
3941

3942
void AdaptiveLibMesh::add_score(const std::string& var_name)
3943
{
3944
  warning(fmt::format(
×
3945
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3946
    this->id_));
3947
}
3948

3949
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3950
  const vector<double>& values, const vector<double>& std_dev)
3951
{
3952
  warning(fmt::format(
×
3953
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3954
    this->id_));
3955
}
3956

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

3964
int AdaptiveLibMesh::get_bin(Position r) const
3965
{
3966
  // look-up a tet using the point locator
3967
  libMesh::Point p(r.x, r.y, r.z);
×
3968

3969
  if (length_multiplier_ > 0.0) {
×
3970
    // Scale the point down
3971
    p /= length_multiplier_;
3972
  }
3973

3974
  // quick rejection check
3975
  if (!bbox_.contains_point(p)) {
×
3976
    return -1;
3977
  }
3978

3979
  const auto& point_locator = pl_.at(thread_num());
×
3980

3981
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3982
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3983
}
3984

3985
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3986
{
3987
  int bin = elem_to_bin_map_[elem->id()];
×
3988
  if (bin >= n_bins() || bin < 0) {
×
3989
    fatal_error(fmt::format("Invalid bin: {}", bin));
3990
  }
3991
  return bin;
3992
}
3993

3994
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3995
{
3996
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3997
}
3998

3999
#endif // OPENMC_LIBMESH_ENABLED
4000

4001
//==============================================================================
4002
// Non-member functions
4003
//==============================================================================
4004

4005
void read_meshes(pugi::xml_node root)
9,988✔
4006
{
4007
  std::unordered_set<int> mesh_ids;
9,988✔
4008

4009
  for (auto node : root.children("mesh")) {
12,360✔
4010
    // Check to make sure multiple meshes in the same file don't share IDs
4011
    int id = std::stoi(get_node_value(node, "id"));
2,372✔
4012
    if (contains(mesh_ids, id)) {
2,372!
4013
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4014
                              "'{}' in the same input file",
4015
        id));
4016
    }
4017
    mesh_ids.insert(id);
2,372✔
4018

4019
    // If we've already read a mesh with the same ID in a *different* file,
4020
    // assume it is the same here
4021
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,372!
4022
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4023
      continue;
×
4024
    }
4025

4026
    std::string mesh_type;
2,372✔
4027
    if (check_for_node(node, "type")) {
2,372✔
4028
      mesh_type = get_node_value(node, "type", true, true);
758✔
4029
    } else {
4030
      mesh_type = "regular";
1,614✔
4031
    }
4032

4033
    // determine the mesh library to use
4034
    std::string mesh_lib;
2,372✔
4035
    if (check_for_node(node, "library")) {
2,372✔
4036
      mesh_lib = get_node_value(node, "library", true, true);
23!
4037
    }
4038

4039
    Mesh::create(node, mesh_type, mesh_lib);
2,372✔
4040
  }
2,372✔
4041
}
9,988✔
4042

4043
void read_meshes(hid_t group)
18✔
4044
{
4045
  std::unordered_set<int> mesh_ids;
18✔
4046

4047
  std::vector<int> ids;
18✔
4048
  read_attribute(group, "ids", ids);
18✔
4049

4050
  for (auto id : ids) {
45✔
4051

4052
    // Check to make sure multiple meshes in the same file don't share IDs
4053
    if (contains(mesh_ids, id)) {
27!
4054
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4055
                              "'{}' in the same HDF5 input file",
4056
        id));
4057
    }
4058
    mesh_ids.insert(id);
27✔
4059

4060
    // If we've already read a mesh with the same ID in a *different* file,
4061
    // assume it is the same here
4062
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
27!
4063
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
27✔
4064
      continue;
27✔
4065
    }
4066

4067
    std::string name = fmt::format("mesh {}", id);
×
4068
    hid_t mesh_group = open_group(group, name.c_str());
×
4069

4070
    std::string mesh_type;
×
4071
    if (object_exists(mesh_group, "type")) {
×
4072
      read_dataset(mesh_group, "type", mesh_type);
×
4073
    } else {
4074
      mesh_type = "regular";
×
4075
    }
4076

4077
    // determine the mesh library to use
4078
    std::string mesh_lib;
×
4079
    if (object_exists(mesh_group, "library")) {
×
4080
      read_dataset(mesh_group, "library", mesh_lib);
×
4081
    }
4082

4083
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4084
  }
×
4085
}
18✔
4086

4087
void meshes_to_hdf5(hid_t group)
5,668✔
4088
{
4089
  // Write number of meshes
4090
  hid_t meshes_group = create_group(group, "meshes");
5,668✔
4091
  int32_t n_meshes = model::meshes.size();
5,668✔
4092
  write_attribute(meshes_group, "n_meshes", n_meshes);
5,668✔
4093

4094
  if (n_meshes > 0) {
5,668✔
4095
    // Write IDs of meshes
4096
    vector<int> ids;
1,746✔
4097
    for (const auto& m : model::meshes) {
3,961✔
4098
      m->to_hdf5(meshes_group);
2,215✔
4099
      ids.push_back(m->id_);
2,215✔
4100
    }
4101
    write_attribute(meshes_group, "ids", ids);
1,746✔
4102
  }
1,746✔
4103

4104
  close_group(meshes_group);
5,668✔
4105
}
5,668✔
4106

4107
void free_memory_mesh()
6,564✔
4108
{
4109
  model::meshes.clear();
6,564✔
4110
  model::mesh_map.clear();
6,564✔
4111
}
6,564✔
4112

4113
extern "C" int n_meshes()
252✔
4114
{
4115
  return model::meshes.size();
252✔
4116
}
4117

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

© 2026 Coveralls, Inc