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

openmc-dev / openmc / 21686031975

04 Feb 2026 07:50PM UTC coverage: 81.024% (-0.7%) from 81.763%
21686031975

Pull #3755

github

web-flow
Merge 27d6053a4 into b41e22f68
Pull Request #3755: Warn users that tally heating score with photon bin but without electron and positron bins.

16378 of 22828 branches covered (71.75%)

Branch coverage included in aggregate %.

22 of 23 new or added lines in 1 file covered. (95.65%)

862 existing lines in 51 files now uncovered.

54491 of 64639 relevant lines covered (84.3%)

8259986.93 hits per line

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

66.85
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cassert>
4
#include <cstdint>        // for uint64_t
5
#include <cstring>        // for memcpy
6
#define _USE_MATH_DEFINES // to make M_PI declared in Intel and MSVC compilers
7
#include <cmath>          // for ceil
8
#include <cstddef>        // for size_t
9
#include <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)
137✔
127
{
128
#if defined(__GNUC__) || defined(__clang__)
129
  // For gcc/clang, use the __atomic_compare_exchange_n intrinsic
130
  return __atomic_compare_exchange_n(
137✔
131
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
137✔
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)
3,404,459✔
148
{
149
  To out;
150
  std::memcpy(&out, &value, sizeof(To));
3,404,459✔
151
  return out;
3,404,459✔
152
}
153

154
inline void atomic_update_double(double* ptr, double value, bool is_min)
3,401,088✔
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);
3,401,088✔
159
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
3,401,088✔
160
  double current = bit_cast_value<double>(current_bits);
3,401,088✔
161
  while (is_min ? (value < current) : (value > current)) {
3,401,088✔
162
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
3,371✔
163
    uint64_t expected_bits = current_bits;
3,371✔
164
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
3,371!
165
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
166
      return;
3,371✔
167
    }
UNCOV
168
    current_bits = expected_bits;
×
UNCOV
169
    current = bit_cast_value<double>(current_bits);
×
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)
1,700,544✔
193
{
194
  atomic_update_double(ptr, value, false);
1,700,544✔
195
}
1,700,544✔
196

197
inline void atomic_min_double(double* ptr, double value)
1,700,544✔
198
{
199
  atomic_update_double(ptr, value, true);
1,700,544✔
200
}
1,700,544✔
201

202
namespace detail {
203

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

208
void MaterialVolumes::add_volume(
808,065✔
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) {
814,113!
219
    // Determine slot to check, making sure it is positive
220
    int slot = (index_material + attempt) % table_size_;
814,113✔
221
    if (slot < 0)
814,113✔
222
      slot += table_size_;
535,694✔
223
    int32_t* slot_ptr = &this->materials(index_elem, slot);
814,113✔
224

225
    // Non-atomic read of current material
226
    int32_t current_val = *slot_ptr;
814,113✔
227

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

243
    // Slot appears to be empty; attempt to claim
244
    if (current_val == EMPTY) {
6,185✔
245
      // Attempt compare-and-swap from EMPTY to index_material
246
      int32_t expected_val = EMPTY;
137✔
247
      bool claimed_slot =
248
        atomic_cas_int32(slot_ptr, expected_val, index_material);
137✔
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)) {
137!
253
#pragma omp atomic
254
        this->volumes(index_elem, slot) += volume;
137✔
255
        if (bbox) {
137✔
256
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
11✔
257
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
11✔
258
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
11✔
259
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
11✔
260
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
11✔
261
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
11✔
262
        }
263
        return;
137✔
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(
294✔
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) {
294✔
343
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
215✔
344
  } else if (mesh_type == RectilinearMesh::mesh_type) {
79✔
345
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
12✔
346
  } else if (mesh_type == CylindricalMesh::mesh_type) {
67✔
347
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
36✔
348
  } else if (mesh_type == SphericalMesh::mesh_type) {
31!
349
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
31✔
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 &&
357
             mesh_library == LibMesh::mesh_lib_type) {
358
    model::meshes.push_back(make_unique<LibMesh>(dataset));
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;
294✔
369

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

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

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

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

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

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

402
  // Ensure no other mesh has the same ID
403
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
2!
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) {
2!
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;
2✔
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(),
2✔
423
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
3✔
424

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

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

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

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

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

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

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

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

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

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

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

498
      // Determine width of rays and number of rays in other directions
499
      int ax1 = (axis + 1) % 3;
51✔
500
      int ax2 = (axis + 2) % 3;
51✔
501
      double min1 = bbox.min[ax1];
51✔
502
      double min2 = bbox.min[ax2];
51✔
503
      double d1 = width[ax1];
51✔
504
      double d2 = width[ax2];
51✔
505
      int n1 = n_rays[ax1];
51✔
506
      int n2 = n_rays[ax2];
51✔
507
      if (n1 == 0 || n2 == 0) {
51✔
508
        continue;
12✔
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;
39✔
514
      int remainder = n1 % mpi::n_procs;
39✔
515
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
39!
516
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
39✔
517
      int i1_end = i1_start + n1_local;
39✔
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) {
3,160✔
522
        for (int i2 = 0; i2 < n2; ++i2) {
595,668✔
523
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
592,547✔
524
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
592,547✔
525

526
          p.from_source(&site);
592,547✔
527

528
          // Determine particle's location
529
          if (!exhaustive_find_cell(p)) {
592,547✔
530
            out_of_model = true;
7,986✔
531
            continue;
7,986✔
532
          }
533

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

538
          // Initialize last cells from current cell
539
          for (int j = 0; j < p.n_coord(); ++j) {
1,169,122✔
540
            p.cell_last(j) = p.coord(j).cell();
584,561✔
541
          }
542
          p.n_coord_last() = p.n_coord();
584,561✔
543

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

549
            // Find the distance to the nearest boundary
550
            BoundaryInfo boundary = distance_to_boundary(p);
764,335✔
551

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

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

561
            // Add volumes to any mesh elements that were crossed
562
            int i_material = p.material();
764,335✔
563
            if (i_material != C_NONE) {
764,335✔
564
              i_material = model::materials[i_material]->id();
226,501✔
565
            }
566
            double cumulative_frac = 0.0;
764,335✔
567
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
1,572,400✔
568
              int mesh_index = bins[i_bin];
808,065✔
569
              double length = distance * length_fractions[i_bin];
808,065✔
570
              double volume = length * d1 * d2;
808,065✔
571

572
              if (compute_bboxes) {
808,065✔
573
                double axis_start = r0[axis] + distance * cumulative_frac;
566,848✔
574
                double axis_end = axis_start + length;
566,848✔
575
                cumulative_frac += length_fractions[i_bin];
566,848✔
576

577
                Position contrib_min = site.r;
566,848✔
578
                Position contrib_max = site.r;
566,848✔
579

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

587
                BoundingBox contrib_bbox {contrib_min, contrib_max};
566,848✔
588
                contrib_bbox &= bbox;
566,848✔
589

590
                result.add_volume(
566,848✔
591
                  mesh_index, i_material, volume, &contrib_bbox);
592
              } else {
593
                // Add volume to result
594
                result.add_volume(mesh_index, i_material, volume);
241,217✔
595
              }
596
            }
597

598
            if (distance == max_distance)
764,335✔
599
              break;
584,561✔
600

601
            // cross next geometric surface
602
            for (int j = 0; j < p.n_coord(); ++j) {
359,548✔
603
              p.cell_last(j) = p.coord(j).cell();
179,774✔
604
            }
605
            p.n_coord_last() = p.n_coord();
179,774✔
606

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

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

627
  // Check for errors
628
  if (out_of_model) {
17✔
629
    throw std::runtime_error("Mesh not fully contained in geometry.");
1✔
630
  } else if (result.table_full()) {
16!
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();
16✔
637

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

UNCOV
652
      for (int i = 1; i < mpi::n_procs; ++i) {
×
653
        // Receive material indices and volumes from process i
UNCOV
654
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
655
          MPI_STATUS_IGNORE);
UNCOV
656
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
657
          MPI_STATUS_IGNORE);
UNCOV
658
        if (compute_bboxes) {
×
UNCOV
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
UNCOV
666
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
UNCOV
667
          for (int k = 0; k < table_size; ++k) {
×
UNCOV
668
            int index = index_elem * table_size + k;
×
UNCOV
669
            if (mats[index] != EMPTY) {
×
UNCOV
670
              if (compute_bboxes) {
×
UNCOV
671
                int bbox_index = index * 6;
×
672
                BoundingBox slot_bbox {
UNCOV
673
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
UNCOV
674
                    recv_bboxes[bbox_index + 2]},
×
UNCOV
675
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
UNCOV
676
                    recv_bboxes[bbox_index + 5]}};
×
UNCOV
677
                result.add_volume_unsafe(
×
UNCOV
678
                  index_elem, mats[index], vols[index], &slot_bbox);
×
679
              } else {
UNCOV
680
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
681
              }
682
            }
683
          }
684
        }
685
      }
UNCOV
686
    } else {
×
687
      // Send material indices and volumes to process 0
UNCOV
688
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
×
UNCOV
689
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
×
UNCOV
690
      if (compute_bboxes) {
×
UNCOV
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;
16✔
698
#else
699
  double t_mpi = 0.0;
700
#endif
701

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

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

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

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

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

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

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

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

754
  // Close group
755
  close_group(mesh_group);
255✔
756
}
255✔
757

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

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

766
  if (n_dimension_ > 2) {
464,757✔
767
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
926,624✔
768
  } else if (n_dimension_ > 1) {
1,445✔
769
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
2,840✔
770
  } else {
771
    return fmt::format("Mesh Index ({})", ijk[0]);
50✔
772
  }
773
}
774

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

