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

openmc-dev / openmc / 30177671737

25 Jul 2026 10:29PM UTC coverage: 81.4% (-0.01%) from 81.414%
30177671737

Pull #4028

github

web-flow
Merge 66c344140 into ce78bdcb9
Pull Request #4028: Allow mesh material volume calculations outside model geometry

18390 of 26644 branches covered (69.02%)

Branch coverage included in aggregate %.

80 of 80 new or added lines in 1 file covered. (100.0%)

7 existing lines in 2 files now uncovered.

60050 of 69720 relevant lines covered (86.13%)

49116910.99 hits per line

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

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

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

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

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

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

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

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

58
namespace openmc {
59

60
//==============================================================================
61
// Global variables
62
//==============================================================================
63

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

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

74
namespace model {
75

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

79
} // namespace model
80

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

88
//==============================================================================
89
// Helper functions
90
//==============================================================================
91

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

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

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

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

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

140
// Helper function equivalent to std::bit_cast in C++20
141
template<typename To, typename From>
142
inline To bit_cast_value(const From& value)
39,274,322✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
63,113✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
39,274,128✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
39,274,128✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
39,274,128✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
39,274,128✔
155
  double current = bit_cast_value<double>(current_bits);
39,274,128✔
156
  while (is_min ? (value < current) : (value > current)) {
39,274,322✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
63,113✔
158
    uint64_t expected_bits = current_bits;
63,113✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
63,113✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
39,274,128✔
162
    }
163
    current_bits = expected_bits;
194✔
164
    current = bit_cast_value<double>(current_bits);
194✔
165
  }
166

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

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

187
inline void atomic_max_double(double* ptr, double value)
19,637,064✔
188
{
189
  atomic_update_double(ptr, value, false);
6,545,688✔
190
}
6,545,688✔
191

192
inline void atomic_min_double(double* ptr, double value)
19,637,064✔
193
{
194
  atomic_update_double(ptr, value, true);
6,545,688✔
195
}
196

197
namespace detail {
198

199
//==============================================================================
200
// MaterialVolumes implementation
201
//==============================================================================
202

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

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

220
    // Non-atomic read of current material
221
    int32_t current_val = *slot_ptr;
9,488,661✔
222

223
    // Found the desired material; accumulate volume and bbox
224
    if (current_val == index_material) {
9,488,661✔
225
#pragma omp atomic
5,307,127✔
226
      this->volumes(index_elem, slot) += volume;
9,485,490✔
227
      if (bbox) {
9,485,490✔
228
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,543,927✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,543,927✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,543,927✔
231
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,543,927✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,543,927✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,543,927✔
234
      }
235
      return;
9,485,490✔
236
    }
237

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

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

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

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

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

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

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

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

326
} // namespace detail
327

328
//==============================================================================
329
// Mesh implementation
330
//==============================================================================
331

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

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

365
  return model::meshes.back();
3,464✔
366
}
367

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

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

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

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

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

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

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

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

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

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

423
vector<double> Mesh::volumes() const
331✔
424
{
425
  vector<double> volumes(n_bins());
331✔
426
  for (int i = 0; i < n_bins(); i++) {
1,243,675✔
427
    volumes[i] = this->volume(i);
1,243,344✔
428
  }
429
  return volumes;
331✔
430
}
×
431

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

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

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

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

473
  Timer timer;
231✔
474
  timer.start();
231✔
475

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

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

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

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

491
#pragma omp parallel
126✔
492
  {
105✔
493
    // Preallocate vector for mesh indices and length fractions and particle
494
    vector<int> bins;
105✔
495
    vector<double> length_fractions;
105✔
496
    Particle p;
105✔
497

498
    SourceSite site;
105✔
499
    site.E = 1.0;
105✔
500
    site.particle = ParticleType::neutron();
105✔
501

502
    bool verbose = settings::verbosity >= 10;
105✔
503

504
    // Save the cells occupied immediately before a boundary crossing.
505
    auto save_cell_state = [&p]() {
8,787,345✔
506
      for (int j = 0; j < p.n_coord(); ++j) {
17,574,690✔
507
        p.cell_last(j) = p.coord(j).cell();
8,787,345✔
508
      }
509
      p.n_coord_last() = p.n_coord();
8,787,345✔
510
    };
8,787,450✔
511

512
    // Initialize cell history after locating a ray inside the model.
513
    auto initialize_cell_state = [&p, &save_cell_state]() {
6,700,903✔
514
      if (p.cell_born() == C_NONE)
6,700,903!
515
        p.cell_born() = p.lowest_coord().cell();
6,700,903✔
516

517
      save_cell_state();
6,700,903✔
518
    };
6,701,008✔
519

520
    // Reset a failed coordinate search while preserving position and direction.
521
    auto reset_geometry_state = [&p]() {
77,330✔
522
      Position r = p.r();
77,330✔
523
      Direction u = p.u();
77,330✔
524
      p.init_from_r_u(r, u);
77,330✔
525
    };
77,435✔
526

527
    for (int axis = 0; axis < 3; ++axis) {
420✔
528
      // Set starting position and direction
529
      site.r = {0.0, 0.0, 0.0};
315✔
530
      site.r[axis] = bbox.min[axis];
315✔
531
      site.u = {0.0, 0.0, 0.0};
315✔
532
      site.u[axis] = 1.0;
315✔
533

534
      // Determine width of rays and number of rays in other directions
535
      int ax1 = (axis + 1) % 3;
315✔
536
      int ax2 = (axis + 2) % 3;
315✔
537
      double min1 = bbox.min[ax1];
315✔
538
      double min2 = bbox.min[ax2];
315✔
539
      double d1 = width[ax1];
315✔
540
      double d2 = width[ax2];
315✔
541
      int n1 = n_rays[ax1];
315✔
542
      int n2 = n_rays[ax2];
315✔
543
      if (n1 == 0 || n2 == 0) {
315✔
544
        continue;
60✔
545
      }
546

547
      // Divide rays in first direction over MPI processes by computing starting
548
      // and ending indices
549
      int min_work = n1 / mpi::n_procs;
255✔
550
      int remainder = n1 % mpi::n_procs;
255✔
551
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
255!
552
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
255!
553
      int i1_end = i1_start + n1_local;
255✔
554

555
      // Add the contribution from a ray segment. The positions used here are
556
      // kept separate from the particle position because the latter is moved a
557
      // tiny distance across each surface for robust geometry searches.
558
      auto add_segment = [&](const Position& r0, const Position& r1,
8,928,431✔
559
                           int i_material) {
560
        double distance = r1[axis] - r0[axis];
8,928,431✔
561
        if (distance <= 0.0)
8,928,431!
562
          return;
563

564
        bins.clear();
8,928,431✔
565
        length_fractions.clear();
8,928,431✔
566
        this->bins_crossed(r0, r1, site.u, bins, length_fractions);
35,111,183✔
567

568
        double cumulative_frac = 0.0;
8,928,431✔
569
        for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
18,417,092✔
570
          int mesh_index = bins[i_bin];
9,488,661✔
571
          double length = distance * length_fractions[i_bin];
9,488,661✔
572
          double volume = length * d1 * d2;
35,671,413✔
573

574
          if (compute_bboxes) {
9,488,661✔
575
            double axis_start = r0[axis] + distance * cumulative_frac;
6,545,688✔
576
            double axis_end = axis_start + length;
6,545,688✔
577
            cumulative_frac += length_fractions[i_bin];
6,545,688✔
578

579
            Position contrib_min = site.r;
6,545,688✔
580
            Position contrib_max = site.r;
6,545,688✔
581

582
            contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
6,545,688✔
583
            contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
6,545,688✔
584
            contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
6,545,688✔
585
            contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
6,545,688✔
586
            contrib_min[axis] = std::min(axis_start, axis_end);
6,545,688!
587
            contrib_max[axis] = std::max(axis_start, axis_end);
13,091,376!
588

589
            BoundingBox contrib_bbox {contrib_min, contrib_max};
6,545,688✔
590
            contrib_bbox &= bbox;
6,545,688✔
591

592
            result.add_volume(mesh_index, i_material, volume, &contrib_bbox);
6,545,688✔
593
          } else {
594
            result.add_volume(mesh_index, i_material, volume);
2,942,973✔
595
          }
596
        }
597
      };
255✔
598

599
      // Loop over rays on face of bounding box
600
#pragma omp for collapse(2)
601
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
18,230✔
602
        for (int i2 = 0; i2 < n2; ++i2) {
3,092,820✔
603
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,074,845✔
604
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,074,845✔
605

606
          p.from_source(&site);
3,074,845✔
607

608
          // Set the physical endpoint of this ray at the far mesh face.
609
          Position r_mesh_end = site.r;
3,074,845✔
610
          r_mesh_end[axis] = bbox.max[axis];
3,074,845✔
611

612
          // Determine particle's location
613
          bool inside_model = exhaustive_find_cell(p, verbose);
3,074,845✔
614

615
          if (inside_model)
3,074,845✔
616
            initialize_cell_state();
3,028,915✔
617

618
          // Physical position through which volume has been accumulated. This
619
          // differs by TINY_BIT from p.r() after crossing a surface.
620
          Position r_scored = site.r;
3,074,845✔
621

622
          while (r_scored[axis] < r_mesh_end[axis]) {
4,071,233!
623
            if (!inside_model) {
4,071,233✔
624
              // The ray is outside the model. Advance to the next surface of
625
              // any cell in the root universe, as is done for ray-traced
626
              // plots. Undefined space traversed along the way is void.
627
              Position r0 = p.r();
81,080✔
628
              p.advance_to_boundary_from_void();
81,080✔
629

630
              // If no model surface lies before the mesh edge, score the
631
              // remaining exterior interval as void and finish the ray.
632
              double distance_to_mesh_end = r_mesh_end[axis] - r0[axis];
81,080✔
633
              if (p.boundary().surface() == SURFACE_NONE ||
81,080✔
634
                  p.boundary().distance() >= distance_to_mesh_end) {
35,150!
635
                add_segment(r_scored, r_mesh_end, MATERIAL_VOID);
45,930✔
636
                break;
45,930✔
637
              }
638

639
              // Determine the physical position of the model boundary.
640
              Position r_boundary = r0 + p.boundary().distance() * p.u();
35,150✔
641

642
              // Score the exterior interval and record its physical endpoint.
643
              add_segment(r_scored, r_boundary, MATERIAL_VOID);
35,150✔
644
              r_scored = r_boundary;
35,150✔
645

646
              // Check whether advancing through the surface entered the model.
647
              inside_model = exhaustive_find_cell(p, verbose);
35,150✔
648
              if (inside_model) {
35,150✔
649
                initialize_cell_state();
16,950✔
650
              } else {
651
                // Clear any partial coordinate search before looking for the
652
                // next surface from undefined space.
653
                reset_geometry_state();
18,200✔
654
              }
655
              continue;
35,150✔
656
            }
35,150✔
657

658
            // Find the distance to the nearest boundary
659
            BoundaryInfo boundary = distance_to_boundary(p);
3,990,153✔
660

661
            // Convert the material index to a user-facing ID
662
            int i_material = p.material();
3,990,153✔
663
            if (i_material != C_NONE) {
3,990,153✔
664
              i_material = model::materials[i_material]->id();
1,305,699✔
665
            }
666

667
            // If no model boundary lies before the mesh edge, score the
668
            // remaining material interval and finish the ray.
669
            double distance_to_mesh_end = r_mesh_end[axis] - p.r()[axis];
3,990,153✔
670
            if (boundary.distance() >= distance_to_mesh_end) {
3,990,153✔
671
              add_segment(r_scored, r_mesh_end, i_material);
3,028,915✔
672
              break;
673
            }
674

675
            // Determine the physical position of the model boundary.
676
            Position r_boundary = p.r() + boundary.distance() * p.u();
961,238✔
677

678
            // Score the material interval and record its physical endpoint.
679
            add_segment(r_scored, r_boundary, i_material);
961,238✔
680
            r_scored = r_boundary;
961,238✔
681

682
            // Cross the next geometric surface. The small forward movement
683
            // and neighbor-list search mirror Ray::trace, allowing a failed
684
            // search to mean that the ray has left the model rather than that
685
            // a transport particle has been lost.
686
            save_cell_state();
961,238✔
687

688
            // Move just beyond the surface to make the next search robust.
689
            p.move_distance(boundary.distance() + TINY_BIT);
961,238✔
690

691
            // Set surface that particle is on and adjust coordinate levels
692
            p.surface() = boundary.surface();
961,238✔
693
            p.n_coord() = boundary.coord_level();
961,238✔
694

695
            // Update the geometry state according to the boundary type.
696
            if (boundary.lattice_translation()[0] != 0 ||
961,238!
697
                boundary.lattice_translation()[1] != 0 ||
961,238!
698
                boundary.lattice_translation()[2] != 0) {
961,238!
699
              // Particle crosses lattice boundary
700
              cross_lattice(p, boundary, verbose);
×
701
              inside_model = true;
702
            } else {
703
              // Search for the cell on the opposite side of a surface.
704
              inside_model = neighbor_list_find_cell(p, verbose);
961,238✔
705
            }
706

707
            // Treat a failed cell search as a transition to exterior void.
708
            if (!inside_model) {
961,238✔
709
              // Reset the geometry state so the next iteration can search for
710
              // another disjoint portion of the model.
711
              reset_geometry_state();
16,950✔
712
            }
713
          }
714
        }
715
      }
716
    }
717
  }
105✔
718

719
  // Check for errors
720
  if (result.table_full()) {
231!
UNCOV
721
    throw std::runtime_error("Maximum number of materials for mesh material "
×
722
                             "volume calculation insufficient.");
×
723
  }
724

725
  // Compute time for raytracing
726
  double t_raytrace = timer.elapsed();
231✔
727

728
#ifdef OPENMC_MPI
729
  // Combine results from multiple MPI processes
730
  if (mpi::n_procs > 1) {
84!
731
    int total = this->n_bins() * table_size;
732
    int total_bbox = total * 6;
733
    if (mpi::master) {
×
734
      // Allocate temporary buffer for receiving data
735
      vector<int32_t> mats(total);
736
      vector<double> vols(total);
×
737
      vector<double> recv_bboxes;
×
738
      if (compute_bboxes) {
×
739
        recv_bboxes.resize(total_bbox);
×
740
      }
741

742
      for (int i = 1; i < mpi::n_procs; ++i) {
×
743
        // Receive material indices and volumes from process i
744
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
745
          MPI_STATUS_IGNORE);
746
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
747
          MPI_STATUS_IGNORE);
748
        if (compute_bboxes) {
×
749
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
750
            mpi::intracomm, MPI_STATUS_IGNORE);
751
        }
752

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

786
  // Report time for MPI communication
787
  double t_mpi = timer.elapsed() - t_raytrace;
84✔
788
#else
789
  double t_mpi = 0.0;
126✔
790
#endif
791

792
  // Normalize based on known volumes of elements
793
  for (int i = 0; i < this->n_bins(); ++i) {
2,563✔
794
    // Estimated total volume in element i
795
    double volume = 0.0;
796
    for (int j = 0; j < table_size; ++j) {
15,488✔
797
      volume += result.volumes(i, j);
13,156✔
798
    }
799
    // Renormalize volumes based on known volume of element i
800
    double norm = this->volume(i) / volume;
2,332✔
801
    for (int j = 0; j < table_size; ++j) {
15,488✔
802
      result.volumes(i, j) *= norm;
13,156✔
803
    }
804
  }
