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

openmc-dev / openmc / 29607439152

17 Jul 2026 07:24PM UTC coverage: 81.337% (+0.001%) from 81.336%
29607439152

Pull #4021

github

web-flow
Merge 6ee22ed06 into db673b9ac
Pull Request #4021: MeshSurfaceFilter partial current labels

18335 of 26595 branches covered (68.94%)

Branch coverage included in aggregate %.

41 of 42 new or added lines in 6 files covered. (97.62%)

2 existing lines in 2 files now uncovered.

59864 of 69547 relevant lines covered (86.08%)

47908935.09 hits per line

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

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

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

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

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

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

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

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

59
namespace openmc {
60

61
//==============================================================================
62
// Global variables
63
//==============================================================================
64

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

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

75
namespace model {
76

77
std::unordered_map<int32_t, int32_t> mesh_map;
78
vector<unique_ptr<Mesh>> meshes;
79

80
} // namespace model
81

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

89
//==============================================================================
90
// Helper functions
91
//==============================================================================
92

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

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

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

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

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

141
// Helper function equivalent to std::bit_cast in C++20
142
template<typename To, typename From>
143
inline To bit_cast_value(const From& value)
38,500,055✔
144
{
145
  To out;
146
  std::memcpy(&out, &value, sizeof(To));
36,671✔
147
  return out;
148
}
149

150
inline void atomic_update_double(double* ptr, double value, bool is_min)
38,499,840✔
151
{
152
#if defined(__GNUC__) || defined(__clang__)
153
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
38,499,840✔
154
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
38,499,840✔
155
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
38,499,840✔
156
  double current = bit_cast_value<double>(current_bits);
38,499,840✔
157
  while (is_min ? (value < current) : (value > current)) {
38,500,055✔
158
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
36,671✔
159
    uint64_t expected_bits = current_bits;
36,671✔
160
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
36,671✔
161
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
162
      return;
38,499,840✔
163
    }
164
    current_bits = expected_bits;
215✔
165
    current = bit_cast_value<double>(current_bits);
215✔
166
  }
167

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

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

188
inline void atomic_max_double(double* ptr, double value)
19,249,920✔
189
{
190
  atomic_update_double(ptr, value, false);
6,416,640✔
191
}
6,416,640✔
192

193
inline void atomic_min_double(double* ptr, double value)
19,249,920✔
194
{
195
  atomic_update_double(ptr, value, true);
6,416,640✔
196
}
197

198
namespace detail {
199

200
//==============================================================================
201
// MaterialVolumes implementation
202
//==============================================================================
203

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

213
  // Loop for linear probing
214
  for (int attempt = 0; attempt < table_size_; ++attempt) {
9,070,027!
215
    // Determine slot to check, making sure it is positive
216
    int slot = (index_material + attempt) % table_size_;
9,070,027✔
217
    if (slot < 0)
9,070,027✔
218
      slot += table_size_;
5,845,834✔
219
    int32_t* slot_ptr = &this->materials(index_elem, slot);
9,070,027✔
220

221
    // Non-atomic read of current material
222
    int32_t current_val = *slot_ptr;
9,070,027✔
223

224
    // Found the desired material; accumulate volume and bbox
225
    if (current_val == index_material) {
9,070,027✔
226
#pragma omp atomic
5,330,995✔
227
      this->volumes(index_elem, slot) += volume;
9,068,444✔
228
      if (bbox) {
9,068,444✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,416,462✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,416,462✔
231
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,416,462✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,416,462✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,416,462✔
234
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,416,462✔
235
      }
236
      return;
9,068,444✔
237
    }
238

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

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

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

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

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

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

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

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

327
} // namespace detail
328

329
//==============================================================================
330
// Mesh implementation
331
//==============================================================================
332

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

363
  // Map ID to position in vector
364
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3,328✔
365

366
  return model::meshes.back();
3,328✔
367
}
368

369
Mesh::Mesh(pugi::xml_node node)
3,372✔
370
{
371
  // Read mesh id
372
  id_ = std::stoi(get_node_value(node, "id"));
6,744✔
373
  if (check_for_node(node, "name"))
3,372✔
374
    name_ = get_node_value(node, "name");
15✔
375
}
3,372✔
376

377
Mesh::Mesh(hid_t group)
44✔
378
{
379
  // Read mesh ID
380
  read_attribute(group, "id", id_);
44✔
381

382
  // Read mesh name
383
  if (object_exists(group, "name")) {
44!
384
    read_dataset(group, "name", name_);
×
385
  }
386
}
44✔
387

388
void Mesh::set_id(int32_t id)
23✔
389
{
390
  assert(id >= 0 || id == C_NONE);
23!
391

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

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

404
  // If no ID is specified, auto-assign the next ID in the sequence
405
  if (id == C_NONE) {
23✔
406
    id = 0;
1✔
407
    for (const auto& m : model::meshes) {
3✔
408
      id = std::max(id, m->id_);
3✔
409
    }
410
    ++id;
1✔
411
  }
412

413
  // Update ID and entry in the mesh map
414
  id_ = id;
23✔
415

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

421
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
23✔
422
}
23✔
423

424
vector<double> Mesh::volumes() const
287✔
425
{
426
  vector<double> volumes(n_bins());
287✔
427
  for (int i = 0; i < n_bins(); i++) {
1,122,895✔
428
    volumes[i] = this->volume(i);
1,122,608✔
429
  }
430
  return volumes;
287✔
431
}
×
432

433
//! Default (Cartesian) axis labels used for surface bin labels.
434
std::array<const char*, 3> Mesh::axis_labels() const
427,460✔
435
{
436
  return {"x", "y", "z"};
427,460✔
437
}
438

439
//! Build the surface component of a mesh surface tally bin label.
440
//! surf_index: 0=out/min, 1=in/min, 2=out/max, 3=in/max
441
std::string Mesh::surface_bin_label(int surf_index) const
1,396,868✔
442
{
443
  auto labels = this->axis_labels();
1,396,868✔
444
  int dim = surf_index / 4;
1,396,868✔
445
  int code = surf_index % 4;
1,396,868✔
446
  bool incoming = (code == 1) || (code == 3);
1,396,868✔
447
  bool max = (code == 2) || (code == 3);
1,396,868✔
448
  return fmt::format(" {}, {}-{}", incoming ? "Incoming" : "Outgoing",
1,396,868✔
449
    labels[dim], max ? "max" : "min");
2,793,736✔
450
}
451

UNCOV
452
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
453
  int32_t* materials, double* volumes) const
454
{
455
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
456
}
×
457

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

474
  Timer timer;
209✔
475
  timer.start();
209✔
476

477
  // Create object for keeping track of materials/volumes
478
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
209✔
479
  bool compute_bboxes = bboxes != nullptr;
209✔
480

481
  // Determine bounding box
482
  auto bbox = this->bounding_box();
209✔
483

484
  std::array<int, 3> n_rays = {nx, ny, nz};
209✔
485

486
  // Determine effective width of rays
487
  Position width = bbox.max - bbox.min;
209✔
488
  width.x = (nx > 0) ? width.x / nx : 0.0;
209✔
489
  width.y = (ny > 0) ? width.y / ny : 0.0;
209✔
490
  width.z = (nz > 0) ? width.z / nz : 0.0;
209✔
491

492
  // Set flag for mesh being contained within model
493
  bool out_of_model = false;
209✔
494

495
#pragma omp parallel
114✔
496
  {
95✔
497
    // Preallocate vector for mesh indices and length fractions and particle
498
    vector<int> bins;
95✔
499
    vector<double> length_fractions;
95✔
500
    Particle p;
95✔
501

502
    SourceSite site;
95✔
503
    site.E = 1.0;
95✔
504
    site.particle = ParticleType::neutron();
95✔
505

506
    for (int axis = 0; axis < 3; ++axis) {
380✔
507
      // Set starting position and direction
508
      site.r = {0.0, 0.0, 0.0};
285✔
509
      site.r[axis] = bbox.min[axis];
285✔
510
      site.u = {0.0, 0.0, 0.0};
285✔
511
      site.u[axis] = 1.0;
285✔
512

513
      // Determine width of rays and number of rays in other directions
514
      int ax1 = (axis + 1) % 3;
285✔
515
      int ax2 = (axis + 2) % 3;
285✔
516
      double min1 = bbox.min[ax1];
285✔
517
      double min2 = bbox.min[ax2];
285✔
518
      double d1 = width[ax1];
285✔
519
      double d2 = width[ax2];
285✔
520
      int n1 = n_rays[ax1];
285✔
521
      int n2 = n_rays[ax2];
285✔
522
      if (n1 == 0 || n2 == 0) {
285✔
523
        continue;
60✔
524
      }
525

526
      // Divide rays in first direction over MPI processes by computing starting
527
      // and ending indices
528
      int min_work = n1 / mpi::n_procs;
225✔
529
      int remainder = n1 % mpi::n_procs;
225✔
530
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
225!
531
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
225!
532
      int i1_end = i1_start + n1_local;
225✔
533

534
      // Loop over rays on face of bounding box
535
#pragma omp for collapse(2)
536
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
17,600✔
537
        for (int i2 = 0; i2 < n2; ++i2) {
3,080,220✔
538
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,062,845✔
539
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,062,845✔
540

541
          p.from_source(&site);
3,062,845✔
542

543
          // Determine particle's location
544
          if (!exhaustive_find_cell(p)) {
3,062,845✔
545
            out_of_model = true;
39,930✔
546
            continue;
39,930✔
547
          }
548

549
          // Set birth cell attribute
550
          if (p.cell_born() == C_NONE)
3,022,915!
551
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
552

553
          // Initialize last cells from current cell
554
          for (int j = 0; j < p.n_coord(); ++j) {
6,045,830✔
555
            p.cell_last(j) = p.coord(j).cell();
3,022,915✔
556
          }
557
          p.n_coord_last() = p.n_coord();
3,022,915✔
558

559
          while (true) {
4,848,995✔
560
            // Ray trace from r_start to r_end
561
            Position r0 = p.r();
3,935,955✔
562
            double max_distance = bbox.max[axis] - r0[axis];
3,935,955✔
563

564
            // Find the distance to the nearest boundary
565
            BoundaryInfo boundary = distance_to_boundary(p);
3,935,955✔
566

567
            // Advance particle forward
568
            double distance = std::min(boundary.distance(), max_distance);
3,935,955✔
569
            p.move_distance(distance);
3,935,955✔
570

571
            // Determine what mesh elements were crossed by particle
572
            bins.clear();
3,935,955✔
573
            length_fractions.clear();
3,935,955✔
574
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
3,935,955✔
575

576
            // Add volumes to any mesh elements that were crossed
577
            int i_material = p.material();
3,935,955✔
578
            if (i_material != C_NONE) {
3,935,955✔
579
              i_material = model::materials[i_material]->id();
1,252,125✔
580
            }
581
            double cumulative_frac = 0.0;
3,935,955✔
582
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
8,090,560✔
583
              int mesh_index = bins[i_bin];
4,154,605✔
584
              double length = distance * length_fractions[i_bin];
4,154,605✔
585
              double volume = length * d1 * d2;
4,154,605✔
586

587
              if (compute_bboxes) {
4,154,605✔
588
                double axis_start = r0[axis] + distance * cumulative_frac;
2,948,520✔
589
                double axis_end = axis_start + length;
2,948,520✔
590
                cumulative_frac += length_fractions[i_bin];
2,948,520✔
591

592
                Position contrib_min = site.r;
2,948,520✔
593
                Position contrib_max = site.r;
2,948,520✔
594

595
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,948,520✔
596
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,948,520✔
597
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,948,520✔
598
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,948,520✔
599
                contrib_min[axis] = std::min(axis_start, axis_end);
2,948,520!
600
                contrib_max[axis] = std::max(axis_start, axis_end);
5,897,040!
601

602
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,948,520✔
603
                contrib_bbox &= bbox;
2,948,520✔
604

605
                result.add_volume(
2,948,520✔
606
                  mesh_index, i_material, volume, &contrib_bbox);
607
              } else {
608
                // Add volume to result
609
                result.add_volume(mesh_index, i_material, volume);
1,206,085✔
610
              }
611
            }
612

613
            if (distance == max_distance)
3,935,955✔
614
              break;
615

616
            // cross next geometric surface
617
            for (int j = 0; j < p.n_coord(); ++j) {
1,826,080✔
618
              p.cell_last(j) = p.coord(j).cell();
913,040✔
619
            }
620
            p.n_coord_last() = p.n_coord();
913,040✔
621

622
            // Set surface that particle is on and adjust coordinate levels
623
            p.surface() = boundary.surface();
913,040✔
624
            p.n_coord() = boundary.coord_level();
913,040✔
625

626
            if (boundary.lattice_translation()[0] != 0 ||
913,040!
627
                boundary.lattice_translation()[1] != 0 ||
913,040!
628
                boundary.lattice_translation()[2] != 0) {
913,040!
629
              // Particle crosses lattice boundary
630
              cross_lattice(p, boundary);
×
631
            } else {
632
              // Particle crosses surface
633
              const auto& surf {model::surfaces[p.surface_index()].get()};
913,040✔
634
              p.cross_surface(*surf);
913,040✔
635
            }
636
          }
913,040✔
637
        }
638
      }