782
Position StructuredMesh::sample_element(
131,858✔
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);
131,858✔
787
  double x_max = positive_grid_boundary(ijk, 0);
131,858✔
788

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

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

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

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

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

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

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

820
  // get the filename of the unstructured mesh to load
UNCOV
821
  if (check_for_node(node, "filename")) {
×
UNCOV
822
    filename_ = get_node_value(node, "filename");
×
UNCOV
823
    if (!file_exists(filename_)) {
×
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

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

835
  // check if mesh tally data should be written with
836
  // statepoint files
UNCOV
837
  if (check_for_node(node, "output")) {
×
838
    output_ = get_node_value_bool(node, "output");
×
839
  }
UNCOV
840
}
×
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

UNCOV
904
Position UnstructuredMesh::sample_tet(
×
905
  std::array<Position, 4> coords, uint64_t* seed) const
906
{
907
  // Uniform distribution
UNCOV
908
  double s = prn(seed);
×
UNCOV
909
  double t = prn(seed);
×
UNCOV
910
  double u = prn(seed);
×
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
UNCOV
915
  if (s + t > 1) {
×
UNCOV
916
    s = 1.0 - s;
×
UNCOV
917
    t = 1.0 - t;
×
918
  }
UNCOV
919
  if (s + t + u > 1) {
×
UNCOV
920
    if (t + u > 1) {
×
UNCOV
921
      double old_t = t;
×
UNCOV
922
      t = 1.0 - u;
×
UNCOV
923
      u = 1.0 - s - old_t;
×
UNCOV
924
    } else if (t + u <= 1) {
×
UNCOV
925
      double old_s = s;
×
UNCOV
926
      s = 1.0 - t - u;
×
UNCOV
927
      u = old_s + t + u - 1;
×
928
    }
929
  }
UNCOV
930
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
×
UNCOV
931
         u * (coords[3] - coords[0]) + coords[0];
×
932
}
933

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

UNCOV
936
std::string UnstructuredMesh::get_mesh_type() const
×
937
{
UNCOV
938
  return mesh_type;
×
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

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

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

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

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

UNCOV
971
  int num_elem_skipped = 0;
×
972

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

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

982
    // write linear tet element
UNCOV
983
    if (conn.size() == 4) {
×
UNCOV
984
      xt::view(elem_types, i, xt::all()) =
×
UNCOV
985
        static_cast<int>(ElementType::LINEAR_TET);
×
UNCOV
986
      xt::view(connectivity, i, xt::all()) =
×
UNCOV
987
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
×
988
      // write linear hex element
UNCOV
989
    } else if (conn.size() == 8) {
×
UNCOV
990
      xt::view(elem_types, i, xt::all()) =
×
UNCOV
991
        static_cast<int>(ElementType::LINEAR_HEX);
×
UNCOV
992
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
×
UNCOV
993
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
×
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
    }
UNCOV
1000
  }
×
1001

1002
  // warn users that some elements were skipped
UNCOV
1003
  if (num_elem_skipped > 0) {
×
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

UNCOV
1010
  write_dataset(mesh_group, "volumes", volumes);
×
UNCOV
1011
  write_dataset(mesh_group, "connectivity", connectivity);
×
UNCOV
1012
  write_dataset(mesh_group, "element_types", elem_types);
×
UNCOV
1013
}
×
1014

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

UNCOV
1020
ElementType UnstructuredMesh::element_type(int bin) const
×
1021
{
UNCOV
1022
  auto conn = connectivity(bin);
×
1023

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

1032
StructuredMesh::MeshIndex StructuredMesh::get_indices(
105,242,325✔
1033
  Position r, bool& in_mesh) const
1034
{
1035
  MeshIndex ijk;
1036
  in_mesh = true;
105,242,325✔
1037
  for (int i = 0; i < n_dimension_; ++i) {
413,550,653✔
1038
    ijk[i] = get_index_in_direction(r[i], i);
308,308,328✔
1039

1040
    if (ijk[i] < 1 || ijk[i] > shape_[i])
308,308,328✔
1041
      in_mesh = false;
9,122,506✔
1042
  }
1043
  return ijk;
105,242,325✔
1044
}
1045

1046
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
155,642,596✔
1047
{
1048
  switch (n_dimension_) {
155,642,596!
1049
  case 1:
80,055✔
1050
    return ijk[0] - 1;
80,055✔
1051
  case 2:
10,625,530✔
1052
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
10,625,530✔
1053
  case 3:
144,937,011✔
1054
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
144,937,011✔
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
714,765✔
1061
{
1062
  MeshIndex ijk;
1063
  if (n_dimension_ == 1) {
714,765✔
1064
    ijk[0] = bin + 1;
25✔
1065
  } else if (n_dimension_ == 2) {
714,740✔
1066
    ijk[0] = bin % shape_[0] + 1;
1,420✔
1067
    ijk[1] = bin / shape_[0] + 1;
1,420✔
1068
  } else if (n_dimension_ == 3) {
713,320!
1069
    ijk[0] = bin % shape_[0] + 1;
713,320✔
1070
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
713,320✔
1071
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
713,320✔
1072
  }
1073
  return ijk;
714,765✔
1074
}
1075

1076
int StructuredMesh::get_bin(Position r) const
22,218,926✔
1077
{
1078
  // Determine indices
1079
  bool in_mesh;
1080
  MeshIndex ijk = get_indices(r, in_mesh);
22,218,926✔
1081
  if (!in_mesh)
22,218,926✔
1082
    return -1;
1,782,918✔
1083

1084
  // Convert indices to bin
1085
  return get_bin_from_indices(ijk);
20,436,008✔
1086
}
1087

1088
int StructuredMesh::n_bins() const
111,235✔
1089
{
1090
  return std::accumulate(
111,235✔
1091
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
222,470✔
1092
}
1093

1094
int StructuredMesh::n_surface_bins() const
40✔
1095
{
1096
  return 4 * n_dimension_ * n_bins();
40✔
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
UNCOV
1134
  MPI_Reduce(
×
UNCOV
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
UNCOV
1138
  if (outside) {
×
UNCOV
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(
83,471,670✔
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();
83,471,670✔
1169
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
83,471,670✔
1170
    return;
1,058,310✔
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;
82,413,360✔
1175
  Position local_r = local_coords(r0);
82,413,360✔
1176

1177
  const int n = n_dimension_;
82,413,360✔
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};
82,413,360✔
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);
82,413,360✔
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) {
82,413,360✔
1192
    if (in_mesh) {
30,123✔
1193
      tally.track(ijk, 1.0);
30,079✔
1194
    }
1195
    return;
30,123✔
1196
  }
1197

1198
  // Calculate initial distances to next surfaces in all three dimensions
1199
  std::array<MeshDistance, 3> distances;
164,766,474✔
1200
  for (int k = 0; k < n; ++k) {
322,288,178✔
1201
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
239,904,941✔
1202
  }
1203

1204
  // Loop until r = r1 is eventually reached
1205
  while (true) {
68,024,702✔
1206

1207
    if (in_mesh) {
150,407,939✔
1208

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

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

1218
      // update position and leave, if we have reached end position
1219
      traveled_distance = distances[k].distance;
142,620,634✔
1220
      if (traveled_distance >= total_distance)
142,620,634✔
1221
        return;
75,205,971✔
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);
67,414,663✔
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;
67,414,663✔
1230
      distances[k] =
67,414,663✔
1231
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
67,414,663✔
1232

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

1236
      // If we are still inside the mesh, tally inward current for the next
1237
      // cell
1238
      if (in_mesh)
67,414,663✔
1239
        tally.surface(ijk, k, !distances[k].max_surface, true);
66,206,936✔
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};
7,787,305✔
1247
      for (int k = 0; k < n; ++k) {
31,017,914✔
1248
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
31,737,551✔
1249
            (distances[k].distance > traveled_distance)) {
8,506,942✔
1250
          traveled_distance = distances[k].distance;
8,059,510✔
1251
          k_max = k;
8,059,510✔
1252
        }
1253
      }
1254
      // Assure some distance is traveled
1255
      if (k_max == -1) {
7,787,305✔
1256
        traveled_distance += TINY_BIT;
10✔
1257
      }
1258

1259
      // If r1 is not inside the mesh, exit here
1260
      if (traveled_distance >= total_distance)
7,787,305✔
1261
        return;
7,177,266✔
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);
610,039✔
1266
      for (int k = 0; k < n; ++k) {
2,421,198✔
1267
        distances[k] =
1,811,159✔
1268
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
1,811,159✔
1269
      }
1270

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

1278
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
73,278,255✔
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(
73,278,255✔
1287
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1288
      : mesh(_mesh), bins(_bins), lengths(_lengths)
73,278,255✔
1289
    {}
73,278,255✔
1290
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
128,907,465✔
1291
    void track(const MeshIndex& ijk, double l) const
129,919,389✔
1292
    {
1293
      bins.push_back(mesh->get_bin_from_indices(ijk));
129,919,389✔
1294
      lengths.push_back(l);
129,919,389✔
1295
    }
129,919,389✔
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));
73,278,255✔
1304
}
73,278,255✔
1305

1306
void StructuredMesh::surface_bins_crossed(
10,193,415✔
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)
10,193,415✔
1315
      : mesh(_mesh), bins(_bins)
10,193,415✔
1316
    {}
10,193,415✔
1317
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
5,287,199✔
1318
    {
1319
      int i_bin =
1320
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
5,287,199✔
1321
      if (max)
5,287,199✔
1322
        i_bin += 2;
2,641,040✔
1323
      if (inward)
5,287,199✔
1324
        i_bin += 1;
2,598,390✔
1325
      bins.push_back(i_bin);
5,287,199✔
1326
    }
5,287,199✔
1327
    void track(const MeshIndex& idx, double l) const {}
12,731,324✔
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));
10,193,415✔
1335
}
10,193,415✔
1336

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

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