805

806
  // Get total time and normalization time
807
  timer.stop();
231✔
808
  double t_total = timer.elapsed();
231✔
809
  double t_norm = t_total - t_raytrace - t_mpi;
231✔
810

811
  // Show timing statistics
812
  if (settings::verbosity < 7 || !mpi::master)
231!
813
    return;
55✔
814
  header("Timing Statistics", 7);
176✔
815
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
176✔
816
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
176✔
817
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
176✔
818
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
176✔
819
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
352✔
820
    n_total / t_raytrace);
176✔
821
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
256✔
822
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
176✔
823
  std::fflush(stdout);
176✔
824
}
825

826
void Mesh::to_hdf5(hid_t group) const
3,368✔
827
{
828
  // Create group for mesh
829
  std::string group_name = fmt::format("mesh {}", id_);
3,368✔
830
  hid_t mesh_group = create_group(group, group_name.c_str());
3,368✔
831

832
  // Write mesh type
833
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,368✔
834

835
  // Write mesh ID
836
  write_attribute(mesh_group, "id", id_);
3,368✔
837

838
  // Write mesh name
839
  write_dataset(mesh_group, "name", name_);
3,368✔
840

841
  // Write mesh data
842
  this->to_hdf5_inner(mesh_group);
3,368✔
843

844
  // Close group
845
  close_group(mesh_group);
3,368✔
846
}
3,368✔
847

848
//==============================================================================
849
// Structured Mesh implementation
850
//==============================================================================
851

852
std::string StructuredMesh::bin_label(int bin) const
5,315,732✔
853
{
854
  MeshIndex ijk = get_indices_from_bin(bin);
5,315,732✔
855

856
  if (n_dimension_ > 2) {
5,315,732✔
857
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,299,133✔
858
  } else if (n_dimension_ > 1) {
16,599✔
859
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,236✔
860
  } else {
861
    return fmt::format("Mesh Index ({})", ijk[0]);
363✔
862
  }
863
}
864

865
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,938✔
866
{
867
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,938✔
868
}
869

870
Position StructuredMesh::sample_element(
1,438,198✔
871
  const MeshIndex& ijk, uint64_t* seed) const