639
    }
640
  }
95✔
641

642
  // Check for errors
643
  if (out_of_model) {
209✔
644
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
645
  } else if (result.table_full()) {
198!
646
    throw std::runtime_error("Maximum number of materials for mesh material "
×
647
                             "volume calculation insufficient.");
×
648
  }
649

650
  // Compute time for raytracing
651
  double t_raytrace = timer.elapsed();
198✔
652

653
#ifdef OPENMC_MPI
654
  // Combine results from multiple MPI processes
655
  if (mpi::n_procs > 1) {
72!
656
    int total = this->n_bins() * table_size;
657
    int total_bbox = total * 6;
658
    if (mpi::master) {
×
659
      // Allocate temporary buffer for receiving data
660
      vector<int32_t> mats(total);
661
      vector<double> vols(total);
×
662
      vector<double> recv_bboxes;
×
663
      if (compute_bboxes) {
×
664
        recv_bboxes.resize(total_bbox);
×
665
      }
666

667
      for (int i = 1; i < mpi::n_procs; ++i) {
×
668
        // Receive material indices and volumes from process i
669
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
670
          MPI_STATUS_IGNORE);
671
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
672
          MPI_STATUS_IGNORE);
673
        if (compute_bboxes) {
×
674
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
675
            mpi::intracomm, MPI_STATUS_IGNORE);
676
        }
677

678
        // Combine with existing results; we can call thread unsafe version of
679
        // add_volume because each thread is operating on a different element
680
#pragma omp for
681
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
682
          for (int k = 0; k < table_size; ++k) {
×
683
            int index = index_elem * table_size + k;
684
            if (mats[index] != EMPTY) {
×
685
              if (compute_bboxes) {
×
686
                int bbox_index = index * 6;
687
                BoundingBox slot_bbox {
688
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
689
                    recv_bboxes[bbox_index + 2]},
690
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
691
                    recv_bboxes[bbox_index + 5]}};
×
692
                result.add_volume_unsafe(
693
                  index_elem, mats[index], vols[index], &slot_bbox);
×
694
              } else {
695
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
696
              }
697
            }
698
          }
699
        }
700
      }
701
    } else {
702
      // Send material indices and volumes to process 0
703
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
704
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
705
      if (compute_bboxes) {
×
706
        MPI_Send(bboxes, total_bbox, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
707
      }
708
    }
709
  }
710

711
  // Report time for MPI communication
712
  double t_mpi = timer.elapsed() - t_raytrace;
72✔
713
#else
714
  double t_mpi = 0.0;
108✔
715
#endif
716

717
  // Normalize based on known volumes of elements
718
  for (int i = 0; i < this->n_bins(); ++i) {
1,111✔
719
    // Estimated total volume in element i
720
    double volume = 0.0;
721
    for (int j = 0; j < table_size; ++j) {
8,349✔
722
      volume += result.volumes(i, j);
7,436✔
723
    }
724
    // Renormalize volumes based on known volume of element i
725
    double norm = this->volume(i) / volume;
913✔
726
    for (int j = 0; j < table_size; ++j) {
8,349✔
727
      result.volumes(i, j) *= norm;
7,436✔
728
    }
729
  }
730

731
  // Get total time and normalization time
732
  timer.stop();
198✔
733
  double t_total = timer.elapsed();
198✔
734
  double t_norm = t_total - t_raytrace - t_mpi;
198✔
735

736
  // Show timing statistics
737
  if (settings::verbosity < 7 || !mpi::master)
198!
738
    return;
44✔
739
  header("Timing Statistics", 7);
154✔
740
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
154✔
741
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
154✔
742
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
154✔
743
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
154✔
744
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
308✔
745
    n_total / t_raytrace);
154✔
746
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
224✔
747
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
154✔
748
  std::fflush(stdout);
154✔
749
}
750

751
void Mesh::to_hdf5(hid_t group) const
3,214✔
752
{
753
  // Create group for mesh
754
  std::string group_name = fmt::format("mesh {}", id_);
3,214✔
755
  hid_t mesh_group = create_group(group, group_name.c_str());
3,214✔
756

757
  // Write mesh type
758
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,214✔
759

760
  // Write mesh ID
761
  write_attribute(mesh_group, "id", id_);
3,214✔
762

763
  // Write mesh name
764
  write_dataset(mesh_group, "name", name_);
3,214✔
765

766
  // Write mesh data
767
  this->to_hdf5_inner(mesh_group);
3,214✔
768

769
  // Close group
770
  close_group(mesh_group);
3,214✔
771
}
3,214✔
772

773
//==============================================================================
774
// Structured Mesh implementation
775
//==============================================================================
776

777
std::string StructuredMesh::bin_label(int bin) const
5,193,676✔
778
{
779
  MeshIndex ijk = get_indices_from_bin(bin);
5,193,676✔
780

781
  if (n_dimension_ > 2) {
5,193,676✔
782
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,177,341✔
783
  } else if (n_dimension_ > 1) {
16,335✔
784
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,060✔
785
  } else {
786
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
787
  }
788
}
789

790
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,817✔
791
{
792
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,817✔
793
}
794

795
Position StructuredMesh::sample_element(
1,441,137✔
796
  const MeshIndex& ijk, uint64_t* seed) const