1345
  // Check that dimensions are all greater than zero
1346
  if (xt::any(shape <= 0)) {
217!
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_) {
217!
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) {
217✔
1359

1360
    // Check to ensure width has same dimensions
1361
    if (width_.size() != n_dimension_) {
6!
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)) {
6!
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_);
6✔
1375

1376
  } else if (upper_right_.size() > 0) {
211!
1377

1378
    // Check to ensure upper_right_ has same dimensions
1379
    if (upper_right_.size() != n_dimension_) {
211!
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_)) {
211!
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);
211✔
1395
  }
1396

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

1400
  element_volume_ = 1.0;
217✔
1401
  for (int i = 0; i < n_dimension_; i++) {
804✔
1402
    element_volume_ *= width_[i];
587✔
1403
  }
1404
  return 0;
217✔
1405
}
217✔
1406

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1508
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
260,906,736✔
1509
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1510
  double l) const
1511
{
1512
  MeshDistance d;
260,906,736✔
1513
  d.next_index = ijk[i];
260,906,736✔
1514
  if (std::abs(u[i]) < FP_PRECISION)
260,906,736✔
1515
    return d;
1,266,258✔
1516

1517
  d.max_surface = (u[i] > 0);
259,640,478✔
1518
  if (d.max_surface && (ijk[i] <= shape_[i])) {
259,640,478✔
1519
    d.next_index++;
132,016,479✔
1520
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
132,016,479✔
1521
  } else if (!d.max_surface && (ijk[i] >= 1)) {
127,623,999✔
1522
    d.next_index--;
125,713,238✔
1523
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
125,713,238✔
1524
  }
1525

1526
  return d;
259,640,478✔
1527
}
1528