872
{
873
  // lookup the lower/upper bounds for the mesh element
874
  double x_min = negative_grid_boundary(ijk, 0);
1,438,198✔
875
  double x_max = positive_grid_boundary(ijk, 0);
1,438,198✔
876

877
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,438,198!
878
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,438,198!
879

880
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,438,198!
881
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,438,198!
882

883
  return {x_min + (x_max - x_min) * prn(seed),
1,438,198✔
884
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,438,198✔
885
}
886

887
//==============================================================================
888
// Unstructured Mesh implementation
889
//==============================================================================
890

891
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49!
892
{
893
  n_dimension_ = 3;
49✔
894

895
  // check the mesh type
896
  if (check_for_node(node, "type")) {
49!
897
    auto temp = get_node_value(node, "type", true, true);
49!
898
    if (temp != mesh_type) {
49!
899
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
900
    }
901
  }
49✔
902

903
  // check if a length unit multiplier was specified
904
  if (check_for_node(node, "length_multiplier")) {
49!
905
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
906
  }
907

908
  // get the filename of the unstructured mesh to load
909
  if (check_for_node(node, "filename")) {
49!
910
    filename_ = get_node_value(node, "filename");
49!
911
    if (!file_exists(filename_)) {
49!
912
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
913
    }
914
  } else {
915
    fatal_error(fmt::format(
×
916
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
917
  }
918

919
  if (check_for_node(node, "options")) {
49!
920
    options_ = get_node_value(node, "options");
16!
921
  }
922

923
  // check if mesh tally data should be written with
924
  // statepoint files
925
  if (check_for_node(node, "output")) {
49!
926
    output_ = get_node_value_bool(node, "output");
×
927
  }
928
}
49✔
929

930
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
931
{
932
  n_dimension_ = 3;
×
933

934
  // check the mesh type
935
  if (object_exists(group, "type")) {
×
936
    std::string temp;
×
937
    read_dataset(group, "type", temp);
×
938
    if (temp != mesh_type) {
×
939
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
940
    }
941
  }
×
942

943
  // check if a length unit multiplier was specified
944
  if (object_exists(group, "length_multiplier")) {
×
945
    read_dataset(group, "length_multiplier", length_multiplier_);
×
946
  }
947

948
  // get the filename of the unstructured mesh to load
949
  if (object_exists(group, "filename")) {
×
950
    read_dataset(group, "filename", filename_);
×
951
    if (!file_exists(filename_)) {
×
952
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
953
    }
954
  } else {
955
    fatal_error(fmt::format(
×
956
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
957
  }
958

959
  if (attribute_exists(group, "options")) {
×
960
    read_attribute(group, "options", options_);
×
961
  }
962

963
  // check if mesh tally data should be written with
964
  // statepoint files
965
  if (attribute_exists(group, "output")) {
×
966
    read_attribute(group, "output", output_);
×
967
  }
968
}
×
969

970
void UnstructuredMesh::determine_bounds()
25✔
971
{
972
  double xmin = INFTY;
25✔
973
  double ymin = INFTY;
25✔
974
  double zmin = INFTY;
25✔
975
  double xmax = -INFTY;
25✔
976
  double ymax = -INFTY;
25✔
977
  double zmax = -INFTY;
25✔
978
  int n = this->n_vertices();
25✔
979
  for (int i = 0; i < n; ++i) {
55,951✔
980
    auto v = this->vertex(i);
55,926✔
981
    xmin = std::min(v.x, xmin);
55,926✔
982
    ymin = std::min(v.y, ymin);
55,926✔
983
    zmin = std::min(v.z, zmin);
55,926✔
984
    xmax = std::max(v.x, xmax);
55,926✔
985
    ymax = std::max(v.y, ymax);
55,926✔
986
    zmax = std::max(v.z, zmax);
79,911✔
987
  }
988
  lower_left_ = {xmin, ymin, zmin};
25✔
989
  upper_right_ = {xmax, ymax, zmax};
25✔
990
}
25✔
991

992
Position UnstructuredMesh::sample_tet(
601,230✔
993
  std::array<Position, 4> coords, uint64_t* seed) const
994
{
995
  // Uniform distribution
996
  double s = prn(seed);
601,230✔
997
  double t = prn(seed);
601,230✔
998
  double u = prn(seed);
601,230✔
999

1000
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
1001
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
1002
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
1003
  if (s + t > 1) {
601,230✔
1004
    s = 1.0 - s;
300,882✔
1005
    t = 1.0 - t;
300,882✔
1006
  }
1007
  if (s + t + u > 1) {
601,230✔
1008
    if (t + u > 1) {
400,122✔
1009
      double old_t = t;
200,373✔
1010
      t = 1.0 - u;
200,373✔
1011
      u = 1.0 - s - old_t;
200,373✔
1012
    } else if (t + u <= 1) {
199,749!
1013
      double old_s = s;
199,749✔
1014
      s = 1.0 - t - u;
199,749✔
1015
      u = old_s + t + u - 1;
199,749✔
1016
    }
1017
  }
1018
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690✔
1019
         u * (coords[3] - coords[0]) + coords[0];
601,230✔
1020
}
1021

1022
const std::string UnstructuredMesh::mesh_type = "unstructured";
1023

1024
std::string UnstructuredMesh::get_mesh_type() const
34✔
1025
{
1026
  return mesh_type;
34✔
1027
}
1028

1029
void UnstructuredMesh::surface_bins_crossed(
×
1030
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1031
{
1032
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
1033
}
1034

1035
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
1036
{
1037
  return fmt::format("Mesh Index ({})", bin);
207,736✔
1038
};
1039

1040
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
1041
{
1042
  write_dataset(mesh_group, "filename", filename_);
34!
1043
  write_dataset(mesh_group, "library", this->library());
34!
1044
  if (!options_.empty()) {
34✔
1045
    write_attribute(mesh_group, "options", options_);
8✔
1046
  }
1047

1048
  if (length_multiplier_ > 0.0)
34!
1049
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
1050

1051
  // write vertex coordinates
1052
  tensor::Tensor<double> vertices(
34✔
1053
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
34✔
1054
  for (int i = 0; i < this->n_vertices(); i++) {
72,939!
1055
    auto v = this->vertex(i);
72,905!
1056
    vertices.slice(i) = {v.x, v.y, v.z};
145,810!
1057
  }
1058
  write_dataset(mesh_group, "vertices", vertices);
34!
1059

1060
  int num_elem_skipped = 0;
34✔
1061

1062
  // write element types and connectivity
1063
  vector<double> volumes;
34!
1064
  tensor::Tensor<int> connectivity(
34✔
1065
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
1066
  tensor::Tensor<int> elem_types(
34✔
1067
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
1068
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
1069
    auto conn = this->connectivity(i);
351,736!
1070

1071
    volumes.emplace_back(this->volume(i));
351,736!
1072

1073
    // write linear tet element
1074
    if (conn.size() == 4) {
351,736✔
1075
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
347,736!
1076
      connectivity.slice(i) = {
347,736!
1077
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
695,472!
1078
      // write linear hex element
1079
    } else if (conn.size() == 8) {
4,000!
1080
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
4,000!
1081
      connectivity.slice(i) = {
4,000!
1082
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
8,000!
1083
    } else {
1084
      num_elem_skipped++;
×
1085
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
1086
      connectivity.slice(i) = -1;
×
1087
    }
1088
  }
351,736✔
1089

1090
  // warn users that some elements were skipped
1091
  if (num_elem_skipped > 0) {
34!
1092
    warning(fmt::format("The connectivity of {} elements "
×
1093
                        "on mesh {} were not written "
1094
                        "because they are not of type linear tet/hex.",
1095
      num_elem_skipped, this->id_));
×
1096
  }
1097

1098
  write_dataset(mesh_group, "volumes", volumes);
34!
1099
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1100
  write_dataset(mesh_group, "element_types", elem_types);
34!
1101
}
102✔
1102

1103
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
25✔
1104
{
1105
  length_multiplier_ = length_multiplier;
25✔
1106
}
25✔
1107

1108
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1109
{
1110
  auto conn = connectivity(bin);
120,000✔
1111

1112
  if (conn.size() == 4)
120,000!
1113
    return ElementType::LINEAR_TET;
1114
  else if (conn.size() == 8)
×
1115
    return ElementType::LINEAR_HEX;
1116
  else
1117
    return ElementType::UNSUPPORTED;
×
1118
}
120,000✔
1119

1120
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,791,176,832✔
1121
  Position r, bool& in_mesh) const
1122
{
1123
  MeshIndex ijk;
1,791,176,832✔
1124
  in_mesh = true;
1,791,176,832✔
1125
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1126
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1127

1128
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1129
      in_mesh = false;
102,839,607✔
1130
  }
1131
  return ijk;
1,791,176,832✔
1132
}
1133

1134
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1135
{
1136
  switch (n_dimension_) {
2,147,483,647!
1137
  case 1:
880,627✔
1138
    return ijk[0] - 1;
880,627✔
1139
  case 2:
141,663,269✔
1140
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
141,663,269✔
1141
  case 3:
2,147,483,647✔
1142
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,147,483,647✔
1143
  default:
×
1144
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1145
  }
1146
}
1147

1148
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,090,026✔
1149
{
1150
  MeshIndex ijk;
8,090,026✔
1151
  if (n_dimension_ == 1) {
8,090,026✔
1152
    ijk[0] = bin + 1;
363✔
1153
  } else if (n_dimension_ == 2) {
8,089,663✔
1154
    ijk[0] = bin % shape_[0] + 1;
16,236✔
1155
    ijk[1] = bin / shape_[0] + 1;
16,236✔
1156
  } else if (n_dimension_ == 3) {
8,073,427!
1157
    ijk[0] = bin % shape_[0] + 1;
8,073,427✔
1158
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,073,427✔
1159
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,073,427✔
1160
  }
1161
  return ijk;
8,090,026✔
1162
}
1163

1164
int StructuredMesh::get_bin(Position r) const
576,161,825✔
1165
{
1166
  // Determine indices
1167
  bool in_mesh;
576,161,825✔
1168
  MeshIndex ijk = get_indices(r, in_mesh);
576,161,825✔
1169
  if (!in_mesh)
576,161,825✔
1170
    return -1;
1171

1172
  // Convert indices to bin
1173
  return get_bin_from_indices(ijk);
555,067,668✔
1174
}
1175

1176
int StructuredMesh::n_bins() const
1,260,840✔
1177
{
1178
  // Bin indices are stored as 32-bit ints in the tally system.
1179
  int64_t n = 1;
1,260,840✔
1180
  for (int i = 0; i < n_dimension_; ++i)
5,042,900✔
1181
    n *= shape_[i];
3,782,060✔
1182
  if (n > std::numeric_limits<int>::max()) {
1,260,840!
1183
    fatal_error(fmt::format(
×
1184
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1185
  }
1186
  return static_cast<int>(n);
1,260,840✔
1187
}
1188

1189
int StructuredMesh::n_surface_bins() const
436✔
1190
{
1191
  // Surface bin indices are stored as 32-bit ints in the tally system.
1192
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
436✔
1193
  if (n > std::numeric_limits<int>::max()) {
436!
1194
    fatal_error(fmt::format(
×
1195
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1196
  }
1197
  return static_cast<int>(n);
436✔
1198
}
1199

1200
tensor::Tensor<double> StructuredMesh::count_sites(
×
1201
  const SourceSite* bank, int64_t length, bool* outside) const
1202
{
1203
  // Determine shape of array for counts
1204
  std::size_t m = this->n_bins();
×
1205
  vector<std::size_t> shape = {m};
×
1206

1207
  // Create array of zeros
1208
  auto cnt = tensor::zeros<double>(shape);
×
1209
  bool outside_ = false;
1210

1211
  for (int64_t i = 0; i < length; i++) {
×
1212
    const auto& site = bank[i];
×
1213

1214
    // determine scoring bin for entropy mesh
1215
    int mesh_bin = get_bin(site.r);
×
1216

1217
    // if outside mesh, skip particle
1218
    if (mesh_bin < 0) {
×
1219
      outside_ = true;
×
1220
      continue;
×
1221
    }
1222

1223
    // Add to appropriate bin
1224
    cnt(mesh_bin) += site.wgt;
×
1225
  }
1226

1227
  // Create reduced count data
1228
  auto counts = tensor::zeros<double>(shape);
×
1229
  int total = cnt.size();
×
1230

1231
#ifdef OPENMC_MPI
1232
  // collect values from all processors
1233
  MPI_Reduce(
×
1234
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1235

1236
  // Check if there were sites outside the mesh for any processor
1237
  if (outside) {
×
1238
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1239
  }
1240
#else
1241
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1242
  if (outside)
×
1243
    *outside = outside_;
1244
#endif
1245

1246
  return counts;
×
1247
}
×
1248

1249
// raytrace through the mesh. The template class T will do the tallying.
1250
// A modern optimizing compiler can recognize the noop method of T and
1251
// eliminate that call entirely.
1252
template<class T>
1253
void StructuredMesh::raytrace_mesh(
1,262,185,691✔
1254
  Position r0, Position r1, const Direction& u, T tally) const
1255
{
1256
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1257
  // enable/disable tally calls for now, T template type needs to provide both
1258
  // surface and track methods, which might be empty. modern optimizing
1259
  // compilers will (hopefully) eliminate the complete code (including
1260
  // calculation of parameters) but for the future: be explicit
1261

1262
  // Compute the length of the entire track.
1263
  double total_distance = (r1 - r0).norm();
1,262,185,691✔
1264
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,262,185,691✔
1265
    return;
1266

1267
  // keep a copy of the original global position to pass to get_indices,
1268
  // which performs its own transformation to local coordinates
1269
  Position global_r = r0;
1,207,839,179✔
1270
  Position local_r = local_coords(r0);
1,207,839,179✔
1271

1272
  const int n = n_dimension_;
1,207,839,179✔
1273

1274
  // Flag if position is inside the mesh
1275
  bool in_mesh;
1276

1277
  // Position is r = r0 + u * traveled_distance, start at r0
1278
  double traveled_distance {0.0};
1,207,839,179✔
1279

1280
  // Calculate index of current cell. Offset the position a tiny bit in
1281
  // direction of flight
1282
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,207,839,179✔
1283

1284
  // if track is very short, assume that it is completely inside one cell.
1285
  // Only the current cell will score and no surfaces
1286
  if (total_distance < 2 * TINY_BIT) {
1,207,839,179✔
1287
    if (in_mesh) {
675,882✔
1288
      tally.track(ijk, 1.0);
675,398✔
1289
    }
1290
    return;
675,882✔
1291
  }
1292

1293
  // Calculate initial distances to next surfaces in all three dimensions
1294
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1295
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1296
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1297
  }
1298

1299
  // Loop until r = r1 is eventually reached
1300
  while (true) {
1301

1302
    if (in_mesh) {
2,068,428,517✔
1303

1304
      // find surface with minimal distance to current position
1305
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,981,961,505✔
1306
                     distances.begin();
1,981,961,505✔
1307

1308
      // Tally track length delta since last step
1309
      tally.track(ijk,
1,981,961,505✔
1310
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1311
          total_distance);
1312

1313
      // update position and leave, if we have reached end position
1314
      traveled_distance = distances[k].distance;
1,981,961,505✔
1315
      if (traveled_distance >= total_distance)
1,981,961,505✔
1316
        return;
1317

1318
      // If we have not reached r1, we have hit a surface. Tally outward
1319
      // current
1320
      tally.surface(ijk, k, distances[k].max_surface, false);
854,089,392✔
1321

1322
      // Update cell and calculate distance to next surface in k-direction.
1323
      // The two other directions are still valid!
1324
      ijk[k] = distances[k].next_index;
854,089,392✔
1325
      distances[k] =
854,089,392✔
1326
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
854,089,392✔
1327

1328
      // Check if we have left the interior of the mesh
1329
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
860,941,491✔
1330

1331
      // If we are still inside the mesh, tally inward current for the next
1332
      // cell
1333
      if (in_mesh)
29,576,976✔
1334
        tally.surface(ijk, k, !distances[k].max_surface, true);
859,848,992✔
1335

1336
    } else { // not inside mesh
1337

1338
      // For all directions outside the mesh, find the distance that we need
1339
      // to travel to reach the next surface. Use the largest distance, as
1340
      // only this will cross all outer surfaces.
1341
      int k_max {-1};
1342
      for (int k = 0; k < n; ++k) {
344,399,086✔
1343
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,932,074✔
1344
            (distances[k].distance > traveled_distance)) {
94,474,927✔
1345
          traveled_distance = distances[k].distance;
1346
          k_max = k;
1347
        }
1348
      }
1349
      // Assure some distance is traveled
1350
      if (k_max == -1) {
86,467,012✔
1351
        traveled_distance += TINY_BIT;
110✔
1352
      }
1353

1354
      // If r1 is not inside the mesh, exit here
1355
      if (traveled_distance >= total_distance)
86,467,012✔
1356
        return;
1357

1358
      // Calculate the new cell index and update all distances to next
1359
      // surfaces.
1360
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,175,828✔
1361
      for (int k = 0; k < n; ++k) {
28,494,774✔
1362
        distances[k] =
21,318,946✔
1363
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,318,946✔
1364
      }
1365

1366
      // If inside the mesh, Tally inward current
1367
      if (in_mesh && k_max >= 0)
7,175,828!
1368
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
831,665,276✔
1369
    }
1370
  }
1371
}
1372

1373
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,150,058,060✔
1374
  vector<int>& bins, vector<double>& lengths) const
1375
{
1376

1377
  // Helper tally class.
1378
  // stores a pointer to the mesh class and references to bins and lengths
1379
  // parameters. Performs the actual tally through the track method.
1380
  struct TrackAggregator {
1,150,058,060✔
1381
    TrackAggregator(
1,150,058,060✔
1382
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1383
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,150,058,060✔
1384
    {}
1385
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1386
    void track(const MeshIndex& ijk, double l) const
1,842,592,207✔
1387
    {
1388
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,842,592,207✔
1389
      lengths.push_back(l);
1,842,592,207✔
1390
    }
1,842,592,207✔
1391

1392
    const StructuredMesh* mesh;
1393
    vector<int>& bins;
1394
    vector<double>& lengths;
1395
  };
1396

1397
  // Perform the mesh raytrace with the helper class.
1398
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,150,058,060✔
1399
}
1,150,058,060✔
1400

1401
void StructuredMesh::surface_bins_crossed(
112,127,631✔
1402
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1403
{
1404

1405
  // Helper tally class.
1406
  // stores a pointer to the mesh class and a reference to the bins parameter.
1407
  // Performs the actual tally through the surface method.
1408
  struct SurfaceAggregator {
112,127,631✔
1409
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,631✔
1410
      : mesh(_mesh), bins(_bins)
112,127,631✔
1411
    {}
1412
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,332✔
1413
    {
1414
      int i_bin =
58,159,332✔
1415
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,332✔
1416
      if (max)
58,159,332✔
1417
        i_bin += 2;
29,051,517✔
1418
      if (inward)
58,159,332✔
1419
        i_bin += 1;
28,582,356✔
1420
      bins.push_back(i_bin);
58,159,332✔
1421
    }
58,159,332✔
1422
    void track(const MeshIndex& idx, double l) const {}
1423

1424
    const StructuredMesh* mesh;
1425
    vector<int>& bins;
1426
  };
1427

1428
  // Perform the mesh raytrace with the helper class.
1429
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,631✔
1430
}
112,127,631✔
1431

1432
//==============================================================================
1433
// RegularMesh implementation
1434
//==============================================================================
1435

1436
int RegularMesh::set_grid()
2,570✔
1437
{
1438
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,570✔
1439

1440
  // Check that dimensions are all greater than zero
1441
  if ((shape <= 0).any()) {
7,710!
1442
    set_errmsg("All entries for a regular mesh dimensions "
×
1443
               "must be positive.");
1444
    return OPENMC_E_INVALID_ARGUMENT;
×
1445
  }
1446

1447
  // Make sure lower_left and dimension match
1448
  if (lower_left_.size() != n_dimension_) {
2,570!
1449
    set_errmsg("Number of entries in lower_left must be the same "
×
1450
               "as the regular mesh dimensions.");
1451
    return OPENMC_E_INVALID_ARGUMENT;
×
1452
  }
1453
  if (width_.size() > 0) {
2,570✔
1454

1455
    // Check to ensure width has same dimensions
1456
    if (width_.size() != n_dimension_) {
46!
1457
      set_errmsg("Number of entries on width must be the same as "
×
1458
                 "the regular mesh dimensions.");
1459
      return OPENMC_E_INVALID_ARGUMENT;
×
1460
    }
1461

1462
    // Check for negative widths
1463
    if ((width_ < 0.0).any()) {
138!
1464
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1465
      return OPENMC_E_INVALID_ARGUMENT;
×
1466
    }
1467

1468
    // Set width and upper right coordinate
1469
    upper_right_ = lower_left_ + shape * width_;
138✔
1470

1471
  } else if (upper_right_.size() > 0) {
2,524!
1472

1473
    // Check to ensure upper_right_ has same dimensions
1474
    if (upper_right_.size() != n_dimension_) {
2,524!
1475
      set_errmsg("Number of entries on upper_right must be the "
×
1476
                 "same as the regular mesh dimensions.");
1477
      return OPENMC_E_INVALID_ARGUMENT;
×
1478
    }
1479

1480
    // Check that upper-right is above lower-left
1481
    if ((upper_right_ < lower_left_).any()) {
7,572!
1482
      set_errmsg(
×
1483
        "The upper_right coordinates of a regular mesh must be greater than "
1484
        "the lower_left coordinates.");
1485
      return OPENMC_E_INVALID_ARGUMENT;
×
1486
    }
1487

1488
    // Set width
1489
    width_ = (upper_right_ - lower_left_) / shape;
7,572✔
1490
  }
1491

1492
  // Set material volumes
1493
  volume_frac_ = 1.0 / shape.prod();
2,570✔
1494

1495
  element_volume_ = 1.0;
2,570✔
1496
  for (int i = 0; i < n_dimension_; i++) {
9,685✔
1497
    element_volume_ *= width_[i];
7,115✔
1498
  }
1499
  return 0;
1500
}
2,570✔
1501

1502
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,533✔
1503
{
1504
  // Determine number of dimensions for mesh
1505
  if (!check_for_node(node, "dimension")) {
2,533!
1506
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1507
  }
1508

1509
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,533✔
1510
  int n = n_dimension_ = shape.size();
2,533!
1511
  if (n != 1 && n != 2 && n != 3) {
2,533!
1512
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1513
  }
1514
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,533✔
1515

1516
  // Check for lower-left coordinates
1517
  if (check_for_node(node, "lower_left")) {
2,533!
1518
    // Read mesh lower-left corner location
1519
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,533✔
1520
  } else {
1521
    fatal_error("Must specify <lower_left> on a mesh.");
×
1522
  }
1523

1524
  if (check_for_node(node, "width")) {
2,533✔
1525
    // Make sure one of upper-right or width were specified
1526
    if (check_for_node(node, "upper_right")) {
46!
1527
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1528
    }
1529

1530
    width_ = get_node_tensor<double>(node, "width");
92✔
1531

1532
  } else if (check_for_node(node, "upper_right")) {
2,487!
1533

1534
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,974✔
1535

1536
  } else {
1537
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1538
  }
1539

1540
  if (int err = set_grid()) {
2,533!
1541
    fatal_error(openmc_err_msg);
×
1542
  }
1543
}
2,533✔
1544

1545
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
37✔
1546
{
1547
  // Determine number of dimensions for mesh
1548
  if (!object_exists(group, "dimension")) {
37!
1549
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1550
  }
1551

1552
  tensor::Tensor<int> shape;
37✔
1553
  read_dataset(group, "dimension", shape);
37✔
1554
  int n = n_dimension_ = shape.size();
37!
1555
  if (n != 1 && n != 2 && n != 3) {
37!
1556
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1557
  }
1558
  std::copy(shape.begin(), shape.end(), shape_.begin());
37✔
1559

1560
  // Check for lower-left coordinates
1561
  if (object_exists(group, "lower_left")) {
37!
1562
    // Read mesh lower-left corner location
1563
    read_dataset(group, "lower_left", lower_left_);
37✔
1564
  } else {
1565
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1566
  }
1567

1568
  if (object_exists(group, "upper_right")) {
37!
1569

1570
    read_dataset(group, "upper_right", upper_right_);
37✔
1571

1572
  } else {
1573
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1574
  }
1575

1576
  if (int err = set_grid()) {
37!
1577
    fatal_error(openmc_err_msg);
×
1578
  }
1579
}
37✔
1580

1581
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1582
{
1583
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1584
}
1585

1586
const std::string RegularMesh::mesh_type = "regular";
1587

1588
std::string RegularMesh::get_mesh_type() const
3,675✔
1589
{
1590
  return mesh_type;
3,675✔
1591
}
1592

1593
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,953,614,409✔
1594
{
1595
  return lower_left_[i] + ijk[i] * width_[i];
1,953,614,409✔
1596
}
1597

1598
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,883,637,132✔
1599
{
1600
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,883,637,132✔
1601
}
1602

1603
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1604
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1605
  double l) const
1606
{
1607
  MeshDistance d;
2,147,483,647✔
1608
  d.next_index = ijk[i];
2,147,483,647✔
1609
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1610
    return d;
15,938,572✔
1611

1612
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1613
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1614
    d.next_index++;
1,949,299,815✔
1615
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,949,299,815✔
1616
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,900,904,082✔
1617
    d.next_index--;
1,879,322,538✔
1618
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,879,322,538✔
1619
  }
1620

1621
  return d;
2,147,483,647✔
1622
}
1623

1624
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1625
  Position plot_ll, Position plot_ur) const
1626
{
1627
  // Figure out which axes lie in the plane of the plot.
1628
  array<int, 2> axes {-1, -1};
22✔
1629
  if (plot_ur.z == plot_ll.z) {
22!
1630
    axes[0] = 0;
22!
1631
    if (n_dimension_ > 1)
22!
1632
      axes[1] = 1;
22✔
1633
  } else if (plot_ur.y == plot_ll.y) {
×
1634
    axes[0] = 0;
×
1635
    if (n_dimension_ > 2)
×
1636
      axes[1] = 2;
×
1637
  } else if (plot_ur.x == plot_ll.x) {
×
1638
    if (n_dimension_ > 1)
×
1639
      axes[0] = 1;
×
1640
    if (n_dimension_ > 2)
×
1641
      axes[1] = 2;
×
1642
  } else {
1643
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1644
  }
1645

1646
  // Get the coordinates of the mesh lines along both of the axes.
1647
  array<vector<double>, 2> axis_lines;
1648
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1649
    int axis = axes[i_ax];
44!
1650
    if (axis == -1)
44!
1651
      continue;
×
1652
    auto& lines {axis_lines[i_ax]};
44✔
1653

1654
    double coord = lower_left_[axis];
44✔
1655
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1656
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1657
        lines.push_back(coord);
242✔
1658
      coord += width_[axis];
242✔
1659
    }
1660
  }
1661

1662
  return {axis_lines[0], axis_lines[1]};
44✔
1663
}
1664

1665
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,498✔
1666
{
1667
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,498✔
1668
  write_dataset(mesh_group, "lower_left", lower_left_);
2,498✔
1669
  write_dataset(mesh_group, "upper_right", upper_right_);
2,498✔
1670
  write_dataset(mesh_group, "width", width_);
2,498✔
1671
}
2,498✔
1672

1673
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1674
  const SourceSite* bank, int64_t length, bool* outside) const
1675
{
1676
  // Determine shape of array for counts
1677
  std::size_t m = this->n_bins();
7,820✔
1678
  vector<std::size_t> shape = {m};
7,820✔
1679

1680
  // Create array of zeros
1681
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1682
  bool outside_ = false;
2,892✔
1683

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

1687
    // determine scoring bin for entropy mesh
1688
    int mesh_bin = get_bin(site.r);
7,667,451✔
1689

1690
    // if outside mesh, skip particle
1691
    if (mesh_bin < 0) {
7,667,451!
1692
      outside_ = true;
×
1693
      continue;
×
1694
    }
1695

1696
    // Add to appropriate bin
1697
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1698
  }
1699

1700
  // Create reduced count data
1701
  auto counts = tensor::zeros<double>(shape);
7,820✔
1702
  int total = cnt.size();
7,820✔
1703

1704
#ifdef OPENMC_MPI
1705
  // collect values from all processors
1706
  MPI_Reduce(
2,892✔
1707
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1708

1709
  // Check if there were sites outside the mesh for any processor
1710
  if (outside) {
2,892!
1711
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1712
  }
1713
#else
1714
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1715
  if (outside)
4,928!
1716
    *outside = outside_;
4,928✔
1717
#endif
1718

1719
  return counts;
7,820✔
1720
}
7,820✔
1721

1722
double RegularMesh::volume(const MeshIndex& ijk) const
1,246,017✔
1723
{
1724
  return element_volume_;
1,246,017✔
1725
}
1726

1727
//==============================================================================
1728
// RectilinearMesh implementation
1729
//==============================================================================
1730

1731
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1732
{
1733
  n_dimension_ = 3;
133✔
1734

1735
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1736
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1737
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1738

1739
  if (int err = set_grid()) {
133!
1740
    fatal_error(openmc_err_msg);
×
1741
  }
1742
}
133✔
1743

1744
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1745
{
1746
  n_dimension_ = 3;
11✔
1747

1748
  read_dataset(group, "x_grid", grid_[0]);
11✔
1749
  read_dataset(group, "y_grid", grid_[1]);
11✔
1750
  read_dataset(group, "z_grid", grid_[2]);
11✔
1751

1752
  if (int err = set_grid()) {
11!
1753
    fatal_error(openmc_err_msg);
×
1754
  }
1755
}
11✔
1756

1757
const std::string RectilinearMesh::mesh_type = "rectilinear";
1758

1759
std::string RectilinearMesh::get_mesh_type() const
286✔
1760
{
1761
  return mesh_type;
286✔
1762
}
1763

1764
double RectilinearMesh::positive_grid_boundary(
26,505,985✔
1765
  const MeshIndex& ijk, int i) const
1766
{
1767
  return grid_[i][ijk[i]];
26,505,985✔
1768
}
1769

1770
double RectilinearMesh::negative_grid_boundary(
25,739,428✔
1771
  const MeshIndex& ijk, int i) const
1772
{
1773
  return grid_[i][ijk[i] - 1];
25,739,428✔
1774
}
1775

1776
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,131✔
1777
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1778
  double l) const
1779
{
1780
  MeshDistance d;
53,602,131✔
1781
  d.next_index = ijk[i];
53,602,131✔
1782
  if (std::abs(u[i]) < FP_PRECISION)
53,602,131✔
1783
    return d;
571,824✔
1784

1785
  d.max_surface = (u[i] > 0);
53,030,307✔
1786
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,307✔
1787
    d.next_index++;
26,505,985✔
1788
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,985✔
1789
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,322✔
1790
    d.next_index--;
25,739,428✔
1791
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,428✔
1792
  }
1793
  return d;
53,030,307✔
1794
}
1795

1796
int RectilinearMesh::set_grid()
188✔
1797
{
1798
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1799
    static_cast<int>(grid_[1].size()) - 1,
188✔
1800
    static_cast<int>(grid_[2].size()) - 1};
188✔
1801

1802
  for (const auto& g : grid_) {
752✔
1803
    if (g.size() < 2) {
564!
1804
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1805
                 "must each have at least 2 points");
1806
      return OPENMC_E_INVALID_ARGUMENT;
×
1807
    }
1808
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
564!
1809
        g.end()) {
564!
1810
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1811
                 "rectilinear meshes must be sorted and unique.");
1812
      return OPENMC_E_INVALID_ARGUMENT;
×
1813
    }
1814
  }
1815

1816
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1817
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1818

1819
  return 0;
188✔
1820
}
1821