797
{
798
  // lookup the lower/upper bounds for the mesh element
799
  double x_min = negative_grid_boundary(ijk, 0);
1,441,137✔
800
  double x_max = positive_grid_boundary(ijk, 0);
1,441,137✔
801

802
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,441,137!
803
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,441,137!
804

805
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,441,137!
806
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,441,137!
807

808
  return {x_min + (x_max - x_min) * prn(seed),
1,441,137✔
809
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,441,137✔
810
}
811

812
//==============================================================================
813
// Unstructured Mesh implementation
814
//==============================================================================
815

816
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49!
817
{
818
  n_dimension_ = 3;
49✔
819

820
  // check the mesh type
821
  if (check_for_node(node, "type")) {
49!
822
    auto temp = get_node_value(node, "type", true, true);
49!
823
    if (temp != mesh_type) {
49!
824
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
825
    }
826
  }
49✔
827

828
  // check if a length unit multiplier was specified
829
  if (check_for_node(node, "length_multiplier")) {
49!
830
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
831
  }
832

833
  // get the filename of the unstructured mesh to load
834
  if (check_for_node(node, "filename")) {
49!
835
    filename_ = get_node_value(node, "filename");
49!
836
    if (!file_exists(filename_)) {
49!
837
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
838
    }
839
  } else {
840
    fatal_error(fmt::format(
×
841
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
842
  }
843

844
  if (check_for_node(node, "options")) {
49!
845
    options_ = get_node_value(node, "options");
16!
846
  }
847

848
  // check if mesh tally data should be written with
849
  // statepoint files
850
  if (check_for_node(node, "output")) {
49!
851
    output_ = get_node_value_bool(node, "output");
×
852
  }
853
}
49✔
854

855
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
856
{
857
  n_dimension_ = 3;
×
858

859
  // check the mesh type
860
  if (object_exists(group, "type")) {
×
861
    std::string temp;
×
862
    read_dataset(group, "type", temp);
×
863
    if (temp != mesh_type) {
×
864
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
865
    }
866
  }
×
867

868
  // check if a length unit multiplier was specified
869
  if (object_exists(group, "length_multiplier")) {
×
870
    read_dataset(group, "length_multiplier", length_multiplier_);
×
871
  }
872

873
  // get the filename of the unstructured mesh to load
874
  if (object_exists(group, "filename")) {
×
875
    read_dataset(group, "filename", filename_);
×
876
    if (!file_exists(filename_)) {
×
877
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
878
    }
879
  } else {
880
    fatal_error(fmt::format(
×
881
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
882
  }
883

884
  if (attribute_exists(group, "options")) {
×
885
    read_attribute(group, "options", options_);
×
886
  }
887

888
  // check if mesh tally data should be written with
889
  // statepoint files
890
  if (attribute_exists(group, "output")) {
×
891
    read_attribute(group, "output", output_);
×
892
  }
893
}
×
894

895
void UnstructuredMesh::determine_bounds()
25✔
896
{
897
  double xmin = INFTY;
25✔
898
  double ymin = INFTY;
25✔
899
  double zmin = INFTY;
25✔
900
  double xmax = -INFTY;
25✔
901
  double ymax = -INFTY;
25✔
902
  double zmax = -INFTY;
25✔
903
  int n = this->n_vertices();
25✔
904
  for (int i = 0; i < n; ++i) {
55,951✔
905
    auto v = this->vertex(i);
55,926✔
906
    xmin = std::min(v.x, xmin);
55,926✔
907
    ymin = std::min(v.y, ymin);
55,926✔
908
    zmin = std::min(v.z, zmin);
55,926✔
909
    xmax = std::max(v.x, xmax);
55,926✔
910
    ymax = std::max(v.y, ymax);
55,926✔
911
    zmax = std::max(v.z, zmax);
79,911✔
912
  }
913
  lower_left_ = {xmin, ymin, zmin};
25✔
914
  upper_right_ = {xmax, ymax, zmax};
25✔
915
}
25✔
916

917
Position UnstructuredMesh::sample_tet(
601,230✔
918
  std::array<Position, 4> coords, uint64_t* seed) const
919
{
920
  // Uniform distribution
921
  double s = prn(seed);
601,230✔
922
  double t = prn(seed);
601,230✔
923
  double u = prn(seed);
601,230✔
924

925
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
926
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
927
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
928
  if (s + t > 1) {
601,230✔
929
    s = 1.0 - s;
300,301✔
930
    t = 1.0 - t;
300,301✔
931
  }
932
  if (s + t + u > 1) {
601,230✔
933
    if (t + u > 1) {
401,096✔
934
      double old_t = t;
200,214✔
935
      t = 1.0 - u;
200,214✔
936
      u = 1.0 - s - old_t;
200,214✔
937
    } else if (t + u <= 1) {
200,882!
938
      double old_s = s;
200,882✔
939
      s = 1.0 - t - u;
200,882✔
940
      u = old_s + t + u - 1;
200,882✔
941
    }
942
  }
943
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690✔
944
         u * (coords[3] - coords[0]) + coords[0];
601,230✔
945
}
946

947
const std::string UnstructuredMesh::mesh_type = "unstructured";
948

949
std::string UnstructuredMesh::get_mesh_type() const
34✔
950
{
951
  return mesh_type;
34✔
952
}
953

954
void UnstructuredMesh::surface_bins_crossed(
×
955
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
956
{
957
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
958
}
959

960
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
961
{
962
  return fmt::format("Mesh Index ({})", bin);
207,736✔
963
};
964

965
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
966
{
967
  write_dataset(mesh_group, "filename", filename_);
34!
968
  write_dataset(mesh_group, "library", this->library());
34!
969
  if (!options_.empty()) {
34✔
970
    write_attribute(mesh_group, "options", options_);
8✔
971
  }
972

973
  if (length_multiplier_ > 0.0)
34!
974
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
975

976
  // write vertex coordinates
977
  tensor::Tensor<double> vertices(
34✔
978
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
34✔
979
  for (int i = 0; i < this->n_vertices(); i++) {
72,939!
980
    auto v = this->vertex(i);
72,905!
981
    vertices.slice(i) = {v.x, v.y, v.z};
145,810!
982
  }
983
  write_dataset(mesh_group, "vertices", vertices);
34!
984

985
  int num_elem_skipped = 0;
34✔
986

987
  // write element types and connectivity
988
  vector<double> volumes;
34!
989
  tensor::Tensor<int> connectivity(
34✔
990
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
991
  tensor::Tensor<int> elem_types(
34✔
992
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
993
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
994
    auto conn = this->connectivity(i);
351,736!
995

996
    volumes.emplace_back(this->volume(i));
351,736!
997

998
    // write linear tet element
999
    if (conn.size() == 4) {
351,736✔
1000
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
347,736!
1001
      connectivity.slice(i) = {
347,736!
1002
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
695,472!
1003
      // write linear hex element
1004
    } else if (conn.size() == 8) {
4,000!
1005
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
4,000!
1006
      connectivity.slice(i) = {
4,000!
1007
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
8,000!
1008
    } else {
1009
      num_elem_skipped++;
×
1010
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
1011
      connectivity.slice(i) = -1;
×
1012
    }
1013
  }
351,736✔
1014

1015
  // warn users that some elements were skipped
1016
  if (num_elem_skipped > 0) {
34!
1017
    warning(fmt::format("The connectivity of {} elements "
×
1018
                        "on mesh {} were not written "
1019
                        "because they are not of type linear tet/hex.",
1020
      num_elem_skipped, this->id_));
×
1021
  }
1022

1023
  write_dataset(mesh_group, "volumes", volumes);
34!
1024
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1025
  write_dataset(mesh_group, "element_types", elem_types);
34!
1026
}
102✔
1027

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

1033
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1034
{
1035
  auto conn = connectivity(bin);
120,000✔
1036

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

1045
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,618,297,598✔
1046
  Position r, bool& in_mesh) const
1047
{
1048
  MeshIndex ijk;
1,618,297,598✔
1049
  in_mesh = true;
1,618,297,598✔
1050
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1051
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1052

1053
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1054
      in_mesh = false;
102,839,856✔
1055
  }
1056
  return ijk;
1,618,297,598✔
1057
}
1058

1059
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1060
{
1061
  switch (n_dimension_) {
2,147,483,647!
1062
  case 1:
880,605✔
1063
    return ijk[0] - 1;
880,605✔
1064
  case 2:
141,663,247✔
1065
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
141,663,247✔
1066
  case 3:
2,079,083,638✔
1067
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,079,083,638✔
1068
  default:
×
1069
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1070
  }
1071
}
1072

1073
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,848,754✔
1074
{
1075
  MeshIndex ijk;
7,848,754✔
1076
  if (n_dimension_ == 1) {
7,848,754✔
1077
    ijk[0] = bin + 1;
275✔
1078
  } else if (n_dimension_ == 2) {
7,848,479✔
1079
    ijk[0] = bin % shape_[0] + 1;
16,060✔
1080
    ijk[1] = bin / shape_[0] + 1;
16,060✔
1081
  } else if (n_dimension_ == 3) {
7,832,419!
1082
    ijk[0] = bin % shape_[0] + 1;
7,832,419✔
1083
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,832,419✔
1084
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,832,419✔
1085
  }
1086
  return ijk;
7,848,754✔
1087
}
1088

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

1097
  // Convert indices to bin
1098
  return get_bin_from_indices(ijk);
405,491,792✔
1099
}
1100

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

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

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

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

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

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

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

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

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

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

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

1171
  return counts;
×
1172
}
×
1173

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

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

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

1197
  const int n = n_dimension_;
1,184,535,562✔
1198

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

1202
  // Position is r = r0 + u * traveled_distance, start at r0
1203
  double traveled_distance {0.0};
1,184,535,562✔
1204

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

1209
  // if track is very short, assume that it is completely inside one cell.
1210
  // Only the current cell will score and no surfaces
1211
  if (total_distance < 2 * TINY_BIT) {
1,184,535,562✔
1212
    if (in_mesh) {
361,888✔
1213
      tally.track(ijk, 1.0);
361,404✔
1214
    }
1215
    return;
361,888✔
1216
  }
1217

1218
  // Calculate initial distances to next surfaces in all three dimensions
1219
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1220
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1221
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1222
  }
1223

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

1227
    if (in_mesh) {
1,984,126,492✔
1228

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

1233
      // Tally track length delta since last step
1234
      tally.track(ijk,
1,897,659,669✔
1235
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1236
          total_distance);
1237

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

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

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

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

1256
      // If we are still inside the mesh, tally inward current for the next
1257
      // cell
1258
      if (in_mesh)
29,576,899✔
1259
        tally.surface(ijk, k, !distances[k].max_surface, true);
798,536,601✔
1260

1261
    } else { // not inside mesh
1262

1263
      // For all directions outside the mesh, find the distance that we need
1264
      // to travel to reach the next surface. Use the largest distance, as
1265
      // only this will cross all outer surfaces.
1266
      int k_max {-1};
1267
      for (int k = 0; k < n; ++k) {
344,398,330✔
1268
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,931,507✔
1269
            (distances[k].distance > traveled_distance)) {
94,474,738✔
1270
          traveled_distance = distances[k].distance;
1271
          k_max = k;
1272
        }
1273
      }
1274
      // Assure some distance is traveled
1275
      if (k_max == -1) {
86,466,823✔
1276
        traveled_distance += TINY_BIT;
110✔
1277
      }
1278

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

1283
      // Calculate the new cell index and update all distances to next
1284
      // surfaces.
1285
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,175,828✔
1286
      for (int k = 0; k < n; ++k) {
28,494,774✔
1287
        distances[k] =
21,318,946✔
1288
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,318,946✔
1289
      }
1290

1291
      // If inside the mesh, Tally inward current
1292
      if (in_mesh && k_max >= 0)
7,175,828!
1293
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
770,352,951✔
1294
    }
1295
  }
1296
}
1297

1298
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,124,060,808✔
1299
  vector<int>& bins, vector<double>& lengths) const
1300
{
1301

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

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

1322
  // Perform the mesh raytrace with the helper class.
1323
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,124,060,808✔
1324
}
1,124,060,808✔
1325

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

1330
  // Helper tally class.
1331
  // stores a pointer to the mesh class and a reference to the bins parameter.
1332
  // Performs the actual tally through the surface method.
1333
  struct SurfaceAggregator {
112,127,565✔
1334
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,565✔
1335
      : mesh(_mesh), bins(_bins)
112,127,565✔
1336
    {}
1337
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,189✔
1338
    {
1339
      int i_bin =
58,159,189✔
1340
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,189✔
1341
      if (max)
58,159,189✔
1342
        i_bin += 2;
29,051,440✔
1343
      if (inward)
58,159,189✔
1344
        i_bin += 1;
28,582,290✔
1345
      bins.push_back(i_bin);
58,159,189✔
1346
    }
58,159,189✔
1347
    void track(const MeshIndex& idx, double l) const {}
1348

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

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

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

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

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

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

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

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

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

1396
  } else if (upper_right_.size() > 0) {
2,421!
1397

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

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

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

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

1420
  element_volume_ = 1.0;
2,467✔
1421
  for (int i = 0; i < n_dimension_; i++) {
9,306✔
1422
    element_volume_ *= width_[i];
6,839✔
1423
  }
1424
  return 0;
1425
}
2,467✔
1426

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1506
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1507
{
1508
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1509
}
1510

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

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

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

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

1528
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1529
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1530
  double l) const
1531
{
1532
  MeshDistance d;
2,147,483,647✔
1533
  d.next_index = ijk[i];
2,147,483,647✔
1534
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1535
    return d;
15,259,704✔
1536

1537
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1538
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1539
    d.next_index++;
1,884,192,329✔
1540
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,884,192,329✔
1541
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,836,417,985✔
1542
    d.next_index--;
1,814,836,463✔
1543
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,814,836,463✔
1544
  }
1545

1546
  return d;
2,147,483,647✔
1547
}
1548

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

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

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

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

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

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

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

1609
  for (int64_t i = 0; i < length; i++) {
7,675,271✔
1610
    const auto& site = bank[i];
7,667,451✔
1611

1612
    // determine scoring bin for entropy mesh
1613
    int mesh_bin = get_bin(site.r);
7,667,451✔
1614

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

1621
    // Add to appropriate bin
1622
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1623
  }
1624

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

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

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

1644
  return counts;
7,820✔
1645
}
7,820✔
1646

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

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

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

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

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

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

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

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

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

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

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

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

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

1710
  d.max_surface = (u[i] > 0);
53,030,263✔
1711
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263✔
1712
    d.next_index++;
26,505,963✔
1713
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963✔
1714
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300✔
1715
    d.next_index--;
25,739,406✔
1716
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1717
  }
1718
  return d;
53,030,263✔
1719
}
1720

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

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

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

1744
  return 0;
177✔
1745
}
1746

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1837
std::array<const char*, 3> CylindricalMesh::axis_labels() const
646,272✔
1838
{
1839
  return {"r", "phi", "z"};
646,272✔
1840
}
1841

1842
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1843
  Position r, bool& in_mesh) const
1844
{
1845
  r = local_coords(r);
47,732,091✔
1846

1847
  Position mapped_r;
47,732,091✔
1848
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1849
  mapped_r[2] = r[2];
47,732,091✔
1850

1851
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1852
    mapped_r[1] = 0.0;
1853
  } else {
1854
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1855
    if (mapped_r[1] < 0)
47,732,091✔
1856
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1857
  }
1858

1859
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,091✔
1860

1861
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1862

1863
  return idx;
47,732,091✔
1864
}
1865

1866
Position CylindricalMesh::sample_element(
88,110✔
1867
  const MeshIndex& ijk, uint64_t* seed) const
1868
{
1869
  double r_min = this->r(ijk[0] - 1);
88,110✔
1870
  double r_max = this->r(ijk[0]);
88,110✔
1871

1872
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1873
  double phi_max = this->phi(ijk[1]);
88,110✔
1874

1875
  double z_min = this->z(ijk[2] - 1);
88,110✔
1876
  double z_max = this->z(ijk[2]);
88,110✔
1877

1878
  double r_min_sq = r_min * r_min;
88,110✔
1879
  double r_max_sq = r_max * r_max;
88,110✔
1880
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1881
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1882
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1883

1884
  double x = r * std::cos(phi);
88,110✔
1885
  double y = r * std::sin(phi);
88,110✔
1886

1887
  return origin_ + Position(x, y, z);
88,110✔
1888
}
1889

1890
double CylindricalMesh::find_r_crossing(
142,587,080✔
1891
  const Position& r, const Direction& u, double l, int shell) const
1892
{
1893

1894
  if ((shell < 0) || (shell > shape_[0]))
142,587,080!
1895
    return INFTY;
1896

1897
  // solve r.x^2 + r.y^2 == r0^2
1898
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1899
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1900

1901
  const double r0 = grid_[0][shell];
124,673,183✔
1902
  if (r0 == 0.0)
124,673,183✔
1903
    return INFTY;
1904

1905
  const double denominator = u.x * u.x + u.y * u.y;
117,537,109✔
1906

1907
  // Direction of flight is in z-direction. Will never intersect r.
1908
  if (std::abs(denominator) < FP_PRECISION)
117,537,109✔
1909
    return INFTY;
1910

1911
  // inverse of dominator to help the compiler to speed things up
1912
  const double inv_denominator = 1.0 / denominator;
117,478,149✔
1913

1914
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,478,149✔
1915
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,478,149✔
1916
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,478,149✔
1917

1918
  if (D < 0.0)
117,478,149✔
1919
    return INFTY;
1920

1921
  D = std::sqrt(D);
107,742,027✔
1922

1923
  // Particle is already on the shell surface; avoid spurious crossing
1924
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,742,027✔
1925
    return INFTY;
1926

1927
  // Check -p - D first because it is always smaller as -p + D
1928
  if (-p - D > l)
101,108,653✔
1929
    return -p - D;
1930
  if (-p + D > l)
80,901,059✔
1931
    return -p + D;
50,077,872✔
1932

1933
  return INFTY;
1934
}
1935