1529
std::pair<vector<double>, vector<double>> RegularMesh::plot(
2✔
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};
2✔
1534
  if (plot_ur.z == plot_ll.z) {
2!
1535
    axes[0] = 0;
2✔
1536
    if (n_dimension_ > 1)
2!
1537
      axes[1] = 1;
2✔
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;
2✔
1553
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
6✔
1554
    int axis = axes[i_ax];
4✔
1555
    if (axis == -1)
4!
1556
      continue;
×
1557
    auto& lines {axis_lines[i_ax]};
4✔
1558

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

1567
  return {axis_lines[0], axis_lines[1]};
4✔
1568
}
2✔
1569

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

1578
xt::xtensor<double, 1> RegularMesh::count_sites(
723✔
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();
723✔
1583
  vector<std::size_t> shape = {m};
723✔
1584

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

1589
  for (int64_t i = 0; i < length; i++) {
697,764✔
1590
    const auto& site = bank[i];
697,041✔
1591

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

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

1601
    // Add to appropriate bin
1602
    cnt(mesh_bin) += site.wgt;
697,041✔
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();
723✔
1609
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
723✔
1610

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

1616
  // Check if there were sites outside the mesh for any processor
1617
  if (outside) {
723!
1618
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
723✔
1619
  }
1620
#else
1621
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1622
  if (outside)
1623
    *outside = outside_;
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);
723✔
1628
  xt::xarray<double> counts = arr;
723✔
1629

1630
  return counts;
1,446✔
1631
}
723✔
1632

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

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

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

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

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

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

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

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

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

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

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

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

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

1696
  d.max_surface = (u[i] > 0);
4,820,933✔
1697
  if (d.max_surface && (ijk[i] <= shape_[i])) {
4,820,933✔
1698
    d.next_index++;
2,409,633✔
1699
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
2,409,633✔
1700
  } else if (!d.max_surface && (ijk[i] > 0)) {
2,411,300✔
1701
    d.next_index--;
2,339,946✔
1702
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
2,339,946✔
1703
  }
1704
  return d;
4,820,933✔
1705
}
1706

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

1713
  for (const auto& g : grid_) {
72✔
1714
    if (g.size() < 2) {
54!
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<>()) !=
54✔
1720
        g.end()) {
108!
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()};
18✔
1728
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
18✔
1729

1730
  return 0;
18✔
1731
}
1732

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

1738
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
1✔
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};
1✔
1743
  if (plot_ur.z == plot_ll.z) {
1!
1744
    axes = {0, 1};
×
1745
  } else if (plot_ur.y == plot_ll.y) {
1!
1746
    axes = {0, 2};
1✔
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;
1✔
1755
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
3✔
1756
    int axis = axes[i_ax];
2✔
1757
    vector<double>& lines {axis_lines[i_ax]};
2✔
1758

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

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

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

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

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

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

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

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

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

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

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

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

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

1828
  Position mapped_r;
4,338,788✔
1829
  mapped_r[0] = std::hypot(r.x, r.y);
4,338,788✔
1830
  mapped_r[2] = r[2];
4,338,788✔
1831

1832
  if (mapped_r[0] < FP_PRECISION) {
4,338,788!
1833
    mapped_r[1] = 0.0;
×
1834
  } else {
1835
    mapped_r[1] = std::atan2(r.y, r.x);
4,338,788✔
1836
    if (mapped_r[1] < 0)
4,338,788✔
1837
      mapped_r[1] += 2 * M_PI;
2,170,221✔
1838
  }
1839

1840
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
4,338,788✔
1841

1842
  idx[1] = sanitize_phi(idx[1]);
4,338,788✔
1843

1844
  return idx;
4,338,788✔
1845
}
1846

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

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

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

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

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

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

1871
double CylindricalMesh::find_r_crossing(
12,960,624✔
1872
  const Position& r, const Direction& u, double l, int shell) const
1873
{
1874

1875
  if ((shell < 0) || (shell > shape_[0]))
12,960,624!
1876
    return INFTY;
1,628,532✔
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];
11,332,092✔
1883
  if (r0 == 0.0)
11,332,092✔
1884
    return INFTY;
648,241✔
1885

1886
  const double denominator = u.x * u.x + u.y * u.y;
10,683,851✔
1887

1888
  // Direction of flight is in z-direction. Will never intersect r.
1889
  if (std::abs(denominator) < FP_PRECISION)
10,683,851✔
1890
    return INFTY;
5,360✔
1891

1892
  // inverse of dominator to help the compiler to speed things up
1893
  const double inv_denominator = 1.0 / denominator;
10,678,491✔
1894

1895
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
10,678,491✔
1896
  double c = r.x * r.x + r.y * r.y - r0 * r0;
10,678,491✔
1897
  double D = p * p - c * inv_denominator;
10,678,491✔
1898

1899
  if (D < 0.0)
10,678,491✔
1900
    return INFTY;
884,870✔
1901

1902
  D = std::sqrt(D);
9,793,621✔
1903

1904
  // the solution -p - D is always smaller as -p + D : Check this one first
1905
  if (std::abs(c) <= RADIAL_MESH_TOL)
9,793,621✔
1906
    return INFTY;
601,034✔
1907

1908
  if (-p - D > l)
9,192,587✔
1909
    return -p - D;
1,836,870✔
1910
  if (-p + D > l)
7,355,717✔
1911
    return -p + D;
4,553,619✔
1912

1913
  return INFTY;
2,802,098✔
1914
}
1915

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

1923
  shell = sanitize_phi(shell);
3,997,338✔
1924

1925
  const double p0 = grid_[1][shell];
3,997,338✔
1926

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

1932
  const double c0 = std::cos(p0);
3,997,338✔
1933
  const double s0 = std::sin(p0);
3,997,338✔
1934

1935
  const double denominator = (u.x * s0 - u.y * c0);
3,997,338✔
1936

1937
  // Check if direction of flight is not parallel to phi surface