1822
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,925✔
1823
{
1824
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,925✔
1825
}
1826

1827
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1828
  Position plot_ll, Position plot_ur) const
1829
{
1830
  // Figure out which axes lie in the plane of the plot.
1831
  array<int, 2> axes {-1, -1};
11✔
1832
  if (plot_ur.z == plot_ll.z) {
11!
1833
    axes = {0, 1};
×
1834
  } else if (plot_ur.y == plot_ll.y) {
11!
1835
    axes = {0, 2};
11✔
1836
  } else if (plot_ur.x == plot_ll.x) {
×
1837
    axes = {1, 2};
×
1838
  } else {
1839
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1840
  }
1841

1842
  // Get the coordinates of the mesh lines along both of the axes.
1843
  array<vector<double>, 2> axis_lines;
1844
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1845
    int axis = axes[i_ax];
22✔
1846
    vector<double>& lines {axis_lines[i_ax]};
22✔
1847

1848
    for (auto coord : grid_[axis]) {
110✔
1849
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1850
        lines.push_back(coord);
88✔
1851
    }
1852
  }
1853

1854
  return {axis_lines[0], axis_lines[1]};
22✔
1855
}
1856

1857
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
121✔
1858
{
1859
  write_dataset(mesh_group, "x_grid", grid_[0]);
121✔
1860
  write_dataset(mesh_group, "y_grid", grid_[1]);
121✔
1861
  write_dataset(mesh_group, "z_grid", grid_[2]);
121✔
1862
}
121✔
1863

1864
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1865
{
1866
  double vol {1.0};
132✔
1867

1868
  for (int i = 0; i < n_dimension_; i++) {
528✔
1869
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1870
  }
1871
  return vol;
132✔
1872
}
1873

1874
//==============================================================================
1875
// CylindricalMesh implementation
1876
//==============================================================================
1877

1878
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
411✔
1879
  : PeriodicStructuredMesh {node}
411✔
1880
{
1881
  n_dimension_ = 3;
411✔
1882
  grid_[0] = get_node_array<double>(node, "r_grid");
411✔
1883
  grid_[1] = get_node_array<double>(node, "phi_grid");
411✔
1884
  grid_[2] = get_node_array<double>(node, "z_grid");
411✔
1885
  origin_ = get_node_position(node, "origin");
411✔
1886

1887
  if (int err = set_grid()) {
411!
1888
    fatal_error(openmc_err_msg);
×
1889
  }
1890
}
411✔
1891

1892
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1893
{
1894
  n_dimension_ = 3;
11✔
1895
  read_dataset(group, "r_grid", grid_[0]);
11✔
1896
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1897
  read_dataset(group, "z_grid", grid_[2]);
11✔
1898
  read_dataset(group, "origin", origin_);
11✔
1899

1900
  if (int err = set_grid()) {
11!
1901
    fatal_error(openmc_err_msg);
×
1902
  }
1903
}
11✔
1904

1905
const std::string CylindricalMesh::mesh_type = "cylindrical";
1906

1907
std::string CylindricalMesh::get_mesh_type() const
495✔
1908
{
1909
  return mesh_type;
495✔
1910
}
1911

1912
std::array<const char*, 3> CylindricalMesh::axis_labels() const
646,536✔
1913
{
1914
  return {"r", "phi", "z"};
646,536✔
1915
}
1916

1917
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,102✔
1918
  Position r, bool& in_mesh) const
1919
{
1920
  r = local_coords(r);
47,732,102✔
1921

1922
  Position mapped_r;
47,732,102✔
1923
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,102✔
1924
  mapped_r[2] = r[2];
47,732,102✔
1925

1926
  if (mapped_r[0] < FP_PRECISION) {
47,732,102!
1927
    mapped_r[1] = 0.0;
1928
  } else {
1929
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,102✔
1930
    if (mapped_r[1] < 0)
47,732,102✔
1931
      mapped_r[1] += 2 * PI;
23,874,862✔
1932
  }
1933

1934
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,102✔
1935

1936
  idx[1] = sanitize_phi(idx[1]);
47,732,102✔
1937

1938
  return idx;
47,732,102✔
1939
}
1940

1941
Position CylindricalMesh::sample_element(
88,110✔
1942
  const MeshIndex& ijk, uint64_t* seed) const
1943
{
1944
  double r_min = this->r(ijk[0] - 1);
88,110✔
1945
  double r_max = this->r(ijk[0]);
88,110✔
1946

1947
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1948
  double phi_max = this->phi(ijk[1]);
88,110✔
1949

1950
  double z_min = this->z(ijk[2] - 1);
88,110✔
1951
  double z_max = this->z(ijk[2]);
88,110✔
1952

1953
  double r_min_sq = r_min * r_min;
88,110✔
1954
  double r_max_sq = r_max * r_max;
88,110✔
1955
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1956
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1957
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1958

1959
  double x = r * std::cos(phi);
88,110✔
1960
  double y = r * std::sin(phi);
88,110✔
1961

1962
  return origin_ + Position(x, y, z);
88,110✔
1963
}
1964

1965
double CylindricalMesh::find_r_crossing(
142,589,936✔
1966
  const Position& r, const Direction& u, double l, int shell) const
1967
{
1968

1969
  if ((shell < 0) || (shell > shape_[0]))
142,589,936!
1970
    return INFTY;
1971

1972
  // solve r.x^2 + r.y^2 == r0^2
1973
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1974
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1975

1976
  const double r0 = grid_[0][shell];
124,675,883✔
1977
  if (r0 == 0.0)
124,675,883✔
1978
    return INFTY;
1979

1980
  const double denominator = u.x * u.x + u.y * u.y;
117,539,798✔
1981

1982
  // Direction of flight is in z-direction. Will never intersect r.
1983
  if (std::abs(denominator) < FP_PRECISION)
117,539,798✔
1984
    return INFTY;
1985

1986
  // inverse of dominator to help the compiler to speed things up
1987
  const double inv_denominator = 1.0 / denominator;
117,480,838✔
1988

1989
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,480,838✔
1990
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,480,838✔
1991
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,480,838✔
1992

1993
  if (D < 0.0)
117,480,838✔
1994
    return INFTY;
1995

1996
  D = std::sqrt(D);
107,744,716✔
1997

1998
  // Particle is already on the shell surface; avoid spurious crossing
1999
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,744,716✔
2000
    return INFTY;
2001

2002
  // Check -p - D first because it is always smaller as -p + D
2003
  if (-p - D > l)
101,111,342✔
2004
    return -p - D;
2005
  if (-p + D > l)
80,903,726✔
2006
    return -p + D;
50,079,144✔
2007

2008
  return INFTY;
2009
}
2010

2011
double CylindricalMesh::find_phi_crossing(
74,456,426✔
2012
  const Position& r, const Direction& u, double l, int shell) const
2013
{
2014
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2015
  if (full_phi_ && (shape_[1] == 1))
74,456,426✔
2016
    return INFTY;
2017

2018
  shell = sanitize_phi(shell);
43,970,718✔
2019

2020
  const double p0 = grid_[1][shell];
43,970,718✔
2021

2022
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2023
  // => x(s) * cos(p0) = y(s) * sin(p0)
2024
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2025
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2026

2027
  const double c0 = std::cos(p0);
43,970,718✔
2028
  const double s0 = std::sin(p0);
43,970,718✔
2029

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

2032
  // Check if direction of flight is not parallel to phi surface
2033
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
2034
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
2035
    // Check if solution is in positive direction of flight and crosses the
2036
    // correct phi surface (not -phi)
2037
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
2038
      return s;
20,219,859✔
2039
  }
2040

2041
  return INFTY;
2042
}
2043

2044
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,758✔
2045
  const Position& r, const Direction& u, double l, int shell) const
2046
{
2047
  MeshDistance d;
36,695,758✔
2048
  d.next_index = shell;
36,695,758✔
2049

2050
  // Direction of flight is within xy-plane. Will never intersect z.
2051
  if (std::abs(u.z) < FP_PRECISION)
36,695,758✔
2052
    return d;
1,118,216✔
2053

2054
  d.max_surface = (u.z > 0.0);
35,577,542✔
2055
  if (d.max_surface && (shell <= shape_[2])) {
35,577,542✔
2056
    d.next_index += 1;
16,875,903✔
2057
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,903✔
2058
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
2059
    d.next_index -= 1;
16,846,225✔
2060
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
2061
  }
2062
  return d;
35,577,542✔
2063
}
2064

2065
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,939✔
2066
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2067
  double l) const
2068
{
2069
  if (i == 0) {
145,218,939✔
2070

2071
    return std::min(
142,589,936✔
2072
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,968✔
2073
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,589,936✔
2074

2075
  } else if (i == 1) {
73,923,971✔
2076

2077
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,213✔
2078
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,213✔
2079
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,213✔
2080
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,426✔
2081

2082
  } else {
2083
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,758✔
2084
  }
2085
}
2086

2087
int CylindricalMesh::set_grid()
444✔
2088
{
2089
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
444✔
2090
    static_cast<int>(grid_[1].size()) - 1,
444✔
2091
    static_cast<int>(grid_[2].size()) - 1};
444✔
2092

2093
  for (const auto& g : grid_) {
1,776✔
2094
    if (g.size() < 2) {
1,332!
2095
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2096
                 "must each have at least 2 points");
2097
      return OPENMC_E_INVALID_ARGUMENT;
×
2098
    }
2099
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,332!
2100
        g.end()) {
1,332!
2101
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2102
                 "cylindrical meshes must be sorted and unique.");
2103
      return OPENMC_E_INVALID_ARGUMENT;
×
2104
    }
2105
  }
2106
  if (grid_[0].front() < 0.0) {
444!
2107
    set_errmsg("r-grid for "
×
2108
               "cylindrical meshes must start at r >= 0.");
2109
    return OPENMC_E_INVALID_ARGUMENT;
×
2110
  }
2111
  if (grid_[1].front() < 0.0) {
444!
2112
    set_errmsg("phi-grid for "
×
2113
               "cylindrical meshes must start at phi >= 0.");
2114
    return OPENMC_E_INVALID_ARGUMENT;
×
2115
  }
2116
  if (grid_[1].back() > 2.0 * PI) {
444!
2117
    set_errmsg("phi-grids for "
×
2118
               "cylindrical meshes must end with theta <= 2*pi.");
2119

2120
    return OPENMC_E_INVALID_ARGUMENT;
×
2121
  }
2122

2123
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
444!
2124

2125
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
444✔
2126
    origin_[2] + grid_[2].front()};
444✔
2127
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
444✔
2128
    origin_[2] + grid_[2].back()};
444✔
2129

2130
  return 0;
444✔
2131
}
2132

2133
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,306✔
2134
{
2135
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,306✔
2136
}
2137

2138
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2139
  Position plot_ll, Position plot_ur) const
2140
{
2141
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2142

2143
  // Figure out which axes lie in the plane of the plot.
2144
  array<vector<double>, 2> axis_lines;
2145
  return {axis_lines[0], axis_lines[1]};
2146
}
2147

2148
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
385✔
2149
{
2150
  write_dataset(mesh_group, "r_grid", grid_[0]);
385✔
2151
  write_dataset(mesh_group, "phi_grid", grid_[1]);
385✔
2152
  write_dataset(mesh_group, "z_grid", grid_[2]);
385✔
2153
  write_dataset(mesh_group, "origin", origin_);
385✔
2154
}
385✔
2155

2156
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2157
{
2158
  double r_i = grid_[0][ijk[0] - 1];
792✔
2159
  double r_o = grid_[0][ijk[0]];
792✔
2160

2161
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2162
  double phi_o = grid_[1][ijk[1]];
792✔
2163

2164
  double z_i = grid_[2][ijk[2] - 1];
792✔
2165
  double z_o = grid_[2][ijk[2]];
792✔
2166

2167
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2168
}
2169

2170
//==============================================================================
2171
// SphericalMesh implementation
2172
//==============================================================================
2173