1936
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1937
  const Position& r, const Direction& u, double l, int shell) const
1938
{
1939
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1940
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1941
    return INFTY;
1942

1943
  shell = sanitize_phi(shell);
43,970,718✔
1944

1945
  const double p0 = grid_[1][shell];
43,970,718✔
1946

1947
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1948
  // => x(s) * cos(p0) = y(s) * sin(p0)
1949
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1950
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1951

1952
  const double c0 = std::cos(p0);
43,970,718✔
1953
  const double s0 = std::sin(p0);
43,970,718✔
1954

1955
  const double denominator = (u.x * s0 - u.y * c0);
43,970,718✔
1956

1957
  // Check if direction of flight is not parallel to phi surface
1958
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1959
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1960
    // Check if solution is in positive direction of flight and crosses the
1961
    // correct phi surface (not -phi)
1962
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1963
      return s;
20,219,859✔
1964
  }
1965

1966
  return INFTY;
1967
}
1968

1969
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1970
  const Position& r, const Direction& u, double l, int shell) const
1971
{
1972
  MeshDistance d;
36,695,747✔
1973
  d.next_index = shell;
36,695,747✔
1974

1975
  // Direction of flight is within xy-plane. Will never intersect z.
1976
  if (std::abs(u.z) < FP_PRECISION)
36,695,747✔
1977
    return d;
1,118,216✔
1978

1979
  d.max_surface = (u.z > 0.0);
35,577,531✔
1980
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1981
    d.next_index += 1;
16,875,892✔
1982
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1983
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1984
    d.next_index -= 1;
16,846,225✔
1985
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1986
  }
1987
  return d;
35,577,531✔
1988
}
1989

1990
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,217,489✔
1991
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1992
  double l) const
1993
{
1994
  if (i == 0) {
145,217,489✔
1995

1996
    return std::min(
142,587,080✔
1997
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,293,540✔
1998
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,587,080✔
1999

2000
  } else if (i == 1) {
73,923,949✔
2001

2002
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
2003
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
2004
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
2005
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
2006

2007
  } else {
2008
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
2009
  }
2010
}
2011

2012
int CylindricalMesh::set_grid()
433✔
2013
{
2014
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
2015
    static_cast<int>(grid_[1].size()) - 1,
433✔
2016
    static_cast<int>(grid_[2].size()) - 1};
433✔
2017

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

2045
    return OPENMC_E_INVALID_ARGUMENT;
×
2046
  }
2047

2048
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
433!
2049

2050
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2051
    origin_[2] + grid_[2].front()};
433✔
2052
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2053
    origin_[2] + grid_[2].back()};
433✔
2054

2055
  return 0;
433✔
2056
}
2057

2058
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2059
{
2060
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2061
}
2062

2063
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2064
  Position plot_ll, Position plot_ur) const
2065
{
2066
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2067

2068
  // Figure out which axes lie in the plane of the plot.
2069
  array<vector<double>, 2> axis_lines;
2070
  return {axis_lines[0], axis_lines[1]};
2071
}
2072

2073
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2074
{
2075
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2076
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2077
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2078
  write_dataset(mesh_group, "origin", origin_);
374✔
2079
}
374✔
2080

2081
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2082
{
2083
  double r_i = grid_[0][ijk[0] - 1];
792✔
2084
  double r_o = grid_[0][ijk[0]];
792✔
2085

2086
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2087
  double phi_o = grid_[1][ijk[1]];
792✔
2088

2089
  double z_i = grid_[2][ijk[2] - 1];
792✔
2090
  double z_o = grid_[2][ijk[2]];
792✔
2091

2092
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2093
}
2094

2095
//==============================================================================
2096
// SphericalMesh implementation
2097
//==============================================================================
2098

2099
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2100
  : PeriodicStructuredMesh {node}
345✔
2101
{
2102
  n_dimension_ = 3;
345✔
2103

2104
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2105
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2106
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2107
  origin_ = get_node_position(node, "origin");
345✔
2108

2109
  if (int err = set_grid()) {
345!
2110
    fatal_error(openmc_err_msg);
×
2111
  }
2112
}
345✔
2113

2114
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2115
{
2116
  n_dimension_ = 3;
11✔
2117

2118
  read_dataset(group, "r_grid", grid_[0]);
11✔
2119
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2120
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2121
  read_dataset(group, "origin", origin_);
11✔
2122

2123
  if (int err = set_grid()) {
11!
2124
    fatal_error(openmc_err_msg);
×
2125
  }
2126
}
11✔
2127

2128
const std::string SphericalMesh::mesh_type = "spherical";
2129

2130
std::string SphericalMesh::get_mesh_type() const
385✔
2131
{
2132
  return mesh_type;
385✔
2133
}
2134

2135
std::array<const char*, 3> SphericalMesh::axis_labels() const
323,136✔
2136
{
2137
  return {"r", "theta", "phi"};
323,136✔
2138
}
2139

2140
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2141
  Position r, bool& in_mesh) const
2142
{
2143
  r = local_coords(r);
68,592,128✔
2144

2145
  Position mapped_r;
68,592,128✔
2146
  mapped_r[0] = r.norm();
68,592,128✔
2147

2148
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2149
    mapped_r[1] = 0.0;
2150
    mapped_r[2] = 0.0;
2151
  } else {
2152
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2153
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2154
    if (mapped_r[2] < 0)
68,592,128✔
2155
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2156
  }
2157

2158
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,128✔
2159

2160
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2161
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2162

2163
  return idx;
68,592,128✔
2164
}
2165

2166
Position SphericalMesh::sample_element(
110✔
2167
  const MeshIndex& ijk, uint64_t* seed) const
2168
{
2169
  double r_min = this->r(ijk[0] - 1);
110✔
2170
  double r_max = this->r(ijk[0]);
110✔
2171

2172
  double theta_min = this->theta(ijk[1] - 1);
110✔
2173
  double theta_max = this->theta(ijk[1]);
110✔
2174

2175
  double phi_min = this->phi(ijk[2] - 1);
110✔
2176
  double phi_max = this->phi(ijk[2]);
110✔
2177

2178
  double cos_theta =
110✔
2179
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2180
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2181
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2182
  double r_min_cub = std::pow(r_min, 3);
110✔
2183
  double r_max_cub = std::pow(r_max, 3);
110✔
2184
  // might be faster to do rejection here?
2185
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2186

2187
  double x = r * std::cos(phi) * sin_theta;
110✔
2188
  double y = r * std::sin(phi) * sin_theta;
110✔
2189
  double z = r * cos_theta;
110✔
2190

2191
  return origin_ + Position(x, y, z);
110✔
2192
}
2193

2194
double SphericalMesh::find_r_crossing(
443,974,630✔
2195
  const Position& r, const Direction& u, double l, int shell) const
2196
{
2197
  if ((shell < 0) || (shell > shape_[0]))
443,974,630✔
2198
    return INFTY;
2199

2200
  // solve |r+s*u| = r0
2201
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2202
  const double r0 = grid_[0][shell];
404,353,543✔
2203
  if (r0 == 0.0)
404,353,543✔
2204
    return INFTY;
2205
  const double p = r.dot(u);
396,675,026✔
2206
  double R = r.norm();
396,675,026✔
2207
  double D = p * p - (R - r0) * (R + r0);
396,675,026✔
2208

2209
  // Particle is already on the shell surface; avoid spurious crossing
2210
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,675,026✔
2211
    return INFTY;
2212

2213
  if (D >= 0.0) {
385,966,372✔
2214
    D = std::sqrt(D);
358,089,424✔
2215
    // Check -p - D first because it is always smaller as -p + D
2216
    if (-p - D > l)
358,089,424✔
2217
      return -p - D;
2218
    if (-p + D > l)
293,777,792✔
2219
      return -p + D;
177,238,501✔
2220
  }
2221

2222
  return INFTY;
2223
}
2224

2225
double SphericalMesh::find_theta_crossing(
110,161,348✔
2226
  const Position& r, const Direction& u, double l, int shell) const
2227
{
2228
  // Theta grid is [0, π], thus there is no real surface to cross
2229
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2230
    return INFTY;
2231

2232
  shell = sanitize_theta(shell);
38,358,540✔
2233

2234
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2235
  // yields
2236
  // a*s^2 + 2*b*s + c == 0 with
2237
  // a = cos(theta)^2 - u.z * u.z
2238
  // b = r*u * cos(theta)^2 - u.z * r.z
2239
  // c = r*r * cos(theta)^2 - r.z^2
2240

2241
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2242
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2243
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2244

2245
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2246
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2247
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2248

2249
  // if factor of s^2 is zero, direction of flight is parallel to theta
2250
  // surface
2251
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2252
    // if b vanishes, direction of flight is within theta surface and crossing
2253
    // is not possible
2254
    if (std::abs(b) < FP_PRECISION)
482,548!
2255
      return INFTY;
2256

2257
    const double s = -0.5 * c / b;
×
2258
    // Check if solution is in positive direction of flight and has correct
2259
    // sign
2260
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2261
      return s;
×
2262

2263
    // no crossing is possible
2264
    return INFTY;
2265
  }
2266

2267
  const double p = b / a;
37,875,992✔
2268
  double D = p * p - c / a;
37,875,992✔
2269

2270
  if (D < 0.0)
37,875,992✔
2271
    return INFTY;
2272

2273
  D = std::sqrt(D);
26,921,004✔
2274

2275
  // the solution -p-D is always smaller as -p+D : Check this one first
2276
  double s = -p - D;
26,921,004✔
2277
  // Check if solution is in positive direction of flight and has correct sign
2278
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
26,921,004✔
2279
    return s;
2280

2281
  s = -p + D;
21,638,397✔
2282
  // Check if solution is in positive direction of flight and has correct sign
2283
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
21,638,397✔
2284
    return s;
10,163,296✔
2285

2286
  return INFTY;
2287
}
2288

2289
double SphericalMesh::find_phi_crossing(
111,750,826✔
2290
  const Position& r, const Direction& u, double l, int shell) const
2291
{
2292
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2293
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2294
    return INFTY;
2295

2296
  shell = sanitize_phi(shell);
39,948,018✔
2297

2298
  const double p0 = grid_[2][shell];
39,948,018✔
2299

2300
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2301
  // => x(s) * cos(p0) = y(s) * sin(p0)
2302
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2303
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2304

2305
  const double c0 = std::cos(p0);
39,948,018✔
2306
  const double s0 = std::sin(p0);
39,948,018✔
2307

2308
  const double denominator = (u.x * s0 - u.y * c0);
39,948,018✔
2309

2310
  // Check if direction of flight is not parallel to phi surface
2311
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2312
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2313
    // Check if solution is in positive direction of flight and crosses the
2314
    // correct phi surface (not -phi)
2315
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2316
      return s;
17,579,452✔
2317
  }
2318

2319
  return INFTY;
2320
}
2321

2322
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,943,402✔
2323
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2324
  double l) const
2325
{
2326

2327
  if (i == 0) {
332,943,402✔
2328
    return std::min(
443,974,630✔
2329
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,987,315✔
2330
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,974,630✔
2331

2332
  } else if (i == 1) {
110,956,087✔
2333
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2334
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2335
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2336
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2337

2338
  } else {
2339
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2340
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2341
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2342
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2343
  }
2344
}
2345

2346
int SphericalMesh::set_grid()
378✔
2347
{
2348
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2349
    static_cast<int>(grid_[1].size()) - 1,
378✔
2350
    static_cast<int>(grid_[2].size()) - 1};
378✔
2351

2352
  for (const auto& g : grid_) {
1,512✔
2353
    if (g.size() < 2) {
1,134!
2354
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2355
                 "must each have at least 2 points");
2356
      return OPENMC_E_INVALID_ARGUMENT;
×
2357
    }
2358
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2359
        g.end()) {
1,134!
2360
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2361
                 "spherical meshes must be sorted and unique.");