1938
  if (std::abs(denominator) > FP_PRECISION) {
3,997,338✔
1939
    const double s = -(r.x * s0 - r.y * c0) / denominator;
3,973,634✔
1940
    // Check if solution is in positive direction of flight and crosses the
1941
    // correct phi surface (not -phi)
1942
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
3,973,634✔
1943
      return s;
1,838,169✔
1944
  }
1945

1946
  return INFTY;
2,159,169✔
1947
}
1948

1949
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
3,335,484✔
1950
  const Position& r, const Direction& u, double l, int shell) const
1951
{
1952
  MeshDistance d;
3,335,484✔
1953
  d.next_index = shell;
3,335,484✔
1954

1955
  // Direction of flight is within xy-plane. Will never intersect z.
1956
  if (std::abs(u.z) < FP_PRECISION)
3,335,484✔
1957
    return d;
101,656✔
1958

1959
  d.max_surface = (u.z > 0.0);
3,233,828✔
1960
  if (d.max_surface && (shell <= shape_[2])) {
3,233,828✔
1961
    d.next_index += 1;
1,533,931✔
1962
    d.distance = (grid_[2][shell] - r.z) / u.z;
1,533,931✔
1963
  } else if (!d.max_surface && (shell > 0)) {
1,699,897✔
1964
    d.next_index -= 1;
1,531,223✔
1965
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
1,531,223✔
1966
  }
1967
  return d;
3,233,828✔
1968
}
1969

1970
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
13,199,685✔
1971
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1972
  double l) const
1973
{
1974
  if (i == 0) {
13,199,685✔
1975

1976
    return std::min(
6,480,312✔
1977
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
6,480,312✔
1978
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
12,960,624✔
1979

1980
  } else if (i == 1) {
6,719,373✔
1981

1982
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
3,383,889✔
1983
                      find_phi_crossing(r0, u, l, ijk[i])),
3,383,889✔
1984
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
3,383,889✔
1985
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
6,767,778✔
1986

1987
  } else {
1988
    return find_z_crossing(r0, u, l, ijk[i]);
3,335,484✔
1989
  }
1990
}
1991

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

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

2025
    return OPENMC_E_INVALID_ARGUMENT;
×
2026
  }
2027

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

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

2035
  return 0;
40✔
2036
}
2037

2038
int CylindricalMesh::get_index_in_direction(double r, int i) const
13,016,364✔
2039
{
2040
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
13,016,364✔
2041
}
2042

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

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

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

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

2066
  double phi_i = grid_[1][ijk[1] - 1];
72✔
2067
  double phi_o = grid_[1][ijk[1]];
72✔
2068

2069
  double z_i = grid_[2][ijk[2] - 1];
72✔
2070
  double z_o = grid_[2][ijk[2]];
72✔
2071

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

2075
//==============================================================================
2076
// SphericalMesh implementation
2077
//==============================================================================
2078

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

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

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

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

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

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

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

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

2115
StructuredMesh::MeshIndex SphericalMesh::get_indices(
6,197,750✔
2116
  Position r, bool& in_mesh) const
2117
{
2118
  r = local_coords(r);
6,197,750✔
2119

2120
  Position mapped_r;
6,197,750✔
2121
  mapped_r[0] = r.norm();
6,197,750✔
2122

2123
  if (mapped_r[0] < FP_PRECISION) {
6,197,750!
2124
    mapped_r[1] = 0.0;
×
2125
    mapped_r[2] = 0.0;
×
2126
  } else {
2127
    mapped_r[1] = std::acos(r.z / mapped_r.x);
6,197,750✔
2128
    mapped_r[2] = std::atan2(r.y, r.x);
6,197,750✔
2129
    if (mapped_r[2] < 0)
6,197,750✔
2130
      mapped_r[2] += 2 * M_PI;
3,096,571✔
2131
  }
2132

2133
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
6,197,750✔
2134

2135
  idx[1] = sanitize_theta(idx[1]);
6,197,750✔
2136
  idx[2] = sanitize_phi(idx[2]);
6,197,750✔
2137

2138
  return idx;
6,197,750✔
2139
}
2140

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

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

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

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

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

2166
  return origin_ + Position(x, y, z);
10✔
2167
}
2168

2169
double SphericalMesh::find_r_crossing(
40,280,608✔
2170
  const Position& r, const Direction& u, double l, int shell) const
2171
{
2172
  if ((shell < 0) || (shell > shape_[0]))
40,280,608✔
2173
    return INFTY;
3,601,847✔
2174

2175
  // solve |r+s*u| = r0
2176
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2177
  const double r0 = grid_[0][shell];
36,678,761✔
2178
  if (r0 == 0.0)
36,678,761✔
2179
    return INFTY;
660,149✔
2180
  const double p = r.dot(u);
36,018,612✔
2181
  double c = r.dot(r) - r0 * r0;
36,018,612✔
2182
  double D = p * p - c;
36,018,612✔
2183

2184
  if (std::abs(c) <= RADIAL_MESH_TOL)
36,018,612✔
2185
    return INFTY;
963,514✔
2186

2187
  if (D >= 0.0) {
35,055,098✔
2188
    D = std::sqrt(D);
32,520,830✔
2189
    // the solution -p - D is always smaller as -p + D : Check this one first
2190
    if (-p - D > l)
32,520,830✔
2191
      return -p - D;
5,843,716✔
2192
    if (-p + D > l)
26,677,114✔
2193
      return -p + D;
16,082,300✔
2194
  }
2195

2196
  return INFTY;
13,129,082✔
2197
}
2198

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

2206
  shell = sanitize_theta(shell);
3,487,140✔
2207

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

2215
  const double cos_t = std::cos(grid_[1][shell]);
3,487,140✔
2216
  const bool sgn = std::signbit(cos_t);
3,487,140✔
2217
  const double cos_t_2 = cos_t * cos_t;
3,487,140✔
2218

2219
  const double a = cos_t_2 - u.z * u.z;
3,487,140✔
2220
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
3,487,140✔
2221
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
3,487,140✔
2222

2223
  // if factor of s^2 is zero, direction of flight is parallel to theta
2224
  // surface
2225
  if (std::abs(a) < FP_PRECISION) {
3,487,140✔
2226
    // if b vanishes, direction of flight is within theta surface and crossing
2227
    // is not possible
2228
    if (std::abs(b) < FP_PRECISION)
43,868!
2229
      return INFTY;
43,868✔
2230

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

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

2241
  const double p = b / a;
3,443,272✔
2242
  double D = p * p - c / a;
3,443,272✔
2243

2244
  if (D < 0.0)
3,443,272✔
2245
    return INFTY;
995,908✔
2246

2247
  D = std::sqrt(D);
2,447,364✔
2248

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

2255
  s = -p + D;
1,967,127✔
2256
  // Check if solution is in positive direction of flight and has correct sign
2257
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1,967,127✔
2258
    return s;
923,936✔
2259

2260
  return INFTY;
1,043,191✔
2261
}
2262

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