2174
SphericalMesh::SphericalMesh(pugi::xml_node node)
356✔
2175
  : PeriodicStructuredMesh {node}
356✔
2176
{
2177
  n_dimension_ = 3;
356✔
2178

2179
  grid_[0] = get_node_array<double>(node, "r_grid");
356✔
2180
  grid_[1] = get_node_array<double>(node, "theta_grid");
356✔
2181
  grid_[2] = get_node_array<double>(node, "phi_grid");
356✔
2182
  origin_ = get_node_position(node, "origin");
356✔
2183

2184
  if (int err = set_grid()) {
356!
2185
    fatal_error(openmc_err_msg);
×
2186
  }
2187
}
356✔
2188

2189
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2190
{
2191
  n_dimension_ = 3;
11✔
2192

2193
  read_dataset(group, "r_grid", grid_[0]);
11✔
2194
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2195
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2196
  read_dataset(group, "origin", origin_);
11✔
2197

2198
  if (int err = set_grid()) {
11!
2199
    fatal_error(openmc_err_msg);
×
2200
  }
2201
}
11✔
2202

2203
const std::string SphericalMesh::mesh_type = "spherical";
2204

2205
std::string SphericalMesh::get_mesh_type() const
396✔
2206
{
2207
  return mesh_type;
396✔
2208
}
2209

2210
std::array<const char*, 3> SphericalMesh::axis_labels() const
323,400✔
2211
{
2212
  return {"r", "theta", "phi"};
323,400✔
2213
}
2214

2215
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,139✔
2216
  Position r, bool& in_mesh) const
2217
{
2218
  r = local_coords(r);
68,592,139✔
2219

2220
  Position mapped_r;
68,592,139✔
2221
  mapped_r[0] = r.norm();
68,592,139✔
2222

2223
  if (mapped_r[0] < FP_PRECISION) {
68,592,139!
2224
    mapped_r[1] = 0.0;
2225
    mapped_r[2] = 0.0;
2226
  } else {
2227
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,139✔
2228
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,139✔
2229
    if (mapped_r[2] < 0)
68,592,139✔
2230
      mapped_r[2] += 2 * PI;
34,268,685✔
2231
  }
2232

2233
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,139✔
2234

2235
  idx[1] = sanitize_theta(idx[1]);
68,592,139✔
2236
  idx[2] = sanitize_phi(idx[2]);
68,592,139✔
2237

2238
  return idx;
68,592,139✔
2239
}
2240

2241
Position SphericalMesh::sample_element(
110✔
2242
  const MeshIndex& ijk, uint64_t* seed) const
2243
{
2244
  double r_min = this->r(ijk[0] - 1);
110✔
2245
  double r_max = this->r(ijk[0]);
110✔
2246

2247
  double theta_min = this->theta(ijk[1] - 1);
110✔
2248
  double theta_max = this->theta(ijk[1]);
110✔
2249

2250
  double phi_min = this->phi(ijk[2] - 1);
110✔
2251
  double phi_max = this->phi(ijk[2]);
110✔
2252

2253
  double cos_theta =
110✔
2254
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2255
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2256
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2257
  double r_min_cub = std::pow(r_min, 3);
110✔
2258
  double r_max_cub = std::pow(r_max, 3);
110✔
2259
  // might be faster to do rejection here?
2260
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2261

2262
  double x = r * std::cos(phi) * sin_theta;
110✔
2263
  double y = r * std::sin(phi) * sin_theta;
110✔
2264
  double z = r * cos_theta;
110✔
2265

2266
  return origin_ + Position(x, y, z);
110✔
2267
}
2268

2269
double SphericalMesh::find_r_crossing(
443,989,172✔
2270
  const Position& r, const Direction& u, double l, int shell) const
2271
{
2272
  if ((shell < 0) || (shell > shape_[0]))
443,989,172✔
2273
    return INFTY;
2274

2275
  // solve |r+s*u| = r0
2276
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2277
  const double r0 = grid_[0][shell];
404,368,074✔
2278
  if (r0 == 0.0)
404,368,074✔
2279
    return INFTY;
2280
  const double p = r.dot(u);
396,689,546✔
2281
  double R = r.norm();
396,689,546✔
2282
  double D = p * p - (R - r0) * (R + r0);
396,689,546✔
2283

2284
  // Particle is already on the shell surface; avoid spurious crossing
2285
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,689,546✔
2286
    return INFTY;
2287

2288
  if (D >= 0.0) {
385,980,892✔
2289
    D = std::sqrt(D);
358,103,944✔
2290
    // Check -p - D first because it is always smaller as -p + D
2291
    if (-p - D > l)
358,103,944✔
2292
      return -p - D;
2293
    if (-p + D > l)
293,788,176✔
2294
      return -p + D;
177,245,761✔
2295
  }
2296

2297
  return INFTY;
2298
}
2299

2300
double SphericalMesh::find_theta_crossing(
110,161,370✔
2301
  const Position& r, const Direction& u, double l, int shell) const
2302
{
2303
  // Theta grid is [0, π], thus there is no real surface to cross
2304
  if (full_theta_ && (shape_[1] == 1))
110,161,370✔
2305
    return INFTY;
2306

2307
  shell = sanitize_theta(shell);
38,358,540✔
2308

2309
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2310
  // yields
2311
  // a*s^2 + 2*b*s + c == 0 with
2312
  // a = cos(theta)^2 - u.z * u.z
2313
  // b = r*u * cos(theta)^2 - u.z * r.z
2314
  // c = r*r * cos(theta)^2 - r.z^2
2315

2316
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2317
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2318
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2319

2320
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2321
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2322
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2323

2324
  // if factor of s^2 is zero, direction of flight is parallel to theta
2325
  // surface
2326
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2327
    // if b vanishes, direction of flight is within theta surface and crossing
2328
    // is not possible
2329
    if (std::abs(b) < FP_PRECISION)
482,548!
2330
      return INFTY;
2331

2332
    const double s = -0.5 * c / b;
×
2333
    // Check if solution is in positive direction of flight and has correct
2334
    // sign
2335
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2336
      return s;
×
2337

2338
    // no crossing is possible
2339
    return INFTY;
2340
  }
2341

2342
  const double p = b / a;
37,875,992✔
2343
  double D = p * p - c / a;
37,875,992✔
2344

2345
  if (D < 0.0)
37,875,992✔
2346
    return INFTY;
2347

2348
  D = std::sqrt(D);
26,921,004✔
2349

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

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

2361
  return INFTY;
2362
}
2363

2364
double SphericalMesh::find_phi_crossing(
111,750,848✔
2365
  const Position& r, const Direction& u, double l, int shell) const
2366
{
2367
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2368
  if (full_phi_ && (shape_[2] == 1))
111,750,848✔
2369
    return INFTY;
2370

2371
  shell = sanitize_phi(shell);
39,948,018✔
2372

2373
  const double p0 = grid_[2][shell];
39,948,018✔
2374

2375
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2376
  // => x(s) * cos(p0) = y(s) * sin(p0)
2377
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2378
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2379

2380
  const double c0 = std::cos(p0);
39,948,018✔
2381
  const double s0 = std::sin(p0);
39,948,018✔
2382

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

2385
  // Check if direction of flight is not parallel to phi surface
2386
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2387
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2388
    // Check if solution is in positive direction of flight and crosses the
2389
    // correct phi surface (not -phi)
2390
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2391
      return s;
17,579,452✔
2392
  }
2393

2394
  return INFTY;
2395
}
2396

2397
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,950,695✔
2398
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2399
  double l) const
2400
{
2401

2402
  if (i == 0) {
332,950,695✔
2403
    return std::min(
443,989,172✔
2404
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,994,586✔
2405
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,989,172✔
2406

2407
  } else if (i == 1) {
110,956,109✔
2408
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,685✔
2409
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,685✔
2410
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,685✔
2411
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,370✔
2412

2413
  } else {
2414
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,424✔
2415
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,424✔
2416
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,424✔
2417
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,848✔
2418
  }
2419
}
2420

2421
int SphericalMesh::set_grid()
389✔
2422
{
2423
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
389✔
2424
    static_cast<int>(grid_[1].size()) - 1,
389✔
2425
    static_cast<int>(grid_[2].size()) - 1};
389✔
2426

2427
  for (const auto& g : grid_) {
1,556✔
2428
    if (g.size() < 2) {
1,167!
2429
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2430
                 "must each have at least 2 points");
2431
      return OPENMC_E_INVALID_ARGUMENT;
×
2432
    }
2433
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,167!
2434
        g.end()) {
1,167!
2435
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2436
                 "spherical meshes must be sorted and unique.");
2437
      return OPENMC_E_INVALID_ARGUMENT;
×
2438
    }
2439
    if (g.front() < 0.0) {
1,167!
2440
      set_errmsg("r-, theta-, and phi- grids for "
×
2441
                 "spherical meshes must start at v >= 0.");
2442
      return OPENMC_E_INVALID_ARGUMENT;
×
2443
    }
2444
  }
2445
  if (grid_[1].back() > PI) {
389!
2446
    set_errmsg("theta-grids for "
×
2447
               "spherical meshes must end with theta <= pi.");
2448

2449
    return OPENMC_E_INVALID_ARGUMENT;
×
2450
  }
2451
  if (grid_[2].back() > 2 * PI) {
389!
2452
    set_errmsg("phi-grids for "
×
2453
               "spherical meshes must end with phi <= 2*pi.");
2454
    return OPENMC_E_INVALID_ARGUMENT;
×
2455
  }
2456

2457
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
389!
2458
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
389✔
2459

2460
  double r = grid_[0].back();
389✔
2461
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
389✔
2462
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
389✔
2463

2464
  return 0;
389✔
2465
}
2466

2467
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,417✔
2468
{
2469
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,417✔
2470
}
2471

2472
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2473
  Position plot_ll, Position plot_ur) const
2474
{
2475
  fatal_error("Plot of spherical Mesh not implemented");
×
2476

2477
  // Figure out which axes lie in the plane of the plot.
2478
  array<vector<double>, 2> axis_lines;
2479
  return {axis_lines[0], axis_lines[1]};
2480
}
2481

2482
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
330✔
2483
{
2484
  write_dataset(mesh_group, "r_grid", grid_[0]);
330✔
2485
  write_dataset(mesh_group, "theta_grid", grid_[1]);
330✔
2486
  write_dataset(mesh_group, "phi_grid", grid_[2]);
330✔
2487
  write_dataset(mesh_group, "origin", origin_);
330✔
2488
}
330✔
2489

2490
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2491
{
2492
  double r_i = grid_[0][ijk[0] - 1];
935✔
2493
  double r_o = grid_[0][ijk[0]];
935✔
2494

2495
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2496
  double theta_o = grid_[1][ijk[1]];
935✔
2497

2498
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2499
  double phi_o = grid_[2][ijk[2]];
935✔
2500

2501
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2502
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2503
}
2504

2505
//==============================================================================
2506
// Helper functions for the C API
2507
//==============================================================================
2508

2509
int check_mesh(int32_t index)
6,578✔
2510
{
2511
  if (index < 0 || index >= model::meshes.size()) {
6,578!
2512
    set_errmsg("Index in meshes array is out of bounds.");
×
2513
    return OPENMC_E_OUT_OF_BOUNDS;
×
2514
  }
2515
  return 0;
2516
}
2517

2518
template<class T>
2519
int check_mesh_type(int32_t index)
1,100✔
2520
{
2521
  if (int err = check_mesh(index))
1,100!
2522
    return err;
2523

2524
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2525
  if (!mesh) {
1,100!
2526
    set_errmsg("This function is not valid for input mesh.");
×
2527
    return OPENMC_E_INVALID_TYPE;
×
2528
  }
2529
  return 0;
2530
}
2531

2532
template<class T>
2533
bool is_mesh_type(int32_t index)
2534
{
2535
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2536
  return mesh;
2537
}
2538

2539
//==============================================================================
2540
// C API functions
2541
//==============================================================================
2542

2543
// Return the type of mesh as a C string
2544
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,518✔
2545
{
2546
  if (int err = check_mesh(index))
1,518!
2547
    return err;
2548

2549
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,518✔
2550

2551
  return 0;
1,518✔
2552
}
2553

2554
//! Extend the meshes array by n elements
2555
extern "C" int openmc_extend_meshes(
253✔
2556
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2557
{
2558
  if (index_start)
253!
2559
    *index_start = model::meshes.size();
253✔
2560
  std::string mesh_type;
253✔
2561

2562
  for (int i = 0; i < n; ++i) {
506✔
2563
    if (RegularMesh::mesh_type == type) {
253✔
2564
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2565
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2566
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2567
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2568
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2569
    } else if (SphericalMesh::mesh_type == type) {
22!
2570
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2571
    } else {
2572
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2573
    }
2574
  }
2575
  if (index_end)
253!
2576
    *index_end = model::meshes.size() - 1;
×
2577

2578
  return 0;
253✔
2579
}
253✔
2580

2581
//! Adds a new unstructured mesh to OpenMC
2582
extern "C" int openmc_add_unstructured_mesh(
×
2583
  const char filename[], const char library[], int* id)
2584
{
2585
  std::string lib_name(library);
×
2586
  std::string mesh_file(filename);
×
2587
  bool valid_lib = false;
×
2588

2589
#ifdef OPENMC_DAGMC_ENABLED
2590
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2591
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2592
    valid_lib = true;
2593
  }
2594
#endif
2595

2596
#ifdef OPENMC_LIBMESH_ENABLED
2597
  if (lib_name == LibMesh::mesh_lib_type) {
×
2598
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2599
    valid_lib = true;
2600
  }
2601
#endif
2602

2603
  if (!valid_lib) {
×
2604
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2605
                           "by this build of OpenMC",
2606
      lib_name));
2607
    return OPENMC_E_INVALID_ARGUMENT;
×
2608
  }
2609

2610
  // auto-assign new ID
2611
  model::meshes.back()->set_id(-1);
×
2612
  *id = model::meshes.back()->id_;
2613

2614
  return 0;
2615
}
×
2616

2617
//! Return the index in the meshes array of a mesh with a given ID
2618
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2619
{
2620
  auto pair = model::mesh_map.find(id);
429!
2621
  if (pair == model::mesh_map.end()) {
429!
2622
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2623
    return OPENMC_E_INVALID_ID;
×
2624
  }
2625
  *index = pair->second;
429✔
2626
  return 0;
429✔
2627
}
2628

2629
//! Return the ID of a mesh
2630
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,849✔
2631
{
2632
  if (int err = check_mesh(index))
2,849!
2633
    return err;
2634
  *id = model::meshes[index]->id_;
2,849✔
2635
  return 0;
2,849✔
2636
}
2637

2638
//! Set the ID of a mesh
2639
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2640
{
2641
  if (int err = check_mesh(index))
253!
2642
    return err;
2643
  model::meshes[index]->id_ = id;
253✔
2644
  model::mesh_map[id] = index;
253✔
2645
  return 0;
253✔
2646
}
2647

2648
//! Get the number of elements in a mesh
2649
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
319✔
2650
{
2651
  if (int err = check_mesh(index))
319!
2652
    return err;
2653
  *n = model::meshes[index]->n_bins();
319✔
2654
  return 0;
319✔
2655
}
2656

2657
//! Get the volume of each element in the mesh
2658
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2659
{
2660
  if (int err = check_mesh(index))
88!
2661
    return err;
2662
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2663
    volumes[i] = model::meshes[index]->volume(i);
880✔
2664
  }