2362
      return OPENMC_E_INVALID_ARGUMENT;
×
2363
    }
2364
    if (g.front() < 0.0) {
1,134!
2365
      set_errmsg("r-, theta-, and phi- grids for "
×
2366
                 "spherical meshes must start at v >= 0.");
2367
      return OPENMC_E_INVALID_ARGUMENT;
×
2368
    }
2369
  }
2370
  if (grid_[1].back() > PI) {
378!
2371
    set_errmsg("theta-grids for "
×
2372
               "spherical meshes must end with theta <= pi.");
2373

2374
    return OPENMC_E_INVALID_ARGUMENT;
×
2375
  }
2376
  if (grid_[2].back() > 2 * PI) {
378!
2377
    set_errmsg("phi-grids for "
×
2378
               "spherical meshes must end with phi <= 2*pi.");
2379
    return OPENMC_E_INVALID_ARGUMENT;
×
2380
  }
2381

2382
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2383
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2384

2385
  double r = grid_[0].back();
378✔
2386
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2387
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2388

2389
  return 0;
378✔
2390
}
2391

2392
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2393
{
2394
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2395
}
2396

2397
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2398
  Position plot_ll, Position plot_ur) const
2399
{
2400
  fatal_error("Plot of spherical Mesh not implemented");
×
2401

2402
  // Figure out which axes lie in the plane of the plot.
2403
  array<vector<double>, 2> axis_lines;
2404
  return {axis_lines[0], axis_lines[1]};
2405
}
2406

2407
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2408
{
2409
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2410
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2411
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2412
  write_dataset(mesh_group, "origin", origin_);
319✔
2413
}
319✔
2414

2415
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2416
{
2417
  double r_i = grid_[0][ijk[0] - 1];
935✔
2418
  double r_o = grid_[0][ijk[0]];
935✔
2419

2420
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2421
  double theta_o = grid_[1][ijk[1]];
935✔
2422

2423
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2424
  double phi_o = grid_[2][ijk[2]];
935✔
2425

2426
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2427
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2428
}
2429

2430
//==============================================================================
2431
// Helper functions for the C API
2432
//==============================================================================
2433

2434
int check_mesh(int32_t index)
6,490✔
2435
{
2436
  if (index < 0 || index >= model::meshes.size()) {
6,490!
2437
    set_errmsg("Index in meshes array is out of bounds.");
×
2438
    return OPENMC_E_OUT_OF_BOUNDS;
×
2439
  }
2440
  return 0;
2441
}
2442

2443
template<class T>
2444
int check_mesh_type(int32_t index)
1,100✔
2445
{
2446
  if (int err = check_mesh(index))
1,100!
2447
    return err;
2448

2449
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2450
  if (!mesh) {
1,100!
2451
    set_errmsg("This function is not valid for input mesh.");
×
2452
    return OPENMC_E_INVALID_TYPE;
×
2453
  }
2454
  return 0;
2455
}
2456

2457
template<class T>
2458
bool is_mesh_type(int32_t index)
2459
{
2460
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2461
  return mesh;
2462
}
2463

2464
//==============================================================================
2465
// C API functions
2466
//==============================================================================
2467

2468
// Return the type of mesh as a C string
2469
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2470
{
2471
  if (int err = check_mesh(index))
1,496!
2472
    return err;
2473

2474
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,496✔
2475

2476
  return 0;
1,496✔
2477
}
2478

2479
//! Extend the meshes array by n elements
2480
extern "C" int openmc_extend_meshes(
253✔
2481
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2482
{
2483
  if (index_start)
253!
2484
    *index_start = model::meshes.size();
253✔
2485
  std::string mesh_type;
253✔
2486

2487
  for (int i = 0; i < n; ++i) {
506✔
2488
    if (RegularMesh::mesh_type == type) {
253✔
2489
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2490
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2491
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2492
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2493
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2494
    } else if (SphericalMesh::mesh_type == type) {
22!
2495
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2496
    } else {
2497
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2498
    }
2499
  }
2500
  if (index_end)
253!
2501
    *index_end = model::meshes.size() - 1;
×
2502

2503
  return 0;
253✔
2504
}
253✔
2505

2506
//! Adds a new unstructured mesh to OpenMC
2507
extern "C" int openmc_add_unstructured_mesh(
×
2508
  const char filename[], const char library[], int* id)
2509
{
2510
  std::string lib_name(library);
×
2511
  std::string mesh_file(filename);
×
2512
  bool valid_lib = false;
×
2513

2514
#ifdef OPENMC_DAGMC_ENABLED
2515
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2516
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2517
    valid_lib = true;
2518
  }
2519
#endif
2520

2521
#ifdef OPENMC_LIBMESH_ENABLED
2522
  if (lib_name == LibMesh::mesh_lib_type) {
×
2523
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2524
    valid_lib = true;
2525
  }
2526
#endif
2527

2528
  if (!valid_lib) {
×
2529
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2530
                           "by this build of OpenMC",
2531
      lib_name));
2532
    return OPENMC_E_INVALID_ARGUMENT;
×
2533
  }
2534

2535
  // auto-assign new ID
2536
  model::meshes.back()->set_id(-1);
×
2537
  *id = model::meshes.back()->id_;
2538

2539
  return 0;
2540
}
×
2541

2542
//! Return the index in the meshes array of a mesh with a given ID
2543
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2544
{
2545
  auto pair = model::mesh_map.find(id);
429!
2546
  if (pair == model::mesh_map.end()) {
429!
2547
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2548
    return OPENMC_E_INVALID_ID;
×
2549
  }
2550
  *index = pair->second;
429✔
2551
  return 0;
429✔
2552
}
2553

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

2563
//! Set the ID of a mesh
2564
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2565
{
2566
  if (int err = check_mesh(index))
253!
2567
    return err;
2568
  model::meshes[index]->id_ = id;
253✔
2569
  model::mesh_map[id] = index;
253✔
2570
  return 0;
253✔
2571
}
2572

2573
//! Get the number of elements in a mesh
2574
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2575
{
2576
  if (int err = check_mesh(index))
297!
2577
    return err;
2578
  *n = model::meshes[index]->n_bins();
297✔
2579
  return 0;
297✔
2580
}
2581

2582
//! Get the volume of each element in the mesh
2583
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2584
{
2585
  if (int err = check_mesh(index))
88!
2586
    return err;
2587
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2588
    volumes[i] = model::meshes[index]->volume(i);
880✔
2589
  }
2590
  return 0;
2591
}
2592

2593
//! Get the bounding box of a mesh
2594
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2595
{
2596
  if (int err = check_mesh(index))
176!
2597
    return err;
2598

2599
  BoundingBox bbox = model::meshes[index]->bounding_box();
176✔
2600

2601
  // set lower left corner values
2602
  ll[0] = bbox.min.x;
176✔
2603
  ll[1] = bbox.min.y;
176✔
2604
  ll[2] = bbox.min.z;
176✔
2605

2606
  // set upper right corner values
2607
  ur[0] = bbox.max.x;
176✔
2608
  ur[1] = bbox.max.y;
176✔
2609
  ur[2] = bbox.max.z;
176✔
2610
  return 0;
176✔
2611
}
2612

2613
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2614
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2615
{
2616
  if (int err = check_mesh(index))
209!
2617
    return err;
2618

2619
  try {
209✔
2620
    model::meshes[index]->material_volumes(
209✔
2621
      nx, ny, nz, table_size, materials, volumes, bboxes);
2622
  } catch (const std::exception& e) {
11!
2623
    set_errmsg(e.what());
11✔
2624
    if (starts_with(e.what(), "Mesh")) {
11!
2625
      return OPENMC_E_GEOMETRY;
11✔
2626
    } else {
2627
      return OPENMC_E_ALLOCATE;
×
2628
    }
2629
  }
11✔
2630

2631
  return 0;
2632
}
2633

2634
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2635
  Position width, int basis, int* pixels, int32_t* data)
2636
{
2637
  if (int err = check_mesh(index))
44!
2638
    return err;
2639
  const auto& mesh = model::meshes[index].get();
44!
2640

2641
  int pixel_width = pixels[0];
44✔
2642
  int pixel_height = pixels[1];
44✔
2643

2644
  // get pixel size
2645
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2646
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2647

2648
  // setup basis indices and initial position centered on pixel
2649
  int in_i, out_i;
44✔
2650
  Position xyz = origin;
44✔
2651
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2652
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2653
  switch (basis_enum) {
44!
2654
  case PlotBasis::xy:
2655
    in_i = 0;
2656
    out_i = 1;
2657
    break;
2658
  case PlotBasis::xz:
2659
    in_i = 0;
2660
    out_i = 2;
2661
    break;
2662
  case PlotBasis::yz:
2663
    in_i = 1;
2664
    out_i = 2;
2665
    break;
2666
  default:
×
2667
    UNREACHABLE();
×
2668
  }
2669

2670
  // set initial position
2671
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2672
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2673

2674
#pragma omp parallel
24✔
2675
  {
20✔
2676
    Position r = xyz;
20✔
2677

2678
#pragma omp for
2679
    for (int y = 0; y < pixel_height; y++) {
420✔
2680
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2681
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2682
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2683
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2684
      }
2685
    }
2686
  }
2687

2688
  return 0;
44✔
2689
}
2690

2691
//! Get the dimension of a regular mesh
2692
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2693
  int32_t index, int** dims, int* n)
2694
{
2695
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2696
    return err;
2697
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2698
  *dims = mesh->shape_.data();
11✔
2699
  *n = mesh->n_dimension_;
11✔
2700
  return 0;
11✔
2701
}
2702

2703
//! Set the dimension of a regular mesh
2704
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2705
  int32_t index, int n, const int* dims)
2706
{
2707
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2708
    return err;
2709
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2710

2711
  // Copy dimension
2712
  mesh->n_dimension_ = n;
187✔
2713
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2714
  return 0;
187✔
2715
}
2716

2717
//! Get the regular mesh parameters
2718
extern "C" int openmc_regular_mesh_get_params(
209✔
2719
  int32_t index, double** ll, double** ur, double** width, int* n)
2720
{
2721
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2722
    return err;
2723
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2724

2725
  if (m->lower_left_.empty()) {
209!
2726
    set_errmsg("Mesh parameters have not been set.");
×
2727
    return OPENMC_E_ALLOCATE;
×
2728
  }
2729

2730
  *ll = m->lower_left_.data();
209✔
2731
  *ur = m->upper_right_.data();
209✔
2732
  *width = m->width_.data();
209✔
2733
  *n = m->n_dimension_;
209✔
2734
  return 0;
209✔
2735
}
2736

2737
//! Set the regular mesh parameters
2738
extern "C" int openmc_regular_mesh_set_params(
220✔
2739
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2740
{
2741
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2742
    return err;
2743
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2744

2745
  if (m->n_dimension_ == -1) {
220!
2746
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2747
    return OPENMC_E_UNASSIGNED;
×
2748
  }
2749

2750
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2751
  if (ll && ur) {
220✔
2752
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2753
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2754
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2755
  } else if (ll && width) {
22✔
2756
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2757
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2758
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2759
  } else if (ur && width) {
11!
2760
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2761
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2762
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2763
  } else {
2764
    set_errmsg("At least two parameters must be specified.");
×
2765
    return OPENMC_E_INVALID_ARGUMENT;
×
2766
  }
2767

2768
  // Set material volumes
2769

2770
  // TODO: incorporate this into method in RegularMesh that can be called from
2771
  // here and from constructor
2772
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2773
  m->element_volume_ = 1.0;
220✔
2774
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2775
    m->element_volume_ *= m->width_[i];
660✔
2776
  }
2777

2778
  return 0;
2779
}
220✔
2780

2781
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2782
template<class C>
2783
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2784
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2785
  const int nz)