2270
  shell = sanitize_phi(shell);
3,631,638✔
2271

2272
  const double p0 = grid_[2][shell];
3,631,638✔
2273

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

2279
  const double c0 = std::cos(p0);
3,631,638✔
2280
  const double s0 = std::sin(p0);
3,631,638✔
2281

2282
  const double denominator = (u.x * s0 - u.y * c0);
3,631,638✔
2283

2284
  // Check if direction of flight is not parallel to phi surface
2285
  if (std::abs(denominator) > FP_PRECISION) {
3,631,638✔
2286
    const double s = -(r.x * s0 - r.y * c0) / denominator;
3,610,366✔
2287
    // Check if solution is in positive direction of flight and crosses the
2288
    // correct phi surface (not -phi)
2289
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
3,610,366✔
2290
      return s;
1,598,132✔
2291
  }
2292

2293
  return INFTY;
2,033,506✔
2294
}
2295

2296
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
30,151,425✔
2297
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2298
  double l) const
2299
{
2300

2301
  if (i == 0) {
30,151,425✔
2302
    return std::min(
20,140,304✔
2303
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
20,140,304✔
2304
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
40,280,608✔
2305

2306
  } else if (i == 1) {
10,011,121✔
2307
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
4,969,436✔
2308
                      find_theta_crossing(r0, u, l, ijk[i])),
4,969,436✔
2309
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
4,969,436✔
2310
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
9,938,872✔
2311

2312
  } else {
2313
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
5,041,685✔
2314
                      find_phi_crossing(r0, u, l, ijk[i])),
5,041,685✔
2315
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
5,041,685✔
2316
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
10,083,370✔
2317
  }
2318
}
2319

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

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

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

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

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

2363
  return 0;
35✔
2364
}
2365

2366
int SphericalMesh::get_index_in_direction(double r, int i) const
18,593,250✔
2367
{
2368
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
18,593,250✔
2369
}
2370

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

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

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

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

2394
  double theta_i = grid_[1][ijk[1] - 1];
85✔
2395
  double theta_o = grid_[1][ijk[1]];
85✔
2396

2397
  double phi_i = grid_[2][ijk[2] - 1];
85✔
2398
  double phi_o = grid_[2][ijk[2]];
85✔
2399

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

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

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

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

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

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

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

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

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

2450
  return 0;
134✔
2451
}
2452

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

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

2477
  return 0;
23✔
2478
}
23✔
2479

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

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

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

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

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

2513
  return 0;
×
2514
}
×
2515

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

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

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

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

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

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

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

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

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

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

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

2605
  return 0;
16✔
2606
}
2607

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

2615
  int pixel_width = pixels[0];
4✔
2616
  int pixel_height = pixels[1];
4✔
2617

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

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

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

2648
#pragma omp parallel
2649
  {
2650
    Position r = xyz;
4✔
2651

2652
#pragma omp for
2653
    for (int y = 0; y < pixel_height; y++) {
84✔
2654
      r[out_i] = xyz[out_i] - out_pixel * y;
80✔
2655
      for (int x = 0; x < pixel_width; x++) {
1,680✔
2656
        r[in_i] = xyz[in_i] + in_pixel * x;
1,600✔
2657
        data[pixel_width * y + x] = mesh->get_bin(r);
1,600✔
2658
      }
2659
    }
2660
  }
2661

2662
  return 0;
4✔
2663
}
2664

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

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

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

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

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

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

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

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

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

2742
  // Set material volumes
2743

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

2752
  return 0;
20✔
2753
}
20✔
2754

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

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

2766
  m->n_dimension_ = 3;
8✔
2767

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

2772
  for (int i = 0; i < nx; i++) {
52✔
2773
    m->grid_[0].push_back(grid_x[i]);
44✔
2774
  }
2775
  for (int i = 0; i < ny; i++) {
31✔
2776
    m->grid_[1].push_back(grid_y[i]);
23✔
2777
  }
2778
  for (int i = 0; i < nz; i++) {
29✔
2779
    m->grid_[2].push_back(grid_z[i]);
21✔
2780
  }
2781

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

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

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

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

2807
  return 0;
35✔
2808
}
2809

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

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

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

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

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

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

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

2863
#ifdef OPENMC_DAGMC_ENABLED
2864

2865
const std::string MOABMesh::mesh_lib_type = "moab";
2866

2867
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2868
{
2869
  initialize();
2870
}
2871

2872
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
2873
{
2874
  initialize();
2875
}
2876

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

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

2893
void MOABMesh::initialize()
2894
{
2895

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

2899
  // Initialise MOAB error code
2900
  moab::ErrorCode rval = moab::MB_SUCCESS;
2901

2902
  // Set the dimension
2903
  n_dimension_ = 3;
2904

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

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

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

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

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

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

2964
  // Determine bounds of mesh
2965
  this->determine_bounds();
2966
}
2967

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

2974
  // build acceleration data structures
2975
  compute_barycentric_data(ehs_);
2976
  build_kdtree(ehs_);
2977
}
2978

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3076
  start -= TINY_BIT * dir;
3077
  end += TINY_BIT * dir;
3078

3079
  vector<double> hits;
3080
  intersect_track(start, dir, track_len, hits);
3081

3082
  bins.clear();
3083
  lengths.clear();
3084

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

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

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

3114
    if (bin == -1) {
3115
      continue;
3116
    }
3117

3118
    bins.push_back(bin);
3119
    lengths.push_back(segment_length / track_len);
3120
  }
3121

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

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

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

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

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

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

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

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

3180
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3181

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

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

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

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

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

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

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

3236
  baryc_data_.clear();
3237
  baryc_data_.resize(tets.size());
3238

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

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

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

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

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

3266
  moab::ErrorCode rval;
3267

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

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

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

3291
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3292

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

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

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

3313
int MOABMesh::get_index_from_bin(int bin) const
3314
{
3315
  return bin;
3316
}
3317

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

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

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

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

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

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

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

3374
  auto tet = this->get_ent_handle_from_bin(bin);
3375

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

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

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

3399
  return {centroid[0], centroid[1], centroid[2]};
3400
}
3401

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

3407
Position MOABMesh::vertex(int id) const
3408
{
3409

3410
  moab::ErrorCode rval;
3411

3412
  moab::EntityHandle vert = verts_[id];
3413

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

3420
  return {coords[0], coords[1], coords[2]};
3421
}
3422

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

3427
  auto tet = get_ent_handle_from_bin(bin);
3428

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

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

3442
  return verts;
3443
}
3444

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

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

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

3480
  // return the populated tag handles
3481
  return {value_tag, error_tag};
3482
}
3483

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

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

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

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

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

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

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

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

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

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

3570
#endif
3571

3572
#ifdef OPENMC_LIBMESH_ENABLED
3573