2665
  return 0;
2666
}
2667

2668
//! Get the bounding box of a mesh
2669
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2670
{
2671
  if (int err = check_mesh(index))
176!
2672
    return err;
2673

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

2676
  // set lower left corner values
2677
  ll[0] = bbox.min.x;
176✔
2678
  ll[1] = bbox.min.y;
176✔
2679
  ll[2] = bbox.min.z;
176✔
2680

2681
  // set upper right corner values
2682
  ur[0] = bbox.max.x;
176✔
2683
  ur[1] = bbox.max.y;
176✔
2684
  ur[2] = bbox.max.z;
176✔
2685
  return 0;
176✔
2686
}
2687

2688
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
231✔
2689
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2690
{
2691
  if (int err = check_mesh(index))
231!
2692
    return err;
2693

2694
  try {
231✔
2695
    model::meshes[index]->material_volumes(
231✔
2696
      nx, ny, nz, table_size, materials, volumes, bboxes);
UNCOV
2697
  } catch (const std::exception& e) {
×
UNCOV
2698
    set_errmsg(e.what());
×
UNCOV
2699
    if (starts_with(e.what(), "Mesh")) {
×
UNCOV
2700
      return OPENMC_E_GEOMETRY;
×
2701
    } else {
2702
      return OPENMC_E_ALLOCATE;
×
2703
    }
UNCOV
2704
  }
×
2705

2706
  return 0;
2707
}
2708

2709
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2710
  Position width, int basis, int* pixels, int32_t* data)
2711
{
2712
  if (int err = check_mesh(index))
44!
2713
    return err;
2714
  const auto& mesh = model::meshes[index].get();
44!
2715

2716
  int pixel_width = pixels[0];
44✔
2717
  int pixel_height = pixels[1];
44✔
2718

2719
  // get pixel size
2720
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2721
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2722

2723
  // setup basis indices and initial position centered on pixel
2724
  int in_i, out_i;
44✔
2725
  Position xyz = origin;
44✔
2726
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2727
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2728
  switch (basis_enum) {
44!
2729
  case PlotBasis::xy:
2730
    in_i = 0;
2731
    out_i = 1;
2732
    break;
2733
  case PlotBasis::xz:
2734
    in_i = 0;
2735
    out_i = 2;
2736
    break;
2737
  case PlotBasis::yz:
2738
    in_i = 1;
2739
    out_i = 2;
2740
    break;
2741
  default:
×
2742
    UNREACHABLE();
×
2743
  }
2744

2745
  // set initial position
2746
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2747
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2748

2749
#pragma omp parallel
24✔
2750
  {
20✔
2751
    Position r = xyz;
20✔
2752

2753
#pragma omp for
2754
    for (int y = 0; y < pixel_height; y++) {
420✔
2755
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2756
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2757
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2758
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2759
      }
2760
    }
2761
  }
2762

2763
  return 0;
44✔
2764
}
2765

2766
//! Get the dimension of a regular mesh
2767
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2768
  int32_t index, int** dims, int* n)
2769
{
2770
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2771
    return err;
2772
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2773
  *dims = mesh->shape_.data();
11✔
2774
  *n = mesh->n_dimension_;
11✔
2775
  return 0;
11✔
2776
}
2777

2778
//! Set the dimension of a regular mesh
2779
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2780
  int32_t index, int n, const int* dims)
2781
{
2782
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2783
    return err;
2784
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2785

2786
  // Copy dimension
2787
  mesh->n_dimension_ = n;
187✔
2788
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2789
  return 0;
187✔
2790
}
2791

2792
//! Get the regular mesh parameters
2793
extern "C" int openmc_regular_mesh_get_params(
209✔
2794
  int32_t index, double** ll, double** ur, double** width, int* n)
2795
{
2796
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2797
    return err;
2798
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2799

2800
  if (m->lower_left_.empty()) {
209!
2801
    set_errmsg("Mesh parameters have not been set.");
×
2802
    return OPENMC_E_ALLOCATE;
×
2803
  }
2804

2805
  *ll = m->lower_left_.data();
209✔
2806
  *ur = m->upper_right_.data();
209✔
2807
  *width = m->width_.data();
209✔
2808
  *n = m->n_dimension_;
209✔
2809
  return 0;
209✔
2810
}
2811

2812
//! Set the regular mesh parameters
2813
extern "C" int openmc_regular_mesh_set_params(
220✔
2814
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2815
{
2816
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2817
    return err;
2818
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2819

2820
  if (m->n_dimension_ == -1) {
220!
2821
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2822
    return OPENMC_E_UNASSIGNED;
×
2823
  }
2824

2825
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2826
  if (ll && ur) {
220✔
2827
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2828
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2829
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2830
  } else if (ll && width) {
22✔
2831
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2832
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2833
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2834
  } else if (ur && width) {
11!
2835
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2836
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2837
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2838
  } else {
2839
    set_errmsg("At least two parameters must be specified.");
×
2840
    return OPENMC_E_INVALID_ARGUMENT;
×
2841
  }
2842

2843
  // Set material volumes
2844

2845
  // TODO: incorporate this into method in RegularMesh that can be called from
2846
  // here and from constructor
2847
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2848
  m->element_volume_ = 1.0;
220✔
2849
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2850
    m->element_volume_ *= m->width_[i];
660✔
2851
  }
2852

2853
  return 0;
2854
}
220✔
2855

2856
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2857
template<class C>
2858
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2859
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2860
  const int nz)
2861
{
2862
  if (int err = check_mesh_type<C>(index))
88!
2863
    return err;
2864

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

2867
  m->n_dimension_ = 3;
88✔
2868

2869
  m->grid_[0].reserve(nx);
88✔
2870
  m->grid_[1].reserve(ny);
88✔
2871
  m->grid_[2].reserve(nz);
88✔
2872

2873
  for (int i = 0; i < nx; i++) {
572✔
2874
    m->grid_[0].push_back(grid_x[i]);
484✔
2875
  }
2876
  for (int i = 0; i < ny; i++) {
341✔
2877
    m->grid_[1].push_back(grid_y[i]);
253✔
2878
  }
2879
  for (int i = 0; i < nz; i++) {
319✔
2880
    m->grid_[2].push_back(grid_z[i]);
231✔
2881
  }
2882

2883
  int err = m->set_grid();
88✔
2884
  return err;
88✔
2885
}
2886

2887
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2888
template<class C>
2889
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2890
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2891
{
2892
  if (int err = check_mesh_type<C>(index))
385!
2893
    return err;
2894
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2895

2896
  if (m->lower_left_.empty()) {
385!
2897
    set_errmsg("Mesh parameters have not been set.");
×
2898
    return OPENMC_E_ALLOCATE;
×
2899
  }
2900

2901
  *grid_x = m->grid_[0].data();
385✔
2902
  *nx = m->grid_[0].size();
385✔
2903
  *grid_y = m->grid_[1].data();
385✔
2904
  *ny = m->grid_[1].size();
385✔
2905
  *grid_z = m->grid_[2].data();
385✔
2906
  *nz = m->grid_[2].size();
385✔
2907

2908
  return 0;
385✔
2909
}
2910

2911
//! Get the rectilinear mesh grid
2912
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2913
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2914
{
2915
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2916
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2917
}
2918

2919
//! Set the rectilienar mesh parameters
2920
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2921
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2922
  const double* grid_z, const int nz)
2923
{
2924
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2925
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2926
}
2927

2928
//! Get the cylindrical mesh grid
2929
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2930
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2931
{
2932
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2933
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2934
}
2935

2936
//! Set the cylindrical mesh parameters
2937
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2938
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2939
  const double* grid_z, const int nz)
2940
{
2941
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2942
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2943
}
2944

2945
//! Get the spherical mesh grid
2946
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2947
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2948
{
2949

2950
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2951
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2952
  ;
121✔
2953
}
2954

2955
//! Set the spherical mesh parameters
2956
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2957
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2958
  const double* grid_z, const int nz)
2959
{
2960
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2961
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2962
}
2963

2964
#ifdef OPENMC_DAGMC_ENABLED
2965

2966
const std::string MOABMesh::mesh_lib_type = "moab";
2967

2968
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2969
{
2970
  initialize();
24✔
2971
}
24!
2972

2973
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2974
{
2975
  initialize();
×
2976
}
×
2977

2978
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2979
  : UnstructuredMesh()
×
2980
{
2981
  n_dimension_ = 3;
2982
  filename_ = filename;
×
2983
  set_length_multiplier(length_multiplier);
×
2984
  initialize();
×
2985
}
×
2986

2987
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2988
{
2989
  mbi_ = external_mbi;
1✔
2990
  filename_ = "unknown (external file)";
1✔
2991
  this->initialize();
1✔
2992
}
1!
2993

2994
void MOABMesh::initialize()
25✔
2995
{
2996

2997
  // Create the MOAB interface and load data from file
2998
  this->create_interface();
25✔
2999

3000
  // Initialise MOAB error code
3001
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
3002

3003
  // Set the dimension
3004
  n_dimension_ = 3;
25✔
3005

3006
  // set member range of tetrahedral entities
3007
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
3008
  if (rval != moab::MB_SUCCESS) {
25!
3009
    fatal_error("Failed to get all tetrahedral elements");
3010
  }
3011

3012
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
3013
    warning("Non-tetrahedral elements found in unstructured "
×
3014
            "mesh file: " +
3015
            filename_);
3016
  }
3017

3018
  // set member range of vertices
3019
  int vertex_dim = 0;
25✔
3020
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
3021
  if (rval != moab::MB_SUCCESS) {
25!
3022
    fatal_error("Failed to get all vertex handles");
3023
  }
3024

3025
  // make an entity set for all tetrahedra
3026
  // this is used for convenience later in output
3027
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
3028
  if (rval != moab::MB_SUCCESS) {
25!
3029
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3030
  }
3031

3032
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
3033
  if (rval != moab::MB_SUCCESS) {
25!
3034
    fatal_error("Failed to add tetrahedra to an entity set.");
3035
  }
3036

3037
  if (length_multiplier_ > 0.0) {
25!
3038
    // get the connectivity of all tets
3039
    moab::Range adj;
×
3040
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
3041
    if (rval != moab::MB_SUCCESS) {
×
3042
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3043
    }
3044
    // scale all vertex coords by multiplier (done individually so not all
3045
    // coordinates are in memory twice at once)
3046
    for (auto vert : adj) {
×
3047
      // retrieve coords
3048
      std::array<double, 3> coord;
3049
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
3050
      if (rval != moab::MB_SUCCESS) {
×
3051
        fatal_error("Could not get coordinates of vertex.");
3052
      }
3053
      // scale coords
3054
      for (auto& c : coord) {
×
3055
        c *= length_multiplier_;
3056
      }
3057
      // set new coords
3058
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
3059
      if (rval != moab::MB_SUCCESS) {
×
3060
        fatal_error("Failed to set new vertex coordinates");
3061
      }
3062
    }
3063
  }
3064

3065
  // Determine bounds of mesh
3066
  this->determine_bounds();
25✔
3067
}
25✔
3068

3069
void MOABMesh::prepare_for_point_location()
21✔
3070
{
3071
  // if the KDTree has already been constructed, do nothing
3072
  if (kdtree_)
21!
3073
    return;
3074

3075
  // build acceleration data structures
3076
  compute_barycentric_data(ehs_);
21✔
3077
  build_kdtree(ehs_);
21✔
3078
}
3079

3080
void MOABMesh::create_interface()
25✔
3081
{
3082
  // Do not create a MOAB instance if one is already in memory
3083
  if (mbi_)
25✔
3084
    return;
3085

3086
  // create MOAB instance
3087
  mbi_ = std::make_shared<moab::Core>();
24!
3088

3089
  // load unstructured mesh file
3090
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
3091
  if (rval != moab::MB_SUCCESS) {
24!
3092
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3093
  }
3094
}
3095

3096
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
3097
{
3098
  moab::Range all_tris;
21✔
3099
  int adj_dim = 2;
21✔
3100
  write_message("Getting tet adjacencies...", 7);
21✔
3101
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
3102
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3103
  if (rval != moab::MB_SUCCESS) {
21!
3104
    fatal_error("Failed to get adjacent triangles for tets");
3105
  }
3106

3107
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3108
    warning("Non-triangle elements found in tet adjacencies in "
×
3109
            "unstructured mesh file: " +
3110
            filename_);
×
3111
  }
3112

3113
  // combine into one range
3114
  moab::Range all_tets_and_tris;
21✔
3115
  all_tets_and_tris.merge(all_tets);
21✔
3116
  all_tets_and_tris.merge(all_tris);
21✔
3117

3118
  // create a kd-tree instance
3119
  write_message(
21✔
3120
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3121
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3122

3123
  // Determine what options to use
3124
  std::ostringstream options_stream;
21✔
3125
  if (options_.empty()) {
21✔
3126
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3127
  } else {
3128
    options_stream << options_;
16✔
3129
  }
3130
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3131

3132
  // Build the k-d tree
3133
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3134
  if (rval != moab::MB_SUCCESS) {
21!
3135
    fatal_error("Failed to construct KDTree for the "
3136
                "unstructured mesh file: " +
3137
                filename_);
×
3138
  }
3139
}
21✔
3140

3141
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3142
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3143
{
3144
  hits.clear();
1,543,584!
3145

3146
  moab::ErrorCode rval;
1,543,584✔
3147
  vector<moab::EntityHandle> tris;
1,543,584✔
3148
  // get all intersections with triangles in the tet mesh
3149
  // (distances are relative to the start point, not the previous
3150
  // intersection)
3151
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3152
    dir.array(), start.array(), tris, hits, 0, track_len);
3153
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3154
    fatal_error(
3155
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3156
  }
3157

3158
  // remove duplicate intersection distances
3159
  std::unique(hits.begin(), hits.end());
1,543,584✔
3160

3161
  // sorts by first component of std::pair by default
3162
  std::sort(hits.begin(), hits.end());
1,543,584✔
3163
}
1,543,584✔
3164

3165
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3166
  vector<int>& bins, vector<double>& lengths) const
3167
{
3168
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3169
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3170
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3171
  dir.normalize();
1,543,584✔
3172

3173
  double track_len = (end - start).length();
1,543,584✔
3174
  if (track_len == 0.0)
1,543,584!
3175
    return;
721,692✔
3176

3177
  start -= TINY_BIT * dir;
1,543,584✔
3178
  end += TINY_BIT * dir;
1,543,584✔
3179

3180
  vector<double> hits;
1,543,584✔
3181
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3182

3183
  bins.clear();
1,543,584!
3184
  lengths.clear();
1,543,584!
3185

3186
  // if there are no intersections the track may lie entirely
3187
  // within a single tet. If this is the case, apply entire
3188
  // score to that tet and return.
3189
  if (hits.size() == 0) {
1,543,584✔
3190
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3191
    int bin = this->get_bin(midpoint);
721,692✔
3192
    if (bin != -1) {
721,692✔
3193
      bins.push_back(bin);
242,866✔
3194
      lengths.push_back(1.0);
242,866✔
3195
    }
3196
    return;
721,692✔
3197
  }
3198

3199
  // for each segment in the set of tracks, try to look up a tet
3200
  // at the midpoint of the segment
3201
  Position current = r0;
3202
  double last_dist = 0.0;
3203
  for (const auto& hit : hits) {
5,516,161✔
3204
    // get the segment length
3205
    double segment_length = hit - last_dist;
4,694,269✔
3206
    last_dist = hit;
4,694,269✔
3207
    // find the midpoint of this segment
3208
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3209
    // try to find a tet for this position
3210
    int bin = this->get_bin(midpoint);
4,694,269✔
3211

3212
    // determine the start point for this segment
3213
    current = r0 + u * hit;
4,694,269✔
3214

3215
    if (bin == -1) {
4,694,269✔
3216
      continue;
20,522✔
3217
    }
3218

3219
    bins.push_back(bin);
4,673,747✔
3220
    lengths.push_back(segment_length / track_len);
4,673,747✔
3221
  }
3222

3223
  // tally remaining portion of track after last hit if
3224
  // the last segment of the track is in the mesh but doesn't
3225
  // reach the other side of the tet
3226
  if (hits.back() < track_len) {
821,892!
3227
    Position segment_start = r0 + u * hits.back();
821,892✔
3228
    double segment_length = track_len - hits.back();
821,892✔
3229
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3230
    int bin = this->get_bin(midpoint);
821,892✔
3231
    if (bin != -1) {
821,892✔
3232
      bins.push_back(bin);
766,509✔
3233
      lengths.push_back(segment_length / track_len);
766,509✔
3234
    }
3235
  }
3236
};
1,543,584✔
3237