2786
{
2787
  if (int err = check_mesh_type<C>(index))
88!
2788
    return err;
2789

2790
  C* m = dynamic_cast<C*>(model::meshes[index].get());
88!
2791

2792
  m->n_dimension_ = 3;
88✔
2793

2794
  m->grid_[0].reserve(nx);
88✔
2795
  m->grid_[1].reserve(ny);
88✔
2796
  m->grid_[2].reserve(nz);
88✔
2797

2798
  for (int i = 0; i < nx; i++) {
572✔
2799
    m->grid_[0].push_back(grid_x[i]);
484✔
2800
  }
2801
  for (int i = 0; i < ny; i++) {
341✔
2802
    m->grid_[1].push_back(grid_y[i]);
253✔
2803
  }
2804
  for (int i = 0; i < nz; i++) {
319✔
2805
    m->grid_[2].push_back(grid_z[i]);
231✔
2806
  }
2807

2808
  int err = m->set_grid();
88✔
2809
  return err;
88✔
2810
}
2811

2812
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2813
template<class C>
2814
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2815
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2816
{
2817
  if (int err = check_mesh_type<C>(index))
385!
2818
    return err;
2819
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2820

2821
  if (m->lower_left_.empty()) {
385!
2822
    set_errmsg("Mesh parameters have not been set.");
×
2823
    return OPENMC_E_ALLOCATE;
×
2824
  }
2825

2826
  *grid_x = m->grid_[0].data();
385✔
2827
  *nx = m->grid_[0].size();
385✔
2828
  *grid_y = m->grid_[1].data();
385✔
2829
  *ny = m->grid_[1].size();
385✔
2830
  *grid_z = m->grid_[2].data();
385✔
2831
  *nz = m->grid_[2].size();
385✔
2832

2833
  return 0;
385✔
2834
}
2835

2836
//! Get the rectilinear mesh grid
2837
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2838
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2839
{
2840
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2841
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2842
}
2843

2844
//! Set the rectilienar mesh parameters
2845
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2846
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2847
  const double* grid_z, const int nz)
2848
{
2849
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2850
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2851
}
2852

2853
//! Get the cylindrical mesh grid
2854
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2855
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2856
{
2857
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2858
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2859
}
2860

2861
//! Set the cylindrical mesh parameters
2862
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2863
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2864
  const double* grid_z, const int nz)
2865
{
2866
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2867
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2868
}
2869

2870
//! Get the spherical mesh grid
2871
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2872
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2873
{
2874

2875
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2876
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2877
  ;
121✔
2878
}
2879

2880
//! Set the spherical mesh parameters
2881
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2882
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2883
  const double* grid_z, const int nz)
2884
{
2885
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2886
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2887
}
2888

2889
#ifdef OPENMC_DAGMC_ENABLED
2890

2891
const std::string MOABMesh::mesh_lib_type = "moab";
2892

2893
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2894
{
2895
  initialize();
24✔
2896
}
24!
2897

2898
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2899
{
2900
  initialize();
×
2901
}
×
2902

2903
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2904
  : UnstructuredMesh()
×
2905
{
2906
  n_dimension_ = 3;
2907
  filename_ = filename;
×
2908
  set_length_multiplier(length_multiplier);
×
2909
  initialize();
×
2910
}
×
2911

2912
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2913
{
2914
  mbi_ = external_mbi;
1✔
2915
  filename_ = "unknown (external file)";
1✔
2916
  this->initialize();
1✔
2917
}
1!
2918

2919
void MOABMesh::initialize()
25✔
2920
{
2921

2922
  // Create the MOAB interface and load data from file
2923
  this->create_interface();
25✔
2924

2925
  // Initialise MOAB error code
2926
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2927

2928
  // Set the dimension
2929
  n_dimension_ = 3;
25✔
2930

2931
  // set member range of tetrahedral entities
2932
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2933
  if (rval != moab::MB_SUCCESS) {
25!
2934
    fatal_error("Failed to get all tetrahedral elements");
2935
  }
2936

2937
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2938
    warning("Non-tetrahedral elements found in unstructured "
×
2939
            "mesh file: " +
2940
            filename_);
2941
  }
2942

2943
  // set member range of vertices
2944
  int vertex_dim = 0;
25✔
2945
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2946
  if (rval != moab::MB_SUCCESS) {
25!
2947
    fatal_error("Failed to get all vertex handles");
2948
  }
2949

2950
  // make an entity set for all tetrahedra
2951
  // this is used for convenience later in output
2952
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2953
  if (rval != moab::MB_SUCCESS) {
25!
2954
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2955
  }
2956

2957
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2958
  if (rval != moab::MB_SUCCESS) {
25!
2959
    fatal_error("Failed to add tetrahedra to an entity set.");
2960
  }
2961

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

2990
  // Determine bounds of mesh
2991
  this->determine_bounds();
25✔
2992
}
25✔
2993

2994
void MOABMesh::prepare_for_point_location()
21✔
2995
{
2996
  // if the KDTree has already been constructed, do nothing
2997
  if (kdtree_)
21!
2998
    return;
2999

3000
  // build acceleration data structures
3001
  compute_barycentric_data(ehs_);
21✔
3002
  build_kdtree(ehs_);
21✔
3003
}
3004

3005
void MOABMesh::create_interface()
25✔
3006
{
3007
  // Do not create a MOAB instance if one is already in memory
3008
  if (mbi_)
25✔
3009
    return;
3010

3011
  // create MOAB instance
3012
  mbi_ = std::make_shared<moab::Core>();
24!
3013

3014
  // load unstructured mesh file
3015
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
3016
  if (rval != moab::MB_SUCCESS) {
24!
3017
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3018
  }
3019
}
3020

3021
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
3022
{
3023
  moab::Range all_tris;
21✔
3024
  int adj_dim = 2;
21✔
3025
  write_message("Getting tet adjacencies...", 7);
21✔
3026
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
3027
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3028
  if (rval != moab::MB_SUCCESS) {
21!
3029
    fatal_error("Failed to get adjacent triangles for tets");
3030
  }
3031

3032
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3033
    warning("Non-triangle elements found in tet adjacencies in "
×
3034
            "unstructured mesh file: " +
3035
            filename_);
×
3036
  }
3037

3038
  // combine into one range
3039
  moab::Range all_tets_and_tris;
21✔
3040
  all_tets_and_tris.merge(all_tets);
21✔
3041
  all_tets_and_tris.merge(all_tris);
21✔
3042

3043
  // create a kd-tree instance
3044
  write_message(
21✔
3045
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3046
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3047

3048
  // Determine what options to use
3049
  std::ostringstream options_stream;
21✔
3050
  if (options_.empty()) {
21✔
3051
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3052
  } else {
3053
    options_stream << options_;
16✔
3054
  }
3055
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3056

3057
  // Build the k-d tree
3058
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3059
  if (rval != moab::MB_SUCCESS) {
21!
3060
    fatal_error("Failed to construct KDTree for the "
3061
                "unstructured mesh file: " +
3062
                filename_);
×
3063
  }
3064
}
21✔
3065

3066
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3067
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3068
{
3069
  hits.clear();
1,543,584!
3070

3071
  moab::ErrorCode rval;
1,543,584✔
3072
  vector<moab::EntityHandle> tris;
1,543,584✔
3073
  // get all intersections with triangles in the tet mesh
3074
  // (distances are relative to the start point, not the previous
3075
  // intersection)
3076
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3077
    dir.array(), start.array(), tris, hits, 0, track_len);
3078
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3079
    fatal_error(
3080
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3081
  }
3082

3083
  // remove duplicate intersection distances
3084
  std::unique(hits.begin(), hits.end());
1,543,584✔
3085

3086
  // sorts by first component of std::pair by default
3087
  std::sort(hits.begin(), hits.end());
1,543,584✔
3088
}
1,543,584✔
3089

3090
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3091
  vector<int>& bins, vector<double>& lengths) const
3092
{
3093
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3094
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3095
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3096
  dir.normalize();
1,543,584✔
3097

3098
  double track_len = (end - start).length();
1,543,584✔
3099
  if (track_len == 0.0)
1,543,584!
3100
    return;
721,692✔
3101

3102
  start -= TINY_BIT * dir;
1,543,584✔
3103
  end += TINY_BIT * dir;
1,543,584✔
3104

3105
  vector<double> hits;
1,543,584✔
3106
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3107

3108
  bins.clear();
1,543,584!
3109
  lengths.clear();
1,543,584!
3110

3111
  // if there are no intersections the track may lie entirely
3112
  // within a single tet. If this is the case, apply entire
3113
  // score to that tet and return.
3114
  if (hits.size() == 0) {
1,543,584✔
3115
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3116
    int bin = this->get_bin(midpoint);
721,692✔
3117
    if (bin != -1) {
721,692✔
3118
      bins.push_back(bin);
242,866✔
3119
      lengths.push_back(1.0);
242,866✔
3120
    }
3121
    return;
721,692✔
3122
  }
3123

3124
  // for each segment in the set of tracks, try to look up a tet
3125
  // at the midpoint of the segment
3126
  Position current = r0;
3127
  double last_dist = 0.0;
3128
  for (const auto& hit : hits) {
5,516,161✔
3129
    // get the segment length
3130
    double segment_length = hit - last_dist;
4,694,269✔
3131
    last_dist = hit;
4,694,269✔
3132
    // find the midpoint of this segment
3133
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3134
    // try to find a tet for this position
3135
    int bin = this->get_bin(midpoint);
4,694,269✔
3136

3137
    // determine the start point for this segment
3138
    current = r0 + u * hit;
4,694,269✔
3139

3140
    if (bin == -1) {
4,694,269✔
3141
      continue;
20,522✔
3142
    }
3143

3144
    bins.push_back(bin);
4,673,747✔
3145
    lengths.push_back(segment_length / track_len);
4,673,747✔
3146
  }
3147

3148
  // tally remaining portion of track after last hit if
3149
  // the last segment of the track is in the mesh but doesn't
3150
  // reach the other side of the tet
3151
  if (hits.back() < track_len) {
821,892!
3152
    Position segment_start = r0 + u * hits.back();
821,892✔
3153
    double segment_length = track_len - hits.back();
821,892✔
3154
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3155
    int bin = this->get_bin(midpoint);
821,892✔
3156
    if (bin != -1) {
821,892✔
3157
      bins.push_back(bin);
766,509✔
3158
      lengths.push_back(segment_length / track_len);
766,509✔
3159
    }
3160
  }
3161
};
1,543,584✔
3162

3163
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3164
{
3165
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3166
  // find the leaf of the kd-tree for this position
3167
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3168
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3169
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3170
    return 0;
3171
  }
3172

3173
  // retrieve the tet elements of this leaf
3174
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3175
  moab::Range tets;
6,305,335✔
3176
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3177
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3178
    warning("MOAB error finding tets.");
×
3179
  }
3180

3181
  // loop over the tets in this leaf, returning the containing tet if found
3182
  for (const auto& tet : tets) {
260,211,273✔
3183
    if (point_in_tet(pos, tet)) {
260,208,426✔
3184
      return tet;
6,302,488✔
3185
    }
3186
  }
3187

3188
  // if no tet is found, return an invalid handle
3189
  return 0;
2,847✔
3190
}
14,634,464✔
3191

3192
double MOABMesh::volume(int bin) const
167,880✔
3193
{
3194
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3195
}
3196

3197
std::string MOABMesh::library() const
34✔
3198
{
3199
  return mesh_lib_type;
34✔
3200
}
3201

3202
// Sample position within a tet for MOAB type tets
3203
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3204
{
3205

3206
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3207

3208
  // Get vertex coordinates for MOAB tet
3209
  const moab::EntityHandle* conn1;
200,410✔
3210
  int conn1_size;
200,410✔
3211
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3212
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3213
    fatal_error(fmt::format(
3214
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3215
      conn1_size));
3216
  }
3217
  moab::CartVect p[4];
200,410✔
3218
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3219
  if (rval != moab::MB_SUCCESS) {
200,410!
3220
    fatal_error("Failed to get tet coords");
3221
  }
3222

3223
  std::array<Position, 4> tet_verts;
200,410✔
3224
  for (int i = 0; i < 4; i++) {
1,002,050✔
3225
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3226
  }
3227
  // Samples position within tet using Barycentric stuff
3228
  return this->sample_tet(tet_verts, seed);