3574
const std::string LibMesh::mesh_lib_type = "libmesh";
3575

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

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

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

3602
  m_ = &input_mesh;
3603
  set_length_multiplier(length_multiplier);
3604
  initialize();
3605
}
3606

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

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

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

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

3642
  // assuming that unstructured meshes used in OpenMC are 3D
3643
  n_dimension_ = 3;
3644

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

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

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

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

3668
  // bounding box for the mesh for quick rejection checks
3669
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3670
  libMesh::Point ll = bbox_.min();
3671
  libMesh::Point ur = bbox_.max();
3672
  lower_left_ = {ll(0), ll(1), ll(2)};
3673
  upper_right_ = {ur(0), ur(1), ur(2)};
3674
}
3675

3676
// Sample position within a tet for LibMesh type tets
3677
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
3678
{
3679
  const auto& elem = get_element_from_bin(bin);
3680
  // Get tet vertex coordinates from LibMesh
3681
  std::array<Position, 4> tet_verts;
3682
  for (int i = 0; i < elem.n_nodes(); i++) {
3683
    auto node_ref = elem.node_ref(i);
3684
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3685
  }
3686
  // Samples position within tet using Barycentric coordinates
3687
  return this->sample_tet(tet_verts, seed);
3688
}
3689

3690
Position LibMesh::centroid(int bin) const
3691
{
3692
  const auto& elem = this->get_element_from_bin(bin);
3693
  auto centroid = elem.vertex_average();
3694
  if (length_multiplier_ > 0.0) {
3695
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3696
  } else {
3697
    return {centroid(0), centroid(1), centroid(2)};
3698
  }
3699
}
3700

3701
int LibMesh::n_vertices() const
3702
{
3703
  return m_->n_nodes();
3704
}
3705

3706
Position LibMesh::vertex(int vertex_id) const
3707
{
3708
  const auto node_ref = m_->node_ref(vertex_id);
3709
  if (length_multiplier_ > 0.0) {
3710
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3711
  } else {
3712
    return {node_ref(0), node_ref(1), node_ref(2)};
3713
  }
3714
}
3715

3716
std::vector<int> LibMesh::connectivity(int elem_id) const
3717
{
3718
  std::vector<int> conn;
3719
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3720
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3721
    conn.push_back(elem_ptr->node_id(i));
3722
  }
3723
  return conn;
3724
}
3725

3726
std::string LibMesh::library() const
3727
{
3728
  return mesh_lib_type;
3729
}
3730

3731
int LibMesh::n_bins() const
3732
{
3733
  return m_->n_elem();
3734
}
3735

3736
int LibMesh::n_surface_bins() const
3737
{
3738
  int n_bins = 0;
3739
  for (int i = 0; i < this->n_bins(); i++) {
3740
    const libMesh::Elem& e = get_element_from_bin(i);
3741
    n_bins += e.n_faces();
3742
    // if this is a boundary element, it will only be visited once,
3743
    // the number of surface bins is incremented to
3744
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3745
      // null neighbor pointer indicates a boundary face
3746
      if (!neighbor_ptr) {
3747
        n_bins++;
3748
      }
3749
    }
3750
  }
3751
  return n_bins;
3752
}
3753

3754
void LibMesh::add_score(const std::string& var_name)
3755
{
3756
  if (!equation_systems_) {
3757
    build_eqn_sys();
3758
  }
3759

3760
  // check if this is a new variable
3761
  std::string value_name = var_name + "_mean";
3762
  if (!variable_map_.count(value_name)) {
3763
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3764
    auto var_num =
3765
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3766
    variable_map_[value_name] = var_num;
3767
  }
3768

3769
  std::string std_dev_name = var_name + "_std_dev";
3770
  // check if this is a new variable
3771
  if (!variable_map_.count(std_dev_name)) {
3772
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3773
    auto var_num =
3774
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3775
    variable_map_[std_dev_name] = var_num;
3776
  }
3777
}
3778

3779
void LibMesh::remove_scores()
3780
{
3781
  if (equation_systems_) {
3782
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3783
    eqn_sys.clear();
3784
    variable_map_.clear();
3785
  }
3786
}
3787

3788
void LibMesh::set_score_data(const std::string& var_name,
3789
  const vector<double>& values, const vector<double>& std_dev)
3790
{
3791
  if (!equation_systems_) {
3792
    build_eqn_sys();
3793
  }
3794

3795
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3796

3797
  if (!eqn_sys.is_initialized()) {
3798
    equation_systems_->init();
3799
  }
3800

3801
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3802

3803
  // look up the value variable
3804
  std::string value_name = var_name + "_mean";
3805
  unsigned int value_num = variable_map_.at(value_name);
3806
  // look up the std dev variable
3807
  std::string std_dev_name = var_name + "_std_dev";
3808
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3809

3810
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3811
       it++) {
3812
    if (!(*it)->active()) {
3813
      continue;
3814
    }
3815

3816
    auto bin = get_bin_from_element(*it);
3817

3818
    // set value
3819
    vector<libMesh::dof_id_type> value_dof_indices;
3820
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3821
    assert(value_dof_indices.size() == 1);
3822
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3823

3824
    // set std dev
3825
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3826
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3827
    assert(std_dev_dof_indices.size() == 1);
3828
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3829
  }
3830
}
3831

3832
void LibMesh::write(const std::string& filename) const
3833
{
3834
  write_message(fmt::format(
3835
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3836
  libMesh::ExodusII_IO exo(*m_);
3837
  std::set<std::string> systems_out = {eq_system_name_};
3838
  exo.write_discontinuous_exodusII(
3839
    filename + ".e", *equation_systems_, &systems_out);
3840
}
3841

3842
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3843
  vector<int>& bins, vector<double>& lengths) const
3844
{
3845
  // TODO: Implement triangle crossings here
3846
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3847
}
3848

3849
int LibMesh::get_bin(Position r) const
3850
{
3851
  // look-up a tet using the point locator
3852
  libMesh::Point p(r.x, r.y, r.z);
3853

3854
  if (length_multiplier_ > 0.0) {
3855
    // Scale the point down
3856
    p /= length_multiplier_;
3857
  }
3858

3859
  // quick rejection check
3860
  if (!bbox_.contains_point(p)) {
3861
    return -1;
3862
  }
3863

3864
  const auto& point_locator = pl_.at(thread_num());
3865

3866
  const auto elem_ptr = (*point_locator)(p);
3867
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3868
}
3869

3870
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3871
{
3872
  int bin = elem->id() - first_element_id_;
3873
  if (bin >= n_bins() || bin < 0) {
3874
    fatal_error(fmt::format("Invalid bin: {}", bin));
3875
  }
3876
  return bin;
3877
}
3878

3879
std::pair<vector<double>, vector<double>> LibMesh::plot(
3880
  Position plot_ll, Position plot_ur) const
3881
{
3882
  return {};
3883
}
3884

3885
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3886
{
3887
  return m_->elem_ref(bin);
3888
}
3889

3890
double LibMesh::volume(int bin) const
3891
{
3892
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
3893
         length_multiplier_ * length_multiplier_;
3894
}
3895

3896
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3897
  double length_multiplier,
3898
  const std::set<libMesh::subdomain_id_type>& block_ids)