3238
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3239
{
3240
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3241
  // find the leaf of the kd-tree for this position
3242
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3243
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3244
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3245
    return 0;
3246
  }
3247

3248
  // retrieve the tet elements of this leaf
3249
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3250
  moab::Range tets;
6,305,335✔
3251
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3252
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3253
    warning("MOAB error finding tets.");
×
3254
  }
3255

3256
  // loop over the tets in this leaf, returning the containing tet if found
3257
  for (const auto& tet : tets) {
260,211,273✔
3258
    if (point_in_tet(pos, tet)) {
260,208,426✔
3259
      return tet;
6,302,488✔
3260
    }
3261
  }
3262

3263
  // if no tet is found, return an invalid handle
3264
  return 0;
2,847✔
3265
}
14,634,464✔
3266

3267
double MOABMesh::volume(int bin) const
167,880✔
3268
{
3269
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3270
}
3271

3272
std::string MOABMesh::library() const
34✔
3273
{
3274
  return mesh_lib_type;
34✔
3275
}
3276

3277
// Sample position within a tet for MOAB type tets
3278
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3279
{
3280

3281
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3282

3283
  // Get vertex coordinates for MOAB tet
3284
  const moab::EntityHandle* conn1;
200,410✔
3285
  int conn1_size;
200,410✔
3286
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3287
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3288
    fatal_error(fmt::format(
3289
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3290
      conn1_size));
3291
  }
3292
  moab::CartVect p[4];
200,410✔
3293
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3294
  if (rval != moab::MB_SUCCESS) {
200,410!
3295
    fatal_error("Failed to get tet coords");
3296
  }
3297

3298
  std::array<Position, 4> tet_verts;
200,410✔
3299
  for (int i = 0; i < 4; i++) {
1,002,050✔
3300
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3301
  }
3302
  // Samples position within tet using Barycentric stuff
3303
  return this->sample_tet(tet_verts, seed);
200,410✔
3304
}
3305

3306
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3307
{
3308
  vector<moab::EntityHandle> conn;
167,880✔
3309
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3310
  if (rval != moab::MB_SUCCESS) {
167,880!
3311
    fatal_error("Failed to get tet connectivity");
3312
  }
3313

3314
  moab::CartVect p[4];
167,880✔
3315
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3316
  if (rval != moab::MB_SUCCESS) {
167,880!
3317
    fatal_error("Failed to get tet coords");
3318
  }
3319

3320
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3321
}
167,880✔
3322

3323
int MOABMesh::get_bin(Position r) const
7,317,232✔
3324
{
3325
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3326
  if (tet == 0) {
7,317,232✔
3327
    return -1;
3328
  } else {
3329
    return get_bin_from_ent_handle(tet);
6,302,488✔
3330
  }
3331
}
3332

3333
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3334
{
3335
  moab::ErrorCode rval;
21✔
3336

3337
  baryc_data_.clear();
21!
3338
  baryc_data_.resize(tets.size());
21✔
3339

3340
  // compute the barycentric data for each tet element
3341
  // and store it as a 3x3 matrix
3342
  for (auto& tet : tets) {
239,757✔
3343
    vector<moab::EntityHandle> verts;
239,736✔
3344
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3345
    if (rval != moab::MB_SUCCESS) {
239,736!
3346
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3347
    }
3348

3349
    moab::CartVect p[4];
239,736✔
3350
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3351
    if (rval != moab::MB_SUCCESS) {
239,736!
3352
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3353
    }
3354

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

3357
    // invert now to avoid this cost later
3358
    a = a.transpose().inverse();
239,736✔
3359
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3360
  }
239,736✔
3361
}
21✔
3362

3363
bool MOABMesh::point_in_tet(
260,208,426✔
3364
  const moab::CartVect& r, moab::EntityHandle tet) const
3365
{
3366

3367
  moab::ErrorCode rval;
260,208,426✔
3368

3369
  // get tet vertices
3370
  vector<moab::EntityHandle> verts;
260,208,426✔
3371
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3372
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3373
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3374
    return false;
3375
  }
3376

3377
  // first vertex is used as a reference point for the barycentric data -
3378
  // retrieve its coordinates
3379
  moab::CartVect p_zero;
260,208,426✔
3380
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3381
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3382
    warning("Failed to get coordinates of a vertex in "
×
3383
            "unstructured mesh: " +
3384
            filename_);
×
3385
    return false;
3386
  }
3387

3388
  // look up barycentric data
3389
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3390
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3391

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

3394
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3395
          bary_coords[2] >= 0.0 &&
318,957,185✔
3396
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3397
}
260,208,426✔
3398

3399
int MOABMesh::get_bin_from_index(int idx) const
3400
{
3401
  if (idx >= n_bins()) {
×
3402
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3403
  }
3404
  return ehs_[idx] - ehs_[0];
3405
}
3406

3407
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3408
{
3409
  int bin = get_bin(r);
3410
  *in_mesh = bin != -1;
3411
  return bin;
3412
}
3413

3414
int MOABMesh::get_index_from_bin(int bin) const
3415
{
3416
  return bin;
3417
}
3418

3419
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3420
  Position plot_ll, Position plot_ur) const
3421
{
3422
  // TODO: Implement mesh lines
3423
  return {};
3424
}
3425

3426
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3427
{
3428
  int idx = vert - verts_[0];
815,520✔
3429
  if (idx >= n_vertices()) {
815,520!
3430
    fatal_error(
3431
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3432
  }
3433
  return idx;
815,520✔
3434
}
3435

3436
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3437
{
3438
  int bin = eh - ehs_[0];
266,750,650✔
3439
  if (bin >= n_bins()) {
266,750,650!
3440
    fatal_error(fmt::format("Invalid bin: {}", bin));
3441
  }
3442
  return bin;
266,750,650✔
3443
}
3444

3445
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3446
{
3447
  if (bin >= n_bins()) {
572,170!
3448
    fatal_error(fmt::format("Invalid bin index: ", bin));
3449
  }
3450
  return ehs_[0] + bin;
572,170✔
3451
}
3452

3453
int MOABMesh::n_bins() const
267,526,773✔
3454
{
3455
  return ehs_.size();
267,526,773✔
3456
}
3457

3458
int MOABMesh::n_surface_bins() const
3459
{
3460
  // collect all triangles in the set of tets for this mesh
3461
  moab::Range tris;
×
3462
  moab::ErrorCode rval;
3463
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3464
  if (rval != moab::MB_SUCCESS) {
×
3465
    warning("Failed to get all triangles in the mesh instance");
×
3466
    return -1;
3467
  }
3468
  return 2 * tris.size();
×
3469
}
3470

3471
Position MOABMesh::centroid(int bin) const
3472
{
3473
  moab::ErrorCode rval;
3474

3475
  auto tet = this->get_ent_handle_from_bin(bin);
3476

3477
  // look up the tet connectivity
3478
  vector<moab::EntityHandle> conn;
×
3479
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3480
  if (rval != moab::MB_SUCCESS) {
×
3481
    warning("Failed to get connectivity of a mesh element.");
×
3482
    return {};
3483
  }
3484

3485
  // get the coordinates
3486
  vector<moab::CartVect> coords(conn.size());
×
3487
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3488
  if (rval != moab::MB_SUCCESS) {
×
3489
    warning("Failed to get the coordinates of a mesh element.");
×
3490
    return {};
3491
  }
3492

3493
  // compute the centroid of the element vertices
3494
  moab::CartVect centroid(0.0, 0.0, 0.0);
3495
  for (const auto& coord : coords) {
×
3496
    centroid += coord;
3497
  }
3498
  centroid /= double(coords.size());
3499

3500
  return {centroid[0], centroid[1], centroid[2]};
3501
}
3502

3503
int MOABMesh::n_vertices() const
845,874✔
3504
{
3505
  return verts_.size();
845,874✔
3506
}
3507

3508
Position MOABMesh::vertex(int id) const
86,227✔
3509
{
3510

3511
  moab::ErrorCode rval;
86,227✔
3512

3513
  moab::EntityHandle vert = verts_[id];
86,227✔
3514

3515
  moab::CartVect coords;
86,227✔
3516
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3517
  if (rval != moab::MB_SUCCESS) {
86,227!
3518
    fatal_error("Failed to get the coordinates of a vertex.");
3519
  }
3520

3521
  return {coords[0], coords[1], coords[2]};
86,227✔
3522
}
3523

3524
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3525
{
3526
  moab::ErrorCode rval;
203,880✔
3527

3528
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3529

3530
  // look up the tet connectivity
3531
  vector<moab::EntityHandle> conn;
203,880✔
3532
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3533
  if (rval != moab::MB_SUCCESS) {
203,880!
3534
    fatal_error("Failed to get connectivity of a mesh element.");
3535
    return {};
3536
  }
3537

3538
  std::vector<int> verts(4);
203,880✔
3539
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3540
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3541
  }
3542

3543
  return verts;
203,880✔
3544
}
203,880✔
3545

3546
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3547
  std::string score) const
3548
{
3549
  moab::ErrorCode rval;
3550
  // add a tag to the mesh
3551
  // all scores are treated as a single value
3552
  // with an uncertainty
3553
  moab::Tag value_tag;
3554

3555
  // create the value tag if not present and get handle
3556
  double default_val = 0.0;
3557
  auto val_string = score + "_mean";
3558
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3559
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3560
  if (rval != moab::MB_SUCCESS) {
×
3561
    auto msg =
3562
      fmt::format("Could not create or retrieve the value tag for the score {}"
3563
                  " on unstructured mesh {}",
3564
        score, id_);
×
3565
    fatal_error(msg);
3566
  }
3567

3568
  // create the std dev tag if not present and get handle
3569
  moab::Tag error_tag;
3570
  std::string err_string = score + "_std_dev";
×
3571
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3572
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3573
  if (rval != moab::MB_SUCCESS) {
×
3574
    auto msg =
3575
      fmt::format("Could not create or retrieve the error tag for the score {}"
3576
                  " on unstructured mesh {}",
3577
        score, id_);
×
3578
    fatal_error(msg);
3579
  }
3580

3581
  // return the populated tag handles
3582
  return {value_tag, error_tag};
3583
}
3584

3585
void MOABMesh::add_score(const std::string& score)
3586
{
3587
  auto score_tags = get_score_tags(score);
×
3588
  tag_names_.push_back(score);
3589
}
3590

3591
void MOABMesh::remove_scores()
3592
{
3593
  for (const auto& name : tag_names_) {
×
3594
    auto value_name = name + "_mean";
3595
    moab::Tag tag;
3596
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3597
    if (rval != moab::MB_SUCCESS)
×
3598
      return;
3599

3600
    rval = mbi_->tag_delete(tag);
×
3601
    if (rval != moab::MB_SUCCESS) {
×
3602
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3603
                             " on unstructured mesh {}",
3604
        name, id_);
×
3605
      fatal_error(msg);
3606
    }
3607

3608
    auto std_dev_name = name + "_std_dev";
×
3609
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3610
    if (rval != moab::MB_SUCCESS) {
×
3611
      auto msg =
3612
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3613
                    " on unstructured mesh {}",
3614
          name, id_);
×
3615
    }
3616

3617
    rval = mbi_->tag_delete(tag);
×
3618
    if (rval != moab::MB_SUCCESS) {
×
3619
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3620
                             " on unstructured mesh {}",
3621
        name, id_);
×
3622
      fatal_error(msg);
3623
    }
3624
  }
3625
  tag_names_.clear();
3626
}
3627

3628
void MOABMesh::set_score_data(const std::string& score,
3629
  const vector<double>& values, const vector<double>& std_dev)
3630
{
3631
  auto score_tags = this->get_score_tags(score);
×
3632

3633
  moab::ErrorCode rval;
3634
  // set the score value
3635
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3636
  if (rval != moab::MB_SUCCESS) {
×
3637
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3638
                           "on unstructured mesh {}",
3639
      score, id_);
3640
    warning(msg);
×
3641
  }
3642

3643
  // set the error value
3644
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3645
  if (rval != moab::MB_SUCCESS) {
×
3646
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3647
                           "on unstructured mesh {}",
3648
      score, id_);
3649
    warning(msg);
×
3650
  }
3651
}
3652

3653
void MOABMesh::write(const std::string& base_filename) const
3654
{
3655
  // add extension to the base name
3656
  auto filename = base_filename + ".vtk";
3657
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3658
  filename = settings::path_output + filename;
×
3659

3660
  // write the tetrahedral elements of the mesh only
3661
  // to avoid clutter from zero-value data on other
3662
  // elements during visualization
3663
  moab::ErrorCode rval;
3664
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3665
  if (rval != moab::MB_SUCCESS) {
×
3666
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3667
    warning(msg);
×
3668
  }
3669
}
3670

3671
#endif
3672

3673
#ifdef OPENMC_LIBMESH_ENABLED
3674

3675
const std::string LibMesh::mesh_lib_type = "libmesh";
3676

3677
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3678
{
3679
  // filename_ and length_multiplier_ will already be set by the
3680
  // UnstructuredMesh constructor
3681
  set_mesh_pointer_from_filename(filename_);
25✔
3682
  set_length_multiplier(length_multiplier_);
25✔
3683
  initialize();
25✔
3684
}
25✔
3685

3686
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3687
{
3688
  // filename_ and length_multiplier_ will already be set by the
3689
  // UnstructuredMesh constructor
3690
  set_mesh_pointer_from_filename(filename_);
×
3691
  set_length_multiplier(length_multiplier_);
×
3692
  initialize();
×
3693
}
3694

3695
// create the mesh from a pointer to a libMesh Mesh
3696
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3697
{
3698
  if (!input_mesh.is_replicated()) {
×
3699
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3700
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3701
  }
3702

3703
  m_ = &input_mesh;
3704
  set_length_multiplier(length_multiplier);
×
3705
  initialize();
×
3706
}
3707

3708
// create the mesh from an input file
3709
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3710
{
3711
  n_dimension_ = 3;
3712
  set_mesh_pointer_from_filename(filename);
×
3713
  set_length_multiplier(length_multiplier);
×
3714
  initialize();
×
3715
}
3716