200,410✔
3229
}
3230

3231
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3232
{
3233
  vector<moab::EntityHandle> conn;
167,880✔
3234
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3235
  if (rval != moab::MB_SUCCESS) {
167,880!
3236
    fatal_error("Failed to get tet connectivity");
3237
  }
3238

3239
  moab::CartVect p[4];
167,880✔
3240
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3241
  if (rval != moab::MB_SUCCESS) {
167,880!
3242
    fatal_error("Failed to get tet coords");
3243
  }
3244

3245
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3246
}
167,880✔
3247

3248
int MOABMesh::get_bin(Position r) const
7,317,232✔
3249
{
3250
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3251
  if (tet == 0) {
7,317,232✔
3252
    return -1;
3253
  } else {
3254
    return get_bin_from_ent_handle(tet);
6,302,488✔
3255
  }
3256
}
3257

3258
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3259
{
3260
  moab::ErrorCode rval;
21✔
3261

3262
  baryc_data_.clear();
21!
3263
  baryc_data_.resize(tets.size());
21✔
3264

3265
  // compute the barycentric data for each tet element
3266
  // and store it as a 3x3 matrix
3267
  for (auto& tet : tets) {
239,757✔
3268
    vector<moab::EntityHandle> verts;
239,736✔
3269
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3270
    if (rval != moab::MB_SUCCESS) {
239,736!
3271
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3272
    }
3273

3274
    moab::CartVect p[4];
239,736✔
3275
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3276
    if (rval != moab::MB_SUCCESS) {
239,736!
3277
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3278
    }
3279

3280
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
239,736✔
3281

3282
    // invert now to avoid this cost later
3283
    a = a.transpose().inverse();
239,736✔
3284
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3285
  }
239,736✔
3286
}
21✔
3287

3288
bool MOABMesh::point_in_tet(
260,208,426✔
3289
  const moab::CartVect& r, moab::EntityHandle tet) const
3290
{
3291

3292
  moab::ErrorCode rval;
260,208,426✔
3293

3294
  // get tet vertices
3295
  vector<moab::EntityHandle> verts;
260,208,426✔
3296
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3297
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3298
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3299
    return false;
3300
  }
3301

3302
  // first vertex is used as a reference point for the barycentric data -
3303
  // retrieve its coordinates
3304
  moab::CartVect p_zero;
260,208,426✔
3305
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3306
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3307
    warning("Failed to get coordinates of a vertex in "
×
3308
            "unstructured mesh: " +
3309
            filename_);
×
3310
    return false;
3311
  }
3312

3313
  // look up barycentric data
3314
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3315
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3316

3317
  moab::CartVect bary_coords = a_inv * (r - p_zero);
260,208,426✔
3318

3319
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3320
          bary_coords[2] >= 0.0 &&
318,957,185✔
3321
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3322
}
260,208,426✔
3323

3324
int MOABMesh::get_bin_from_index(int idx) const
3325
{
3326
  if (idx >= n_bins()) {
×
3327
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3328
  }
3329
  return ehs_[idx] - ehs_[0];
3330
}
3331

3332
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3333
{
3334
  int bin = get_bin(r);
3335
  *in_mesh = bin != -1;
3336
  return bin;
3337
}
3338

3339
int MOABMesh::get_index_from_bin(int bin) const
3340
{
3341
  return bin;
3342
}
3343

3344
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3345
  Position plot_ll, Position plot_ur) const
3346
{
3347
  // TODO: Implement mesh lines
3348
  return {};
3349
}
3350

3351
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3352
{
3353
  int idx = vert - verts_[0];
815,520✔
3354
  if (idx >= n_vertices()) {
815,520!
3355
    fatal_error(
3356
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3357
  }
3358
  return idx;
815,520✔
3359
}
3360

3361
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3362
{
3363
  int bin = eh - ehs_[0];
266,750,650✔
3364
  if (bin >= n_bins()) {
266,750,650!
3365
    fatal_error(fmt::format("Invalid bin: {}", bin));
3366
  }
3367
  return bin;
266,750,650✔
3368
}
3369

3370
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3371
{
3372
  if (bin >= n_bins()) {
572,170!
3373
    fatal_error(fmt::format("Invalid bin index: ", bin));
3374
  }
3375
  return ehs_[0] + bin;
572,170✔
3376
}
3377

3378
int MOABMesh::n_bins() const
267,526,773✔
3379
{
3380
  return ehs_.size();
267,526,773✔
3381
}
3382

3383
int MOABMesh::n_surface_bins() const
3384
{
3385
  // collect all triangles in the set of tets for this mesh
3386
  moab::Range tris;
×
3387
  moab::ErrorCode rval;
3388
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3389
  if (rval != moab::MB_SUCCESS) {
×
3390
    warning("Failed to get all triangles in the mesh instance");
×
3391
    return -1;
3392
  }
3393
  return 2 * tris.size();
×
3394
}
3395

3396
Position MOABMesh::centroid(int bin) const
3397
{
3398
  moab::ErrorCode rval;
3399

3400
  auto tet = this->get_ent_handle_from_bin(bin);
3401

3402
  // look up the tet connectivity
3403
  vector<moab::EntityHandle> conn;
×
3404
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3405
  if (rval != moab::MB_SUCCESS) {
×
3406
    warning("Failed to get connectivity of a mesh element.");
×
3407
    return {};
3408
  }
3409

3410
  // get the coordinates
3411
  vector<moab::CartVect> coords(conn.size());
×
3412
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3413
  if (rval != moab::MB_SUCCESS) {
×
3414
    warning("Failed to get the coordinates of a mesh element.");
×
3415
    return {};
3416
  }
3417

3418
  // compute the centroid of the element vertices
3419
  moab::CartVect centroid(0.0, 0.0, 0.0);
3420
  for (const auto& coord : coords) {
×
3421
    centroid += coord;
3422
  }
3423
  centroid /= double(coords.size());
3424

3425
  return {centroid[0], centroid[1], centroid[2]};
3426
}
3427

3428
int MOABMesh::n_vertices() const
845,874✔
3429
{
3430
  return verts_.size();
845,874✔
3431
}
3432

3433
Position MOABMesh::vertex(int id) const
86,227✔
3434
{
3435

3436
  moab::ErrorCode rval;
86,227✔
3437

3438
  moab::EntityHandle vert = verts_[id];
86,227✔
3439

3440
  moab::CartVect coords;
86,227✔
3441
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3442
  if (rval != moab::MB_SUCCESS) {
86,227!
3443
    fatal_error("Failed to get the coordinates of a vertex.");
3444
  }
3445

3446
  return {coords[0], coords[1], coords[2]};
86,227✔
3447
}
3448

3449
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3450
{
3451
  moab::ErrorCode rval;
203,880✔
3452

3453
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3454

3455
  // look up the tet connectivity
3456
  vector<moab::EntityHandle> conn;
203,880✔
3457
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3458
  if (rval != moab::MB_SUCCESS) {
203,880!
3459
    fatal_error("Failed to get connectivity of a mesh element.");
3460
    return {};
3461
  }
3462

3463
  std::vector<int> verts(4);
203,880✔
3464
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3465
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3466
  }
3467

3468
  return verts;
203,880✔
3469
}
203,880✔
3470

3471
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3472
  std::string score) const
3473
{
3474
  moab::ErrorCode rval;
3475
  // add a tag to the mesh
3476
  // all scores are treated as a single value
3477
  // with an uncertainty
3478
  moab::Tag value_tag;
3479

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

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

3506
  // return the populated tag handles
3507
  return {value_tag, error_tag};
3508
}
3509

3510
void MOABMesh::add_score(const std::string& score)
3511
{
3512
  auto score_tags = get_score_tags(score);
×
3513
  tag_names_.push_back(score);
3514
}
3515

3516
void MOABMesh::remove_scores()
3517
{
3518
  for (const auto& name : tag_names_) {
×
3519
    auto value_name = name + "_mean";
3520
    moab::Tag tag;
3521
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3522
    if (rval != moab::MB_SUCCESS)
×
3523
      return;
3524

3525
    rval = mbi_->tag_delete(tag);
×
3526
    if (rval != moab::MB_SUCCESS) {
×
3527
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3528
                             " on unstructured mesh {}",
3529
        name, id_);
×
3530
      fatal_error(msg);
3531
    }
3532

3533
    auto std_dev_name = name + "_std_dev";
×
3534
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3535
    if (rval != moab::MB_SUCCESS) {
×
3536
      auto msg =
3537
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3538
                    " on unstructured mesh {}",
3539
          name, id_);
×
3540
    }
3541

3542
    rval = mbi_->tag_delete(tag);
×
3543
    if (rval != moab::MB_SUCCESS) {
×
3544
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3545
                             " on unstructured mesh {}",
3546
        name, id_);
×
3547
      fatal_error(msg);
3548
    }
3549
  }
3550
  tag_names_.clear();
3551
}
3552

3553
void MOABMesh::set_score_data(const std::string& score,
3554
  const vector<double>& values, const vector<double>& std_dev)
3555
{
3556
  auto score_tags = this->get_score_tags(score);
×
3557

3558
  moab::ErrorCode rval;
3559
  // set the score value
3560
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3561
  if (rval != moab::MB_SUCCESS) {
×
3562
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3563
                           "on unstructured mesh {}",
3564
      score, id_);
3565
    warning(msg);
×
3566
  }
3567

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

3578
void MOABMesh::write(const std::string& base_filename) const
3579
{
3580
  // add extension to the base name
3581
  auto filename = base_filename + ".vtk";
3582
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3583
  filename = settings::path_output + filename;
×
3584

3585
  // write the tetrahedral elements of the mesh only
3586
  // to avoid clutter from zero-value data on other
3587
  // elements during visualization
3588
  moab::ErrorCode rval;
3589
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3590
  if (rval != moab::MB_SUCCESS) {
×
3591
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3592
    warning(msg);
×
3593
  }
3594
}
3595

3596
#endif
3597

3598
#ifdef OPENMC_LIBMESH_ENABLED
3599

3600
const std::string LibMesh::mesh_lib_type = "libmesh";
3601

3602
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3603
{
3604
  // filename_ and length_multiplier_ will already be set by the
3605
  // UnstructuredMesh constructor
3606
  set_mesh_pointer_from_filename(filename_);
25✔
3607
  set_length_multiplier(length_multiplier_);
25✔
3608
  initialize();
25✔
3609
}
25✔
3610

3611
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3612
{
3613
  // filename_ and length_multiplier_ will already be set by the
3614
  // UnstructuredMesh constructor
3615
  set_mesh_pointer_from_filename(filename_);
×
3616
  set_length_multiplier(length_multiplier_);
×
3617
  initialize();
×
3618
}
3619

3620
// create the mesh from a pointer to a libMesh Mesh
3621
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3622
{
3623
  if (!input_mesh.is_replicated()) {
×
3624
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3625
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3626
  }
3627

3628
  m_ = &input_mesh;
3629
  set_length_multiplier(length_multiplier);
×
3630
  initialize();
×
3631
}
3632

3633
// create the mesh from an input file
3634
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3635
{
3636
  n_dimension_ = 3;
3637
  set_mesh_pointer_from_filename(filename);
×
3638
  set_length_multiplier(length_multiplier);
×
3639
  initialize();
×
3640
}
3641

3642
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3643
{
3644
  filename_ = filename;
25✔
3645
  unique_m_ =
25✔
3646
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3647
  m_ = unique_m_.get();
25✔
3648
  m_->read(filename_);
25✔
3649
}
25✔
3650

3651
// build a libMesh equation system for storing values
3652
void LibMesh::build_eqn_sys()
17✔
3653
{
3654
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3655
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3656
  libMesh::ExplicitSystem& eq_sys =
17✔
3657
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3658
}
17✔
3659

3660
// intialize from mesh file
3661
void LibMesh::initialize()
25✔
3662
{
3663
  if (!settings::libmesh_comm) {
25!
3664
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3665
                "communicator.");
3666
  }
3667

3668
  // assuming that unstructured meshes used in OpenMC are 3D
3669
  n_dimension_ = 3;
25✔
3670