3899
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3900
    block_restrict_(!block_ids_.empty()),
3901
    num_active_(
3902
      block_restrict_
3903
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
3904
            m_->active_subdomain_set_elements_end(block_ids_))
3905
        : m_->n_active_elem())
3906
{
3907
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3908
  // contiguous in ID space, so we need to map from bin indices (defined over
3909
  // active elements) to global dof ids
3910
  bin_to_elem_map_.reserve(num_active_);
3911
  elem_to_bin_map_.resize(m_->n_elem(), -1);
3912
  auto begin = block_restrict_
3913
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
3914
                 : m_->active_elements_begin();
3915
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
3916
                             : m_->active_elements_end();
3917
  for (const auto& elem : libMesh::as_range(begin, end)) {
3918
    bin_to_elem_map_.push_back(elem->id());
3919
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3920
  }
3921
}
3922

3923
int AdaptiveLibMesh::n_bins() const
3924
{
3925
  return num_active_;
3926
}
3927

3928
void AdaptiveLibMesh::add_score(const std::string& var_name)
3929
{
3930
  warning(fmt::format(
3931
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3932
    this->id_));
3933
}
3934

3935
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3936
  const vector<double>& values, const vector<double>& std_dev)
3937
{
3938
  warning(fmt::format(
3939
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3940
    this->id_));
3941
}
3942

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

3950
int AdaptiveLibMesh::get_bin(Position r) const
3951
{
3952
  // look-up a tet using the point locator
3953
  libMesh::Point p(r.x, r.y, r.z);
3954

3955
  if (length_multiplier_ > 0.0) {
3956
    // Scale the point down
3957
    p /= length_multiplier_;
3958
  }
3959

3960
  // quick rejection check
3961
  if (!bbox_.contains_point(p)) {
3962
    return -1;
3963
  }
3964

3965
  const auto& point_locator = pl_.at(thread_num());
3966

3967
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
3968
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3969
}
3970

3971
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3972
{
3973
  int bin = elem_to_bin_map_[elem->id()];
3974
  if (bin >= n_bins() || bin < 0) {
3975
    fatal_error(fmt::format("Invalid bin: {}", bin));
3976
  }
3977
  return bin;
3978
}
3979

3980
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3981
{
3982
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3983
}
3984

3985
#endif // OPENMC_LIBMESH_ENABLED
3986

3987
//==============================================================================
3988
// Non-member functions
3989
//==============================================================================
3990

3991
void read_meshes(pugi::xml_node root)
1,299✔
3992
{
3993
  std::unordered_set<int> mesh_ids;
1,299✔
3994

3995
  for (auto node : root.children("mesh")) {
1,593✔
3996
    // Check to make sure multiple meshes in the same file don't share IDs
3997
    int id = std::stoi(get_node_value(node, "id"));
294✔
3998
    if (contains(mesh_ids, id)) {
294!
3999
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4000
                              "'{}' in the same input file",
4001
        id));
4002
    }
4003
    mesh_ids.insert(id);
294✔
4004

4005
    // If we've already read a mesh with the same ID in a *different* file,
4006
    // assume it is the same here
4007
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
294!
4008
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4009
      continue;
×
4010
    }
4011

4012
    std::string mesh_type;
294✔
4013
    if (check_for_node(node, "type")) {
294✔
4014
      mesh_type = get_node_value(node, "type", true, true);
87✔
4015
    } else {
4016
      mesh_type = "regular";
207✔
4017
    }
4018

4019
    // determine the mesh library to use
4020
    std::string mesh_lib;
294✔
4021
    if (check_for_node(node, "library")) {
294!
UNCOV
4022
      mesh_lib = get_node_value(node, "library", true, true);
×
4023
    }
4024

4025
    Mesh::create(node, mesh_type, mesh_lib);
294✔
4026
  }
294✔
4027
}
1,299✔
4028

4029
void read_meshes(hid_t group)
2✔
4030
{
4031
  std::unordered_set<int> mesh_ids;
2✔
4032

4033
  std::vector<int> ids;
2✔
4034
  read_attribute(group, "ids", ids);
2✔
4035

4036
  for (auto id : ids) {
5✔
4037

4038
    // Check to make sure multiple meshes in the same file don't share IDs
4039
    if (contains(mesh_ids, id)) {
3!
4040
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4041
                              "'{}' in the same HDF5 input file",
4042
        id));
4043
    }
4044
    mesh_ids.insert(id);
3✔
4045

4046
    // If we've already read a mesh with the same ID in a *different* file,
4047
    // assume it is the same here
4048
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3!
4049
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
3✔
4050
      continue;
3✔
4051
    }
4052

4053
    std::string name = fmt::format("mesh {}", id);
×
4054
    hid_t mesh_group = open_group(group, name.c_str());
×
4055

4056
    std::string mesh_type;
×
4057
    if (object_exists(mesh_group, "type")) {
×
4058
      read_dataset(mesh_group, "type", mesh_type);
×
4059
    } else {
4060
      mesh_type = "regular";
×
4061
    }
4062

4063
    // determine the mesh library to use
4064
    std::string mesh_lib;
×
4065
    if (object_exists(mesh_group, "library")) {
×
4066
      read_dataset(mesh_group, "library", mesh_lib);
×
4067
    }
4068

4069
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4070
  }
×
4071
}
2✔
4072

4073
void meshes_to_hdf5(hid_t group)
608✔
4074
{
4075
  // Write number of meshes
4076
  hid_t meshes_group = create_group(group, "meshes");
608✔
4077
  int32_t n_meshes = model::meshes.size();
608✔
4078
  write_attribute(meshes_group, "n_meshes", n_meshes);
608✔
4079

4080
  if (n_meshes > 0) {
608✔
4081
    // Write IDs of meshes
4082
    vector<int> ids;
188✔
4083
    for (const auto& m : model::meshes) {
427✔
4084
      m->to_hdf5(meshes_group);
239✔
4085
      ids.push_back(m->id_);
239✔
4086
    }
4087
    write_attribute(meshes_group, "ids", ids);
188✔
4088
  }
188✔
4089

4090
  close_group(meshes_group);
608✔
4091
}
608✔
4092

4093
void free_memory_mesh()
857✔
4094
{
4095
  model::meshes.clear();
857✔
4096
  model::mesh_map.clear();
857✔
4097
}
857✔
4098

4099
extern "C" int n_meshes()
28✔
4100
{
4101
  return model::meshes.size();
28✔
4102
}
4103

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