3717
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3718
{
3719
  filename_ = filename;
25✔
3720
  unique_m_ =
25✔
3721
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3722
  m_ = unique_m_.get();
25✔
3723
  m_->read(filename_);
25✔
3724
}
25✔
3725

3726
// build a libMesh equation system for storing values
3727
void LibMesh::build_eqn_sys()
17✔
3728
{
3729
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3730
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3731
  libMesh::ExplicitSystem& eq_sys =
17✔
3732
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3733
}
17✔
3734

3735
// intialize from mesh file
3736
void LibMesh::initialize()
25✔
3737
{
3738
  if (!settings::libmesh_comm) {
25!
3739
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3740
                "communicator.");
3741
  }
3742

3743
  // assuming that unstructured meshes used in OpenMC are 3D
3744
  n_dimension_ = 3;
25✔
3745

3746
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3747
  // Otherwise assume that it is prepared by its owning application
3748
  if (unique_m_) {
25!
3749
    m_->prepare_for_use();
25✔
3750
  }
3751

3752
  // ensure that the loaded mesh is 3 dimensional
3753
  if (m_->mesh_dimension() != n_dimension_) {
25!
3754
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3755
                            "mesh is not a 3D mesh.",
3756
      filename_));
3757
  }
3758

3759
  for (int i = 0; i < num_threads(); i++) {
69✔
3760
    pl_.emplace_back(m_->sub_point_locator());
44✔
3761
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
44✔
3762
    pl_.back()->enable_out_of_mesh_mode();
44✔
3763
  }
3764

3765
  // store first element in the mesh to use as an offset for bin indices
3766
  auto first_elem = *m_->elements_begin();
50✔
3767
  first_element_id_ = first_elem->id();
25✔
3768

3769
  // bounding box for the mesh for quick rejection checks
3770
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3771
  libMesh::Point ll = bbox_.min();
25!
3772
  libMesh::Point ur = bbox_.max();
25!
3773
  if (length_multiplier_ > 0.0) {
25!
3774
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3775
      length_multiplier_ * ll(2)};
3776
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3777
      length_multiplier_ * ur(2)};
3778
  } else {
3779
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3780
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3781
  }
3782
}
25✔
3783

3784
// Sample position within a tet for LibMesh type tets
3785
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3786
{
3787
  const auto& elem = get_element_from_bin(bin);
400,820✔
3788
  // Get tet vertex coordinates from LibMesh
3789
  std::array<Position, 4> tet_verts;
400,820✔
3790
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3791
    const auto& node_ref = elem.node_ref(i);
1,603,280✔
3792
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3793
  }
3794
  // Samples position within tet using Barycentric coordinates
3795
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3796
  if (length_multiplier_ > 0.0) {
400,820!
3797
    return length_multiplier_ * sampled_position;
3798
  } else {
3799
    return sampled_position;
400,820✔
3800
  }
3801
}
3802

3803
Position LibMesh::centroid(int bin) const
3804
{
3805
  const auto& elem = this->get_element_from_bin(bin);
3806
  auto centroid = elem.vertex_average();
3807
  if (length_multiplier_ > 0.0) {
×
3808
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3809
  } else {
3810
    return {centroid(0), centroid(1), centroid(2)};
3811
  }
3812
}
3813

3814
int LibMesh::n_vertices() const
42,644✔
3815
{
3816
  return m_->n_nodes();
42,644✔
3817
}
3818

3819
Position LibMesh::vertex(int vertex_id) const
42,604✔
3820
{
3821
  const auto& node_ref = m_->node_ref(vertex_id);
42,604✔
3822
  if (length_multiplier_ > 0.0) {
42,604!
3823
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3824
  } else {
3825
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3826
  }
3827
}
3828

3829
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3830
{
3831
  std::vector<int> conn;
267,856✔
3832
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3833
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3834
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3835
  }
3836
  return conn;
267,856✔
3837
}
3838

3839
std::string LibMesh::library() const
37✔
3840
{
3841
  return mesh_lib_type;
37✔
3842
}
3843

3844
int LibMesh::n_bins() const
1,788,419✔
3845
{
3846
  return m_->n_elem();
1,788,419✔
3847
}
3848

3849
int LibMesh::n_surface_bins() const
3850
{
3851
  int n_bins = 0;
3852
  for (int i = 0; i < this->n_bins(); i++) {
×
3853
    const libMesh::Elem& e = get_element_from_bin(i);
3854
    n_bins += e.n_faces();
3855
    // if this is a boundary element, it will only be visited once,
3856
    // the number of surface bins is incremented to
3857
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3858
      // null neighbor pointer indicates a boundary face
3859
      if (!neighbor_ptr) {
×
3860
        n_bins++;
3861
      }
3862
    }
3863
  }
3864
  return n_bins;
3865
}
3866

3867
void LibMesh::add_score(const std::string& var_name)
17✔
3868
{
3869
  if (!equation_systems_) {
17!
3870
    build_eqn_sys();
17✔
3871
  }
3872

3873
  // check if this is a new variable
3874
  std::string value_name = var_name + "_mean";
17✔
3875
  if (!variable_map_.count(value_name)) {
17✔
3876
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3877
    auto var_num =
17✔
3878
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3879
    variable_map_[value_name] = var_num;
17✔
3880
  }
3881

3882
  std::string std_dev_name = var_name + "_std_dev";
17✔
3883
  // check if this is a new variable
3884
  if (!variable_map_.count(std_dev_name)) {
17✔
3885
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3886
    auto var_num =
17✔
3887
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3888
    variable_map_[std_dev_name] = var_num;
17✔
3889
  }
3890
}
17✔
3891

3892
void LibMesh::remove_scores()
17✔
3893
{
3894
  if (equation_systems_) {
17!
3895
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3896
    eqn_sys.clear();
17✔
3897
    variable_map_.clear();
17✔
3898
  }
3899
}
17✔
3900

3901
void LibMesh::set_score_data(const std::string& var_name,
17✔
3902
  const vector<double>& values, const vector<double>& std_dev)
3903
{
3904
  if (!equation_systems_) {
17!
3905
    build_eqn_sys();
3906
  }
3907

3908
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3909

3910
  if (!eqn_sys.is_initialized()) {
17!
3911
    equation_systems_->init();
17✔
3912
  }
3913

3914
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3915

3916
  // look up the value variable
3917
  std::string value_name = var_name + "_mean";
17✔
3918
  unsigned int value_num = variable_map_.at(value_name);
17✔
3919
  // look up the std dev variable
3920
  std::string std_dev_name = var_name + "_std_dev";
17✔
3921
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3922

3923
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3924
       it++) {
3925
    if (!(*it)->active()) {
99,856!
3926
      continue;
3927
    }
3928

3929
    auto bin = get_bin_from_element(*it);
99,856✔
3930

3931
    // set value
3932
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3933
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3934
    assert(value_dof_indices.size() == 1);
99,856✔
3935
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3936

3937
    // set std dev
3938
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3939
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3940
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3941
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3942
  }
99,873✔
3943
}
17✔
3944

3945
void LibMesh::write(const std::string& filename) const
17✔
3946
{
3947
  write_message(fmt::format(
17✔
3948
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3949
  libMesh::ExodusII_IO exo(*m_);
17✔
3950
  std::set<std::string> systems_out = {eq_system_name_};
34!
3951
  exo.write_discontinuous_exodusII(
17✔
3952
    filename + ".e", *equation_systems_, &systems_out);
34✔
3953
}
17✔
3954

3955
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3956
  vector<int>& bins, vector<double>& lengths) const
3957
{
3958
  // TODO: Implement triangle crossings here
3959
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3960
}
3961

3962
int LibMesh::get_bin(Position r) const
2,340,604✔
3963
{
3964
  // look-up a tet using the point locator
3965
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3966

3967
  if (length_multiplier_ > 0.0) {
2,340,604!
3968
    // Scale the point down
3969
    p /= length_multiplier_;
2,340,604✔
3970
  }
3971

3972
  // quick rejection check
3973
  if (!bbox_.contains_point(p)) {
2,340,604✔
3974
    return -1;
3975
  }
3976

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

3979
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3980
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3981
}
2,340,604✔
3982

3983
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3984
{
3985
  int bin = elem->id() - first_element_id_;
1,520,434✔
3986
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3987
    fatal_error(fmt::format("Invalid bin: {}", bin));
3988
  }
3989
  return bin;
1,520,434✔
3990
}
3991

3992
std::pair<vector<double>, vector<double>> LibMesh::plot(
3993
  Position plot_ll, Position plot_ur) const
3994
{
3995
  return {};
3996
}
3997

3998
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3999
{
4000
  return m_->elem_ref(bin);
769,460✔
4001
}
4002

4003
double LibMesh::volume(int bin) const
368,640✔
4004
{
4005
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
4006
         length_multiplier_ * length_multiplier_;
368,640✔
4007
}
4008

4009
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4010
  double length_multiplier,
4011
  const std::set<libMesh::subdomain_id_type>& block_ids)
4012
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4013
    block_restrict_(!block_ids_.empty()),
×
4014
    num_active_(
×
4015
      block_restrict_
4016
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
4017
            m_->active_subdomain_set_elements_end(block_ids_))
×
4018
        : m_->n_active_elem())
×
4019
{
4020
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4021
  // contiguous in ID space, so we need to map from bin indices (defined over
4022
  // active elements) to global dof ids
4023
  bin_to_elem_map_.reserve(num_active_);
×
4024
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
4025
  auto begin = block_restrict_
4026
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
4027
                 : m_->active_elements_begin();
×
4028
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
4029
                             : m_->active_elements_end();
×
4030
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
4031
    bin_to_elem_map_.push_back(elem->id());
×
4032
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
4033
  }
4034
}
4035

4036
int AdaptiveLibMesh::n_bins() const
4037
{
4038
  return num_active_;
4039
}
4040

4041
void AdaptiveLibMesh::add_score(const std::string& var_name)
4042
{
4043
  warning(fmt::format(
×
4044
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4045
    this->id_));
4046
}
4047

4048
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4049
  const vector<double>& values, const vector<double>& std_dev)
4050
{
4051
  warning(fmt::format(
×
4052
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4053
    this->id_));
4054
}
4055

4056
void AdaptiveLibMesh::write(const std::string& filename) const
4057
{
4058
  warning(fmt::format(
×
4059
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4060
    this->id_));
4061
}
4062

4063
int AdaptiveLibMesh::get_bin(Position r) const
4064
{
4065
  // look-up a tet using the point locator
4066
  libMesh::Point p(r.x, r.y, r.z);
×
4067

4068
  if (length_multiplier_ > 0.0) {
×
4069
    // Scale the point down
4070
    p /= length_multiplier_;
4071
  }
4072

4073
  // quick rejection check
4074
  if (!bbox_.contains_point(p)) {
×
4075
    return -1;
4076
  }
4077

4078
  const auto& point_locator = pl_.at(thread_num());
×
4079

4080
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4081
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4082
}
4083

4084
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4085
{
4086
  int bin = elem_to_bin_map_[elem->id()];
4087
  if (bin >= n_bins() || bin < 0) {
×
4088
    fatal_error(fmt::format("Invalid bin: {}", bin));
4089
  }
4090
  return bin;
4091
}
4092

4093
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4094
{
4095
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4096
}
4097

4098
#endif // OPENMC_LIBMESH_ENABLED
4099

4100
//==============================================================================
4101
// Non-member functions
4102
//==============================================================================
4103

4104
void read_meshes(pugi::xml_node root)
14,071✔
4105
{
4106
  std::unordered_set<int> mesh_ids;
14,071✔
4107

4108
  for (auto node : root.children("mesh")) {
17,509✔
4109
    // Check to make sure multiple meshes in the same file don't share IDs
4110
    int id = std::stoi(get_node_value(node, "id"));
6,876✔
4111
    if (contains(mesh_ids, id)) {
6,876!
4112
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4113
                              "'{}' in the same input file",
4114
        id));
4115
    }
4116
    mesh_ids.insert(id);
3,438✔
4117

4118
    // If we've already read a mesh with the same ID in a *different* file,
4119
    // assume it is the same here
4120
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,438!
4121
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4122
      continue;
×
4123
    }
4124

4125
    std::string mesh_type;
3,438✔
4126
    if (check_for_node(node, "type")) {
3,438✔
4127
      mesh_type = get_node_value(node, "type", true, true);
983✔
4128
    } else {
4129
      mesh_type = "regular";
2,455✔
4130
    }
4131

4132
    // determine the mesh library to use
4133
    std::string mesh_lib;
3,438✔
4134
    if (check_for_node(node, "library")) {
3,438✔
4135
      mesh_lib = get_node_value(node, "library", true, true);
49!
4136
    }
4137

4138
    Mesh::create(node, mesh_type, mesh_lib);
3,438✔
4139
  }
3,438✔
4140
}
14,071✔
4141

4142
void read_meshes(hid_t group)
48✔
4143
{
4144
  std::unordered_set<int> mesh_ids;
48✔
4145

4146
  std::vector<int> ids;
48✔
4147
  read_attribute(group, "ids", ids);
48✔
4148

4149
  for (auto id : ids) {
107✔
4150

4151
    // Check to make sure multiple meshes in the same file don't share IDs
4152
    if (contains(mesh_ids, id)) {
118!
4153
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4154
                              "'{}' in the same HDF5 input file",
4155
        id));
4156
    }
4157
    mesh_ids.insert(id);
59✔
4158

4159
    // If we've already read a mesh with the same ID in a *different* file,
4160
    // assume it is the same here
4161
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
59✔
4162
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4163
      continue;
33✔
4164
    }
4165

4166
    std::string name = fmt::format("mesh {}", id);
26✔
4167
    hid_t mesh_group = open_group(group, name.c_str());
26✔
4168

4169
    std::string mesh_type;
26✔
4170
    if (object_exists(mesh_group, "type")) {
26!
4171
      read_dataset(mesh_group, "type", mesh_type);
26✔
4172
    } else {
4173
      mesh_type = "regular";
×
4174
    }
4175

4176
    // determine the mesh library to use
4177
    std::string mesh_lib;
26✔
4178
    if (object_exists(mesh_group, "library")) {
26!
4179
      read_dataset(mesh_group, "library", mesh_lib);
×
4180
    }
4181

4182
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26✔
4183
  }
26✔
4184
}
96✔
4185

4186
void meshes_to_hdf5(hid_t group)
7,899✔
4187
{
4188
  // Write number of meshes
4189
  hid_t meshes_group = create_group(group, "meshes");
7,899✔
4190
  int32_t n_meshes = model::meshes.size();
7,899✔
4191
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,899✔
4192

4193
  if (n_meshes > 0) {
7,899✔
4194
    // Write IDs of meshes
4195
    vector<int> ids;
2,436✔
4196
    for (const auto& m : model::meshes) {
5,616✔
4197
      m->to_hdf5(meshes_group);
3,180✔
4198
      ids.push_back(m->id_);
3,180✔
4199
    }
4200
    write_attribute(meshes_group, "ids", ids);
2,436✔
4201
  }
2,436✔
4202

4203
  close_group(meshes_group);
7,899✔
4204
}
7,899✔
4205

4206
void free_memory_mesh()
9,181✔
4207
{
4208
  model::meshes.clear();
9,181✔
4209
  model::mesh_map.clear();
9,181✔
4210
}
9,181✔
4211

4212
extern "C" int n_meshes()
308✔
4213
{
4214
  return model::meshes.size();
308✔
4215
}
4216

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

© 2026 Coveralls, Inc