3671
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3672
  // Otherwise assume that it is prepared by its owning application
3673
  if (unique_m_) {
25!
3674
    m_->prepare_for_use();
25✔
3675
  }
3676

3677
  // ensure that the loaded mesh is 3 dimensional
3678
  if (m_->mesh_dimension() != n_dimension_) {
25!
3679
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3680
                            "mesh is not a 3D mesh.",
3681
      filename_));
3682
  }
3683

3684
  for (int i = 0; i < num_threads(); i++) {
69✔
3685
    pl_.emplace_back(m_->sub_point_locator());
44✔
3686
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
44✔
3687
    pl_.back()->enable_out_of_mesh_mode();
44✔
3688
  }
3689

3690
  // store first element in the mesh to use as an offset for bin indices
3691
  auto first_elem = *m_->elements_begin();
50✔
3692
  first_element_id_ = first_elem->id();
25✔
3693

3694
  // bounding box for the mesh for quick rejection checks
3695
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3696
  libMesh::Point ll = bbox_.min();
25!
3697
  libMesh::Point ur = bbox_.max();
25!
3698
  if (length_multiplier_ > 0.0) {
25!
3699
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3700
      length_multiplier_ * ll(2)};
3701
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3702
      length_multiplier_ * ur(2)};
3703
  } else {
3704
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3705
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3706
  }
3707
}
25✔
3708

3709
// Sample position within a tet for LibMesh type tets
3710
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3711
{
3712
  const auto& elem = get_element_from_bin(bin);
400,820✔
3713
  // Get tet vertex coordinates from LibMesh
3714
  std::array<Position, 4> tet_verts;
400,820✔
3715
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3716
    const auto& node_ref = elem.node_ref(i);
1,603,280✔
3717
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3718
  }
3719
  // Samples position within tet using Barycentric coordinates
3720
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3721
  if (length_multiplier_ > 0.0) {
400,820!
3722
    return length_multiplier_ * sampled_position;
3723
  } else {
3724
    return sampled_position;
400,820✔
3725
  }
3726
}
3727

3728
Position LibMesh::centroid(int bin) const
3729
{
3730
  const auto& elem = this->get_element_from_bin(bin);
3731
  auto centroid = elem.vertex_average();
3732
  if (length_multiplier_ > 0.0) {
×
3733
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3734
  } else {
3735
    return {centroid(0), centroid(1), centroid(2)};
3736
  }
3737
}
3738

3739
int LibMesh::n_vertices() const
42,644✔
3740
{
3741
  return m_->n_nodes();
42,644✔
3742
}
3743

3744
Position LibMesh::vertex(int vertex_id) const
42,604✔
3745
{
3746
  const auto& node_ref = m_->node_ref(vertex_id);
42,604✔
3747
  if (length_multiplier_ > 0.0) {
42,604!
3748
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3749
  } else {
3750
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3751
  }
3752
}
3753

3754
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3755
{
3756
  std::vector<int> conn;
267,856✔
3757
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3758
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3759
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3760
  }
3761
  return conn;
267,856✔
3762
}
3763

3764
std::string LibMesh::library() const
37✔
3765
{
3766
  return mesh_lib_type;
37✔
3767
}
3768

3769
int LibMesh::n_bins() const
1,788,419✔
3770
{
3771
  return m_->n_elem();
1,788,419✔
3772
}
3773

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

3792
void LibMesh::add_score(const std::string& var_name)
17✔
3793
{
3794
  if (!equation_systems_) {
17!
3795
    build_eqn_sys();
17✔
3796
  }
3797

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

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

3817
void LibMesh::remove_scores()
17✔
3818
{
3819
  if (equation_systems_) {
17!
3820
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3821
    eqn_sys.clear();
17✔
3822
    variable_map_.clear();
17✔
3823
  }
3824
}
17✔
3825

3826
void LibMesh::set_score_data(const std::string& var_name,
17✔
3827
  const vector<double>& values, const vector<double>& std_dev)
3828
{
3829
  if (!equation_systems_) {
17!
3830
    build_eqn_sys();
3831
  }
3832

3833
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3834

3835
  if (!eqn_sys.is_initialized()) {
17!
3836
    equation_systems_->init();
17✔
3837
  }
3838

3839
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3840

3841
  // look up the value variable
3842
  std::string value_name = var_name + "_mean";
17✔
3843
  unsigned int value_num = variable_map_.at(value_name);
17✔
3844
  // look up the std dev variable
3845
  std::string std_dev_name = var_name + "_std_dev";
17✔
3846
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3847

3848
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3849
       it++) {
3850
    if (!(*it)->active()) {
99,856!
3851
      continue;
3852
    }
3853

3854
    auto bin = get_bin_from_element(*it);
99,856✔
3855

3856
    // set value
3857
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3858
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3859
    assert(value_dof_indices.size() == 1);
99,856✔
3860
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3861

3862
    // set std dev
3863
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3864
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3865
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3866
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3867
  }
99,873✔
3868
}
17✔
3869

3870
void LibMesh::write(const std::string& filename) const
17✔
3871
{
3872
  write_message(fmt::format(
17✔
3873
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3874
  libMesh::ExodusII_IO exo(*m_);
17✔
3875
  std::set<std::string> systems_out = {eq_system_name_};
34!
3876
  exo.write_discontinuous_exodusII(
17✔
3877
    filename + ".e", *equation_systems_, &systems_out);
34✔
3878
}
17✔
3879

3880
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3881
  vector<int>& bins, vector<double>& lengths) const
3882
{
3883
  // TODO: Implement triangle crossings here
3884
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3885
}
3886

3887
int LibMesh::get_bin(Position r) const
2,340,604✔
3888
{
3889
  // look-up a tet using the point locator
3890
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3891

3892
  if (length_multiplier_ > 0.0) {
2,340,604!
3893
    // Scale the point down
3894
    p /= length_multiplier_;
2,340,604✔
3895
  }
3896

3897
  // quick rejection check
3898
  if (!bbox_.contains_point(p)) {
2,340,604✔
3899
    return -1;
3900
  }
3901

3902
  const auto& point_locator = pl_.at(thread_num());
1,421,808✔
3903

3904
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3905
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3906
}
2,340,604✔
3907

3908
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3909
{
3910
  int bin = elem->id() - first_element_id_;
1,520,434✔
3911
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3912
    fatal_error(fmt::format("Invalid bin: {}", bin));
3913
  }
3914
  return bin;
1,520,434✔
3915
}
3916

3917
std::pair<vector<double>, vector<double>> LibMesh::plot(
3918
  Position plot_ll, Position plot_ur) const
3919
{
3920
  return {};
3921
}
3922

3923
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3924
{
3925
  return m_->elem_ref(bin);
769,460✔
3926
}
3927

3928
double LibMesh::volume(int bin) const
368,640✔
3929
{
3930
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3931
         length_multiplier_ * length_multiplier_;
368,640✔
3932
}
3933

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

3961
int AdaptiveLibMesh::n_bins() const
3962
{
3963
  return num_active_;
3964
}
3965

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

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

3981
void AdaptiveLibMesh::write(const std::string& filename) const
3982
{
3983
  warning(fmt::format(
×
3984
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3985
    this->id_));
3986
}
3987

3988
int AdaptiveLibMesh::get_bin(Position r) const
3989
{
3990
  // look-up a tet using the point locator
3991
  libMesh::Point p(r.x, r.y, r.z);
×
3992

3993
  if (length_multiplier_ > 0.0) {
×
3994
    // Scale the point down
3995
    p /= length_multiplier_;
3996
  }
3997

3998
  // quick rejection check
3999
  if (!bbox_.contains_point(p)) {
×
4000
    return -1;
4001
  }
4002

4003
  const auto& point_locator = pl_.at(thread_num());
×
4004

4005
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4006
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4007
}
4008

4009
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4010
{
4011
  int bin = elem_to_bin_map_[elem->id()];
4012
  if (bin >= n_bins() || bin < 0) {
×
4013
    fatal_error(fmt::format("Invalid bin: {}", bin));
4014
  }
4015
  return bin;
4016
}
4017

4018
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4019
{
4020
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4021
}
4022

4023
#endif // OPENMC_LIBMESH_ENABLED
4024

4025
//==============================================================================
4026
// Non-member functions
4027
//==============================================================================
4028

4029
void read_meshes(pugi::xml_node root)
13,887✔
4030
{
4031
  std::unordered_set<int> mesh_ids;
13,887✔
4032

4033
  for (auto node : root.children("mesh")) {
17,215✔
4034
    // Check to make sure multiple meshes in the same file don't share IDs
4035
    int id = std::stoi(get_node_value(node, "id"));
6,656✔
4036
    if (contains(mesh_ids, id)) {
6,656!
4037
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4038
                              "'{}' in the same input file",
4039
        id));
4040
    }
4041
    mesh_ids.insert(id);
3,328✔
4042

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

4050
    std::string mesh_type;
3,328✔
4051
    if (check_for_node(node, "type")) {
3,328✔
4052
      mesh_type = get_node_value(node, "type", true, true);
950✔
4053
    } else {
4054
      mesh_type = "regular";
2,378✔
4055
    }
4056

4057
    // determine the mesh library to use
4058
    std::string mesh_lib;
3,328✔
4059
    if (check_for_node(node, "library")) {
3,328✔
4060
      mesh_lib = get_node_value(node, "library", true, true);
49!
4061
    }
4062

4063
    Mesh::create(node, mesh_type, mesh_lib);
3,328✔
4064
  }
3,328✔
4065
}
13,887✔
4066

4067
void read_meshes(hid_t group)
22✔
4068
{
4069
  std::unordered_set<int> mesh_ids;
22✔
4070

4071
  std::vector<int> ids;
22✔
4072
  read_attribute(group, "ids", ids);
22✔
4073

4074
  for (auto id : ids) {
55✔
4075

4076
    // Check to make sure multiple meshes in the same file don't share IDs
4077
    if (contains(mesh_ids, id)) {
66!
4078
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4079
                              "'{}' in the same HDF5 input file",
4080
        id));
4081
    }
4082
    mesh_ids.insert(id);
33✔
4083

4084
    // If we've already read a mesh with the same ID in a *different* file,
4085
    // assume it is the same here
4086
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
4087
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4088
      continue;
33✔
4089
    }
4090

4091
    std::string name = fmt::format("mesh {}", id);
×
4092
    hid_t mesh_group = open_group(group, name.c_str());
×
4093

4094
    std::string mesh_type;
×
4095
    if (object_exists(mesh_group, "type")) {
×
4096
      read_dataset(mesh_group, "type", mesh_type);
×
4097
    } else {
4098
      mesh_type = "regular";
×
4099
    }
4100

4101
    // determine the mesh library to use
4102
    std::string mesh_lib;
×
4103
    if (object_exists(mesh_group, "library")) {
×
4104
      read_dataset(mesh_group, "library", mesh_lib);
×
4105
    }
4106

4107
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4108
  }
×
4109
}
44✔
4110

4111
void meshes_to_hdf5(hid_t group)
7,756✔
4112
{
4113
  // Write number of meshes
4114
  hid_t meshes_group = create_group(group, "meshes");
7,756✔
4115
  int32_t n_meshes = model::meshes.size();
7,756✔
4116
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,756✔
4117

4118
  if (n_meshes > 0) {
7,756✔
4119
    // Write IDs of meshes
4120
    vector<int> ids;
2,359✔
4121
    for (const auto& m : model::meshes) {
5,407✔
4122
      m->to_hdf5(meshes_group);
3,048✔
4123
      ids.push_back(m->id_);
3,048✔
4124
    }
4125
    write_attribute(meshes_group, "ids", ids);
2,359✔
4126
  }
2,359✔
4127

4128
  close_group(meshes_group);
7,756✔
4129
}
7,756✔
4130

4131
void free_memory_mesh()
9,067✔
4132
{
4133
  model::meshes.clear();
9,067✔
4134
  model::mesh_map.clear();
9,067✔
4135
}
9,067✔
4136

4137
extern "C" int n_meshes()
308✔
4138
{
4139
  return model::meshes.size();
308✔
4140
}
4141

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