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

openmc-dev / openmc / 20326539317

18 Dec 2025 04:58AM UTC coverage: 82.144% (-0.005%) from 82.149%
20326539317

Pull #3176

github

web-flow
Merge bc4128efd into e0eb91b95
Pull Request #3176: Support rotation in MeshFilter

17039 of 23619 branches covered (72.14%)

Branch coverage included in aggregate %.

90 of 103 new or added lines in 5 files covered. (87.38%)

285 existing lines in 4 files now uncovered.

55201 of 64324 relevant lines covered (85.82%)

43414542.85 hits per line

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

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

9
#ifdef _MSC_VER
10
#include <intrin.h> // for _InterlockedCompareExchange
11
#endif
12

13
#ifdef OPENMC_MPI
14
#include "mpi.h"
15
#endif
16

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

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

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

57
#ifdef OPENMC_DAGMC_ENABLED
58
#include "moab/FileOptions.hpp"
59
#endif
60

61
namespace openmc {
62

63
//==============================================================================
64
// Global variables
65
//==============================================================================
66

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

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

77
namespace model {
78

79
std::unordered_map<int32_t, int32_t> mesh_map;
80
vector<unique_ptr<Mesh>> meshes;
81

82
} // namespace model
83

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

91
//==============================================================================
92
// Helper functions
93
//==============================================================================
94

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

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

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

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

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

143
namespace detail {
144

145
//==============================================================================
146
// MaterialVolumes implementation
147
//==============================================================================
148

149
void MaterialVolumes::add_volume(
2,801,403✔
150
  int index_elem, int index_material, double volume)
151
{
152
  // This method handles adding elements to the materials hash table,
153
  // implementing open addressing with linear probing. Consistency across
154
  // multiple threads is handled by with an atomic compare-and-swap operation.
155
  // Ideally, we would use #pragma omp atomic compare, but it was introduced in
156
  // OpenMP 5.1 and is not widely supported yet.
157

158
  // Loop for linear probing
159
  for (int attempt = 0; attempt < table_size_; ++attempt) {
2,807,089!
160
    // Determine slot to check, making sure it is positive
161
    int slot = (index_material + attempt) % table_size_;
2,807,089✔
162
    if (slot < 0)
2,807,089✔
163
      slot += table_size_;
208,978✔
164
    int32_t* slot_ptr = &this->materials(index_elem, slot);
2,807,089✔
165

166
    // Non-atomic read of current material
167
    int32_t current_val = *slot_ptr;
2,807,089✔
168

169
    // Found the desired material; accumulate volume
170
    if (current_val == index_material) {
2,807,089✔
171
#pragma omp atomic
1,527,713✔
172
      this->volumes(index_elem, slot) += volume;
2,799,979✔
173
      return;
2,799,979✔
174
    }
175

176
    // Slot appears to be empty; attempt to claim
177
    if (current_val == EMPTY) {
7,110✔
178
      // Attempt compare-and-swap from EMPTY to index_material
179
      int32_t expected_val = EMPTY;
1,424✔
180
      bool claimed_slot =
181
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,424✔
182

183
      // If we claimed the slot or another thread claimed it but the same
184
      // material was inserted, proceed to accumulate
185
      if (claimed_slot || (expected_val == index_material)) {
1,424!
186
#pragma omp atomic
789✔
187
        this->volumes(index_elem, slot) += volume;
1,424✔
188
        return;
1,424✔
189
      }
190
    }
191
  }
192

193
  // If table is full, set a flag that can be checked later
UNCOV
194
  table_full_ = true;
×
195
}
196

UNCOV
197
void MaterialVolumes::add_volume_unsafe(
×
198
  int index_elem, int index_material, double volume)
199
{
200
  // Linear probe
UNCOV
201
  for (int attempt = 0; attempt < table_size_; ++attempt) {
×
202
    // Determine slot to check, making sure it is positive
203
    int slot = (index_material + attempt) % table_size_;
×
204
    if (slot < 0)
×
UNCOV
205
      slot += table_size_;
×
206

207
    // Read current material
UNCOV
208
    int32_t current_val = this->materials(index_elem, slot);
×
209

210
    // Found the desired material; accumulate volume
211
    if (current_val == index_material) {
×
212
      this->volumes(index_elem, slot) += volume;
×
UNCOV
213
      return;
×
214
    }
215

216
    // Claim empty slot
217
    if (current_val == EMPTY) {
×
218
      this->materials(index_elem, slot) = index_material;
×
219
      this->volumes(index_elem, slot) += volume;
×
UNCOV
220
      return;
×
221
    }
222
  }
223

224
  // If table is full, set a flag that can be checked later
UNCOV
225
  table_full_ = true;
×
226
}
227

228
} // namespace detail
229

230
//==============================================================================
231
// Mesh implementation
232
//==============================================================================
233

234
template<typename T>
235
const std::unique_ptr<Mesh>& Mesh::create(
2,875✔
236
  T dataset, const std::string& mesh_type, const std::string& mesh_library)
237
{
238
  // Determine mesh type. Add to model vector and map
239
  if (mesh_type == RegularMesh::mesh_type) {
2,875✔
240
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
1,989!
241
  } else if (mesh_type == RectilinearMesh::mesh_type) {
886✔
242
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
114!
243
  } else if (mesh_type == CylindricalMesh::mesh_type) {
772✔
244
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
390!
245
  } else if (mesh_type == SphericalMesh::mesh_type) {
382✔
246
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
335!
247
#ifdef OPENMC_DAGMC_ENABLED
248
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
48!
249
             mesh_library == MOABMesh::mesh_lib_type) {
24✔
250
    model::meshes.push_back(make_unique<MOABMesh>(dataset));
24!
251
#endif
252
#ifdef OPENMC_LIBMESH_ENABLED
253
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
46!
254
             mesh_library == LibMesh::mesh_lib_type) {
23✔
255
    model::meshes.push_back(make_unique<LibMesh>(dataset));
23!
256
#endif
257
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
UNCOV
258
    fatal_error("Unstructured mesh support is not enabled or the mesh "
×
259
                "library is invalid.");
260
  } else {
UNCOV
261
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
262
  }
263

264
  // Map ID to position in vector
265
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
2,875✔
266

267
  return model::meshes.back();
2,875✔
268
}
269

270
Mesh::Mesh(pugi::xml_node node)
2,919✔
271
{
272
  // Read mesh id
273
  id_ = std::stoi(get_node_value(node, "id"));
2,919✔
274
  if (check_for_node(node, "name"))
2,919✔
275
    name_ = get_node_value(node, "name");
16✔
276
}
2,919✔
277

278
Mesh::Mesh(hid_t group)
44✔
279
{
280
  // Read mesh ID
281
  read_attribute(group, "id", id_);
44✔
282

283
  // Read mesh name
284
  if (object_exists(group, "name")) {
44!
UNCOV
285
    read_dataset(group, "name", name_);
×
286
  }
287
}
44✔
288

289
void Mesh::set_id(int32_t id)
23✔
290
{
291
  assert(id >= 0 || id == C_NONE);
19!
292

293
  // Clear entry in mesh map in case one was already assigned
294
  if (id_ != C_NONE) {
23✔
295
    model::mesh_map.erase(id_);
22✔
296
    id_ = C_NONE;
22✔
297
  }
298

299
  // Ensure no other mesh has the same ID
300
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
23!
301
    throw std::runtime_error {
×
UNCOV
302
      fmt::format("Two meshes have the same ID: {}", id)};
×
303
  }
304

305
  // If no ID is specified, auto-assign the next ID in the sequence
306
  if (id == C_NONE) {
23✔
307
    id = 0;
1✔
308
    for (const auto& m : model::meshes) {
3✔
309
      id = std::max(id, m->id_);
2✔
310
    }
311
    ++id;
1✔
312
  }
313

314
  // Update ID and entry in the mesh map
315
  id_ = id;
23✔
316

317
  // find the index of this mesh in the model::meshes vector
318
  // (search in reverse because this mesh was likely just added to the vector)
319
  auto it = std::find_if(model::meshes.rbegin(), model::meshes.rend(),
23✔
320
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
80✔
321

322
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
23✔
323
}
23✔
324

325
vector<double> Mesh::volumes() const
252✔
326
{
327
  vector<double> volumes(n_bins());
252✔
328
  for (int i = 0; i < n_bins(); i++) {
1,125,127✔
329
    volumes[i] = this->volume(i);
1,124,875✔
330
  }
331
  return volumes;
252✔
UNCOV
332
}
×
333

334
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
176✔
335
  int32_t* materials, double* volumes) const
336
{
337
  if (mpi::master) {
176!
338
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
176✔
339
  }
340
  write_message(7, "Number of mesh elements = {}", n_bins());
176✔
341
  write_message(7, "Number of rays (x) = {}", nx);
176✔
342
  write_message(7, "Number of rays (y) = {}", ny);
176✔
343
  write_message(7, "Number of rays (z) = {}", nz);
176✔
344
  int64_t n_total = static_cast<int64_t>(nx) * ny +
176✔
345
                    static_cast<int64_t>(ny) * nz +
176✔
346
                    static_cast<int64_t>(nx) * nz;
176✔
347
  write_message(7, "Total number of rays = {}", n_total);
176✔
348
  write_message(7, "Table size per mesh element = {}", table_size);
176✔
349

350
  Timer timer;
176✔
351
  timer.start();
176✔
352

353
  // Create object for keeping track of materials/volumes
354
  detail::MaterialVolumes result(materials, volumes, table_size);
176✔
355

356
  // Determine bounding box
357
  auto bbox = this->bounding_box();
176✔
358

359
  std::array<int, 3> n_rays = {nx, ny, nz};
176✔
360

361
  // Determine effective width of rays
362
  Position width((nx > 0) ? (bbox.xmax - bbox.xmin) / nx : 0.0,
319✔
363
    (ny > 0) ? (bbox.ymax - bbox.ymin) / ny : 0.0,
341✔
364
    (nz > 0) ? (bbox.zmax - bbox.zmin) / nz : 0.0);
176✔
365

366
  // Set flag for mesh being contained within model
367
  bool out_of_model = false;
176✔
368

369
#pragma omp parallel
96✔
370
  {
371
    // Preallocate vector for mesh indices and length fractions and particle
372
    std::vector<int> bins;
80✔
373
    std::vector<double> length_fractions;
80✔
374
    Particle p;
80✔
375

376
    SourceSite site;
80✔
377
    site.E = 1.0;
80✔
378
    site.particle = ParticleType::neutron;
80✔
379

380
    for (int axis = 0; axis < 3; ++axis) {
320✔
381
      // Set starting position and direction
382
      site.r = {0.0, 0.0, 0.0};
240✔
383
      site.r[axis] = bbox.min()[axis];
240✔
384
      site.u = {0.0, 0.0, 0.0};
240✔
385
      site.u[axis] = 1.0;
240✔
386

387
      // Determine width of rays and number of rays in other directions
388
      int ax1 = (axis + 1) % 3;
240✔
389
      int ax2 = (axis + 2) % 3;
240✔
390
      double min1 = bbox.min()[ax1];
240✔
391
      double min2 = bbox.min()[ax2];
240✔
392
      double d1 = width[ax1];
240✔
393
      double d2 = width[ax2];
240✔
394
      int n1 = n_rays[ax1];
240✔
395
      int n2 = n_rays[ax2];
240✔
396
      if (n1 == 0 || n2 == 0) {
240✔
397
        continue;
60✔
398
      }
399

400
      // Divide rays in first direction over MPI processes by computing starting
401
      // and ending indices
402
      int min_work = n1 / mpi::n_procs;
180✔
403
      int remainder = n1 % mpi::n_procs;
180✔
404
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
180!
405
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
180✔
406
      int i1_end = i1_start + n1_local;
180✔
407

408
      // Loop over rays on face of bounding box
409
#pragma omp for collapse(2)
410
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
9,785✔
411
        for (int i2 = 0; i2 < n2; ++i2) {
572,340✔
412
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
562,735✔
413
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
562,735✔
414

415
          p.from_source(&site);
562,735✔
416

417
          // Determine particle's location
418
          if (!exhaustive_find_cell(p)) {
562,735✔
419
            out_of_model = true;
39,930✔
420
            continue;
39,930✔
421
          }
422

423
          // Set birth cell attribute
424
          if (p.cell_born() == C_NONE)
522,805!
425
            p.cell_born() = p.lowest_coord().cell();
522,805✔
426

427
          // Initialize last cells from current cell
428
          for (int j = 0; j < p.n_coord(); ++j) {
1,045,610✔
429
            p.cell_last(j) = p.coord(j).cell();
522,805✔
430
          }
431
          p.n_coord_last() = p.n_coord();
522,805✔
432

433
          while (true) {
434
            // Ray trace from r_start to r_end
435
            Position r0 = p.r();
1,054,715✔
436
            double max_distance = bbox.max()[axis] - r0[axis];
1,054,715✔
437

438
            // Find the distance to the nearest boundary
439
            BoundaryInfo boundary = distance_to_boundary(p);
1,054,715✔
440

441
            // Advance particle forward
442
            double distance = std::min(boundary.distance(), max_distance);
1,054,715✔
443
            p.move_distance(distance);
1,054,715✔
444

445
            // Determine what mesh elements were crossed by particle
446
            bins.clear();
1,054,715✔
447
            length_fractions.clear();
1,054,715✔
448
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
1,054,715✔
449

450
            // Add volumes to any mesh elements that were crossed
451
            int i_material = p.material();
1,054,715✔
452
            if (i_material != C_NONE) {
1,054,715✔
453
              i_material = model::materials[i_material]->id();
949,025✔
454
            }
455
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,328,080✔
456
              int mesh_index = bins[i_bin];
1,273,365✔
457
              double length = distance * length_fractions[i_bin];
1,273,365✔
458

459
              // Add volume to result
460
              result.add_volume(mesh_index, i_material, length * d1 * d2);
1,273,365✔
461
            }
462

463
            if (distance == max_distance)
1,054,715✔
464
              break;
522,805✔
465

466
            // cross next geometric surface
467
            for (int j = 0; j < p.n_coord(); ++j) {
1,063,820✔
468
              p.cell_last(j) = p.coord(j).cell();
531,910✔
469
            }
470
            p.n_coord_last() = p.n_coord();
531,910✔
471

472
            // Set surface that particle is on and adjust coordinate levels
473
            p.surface() = boundary.surface();
531,910✔
474
            p.n_coord() = boundary.coord_level();
531,910✔
475

476
            if (boundary.lattice_translation()[0] != 0 ||
531,910✔
477
                boundary.lattice_translation()[1] != 0 ||
1,063,820!
478
                boundary.lattice_translation()[2] != 0) {
531,910!
479
              // Particle crosses lattice boundary
480
              cross_lattice(p, boundary);
×
481
            } else {
482
              // Particle crosses surface
483
              const auto& surf {model::surfaces[p.surface_index()].get()};
531,910✔
484
              p.cross_surface(*surf);
531,910✔
485
            }
486
          }
531,910✔
487
        }
488
      }
489
    }
490
  }
80✔
491

492
  // Check for errors
493
  if (out_of_model) {
176✔
494
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
495
  } else if (result.table_full()) {
165!
496
    throw std::runtime_error("Maximum number of materials for mesh material "
×
UNCOV
497
                             "volume calculation insufficient.");
×
498
  }
499

500
  // Compute time for raytracing
501
  double t_raytrace = timer.elapsed();
165✔
502

503
#ifdef OPENMC_MPI
504
  // Combine results from multiple MPI processes
505
  if (mpi::n_procs > 1) {
75!
506
    int total = this->n_bins() * table_size;
×
507
    if (mpi::master) {
×
508
      // Allocate temporary buffer for receiving data
509
      std::vector<int32_t> mats(total);
×
510
      std::vector<double> vols(total);
×
511

512
      for (int i = 1; i < mpi::n_procs; ++i) {
×
513
        // Receive material indices and volumes from process i
514
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
515
          MPI_STATUS_IGNORE);
516
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
517
          MPI_STATUS_IGNORE);
518

519
        // Combine with existing results; we can call thread unsafe version of
520
        // add_volume because each thread is operating on a different element
521
#pragma omp for
522
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
523
          for (int k = 0; k < table_size; ++k) {
×
524
            int index = index_elem * table_size + k;
525
            if (mats[index] != EMPTY) {
×
526
              result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
527
            }
528
          }
529
        }
530
      }
531
    } else {
532
      // Send material indices and volumes to process 0
533
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
×
534
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
×
535
    }
536
  }
537

538
  // Report time for MPI communication
539
  double t_mpi = timer.elapsed() - t_raytrace;
75✔
540
#else
541
  double t_mpi = 0.0;
90✔
542
#endif
543

544
  // Normalize based on known volumes of elements
545
  for (int i = 0; i < this->n_bins(); ++i) {
1,045✔
546
    // Estimated total volume in element i
547
    double volume = 0.0;
880✔
548
    for (int j = 0; j < table_size; ++j) {
7,920✔
549
      volume += result.volumes(i, j);
7,040✔
550
    }
551
    // Renormalize volumes based on known volume of element i
552
    double norm = this->volume(i) / volume;
880✔
553
    for (int j = 0; j < table_size; ++j) {
7,920✔
554
      result.volumes(i, j) *= norm;
7,040✔
555
    }
556
  }
557

558
  // Get total time and normalization time
559
  timer.stop();
165✔
560
  double t_total = timer.elapsed();
165✔
561
  double t_norm = t_total - t_raytrace - t_mpi;
165✔
562

563
  // Show timing statistics
564
  if (settings::verbosity < 7 || !mpi::master)
165!
565
    return;
44✔
566
  header("Timing Statistics", 7);
121✔
567
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
121✔
568
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
121✔
569
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
121✔
570
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
99✔
571
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
99✔
572
    n_total / t_raytrace);
121✔
573
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
99✔
574
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
121✔
575
  std::fflush(stdout);
121✔
576
}
577

578
void Mesh::to_hdf5(hid_t group) const
2,817✔
579
{
580
  // Create group for mesh
581
  std::string group_name = fmt::format("mesh {}", id_);
5,104✔
582
  hid_t mesh_group = create_group(group, group_name.c_str());
2,817✔
583

584
  // Write mesh type
585
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,817✔
586

587
  // Write mesh ID
588
  write_attribute(mesh_group, "id", id_);
2,817✔
589

590
  // Write mesh name
591
  write_dataset(mesh_group, "name", name_);
2,817✔
592

593
  // Write mesh data
594
  this->to_hdf5_inner(mesh_group);
2,817✔
595

596
  // Close group
597
  close_group(mesh_group);
2,817✔
598
}
2,817✔
599

600
//==============================================================================
601
// Structured Mesh implementation
602
//==============================================================================
603

604
std::string StructuredMesh::bin_label(int bin) const
5,129,183✔
605
{
606
  MeshIndex ijk = get_indices_from_bin(bin);
5,129,183✔
607

608
  if (n_dimension_ > 2) {
5,129,183✔
609
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,228,864✔
610
  } else if (n_dimension_ > 1) {
14,751✔
611
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
28,952✔
612
  } else {
613
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
614
  }
615
}
616

617
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,422✔
618
{
619
  // because method is const, shape_ is const as well and can't be adapted
620
  auto tmp_shape = shape_;
2,422✔
621
  return xt::adapt(tmp_shape, {n_dimension_});
4,844✔
622
}
623

624
Position StructuredMesh::sample_element(
1,533,751✔
625
  const MeshIndex& ijk, uint64_t* seed) const
626
{
627
  // lookup the lower/upper bounds for the mesh element
628
  double x_min = negative_grid_boundary(ijk, 0);
1,533,751✔
629
  double x_max = positive_grid_boundary(ijk, 0);
1,533,751✔
630

631
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,533,751!
632
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,533,751!
633

634
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,533,751!
635
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,533,751!
636

637
  return {x_min + (x_max - x_min) * prn(seed),
1,533,751✔
638
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,533,751✔
639
}
640

641
//==============================================================================
642
// Unstructured Mesh implementation
643
//==============================================================================
644

645
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
47✔
646
{
647
  n_dimension_ = 3;
47✔
648

649
  // check the mesh type
650
  if (check_for_node(node, "type")) {
47!
651
    auto temp = get_node_value(node, "type", true, true);
47!
652
    if (temp != mesh_type) {
47!
UNCOV
653
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
654
    }
655
  }
47✔
656

657
  // check if a length unit multiplier was specified
658
  if (check_for_node(node, "length_multiplier")) {
47!
UNCOV
659
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
660
  }
661

662
  // get the filename of the unstructured mesh to load
663
  if (check_for_node(node, "filename")) {
47!
664
    filename_ = get_node_value(node, "filename");
47!
665
    if (!file_exists(filename_)) {
47!
UNCOV
666
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
667
    }
668
  } else {
669
    fatal_error(fmt::format(
×
UNCOV
670
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
671
  }
672

673
  if (check_for_node(node, "options")) {
47!
674
    options_ = get_node_value(node, "options");
16!
675
  }
676

677
  // check if mesh tally data should be written with
678
  // statepoint files
679
  if (check_for_node(node, "output")) {
47!
UNCOV
680
    output_ = get_node_value_bool(node, "output");
×
681
  }
682
}
47✔
683

UNCOV
684
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
685
{
UNCOV
686
  n_dimension_ = 3;
×
687

688
  // check the mesh type
689
  if (object_exists(group, "type")) {
×
690
    std::string temp;
×
691
    read_dataset(group, "type", temp);
×
692
    if (temp != mesh_type) {
×
UNCOV
693
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
694
    }
UNCOV
695
  }
×
696

697
  // check if a length unit multiplier was specified
698
  if (object_exists(group, "length_multiplier")) {
×
UNCOV
699
    read_dataset(group, "length_multiplier", length_multiplier_);
×
700
  }
701

702
  // get the filename of the unstructured mesh to load
703
  if (object_exists(group, "filename")) {
×
704
    read_dataset(group, "filename", filename_);
×
705
    if (!file_exists(filename_)) {
×
UNCOV
706
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
707
    }
708
  } else {
709
    fatal_error(fmt::format(
×
UNCOV
710
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
711
  }
712

713
  if (attribute_exists(group, "options")) {
×
UNCOV
714
    read_attribute(group, "options", options_);
×
715
  }
716

717
  // check if mesh tally data should be written with
718
  // statepoint files
719
  if (attribute_exists(group, "output")) {
×
UNCOV
720
    read_attribute(group, "output", output_);
×
721
  }
UNCOV
722
}
×
723

724
void UnstructuredMesh::determine_bounds()
25✔
725
{
726
  double xmin = INFTY;
25✔
727
  double ymin = INFTY;
25✔
728
  double zmin = INFTY;
25✔
729
  double xmax = -INFTY;
25✔
730
  double ymax = -INFTY;
25✔
731
  double zmax = -INFTY;
25✔
732
  int n = this->n_vertices();
25!
733
  for (int i = 0; i < n; ++i) {
55,951✔
734
    auto v = this->vertex(i);
55,926!
735
    xmin = std::min(v.x, xmin);
55,926✔
736
    ymin = std::min(v.y, ymin);
55,926✔
737
    zmin = std::min(v.z, zmin);
55,926✔
738
    xmax = std::max(v.x, xmax);
55,926✔
739
    ymax = std::max(v.y, ymax);
55,926✔
740
    zmax = std::max(v.z, zmax);
55,926✔
741
  }
742
  lower_left_ = {xmin, ymin, zmin};
25!
743
  upper_right_ = {xmax, ymax, zmax};
25!
744
}
25✔
745

746
Position UnstructuredMesh::sample_tet(
601,230✔
747
  std::array<Position, 4> coords, uint64_t* seed) const
748
{
749
  // Uniform distribution
750
  double s = prn(seed);
601,230✔
751
  double t = prn(seed);
601,230✔
752
  double u = prn(seed);
601,230✔
753

754
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
755
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
756
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
757
  if (s + t > 1) {
601,230✔
758
    s = 1.0 - s;
300,547✔
759
    t = 1.0 - t;
300,547✔
760
  }
761
  if (s + t + u > 1) {
601,230✔
762
    if (t + u > 1) {
400,639✔
763
      double old_t = t;
200,969✔
764
      t = 1.0 - u;
200,969✔
765
      u = 1.0 - s - old_t;
200,969✔
766
    } else if (t + u <= 1) {
199,670!
767
      double old_s = s;
199,670✔
768
      s = 1.0 - t - u;
199,670✔
769
      u = old_s + t + u - 1;
199,670✔
770
    }
771
  }
772
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
773
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
774
}
775

776
const std::string UnstructuredMesh::mesh_type = "unstructured";
777

778
std::string UnstructuredMesh::get_mesh_type() const
32✔
779
{
780
  return mesh_type;
32✔
781
}
782

UNCOV
783
void UnstructuredMesh::surface_bins_crossed(
×
784
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
785
{
UNCOV
786
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
787
}
788

789
std::string UnstructuredMesh::bin_label(int bin) const
205,736✔
790
{
791
  return fmt::format("Mesh Index ({})", bin);
205,736!
792
};
793

794
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
32✔
795
{
796
  write_dataset(mesh_group, "filename", filename_);
32!
797
  write_dataset(mesh_group, "library", this->library());
32!
798
  if (!options_.empty()) {
32✔
799
    write_attribute(mesh_group, "options", options_);
8!
800
  }
801

802
  if (length_multiplier_ > 0.0)
32!
UNCOV
803
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
804

805
  // write vertex coordinates
806
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
32!
807
  for (int i = 0; i < this->n_vertices(); i++) {
70,275!
808
    auto v = this->vertex(i);
70,243!
809
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
70,243!
810
  }
811
  write_dataset(mesh_group, "vertices", vertices);
32!
812

813
  int num_elem_skipped = 0;
32✔
814

815
  // write element types and connectivity
816
  vector<double> volumes;
32✔
817
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
32!
818
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
32!
819
  for (int i = 0; i < this->n_bins(); i++) {
349,768!
820
    auto conn = this->connectivity(i);
349,736!
821

822
    volumes.emplace_back(this->volume(i));
349,736!
823

824
    // write linear tet element
825
    if (conn.size() == 4) {
349,736✔
826
      xt::view(elem_types, i, xt::all()) =
695,472!
827
        static_cast<int>(ElementType::LINEAR_TET);
695,472!
828
      xt::view(connectivity, i, xt::all()) =
695,472!
829
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,043,208!
830
      // write linear hex element
831
    } else if (conn.size() == 8) {
2,000!
832
      xt::view(elem_types, i, xt::all()) =
4,000!
833
        static_cast<int>(ElementType::LINEAR_HEX);
4,000!
834
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000!
835
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000!
836
    } else {
837
      num_elem_skipped++;
×
838
      xt::view(elem_types, i, xt::all()) =
×
839
        static_cast<int>(ElementType::UNSUPPORTED);
×
UNCOV
840
      xt::view(connectivity, i, xt::all()) = -1;
×
841
    }
842
  }
349,736✔
843

844
  // warn users that some elements were skipped
845
  if (num_elem_skipped > 0) {
32!
UNCOV
846
    warning(fmt::format("The connectivity of {} elements "
×
847
                        "on mesh {} were not written "
848
                        "because they are not of type linear tet/hex.",
UNCOV
849
      num_elem_skipped, this->id_));
×
850
  }
851

852
  write_dataset(mesh_group, "volumes", volumes);
32!
853
  write_dataset(mesh_group, "connectivity", connectivity);
32!
854
  write_dataset(mesh_group, "element_types", elem_types);
32!
855
}
32✔
856

857
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
858
{
859
  length_multiplier_ = length_multiplier;
23✔
860
}
23✔
861

862
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
863
{
864
  auto conn = connectivity(bin);
120,000!
865

866
  if (conn.size() == 4)
120,000!
867
    return ElementType::LINEAR_TET;
120,000✔
868
  else if (conn.size() == 8)
×
UNCOV
869
    return ElementType::LINEAR_HEX;
×
870
  else
UNCOV
871
    return ElementType::UNSUPPORTED;
×
872
}
120,000✔
873

874
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,141,589,412✔
875
  Position r, bool& in_mesh) const
876
{
877
  MeshIndex ijk;
878
  in_mesh = true;
1,141,589,412✔
879
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
880
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
881

882
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
883
      in_mesh = false;
102,612,478✔
884
  }
885
  return ijk;
1,141,589,412✔
886
}
887

888
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,689,412,634✔
889
{
890
  switch (n_dimension_) {
1,689,412,634!
891
  case 1:
880,605✔
892
    return ijk[0] - 1;
880,605✔
893
  case 2:
96,174,804✔
894
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
96,174,804✔
895
  case 3:
1,592,357,225✔
896
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,592,357,225✔
897
  default:
×
UNCOV
898
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
899
  }
900
}
901

902
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,879,109✔
903
{
904
  MeshIndex ijk;
905
  if (n_dimension_ == 1) {
7,879,109✔
906
    ijk[0] = bin + 1;
275✔
907
  } else if (n_dimension_ == 2) {
7,878,834✔
908
    ijk[0] = bin % shape_[0] + 1;
14,476✔
909
    ijk[1] = bin / shape_[0] + 1;
14,476✔
910
  } else if (n_dimension_ == 3) {
7,864,358!
911
    ijk[0] = bin % shape_[0] + 1;
7,864,358✔
912
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,864,358✔
913
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,864,358✔
914
  }
915
  return ijk;
7,879,109✔
916
}
917

918
int StructuredMesh::get_bin(Position r) const
247,929,951✔
919
{
920
  // Determine indices
921
  bool in_mesh;
922
  MeshIndex ijk = get_indices(r, in_mesh);
247,929,951✔
923
  if (!in_mesh)
247,929,951✔
924
    return -1;
21,004,880✔
925

926
  // Convert indices to bin
927
  return get_bin_from_indices(ijk);
226,925,071✔
928
}
929

930
int StructuredMesh::n_bins() const
1,139,418✔
931
{
932
  return std::accumulate(
1,139,418✔
933
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,278,836✔
934
}
935

936
int StructuredMesh::n_surface_bins() const
380✔
937
{
938
  return 4 * n_dimension_ * n_bins();
380✔
939
}
940

UNCOV
941
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
942
  const SourceSite* bank, int64_t length, bool* outside) const
943
{
944
  // Determine shape of array for counts
945
  std::size_t m = this->n_bins();
×
UNCOV
946
  vector<std::size_t> shape = {m};
×
947

948
  // Create array of zeros
949
  xt::xarray<double> cnt {shape, 0.0};
×
UNCOV
950
  bool outside_ = false;
×
951

952
  for (int64_t i = 0; i < length; i++) {
×
UNCOV
953
    const auto& site = bank[i];
×
954

955
    // determine scoring bin for entropy mesh
UNCOV
956
    int mesh_bin = get_bin(site.r);
×
957

958
    // if outside mesh, skip particle
959
    if (mesh_bin < 0) {
×
960
      outside_ = true;
×
UNCOV
961
      continue;
×
962
    }
963

964
    // Add to appropriate bin
UNCOV
965
    cnt(mesh_bin) += site.wgt;
×
966
  }
967

968
  // Create copy of count data. Since ownership will be acquired by xtensor,
969
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
970
  // warnings.
971
  int total = cnt.size();
×
UNCOV
972
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
973

974
#ifdef OPENMC_MPI
975
  // collect values from all processors
976
  MPI_Reduce(
×
977
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
978

979
  // Check if there were sites outside the mesh for any processor
980
  if (outside) {
×
981
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
982
  }
983
#else
984
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
×
985
  if (outside)
×
986
    *outside = outside_;
987
#endif
988

989
  // Adapt reduced values in array back into an xarray
990
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
UNCOV
991
  xt::xarray<double> counts = arr;
×
992

993
  return counts;
×
UNCOV
994
}
×
995

996
// raytrace through the mesh. The template class T will do the tallying.
997
// A modern optimizing compiler can recognize the noop method of T and
998
// eliminate that call entirely.
999
template<class T>
1000
void StructuredMesh::raytrace_mesh(
898,547,438✔
1001
  Position r0, Position r1, const Direction& u, T tally) const
1002
{
1003
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1004
  // enable/disable tally calls for now, T template type needs to provide both
1005
  // surface and track methods, which might be empty. modern optimizing
1006
  // compilers will (hopefully) eliminate the complete code (including
1007
  // calculation of parameters) but for the future: be explicit
1008

1009
  // Compute the length of the entire track.
1010
  double total_distance = (r1 - r0).norm();
898,547,438✔
1011
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
898,547,438✔
1012
    return;
11,635,894✔
1013

1014
  // keep a copy of the original global position to pass to get_indices,
1015
  // which performs its own transformation to local coordinates
1016
  Position global_r = r0;
886,911,544✔
1017
  Position local_r = local_coords(r0);
886,911,544✔
1018

1019
  const int n = n_dimension_;
886,911,544✔
1020

1021
  // Flag if position is inside the mesh
1022
  bool in_mesh;
1023

1024
  // Position is r = r0 + u * traveled_distance, start at r0
1025
  double traveled_distance {0.0};
886,911,544✔
1026

1027
  // Calculate index of current cell. Offset the position a tiny bit in
1028
  // direction of flight
1029
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
886,911,544✔
1030

1031
  // if track is very short, assume that it is completely inside one cell.
1032
  // Only the current cell will score and no surfaces
1033
  if (total_distance < 2 * TINY_BIT) {
886,911,544✔
1034
    if (in_mesh) {
331,527✔
1035
      tally.track(ijk, 1.0);
331,043✔
1036
    }
1037
    return;
331,527✔
1038
  }
1039

1040
  // Calculate initial distances to next surfaces in all three dimensions
1041
  std::array<MeshDistance, 3> distances;
1,773,160,034✔
1042
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1043
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1044
  }
1045

1046
  // Loop until r = r1 is eventually reached
1047
  while (true) {
743,702,045✔
1048

1049
    if (in_mesh) {
1,630,282,062✔
1050

1051
      // find surface with minimal distance to current position
1052
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,544,041,895✔
1053
                     distances.begin();
1,544,041,895✔
1054

1055
      // Tally track length delta since last step
1056
      tally.track(ijk,
1,544,041,895✔
1057
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,544,041,895✔
1058
          total_distance);
1059

1060
      // update position and leave, if we have reached end position
1061
      traveled_distance = distances[k].distance;
1,544,041,895✔
1062
      if (traveled_distance >= total_distance)
1,544,041,895✔
1063
        return;
807,087,767✔
1064

1065
      // If we have not reached r1, we have hit a surface. Tally outward
1066
      // current
1067
      tally.surface(ijk, k, distances[k].max_surface, false);
736,954,128✔
1068

1069
      // Update cell and calculate distance to next surface in k-direction.
1070
      // The two other directions are still valid!
1071
      ijk[k] = distances[k].next_index;
736,954,128✔
1072
      distances[k] =
736,954,128✔
1073
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
736,954,128✔
1074

1075
      // Check if we have left the interior of the mesh
1076
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
736,954,128✔
1077

1078
      // If we are still inside the mesh, tally inward current for the next
1079
      // cell
1080
      if (in_mesh)
736,954,128✔
1081
        tally.surface(ijk, k, !distances[k].max_surface, true);
723,605,195✔
1082

1083
    } else { // not inside mesh
1084

1085
      // For all directions outside the mesh, find the distance that we need
1086
      // to travel to reach the next surface. Use the largest distance, as
1087
      // only this will cross all outer surfaces.
1088
      int k_max {-1};
86,240,167✔
1089
      for (int k = 0; k < n; ++k) {
343,516,302✔
1090
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
351,524,217✔
1091
            (distances[k].distance > traveled_distance)) {
94,248,082✔
1092
          traveled_distance = distances[k].distance;
89,264,558✔
1093
          k_max = k;
89,264,558✔
1094
        }
1095
      }
1096
      // Assure some distance is traveled
1097
      if (k_max == -1) {
86,240,167✔
1098
        traveled_distance += TINY_BIT;
110✔
1099
      }
1100

1101
      // If r1 is not inside the mesh, exit here
1102
      if (traveled_distance >= total_distance)
86,240,167✔
1103
        return;
79,492,250✔
1104

1105
      // Calculate the new cell index and update all distances to next
1106
      // surfaces.
1107
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,747,917✔
1108
      for (int k = 0; k < n; ++k) {
26,783,130✔
1109
        distances[k] =
20,035,213✔
1110
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
20,035,213✔
1111
      }
1112

1113
      // If inside the mesh, Tally inward current
1114
      if (in_mesh && k_max >= 0)
6,747,917!
1115
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
6,322,871✔
1116
    }
1117
  }
1118
}
1119

1120
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
786,419,873✔
1121
  vector<int>& bins, vector<double>& lengths) const
1122
{
1123

1124
  // Helper tally class.
1125
  // stores a pointer to the mesh class and references to bins and lengths
1126
  // parameters. Performs the actual tally through the track method.
1127
  struct TrackAggregator {
1128
    TrackAggregator(
786,419,873✔
1129
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1130
      : mesh(_mesh), bins(_bins), lengths(_lengths)
786,419,873✔
1131
    {}
786,419,873✔
1132
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1,408,723,005✔
1133
    void track(const MeshIndex& ijk, double l) const
1,404,328,374✔
1134
    {
1135
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,404,328,374✔
1136
      lengths.push_back(l);
1,404,328,374✔
1137
    }
1,404,328,374✔
1138

1139
    const StructuredMesh* mesh;
1140
    vector<int>& bins;
1141
    vector<double>& lengths;
1142
  };
1143

1144
  // Perform the mesh raytrace with the helper class.
1145
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
786,419,873✔
1146
}
786,419,873✔
1147

1148
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1149
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1150
{
1151

1152
  // Helper tally class.
1153
  // stores a pointer to the mesh class and a reference to the bins parameter.
1154
  // Performs the actual tally through the surface method.
1155
  struct SurfaceAggregator {
1156
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,565✔
1157
      : mesh(_mesh), bins(_bins)
112,127,565✔
1158
    {}
112,127,565✔
1159
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,189✔
1160
    {
1161
      int i_bin =
1162
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,189✔
1163
      if (max)
58,159,189✔
1164
        i_bin += 2;
29,051,440✔
1165
      if (inward)
58,159,189✔
1166
        i_bin += 1;
28,582,290✔
1167
      bins.push_back(i_bin);
58,159,189✔
1168
    }
58,159,189✔
1169
    void track(const MeshIndex& idx, double l) const {}
140,044,564✔
1170

1171
    const StructuredMesh* mesh;
1172
    vector<int>& bins;
1173
  };
1174

1175
  // Perform the mesh raytrace with the helper class.
1176
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1177
}
112,127,565✔
1178

1179
//==============================================================================
1180
// RegularMesh implementation
1181
//==============================================================================
1182

1183
int RegularMesh::set_grid()
2,011✔
1184
{
1185
  auto shape = xt::adapt(shape_, {n_dimension_});
2,011✔
1186

1187
  // Check that dimensions are all greater than zero
1188
  if (xt::any(shape <= 0)) {
2,011!
UNCOV
1189
    set_errmsg("All entries for a regular mesh dimensions "
×
1190
               "must be positive.");
UNCOV
1191
    return OPENMC_E_INVALID_ARGUMENT;
×
1192
  }
1193

1194
  // Make sure lower_left and dimension match
1195
  if (lower_left_.size() != n_dimension_) {
2,011!
UNCOV
1196
    set_errmsg("Number of entries in lower_left must be the same "
×
1197
               "as the regular mesh dimensions.");
UNCOV
1198
    return OPENMC_E_INVALID_ARGUMENT;
×
1199
  }
1200
  if (width_.size() > 0) {
2,011✔
1201

1202
    // Check to ensure width has same dimensions
1203
    if (width_.size() != n_dimension_) {
49!
UNCOV
1204
      set_errmsg("Number of entries on width must be the same as "
×
1205
                 "the regular mesh dimensions.");
UNCOV
1206
      return OPENMC_E_INVALID_ARGUMENT;
×
1207
    }
1208

1209
    // Check for negative widths
1210
    if (xt::any(width_ < 0.0)) {
49!
1211
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
UNCOV
1212
      return OPENMC_E_INVALID_ARGUMENT;
×
1213
    }
1214

1215
    // Set width and upper right coordinate
1216
    upper_right_ = xt::eval(lower_left_ + shape * width_);
49✔
1217

1218
  } else if (upper_right_.size() > 0) {
1,962!
1219

1220
    // Check to ensure upper_right_ has same dimensions
1221
    if (upper_right_.size() != n_dimension_) {
1,962!
UNCOV
1222
      set_errmsg("Number of entries on upper_right must be the "
×
1223
                 "same as the regular mesh dimensions.");
UNCOV
1224
      return OPENMC_E_INVALID_ARGUMENT;
×
1225
    }
1226

1227
    // Check that upper-right is above lower-left
1228
    if (xt::any(upper_right_ < lower_left_)) {
1,962!
UNCOV
1229
      set_errmsg(
×
1230
        "The upper_right coordinates of a regular mesh must be greater than "
1231
        "the lower_left coordinates.");
UNCOV
1232
      return OPENMC_E_INVALID_ARGUMENT;
×
1233
    }
1234

1235
    // Set width
1236
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1,962✔
1237
  }
1238

1239
  // Set material volumes
1240
  volume_frac_ = 1.0 / xt::prod(shape)();
2,011✔
1241

1242
  element_volume_ = 1.0;
2,011✔
1243
  for (int i = 0; i < n_dimension_; i++) {
7,606✔
1244
    element_volume_ *= width_[i];
5,595✔
1245
  }
1246
  return 0;
2,011✔
1247
}
2,011✔
1248

1249
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,000✔
1250
{
1251
  // Determine number of dimensions for mesh
1252
  if (!check_for_node(node, "dimension")) {
2,000!
UNCOV
1253
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1254
  }
1255

1256
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
2,000✔
1257
  int n = n_dimension_ = shape.size();
2,000✔
1258
  if (n != 1 && n != 2 && n != 3) {
2,000!
UNCOV
1259
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1260
  }
1261
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,000✔
1262

1263
  // Check for lower-left coordinates
1264
  if (check_for_node(node, "lower_left")) {
2,000!
1265
    // Read mesh lower-left corner location
1266
    lower_left_ = get_node_xarray<double>(node, "lower_left");
2,000✔
1267
  } else {
UNCOV
1268
    fatal_error("Must specify <lower_left> on a mesh.");
×
1269
  }
1270

1271
  if (check_for_node(node, "width")) {
2,000✔
1272
    // Make sure one of upper-right or width were specified
1273
    if (check_for_node(node, "upper_right")) {
49!
UNCOV
1274
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1275
    }
1276

1277
    width_ = get_node_xarray<double>(node, "width");
49✔
1278

1279
  } else if (check_for_node(node, "upper_right")) {
1,951!
1280

1281
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1,951✔
1282

1283
  } else {
UNCOV
1284
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1285
  }
1286

1287
  if (int err = set_grid()) {
2,000!
UNCOV
1288
    fatal_error(openmc_err_msg);
×
1289
  }
1290
}
2,000✔
1291

1292
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
11✔
1293
{
1294
  // Determine number of dimensions for mesh
1295
  if (!object_exists(group, "dimension")) {
11!
UNCOV
1296
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1297
  }
1298

1299
  xt::xtensor<int, 1> shape;
11✔
1300
  read_dataset(group, "dimension", shape);
11✔
1301
  int n = n_dimension_ = shape.size();
11✔
1302
  if (n != 1 && n != 2 && n != 3) {
11!
UNCOV
1303
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1304
  }
1305
  std::copy(shape.begin(), shape.end(), shape_.begin());
11✔
1306

1307
  // Check for lower-left coordinates
1308
  if (object_exists(group, "lower_left")) {
11!
1309
    // Read mesh lower-left corner location
1310
    read_dataset(group, "lower_left", lower_left_);
11✔
1311
  } else {
UNCOV
1312
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1313
  }
1314

1315
  if (object_exists(group, "upper_right")) {
11!
1316

1317
    read_dataset(group, "upper_right", upper_right_);
11✔
1318

1319
  } else {
UNCOV
1320
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1321
  }
1322

1323
  if (int err = set_grid()) {
11!
UNCOV
1324
    fatal_error(openmc_err_msg);
×
1325
  }
1326
}
11✔
1327

1328
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1329
{
1330
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1331
}
1332

1333
const std::string RegularMesh::mesh_type = "regular";
1334

1335
std::string RegularMesh::get_mesh_type() const
3,104✔
1336
{
1337
  return mesh_type;
3,104✔
1338
}
1339

1340
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,434,709,708✔
1341
{
1342
  return lower_left_[i] + ijk[i] * width_[i];
1,434,709,708✔
1343
}
1344

1345
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,372,970,559✔
1346
{
1347
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,372,970,559✔
1348
}
1349

1350
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1351
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1352
  double l) const
1353
{
1354
  MeshDistance d;
2,147,483,647✔
1355
  d.next_index = ijk[i];
2,147,483,647✔
1356
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1357
    return d;
1,754,214✔
1358

1359
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1360
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1361
    d.next_index++;
1,430,108,455✔
1362
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,430,108,455✔
1363
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,389,787,929✔
1364
    d.next_index--;
1,368,369,306✔
1365
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,368,369,306✔
1366
  }
1367

1368
  return d;
2,147,483,647✔
1369
}
1370

1371
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1372
  Position plot_ll, Position plot_ur) const
1373
{
1374
  // Figure out which axes lie in the plane of the plot.
1375
  array<int, 2> axes {-1, -1};
22✔
1376
  if (plot_ur.z == plot_ll.z) {
22!
1377
    axes[0] = 0;
22✔
1378
    if (n_dimension_ > 1)
22!
1379
      axes[1] = 1;
22✔
1380
  } else if (plot_ur.y == plot_ll.y) {
×
1381
    axes[0] = 0;
×
1382
    if (n_dimension_ > 2)
×
1383
      axes[1] = 2;
×
1384
  } else if (plot_ur.x == plot_ll.x) {
×
1385
    if (n_dimension_ > 1)
×
1386
      axes[0] = 1;
×
1387
    if (n_dimension_ > 2)
×
UNCOV
1388
      axes[1] = 2;
×
1389
  } else {
UNCOV
1390
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1391
  }
1392

1393
  // Get the coordinates of the mesh lines along both of the axes.
1394
  array<vector<double>, 2> axis_lines;
22✔
1395
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1396
    int axis = axes[i_ax];
44✔
1397
    if (axis == -1)
44!
UNCOV
1398
      continue;
×
1399
    auto& lines {axis_lines[i_ax]};
44✔
1400

1401
    double coord = lower_left_[axis];
44✔
1402
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1403
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1404
        lines.push_back(coord);
242✔
1405
      coord += width_[axis];
242✔
1406
    }
1407
  }
1408

1409
  return {axis_lines[0], axis_lines[1]};
44✔
1410
}
22✔
1411

1412
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1,982✔
1413
{
1414
  write_dataset(mesh_group, "dimension", get_x_shape());
1,982✔
1415
  write_dataset(mesh_group, "lower_left", lower_left_);
1,982✔
1416
  write_dataset(mesh_group, "upper_right", upper_right_);
1,982✔
1417
  write_dataset(mesh_group, "width", width_);
1,982✔
1418
}
1,982✔
1419

1420
xt::xtensor<double, 1> RegularMesh::count_sites(
7,839✔
1421
  const SourceSite* bank, int64_t length, bool* outside) const
1422
{
1423
  // Determine shape of array for counts
1424
  std::size_t m = this->n_bins();
7,839✔
1425
  vector<std::size_t> shape = {m};
7,839✔
1426

1427
  // Create array of zeros
1428
  xt::xarray<double> cnt {shape, 0.0};
7,839✔
1429
  bool outside_ = false;
7,839✔
1430

1431
  for (int64_t i = 0; i < length; i++) {
7,675,290✔
1432
    const auto& site = bank[i];
7,667,451✔
1433

1434
    // determine scoring bin for entropy mesh
1435
    int mesh_bin = get_bin(site.r);
7,667,451✔
1436

1437
    // if outside mesh, skip particle
1438
    if (mesh_bin < 0) {
7,667,451!
1439
      outside_ = true;
×
UNCOV
1440
      continue;
×
1441
    }
1442

1443
    // Add to appropriate bin
1444
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1445
  }
1446

1447
  // Create copy of count data. Since ownership will be acquired by xtensor,
1448
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
1449
  // warnings.
1450
  int total = cnt.size();
7,839✔
1451
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
7,839✔
1452

1453
#ifdef OPENMC_MPI
1454
  // collect values from all processors
1455
  MPI_Reduce(
3,615✔
1456
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
3,615✔
1457

1458
  // Check if there were sites outside the mesh for any processor
1459
  if (outside) {
3,615!
1460
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
3,615✔
1461
  }
1462
#else
1463
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
4,224✔
1464
  if (outside)
4,224!
1465
    *outside = outside_;
4,224✔
1466
#endif
1467

1468
  // Adapt reduced values in array back into an xarray
1469
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
7,839✔
1470
  xt::xarray<double> counts = arr;
7,839✔
1471

1472
  return counts;
15,678✔
1473
}
7,839✔
1474

1475
double RegularMesh::volume(const MeshIndex& ijk) const
1,126,096✔
1476
{
1477
  return element_volume_;
1,126,096✔
1478
}
1479

1480
//==============================================================================
1481
// RectilinearMesh implementation
1482
//==============================================================================
1483

1484
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
125✔
1485
{
1486
  n_dimension_ = 3;
125✔
1487

1488
  grid_[0] = get_node_array<double>(node, "x_grid");
125✔
1489
  grid_[1] = get_node_array<double>(node, "y_grid");
125✔
1490
  grid_[2] = get_node_array<double>(node, "z_grid");
125✔
1491

1492
  if (int err = set_grid()) {
125!
UNCOV
1493
    fatal_error(openmc_err_msg);
×
1494
  }
1495
}
125✔
1496

1497
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1498
{
1499
  n_dimension_ = 3;
11✔
1500

1501
  read_dataset(group, "x_grid", grid_[0]);
11✔
1502
  read_dataset(group, "y_grid", grid_[1]);
11✔
1503
  read_dataset(group, "z_grid", grid_[2]);
11✔
1504

1505
  if (int err = set_grid()) {
11!
UNCOV
1506
    fatal_error(openmc_err_msg);
×
1507
  }
1508
}
11✔
1509

1510
const std::string RectilinearMesh::mesh_type = "rectilinear";
1511

1512
std::string RectilinearMesh::get_mesh_type() const
275✔
1513
{
1514
  return mesh_type;
275✔
1515
}
1516

1517
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1518
  const MeshIndex& ijk, int i) const
1519
{
1520
  return grid_[i][ijk[i]];
26,505,963✔
1521
}
1522

1523
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1524
  const MeshIndex& ijk, int i) const
1525
{
1526
  return grid_[i][ijk[i] - 1];
25,739,406✔
1527
}
1528

1529
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087✔
1530
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1531
  double l) const
1532
{
1533
  MeshDistance d;
53,602,087✔
1534
  d.next_index = ijk[i];
53,602,087✔
1535
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087✔
1536
    return d;
571,824✔
1537

1538
  d.max_surface = (u[i] > 0);
53,030,263✔
1539
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263✔
1540
    d.next_index++;
26,505,963✔
1541
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963✔
1542
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300✔
1543
    d.next_index--;
25,739,406✔
1544
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1545
  }
1546
  return d;
53,030,263✔
1547
}
1548

1549
int RectilinearMesh::set_grid()
180✔
1550
{
1551
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
180✔
1552
    static_cast<int>(grid_[1].size()) - 1,
180✔
1553
    static_cast<int>(grid_[2].size()) - 1};
180✔
1554

1555
  for (const auto& g : grid_) {
720✔
1556
    if (g.size() < 2) {
540!
UNCOV
1557
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1558
                 "must each have at least 2 points");
UNCOV
1559
      return OPENMC_E_INVALID_ARGUMENT;
×
1560
    }
1561
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
540✔
1562
        g.end()) {
1,080!
UNCOV
1563
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1564
                 "rectilinear meshes must be sorted and unique.");
UNCOV
1565
      return OPENMC_E_INVALID_ARGUMENT;
×
1566
    }
1567
  }
1568

1569
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
180✔
1570
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
180✔
1571

1572
  return 0;
180✔
1573
}
1574

1575
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892✔
1576
{
1577
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892✔
1578
}
1579

1580
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1581
  Position plot_ll, Position plot_ur) const
1582
{
1583
  // Figure out which axes lie in the plane of the plot.
1584
  array<int, 2> axes {-1, -1};
11✔
1585
  if (plot_ur.z == plot_ll.z) {
11!
UNCOV
1586
    axes = {0, 1};
×
1587
  } else if (plot_ur.y == plot_ll.y) {
11!
1588
    axes = {0, 2};
11✔
1589
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1590
    axes = {1, 2};
×
1591
  } else {
UNCOV
1592
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1593
  }
1594

1595
  // Get the coordinates of the mesh lines along both of the axes.
1596
  array<vector<double>, 2> axis_lines;
11✔
1597
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1598
    int axis = axes[i_ax];
22✔
1599
    vector<double>& lines {axis_lines[i_ax]};
22✔
1600

1601
    for (auto coord : grid_[axis]) {
110✔
1602
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1603
        lines.push_back(coord);
88✔
1604
    }
1605
  }
1606

1607
  return {axis_lines[0], axis_lines[1]};
22✔
1608
}
11✔
1609

1610
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1611
{
1612
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1613
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1614
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1615
}
110✔
1616

1617
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1618
{
1619
  double vol {1.0};
132✔
1620

1621
  for (int i = 0; i < n_dimension_; i++) {
528✔
1622
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1623
  }
1624
  return vol;
132✔
1625
}
1626

1627
//==============================================================================
1628
// CylindricalMesh implementation
1629
//==============================================================================
1630

1631
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
401✔
1632
  : PeriodicStructuredMesh {node}
401✔
1633
{
1634
  n_dimension_ = 3;
401✔
1635
  grid_[0] = get_node_array<double>(node, "r_grid");
401✔
1636
  grid_[1] = get_node_array<double>(node, "phi_grid");
401✔
1637
  grid_[2] = get_node_array<double>(node, "z_grid");
401✔
1638
  origin_ = get_node_position(node, "origin");
401✔
1639

1640
  if (int err = set_grid()) {
401!
UNCOV
1641
    fatal_error(openmc_err_msg);
×
1642
  }
1643
}
401✔
1644

1645
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1646
{
1647
  n_dimension_ = 3;
11✔
1648
  read_dataset(group, "r_grid", grid_[0]);
11✔
1649
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1650
  read_dataset(group, "z_grid", grid_[2]);
11✔
1651
  read_dataset(group, "origin", origin_);
11✔
1652

1653
  if (int err = set_grid()) {
11!
UNCOV
1654
    fatal_error(openmc_err_msg);
×
1655
  }
1656
}
11✔
1657

1658
const std::string CylindricalMesh::mesh_type = "cylindrical";
1659

1660
std::string CylindricalMesh::get_mesh_type() const
484✔
1661
{
1662
  return mesh_type;
484✔
1663
}
1664

1665
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,726,668✔
1666
  Position r, bool& in_mesh) const
1667
{
1668
  r = local_coords(r);
47,726,668✔
1669

1670
  Position mapped_r;
47,726,668✔
1671
  mapped_r[0] = std::hypot(r.x, r.y);
47,726,668✔
1672
  mapped_r[2] = r[2];
47,726,668✔
1673

1674
  if (mapped_r[0] < FP_PRECISION) {
47,726,668!
UNCOV
1675
    mapped_r[1] = 0.0;
×
1676
  } else {
1677
    mapped_r[1] = std::atan2(r.y, r.x);
47,726,668✔
1678
    if (mapped_r[1] < 0)
47,726,668✔
1679
      mapped_r[1] += 2 * M_PI;
23,872,431✔
1680
  }
1681

1682
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,726,668✔
1683

1684
  idx[1] = sanitize_phi(idx[1]);
47,726,668✔
1685

1686
  return idx;
47,726,668✔
1687
}
1688

1689
Position CylindricalMesh::sample_element(
88,110✔
1690
  const MeshIndex& ijk, uint64_t* seed) const
1691
{
1692
  double r_min = this->r(ijk[0] - 1);
88,110✔
1693
  double r_max = this->r(ijk[0]);
88,110✔
1694

1695
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1696
  double phi_max = this->phi(ijk[1]);
88,110✔
1697

1698
  double z_min = this->z(ijk[2] - 1);
88,110✔
1699
  double z_max = this->z(ijk[2]);
88,110✔
1700

1701
  double r_min_sq = r_min * r_min;
88,110✔
1702
  double r_max_sq = r_max * r_max;
88,110✔
1703
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1704
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1705
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1706

1707
  double x = r * std::cos(phi);
88,110✔
1708
  double y = r * std::sin(phi);
88,110✔
1709

1710
  return origin_ + Position(x, y, z);
88,110✔
1711
}
1712

1713
double CylindricalMesh::find_r_crossing(
142,570,168✔
1714
  const Position& r, const Direction& u, double l, int shell) const
1715
{
1716

1717
  if ((shell < 0) || (shell > shape_[0]))
142,570,168!
1718
    return INFTY;
17,913,962✔
1719

1720
  // solve r.x^2 + r.y^2 == r0^2
1721
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1722
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1723

1724
  const double r0 = grid_[0][shell];
124,656,206✔
1725
  if (r0 == 0.0)
124,656,206✔
1726
    return INFTY;
7,130,651✔
1727

1728
  const double denominator = u.x * u.x + u.y * u.y;
117,525,555✔
1729

1730
  // Direction of flight is in z-direction. Will never intersect r.
1731
  if (std::abs(denominator) < FP_PRECISION)
117,525,555✔
1732
    return INFTY;
58,960✔
1733

1734
  // inverse of dominator to help the compiler to speed things up
1735
  const double inv_denominator = 1.0 / denominator;
117,466,595✔
1736

1737
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,466,595✔
1738
  double c = r.x * r.x + r.y * r.y - r0 * r0;
117,466,595✔
1739
  double D = p * p - c * inv_denominator;
117,466,595✔
1740

1741
  if (D < 0.0)
117,466,595✔
1742
    return INFTY;
9,733,570✔
1743

1744
  D = std::sqrt(D);
107,733,025✔
1745

1746
  // the solution -p - D is always smaller as -p + D : Check this one first
1747
  if (std::abs(c) <= RADIAL_MESH_TOL)
107,733,025✔
1748
    return INFTY;
6,611,374✔
1749

1750
  if (-p - D > l)
101,121,651✔
1751
    return -p - D;
20,206,426✔
1752
  if (-p + D > l)
80,915,225✔
1753
    return -p + D;
50,091,351✔
1754

1755
  return INFTY;
30,823,874✔
1756
}
1757

1758
double CylindricalMesh::find_phi_crossing(
74,445,558✔
1759
  const Position& r, const Direction& u, double l, int shell) const
1760
{
1761
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1762
  if (full_phi_ && (shape_[1] == 1))
74,445,558✔
1763
    return INFTY;
30,474,840✔
1764

1765
  shell = sanitize_phi(shell);
43,970,718✔
1766

1767
  const double p0 = grid_[1][shell];
43,970,718✔
1768

1769
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1770
  // => x(s) * cos(p0) = y(s) * sin(p0)
1771
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1772
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1773

1774
  const double c0 = std::cos(p0);
43,970,718✔
1775
  const double s0 = std::sin(p0);
43,970,718✔
1776

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

1779
  // Check if direction of flight is not parallel to phi surface
1780
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1781
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1782
    // Check if solution is in positive direction of flight and crosses the
1783
    // correct phi surface (not -phi)
1784
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1785
      return s;
20,219,859✔
1786
  }
1787

1788
  return INFTY;
23,750,859✔
1789
}
1790

1791
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,690,324✔
1792
  const Position& r, const Direction& u, double l, int shell) const
1793
{
1794
  MeshDistance d;
36,690,324✔
1795
  d.next_index = shell;
36,690,324✔
1796

1797
  // Direction of flight is within xy-plane. Will never intersect z.
1798
  if (std::abs(u.z) < FP_PRECISION)
36,690,324✔
1799
    return d;
1,118,216✔
1800

1801
  d.max_surface = (u.z > 0.0);
35,572,108✔
1802
  if (d.max_surface && (shell <= shape_[2])) {
35,572,108✔
1803
    d.next_index += 1;
16,873,241✔
1804
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,873,241✔
1805
  } else if (!d.max_surface && (shell > 0)) {
18,698,867✔
1806
    d.next_index -= 1;
16,843,453✔
1807
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,843,453✔
1808
  }
1809
  return d;
35,572,108✔
1810
}
1811

1812
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,198,187✔
1813
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1814
  double l) const
1815
{
1816
  if (i == 0) {
145,198,187✔
1817

1818
    return std::min(
71,285,084✔
1819
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,285,084✔
1820
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,570,168✔
1821

1822
  } else if (i == 1) {
73,913,103✔
1823

1824
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,222,779✔
1825
                      find_phi_crossing(r0, u, l, ijk[i])),
37,222,779✔
1826
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,222,779✔
1827
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,445,558✔
1828

1829
  } else {
1830
    return find_z_crossing(r0, u, l, ijk[i]);
36,690,324✔
1831
  }
1832
}
1833

1834
int CylindricalMesh::set_grid()
434✔
1835
{
1836
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
434✔
1837
    static_cast<int>(grid_[1].size()) - 1,
434✔
1838
    static_cast<int>(grid_[2].size()) - 1};
434✔
1839

1840
  for (const auto& g : grid_) {
1,736✔
1841
    if (g.size() < 2) {
1,302!
UNCOV
1842
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
1843
                 "must each have at least 2 points");
UNCOV
1844
      return OPENMC_E_INVALID_ARGUMENT;
×
1845
    }
1846
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,302✔
1847
        g.end()) {
2,604!
UNCOV
1848
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
1849
                 "cylindrical meshes must be sorted and unique.");
UNCOV
1850
      return OPENMC_E_INVALID_ARGUMENT;
×
1851
    }
1852
  }
1853
  if (grid_[0].front() < 0.0) {
434!
UNCOV
1854
    set_errmsg("r-grid for "
×
1855
               "cylindrical meshes must start at r >= 0.");
UNCOV
1856
    return OPENMC_E_INVALID_ARGUMENT;
×
1857
  }
1858
  if (grid_[1].front() < 0.0) {
434!
UNCOV
1859
    set_errmsg("phi-grid for "
×
1860
               "cylindrical meshes must start at phi >= 0.");
UNCOV
1861
    return OPENMC_E_INVALID_ARGUMENT;
×
1862
  }
1863
  if (grid_[1].back() > 2.0 * PI) {
434!
UNCOV
1864
    set_errmsg("phi-grids for "
×
1865
               "cylindrical meshes must end with theta <= 2*pi.");
1866

UNCOV
1867
    return OPENMC_E_INVALID_ARGUMENT;
×
1868
  }
1869

1870
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
434!
1871

1872
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
868✔
1873
    origin_[2] + grid_[2].front()};
868✔
1874
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
868✔
1875
    origin_[2] + grid_[2].back()};
868✔
1876

1877
  return 0;
434✔
1878
}
1879

1880
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,180,004✔
1881
{
1882
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,180,004✔
1883
}
1884

UNCOV
1885
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
1886
  Position plot_ll, Position plot_ur) const
1887
{
UNCOV
1888
  fatal_error("Plot of cylindrical Mesh not implemented");
×
1889

1890
  // Figure out which axes lie in the plane of the plot.
1891
  array<vector<double>, 2> axis_lines;
1892
  return {axis_lines[0], axis_lines[1]};
1893
}
1894

1895
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
1896
{
1897
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
1898
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
1899
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
1900
  write_dataset(mesh_group, "origin", origin_);
374✔
1901
}
374✔
1902

1903
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
1904
{
1905
  double r_i = grid_[0][ijk[0] - 1];
792✔
1906
  double r_o = grid_[0][ijk[0]];
792✔
1907

1908
  double phi_i = grid_[1][ijk[1] - 1];
792✔
1909
  double phi_o = grid_[1][ijk[1]];
792✔
1910

1911
  double z_i = grid_[2][ijk[2] - 1];
792✔
1912
  double z_o = grid_[2][ijk[2]];
792✔
1913

1914
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
1915
}
1916

1917
//==============================================================================
1918
// SphericalMesh implementation
1919
//==============================================================================
1920

1921
SphericalMesh::SphericalMesh(pugi::xml_node node)
346✔
1922
  : PeriodicStructuredMesh {node}
346✔
1923
{
1924
  n_dimension_ = 3;
346✔
1925

1926
  grid_[0] = get_node_array<double>(node, "r_grid");
346✔
1927
  grid_[1] = get_node_array<double>(node, "theta_grid");
346✔
1928
  grid_[2] = get_node_array<double>(node, "phi_grid");
346✔
1929
  origin_ = get_node_position(node, "origin");
346✔
1930

1931
  if (int err = set_grid()) {
346!
UNCOV
1932
    fatal_error(openmc_err_msg);
×
1933
  }
1934
}
346✔
1935

1936
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1937
{
1938
  n_dimension_ = 3;
11✔
1939

1940
  read_dataset(group, "r_grid", grid_[0]);
11✔
1941
  read_dataset(group, "theta_grid", grid_[1]);
11✔
1942
  read_dataset(group, "phi_grid", grid_[2]);
11✔
1943
  read_dataset(group, "origin", origin_);
11✔
1944

1945
  if (int err = set_grid()) {
11!
UNCOV
1946
    fatal_error(openmc_err_msg);
×
1947
  }
1948
}
11✔
1949

1950
const std::string SphericalMesh::mesh_type = "spherical";
1951

1952
std::string SphericalMesh::get_mesh_type() const
385✔
1953
{
1954
  return mesh_type;
385✔
1955
}
1956

1957
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,175,250✔
1958
  Position r, bool& in_mesh) const
1959
{
1960
  r = local_coords(r);
68,175,250✔
1961

1962
  Position mapped_r;
68,175,250✔
1963
  mapped_r[0] = r.norm();
68,175,250✔
1964

1965
  if (mapped_r[0] < FP_PRECISION) {
68,175,250!
1966
    mapped_r[1] = 0.0;
×
UNCOV
1967
    mapped_r[2] = 0.0;
×
1968
  } else {
1969
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,175,250✔
1970
    mapped_r[2] = std::atan2(r.y, r.x);
68,175,250✔
1971
    if (mapped_r[2] < 0)
68,175,250✔
1972
      mapped_r[2] += 2 * M_PI;
34,062,281✔
1973
  }
1974

1975
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,175,250✔
1976

1977
  idx[1] = sanitize_theta(idx[1]);
68,175,250✔
1978
  idx[2] = sanitize_phi(idx[2]);
68,175,250✔
1979

1980
  return idx;
68,175,250✔
1981
}
1982

1983
Position SphericalMesh::sample_element(
110✔
1984
  const MeshIndex& ijk, uint64_t* seed) const
1985
{
1986
  double r_min = this->r(ijk[0] - 1);
110✔
1987
  double r_max = this->r(ijk[0]);
110✔
1988

1989
  double theta_min = this->theta(ijk[1] - 1);
110✔
1990
  double theta_max = this->theta(ijk[1]);
110✔
1991

1992
  double phi_min = this->phi(ijk[2] - 1);
110✔
1993
  double phi_max = this->phi(ijk[2]);
110✔
1994

1995
  double cos_theta =
1996
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
1997
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
1998
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
1999
  double r_min_cub = std::pow(r_min, 3);
110✔
2000
  double r_max_cub = std::pow(r_max, 3);
110✔
2001
  // might be faster to do rejection here?
2002
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2003

2004
  double x = r * std::cos(phi) * sin_theta;
110✔
2005
  double y = r * std::sin(phi) * sin_theta;
110✔
2006
  double z = r * cos_theta;
110✔
2007

2008
  return origin_ + Position(x, y, z);
110✔
2009
}
2010

2011
double SphericalMesh::find_r_crossing(
443,074,280✔
2012
  const Position& r, const Direction& u, double l, int shell) const
2013
{
2014
  if ((shell < 0) || (shell > shape_[0]))
443,074,280✔
2015
    return INFTY;
39,620,317✔
2016

2017
  // solve |r+s*u| = r0
2018
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2019
  const double r0 = grid_[0][shell];
403,453,963✔
2020
  if (r0 == 0.0)
403,453,963✔
2021
    return INFTY;
7,261,639✔
2022
  const double p = r.dot(u);
396,192,324✔
2023
  double c = r.dot(r) - r0 * r0;
396,192,324✔
2024
  double D = p * p - c;
396,192,324✔
2025

2026
  if (std::abs(c) <= RADIAL_MESH_TOL)
396,192,324✔
2027
    return INFTY;
10,598,654✔
2028

2029
  if (D >= 0.0) {
385,593,670✔
2030
    D = std::sqrt(D);
357,716,722✔
2031
    // the solution -p - D is always smaller as -p + D : Check this one first
2032
    if (-p - D > l)
357,716,722✔
2033
      return -p - D;
64,277,774✔
2034
    if (-p + D > l)
293,438,948✔
2035
      return -p + D;
176,899,096✔
2036
  }
2037

2038
  return INFTY;
144,416,800✔
2039
}
2040

2041
double SphericalMesh::find_theta_crossing(
109,327,592✔
2042
  const Position& r, const Direction& u, double l, int shell) const
2043
{
2044
  // Theta grid is [0, π], thus there is no real surface to cross
2045
  if (full_theta_ && (shape_[1] == 1))
109,327,592✔
2046
    return INFTY;
70,969,052✔
2047

2048
  shell = sanitize_theta(shell);
38,358,540✔
2049

2050
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2051
  // yields
2052
  // a*s^2 + 2*b*s + c == 0 with
2053
  // a = cos(theta)^2 - u.z * u.z
2054
  // b = r*u * cos(theta)^2 - u.z * r.z
2055
  // c = r*r * cos(theta)^2 - r.z^2
2056

2057
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2058
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2059
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2060

2061
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2062
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2063
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2064

2065
  // if factor of s^2 is zero, direction of flight is parallel to theta
2066
  // surface
2067
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2068
    // if b vanishes, direction of flight is within theta surface and crossing
2069
    // is not possible
2070
    if (std::abs(b) < FP_PRECISION)
482,548!
2071
      return INFTY;
482,548✔
2072

UNCOV
2073
    const double s = -0.5 * c / b;
×
2074
    // Check if solution is in positive direction of flight and has correct
2075
    // sign
2076
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
UNCOV
2077
      return s;
×
2078

2079
    // no crossing is possible
UNCOV
2080
    return INFTY;
×
2081
  }
2082

2083
  const double p = b / a;
37,875,992✔
2084
  double D = p * p - c / a;
37,875,992✔
2085

2086
  if (D < 0.0)
37,875,992✔
2087
    return INFTY;
10,954,988✔
2088

2089
  D = std::sqrt(D);
26,921,004✔
2090

2091
  // the solution -p-D is always smaller as -p+D : Check this one first
2092
  double s = -p - D;
26,921,004✔
2093
  // Check if solution is in positive direction of flight and has correct sign
2094
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
26,921,004✔
2095
    return s;
5,282,607✔
2096

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

2102
  return INFTY;
11,475,101✔
2103
}
2104

2105
double SphericalMesh::find_phi_crossing(
110,917,070✔
2106
  const Position& r, const Direction& u, double l, int shell) const
2107
{
2108
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2109
  if (full_phi_ && (shape_[2] == 1))
110,917,070✔
2110
    return INFTY;
70,969,052✔
2111

2112
  shell = sanitize_phi(shell);
39,948,018✔
2113

2114
  const double p0 = grid_[2][shell];
39,948,018✔
2115

2116
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2117
  // => x(s) * cos(p0) = y(s) * sin(p0)
2118
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2119
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2120

2121
  const double c0 = std::cos(p0);
39,948,018✔
2122
  const double s0 = std::sin(p0);
39,948,018✔
2123

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

2126
  // Check if direction of flight is not parallel to phi surface
2127
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2128
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2129
    // Check if solution is in positive direction of flight and crosses the
2130
    // correct phi surface (not -phi)
2131
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2132
      return s;
17,579,452✔
2133
  }
2134

2135
  return INFTY;
22,368,566✔
2136
}
2137

2138
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
331,659,471✔
2139
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2140
  double l) const
2141
{
2142

2143
  if (i == 0) {
331,659,471✔
2144
    return std::min(
221,537,140✔
2145
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,537,140✔
2146
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,074,280✔
2147

2148
  } else if (i == 1) {
110,122,331✔
2149
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
54,663,796✔
2150
                      find_theta_crossing(r0, u, l, ijk[i])),
54,663,796✔
2151
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
54,663,796✔
2152
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
109,327,592✔
2153

2154
  } else {
2155
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,458,535✔
2156
                      find_phi_crossing(r0, u, l, ijk[i])),
55,458,535✔
2157
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,458,535✔
2158
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
110,917,070✔
2159
  }
2160
}
2161

2162
int SphericalMesh::set_grid()
379✔
2163
{
2164
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
379✔
2165
    static_cast<int>(grid_[1].size()) - 1,
379✔
2166
    static_cast<int>(grid_[2].size()) - 1};
379✔
2167

2168
  for (const auto& g : grid_) {
1,516✔
2169
    if (g.size() < 2) {
1,137!
UNCOV
2170
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2171
                 "must each have at least 2 points");
UNCOV
2172
      return OPENMC_E_INVALID_ARGUMENT;
×
2173
    }
2174
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,137✔
2175
        g.end()) {
2,274!
UNCOV
2176
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2177
                 "spherical meshes must be sorted and unique.");
UNCOV
2178
      return OPENMC_E_INVALID_ARGUMENT;
×
2179
    }
2180
    if (g.front() < 0.0) {
1,137!
UNCOV
2181
      set_errmsg("r-, theta-, and phi- grids for "
×
2182
                 "spherical meshes must start at v >= 0.");
UNCOV
2183
      return OPENMC_E_INVALID_ARGUMENT;
×
2184
    }
2185
  }
2186
  if (grid_[1].back() > PI) {
379!
UNCOV
2187
    set_errmsg("theta-grids for "
×
2188
               "spherical meshes must end with theta <= pi.");
2189

UNCOV
2190
    return OPENMC_E_INVALID_ARGUMENT;
×
2191
  }
2192
  if (grid_[2].back() > 2 * PI) {
379!
UNCOV
2193
    set_errmsg("phi-grids for "
×
2194
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2195
    return OPENMC_E_INVALID_ARGUMENT;
×
2196
  }
2197

2198
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
379!
2199
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
379✔
2200

2201
  double r = grid_[0].back();
379✔
2202
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
379✔
2203
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
379✔
2204

2205
  return 0;
379✔
2206
}
2207

2208
int SphericalMesh::get_index_in_direction(double r, int i) const
204,525,750✔
2209
{
2210
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
204,525,750✔
2211
}
2212

UNCOV
2213
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2214
  Position plot_ll, Position plot_ur) const
2215
{
UNCOV
2216
  fatal_error("Plot of spherical Mesh not implemented");
×
2217

2218
  // Figure out which axes lie in the plane of the plot.
2219
  array<vector<double>, 2> axis_lines;
2220
  return {axis_lines[0], axis_lines[1]};
2221
}
2222

2223
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2224
{
2225
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2226
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2227
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2228
  write_dataset(mesh_group, "origin", origin_);
319✔
2229
}
319✔
2230

2231
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2232
{
2233
  double r_i = grid_[0][ijk[0] - 1];
935✔
2234
  double r_o = grid_[0][ijk[0]];
935✔
2235

2236
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2237
  double theta_o = grid_[1][ijk[1]];
935✔
2238

2239
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2240
  double phi_o = grid_[2][ijk[2]];
935✔
2241

2242
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
935✔
2243
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2244
}
2245

2246
//==============================================================================
2247
// Helper functions for the C API
2248
//==============================================================================
2249

2250
int check_mesh(int32_t index)
6,336✔
2251
{
2252
  if (index < 0 || index >= model::meshes.size()) {
6,336!
2253
    set_errmsg("Index in meshes array is out of bounds.");
×
UNCOV
2254
    return OPENMC_E_OUT_OF_BOUNDS;
×
2255
  }
2256
  return 0;
6,336✔
2257
}
2258

2259
template<class T>
2260
int check_mesh_type(int32_t index)
1,100✔
2261
{
2262
  if (int err = check_mesh(index))
1,100!
UNCOV
2263
    return err;
×
2264

2265
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2266
  if (!mesh) {
1,100!
2267
    set_errmsg("This function is not valid for input mesh.");
×
UNCOV
2268
    return OPENMC_E_INVALID_TYPE;
×
2269
  }
2270
  return 0;
1,100✔
2271
}
2272

2273
template<class T>
2274
bool is_mesh_type(int32_t index)
2275
{
2276
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2277
  return mesh;
2278
}
2279

2280
//==============================================================================
2281
// C API functions
2282
//==============================================================================
2283

2284
// Return the type of mesh as a C string
2285
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,463✔
2286
{
2287
  if (int err = check_mesh(index))
1,463!
UNCOV
2288
    return err;
×
2289

2290
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,463✔
2291

2292
  return 0;
1,463✔
2293
}
2294

2295
//! Extend the meshes array by n elements
2296
extern "C" int openmc_extend_meshes(
253✔
2297
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2298
{
2299
  if (index_start)
253!
2300
    *index_start = model::meshes.size();
253✔
2301
  std::string mesh_type;
253✔
2302

2303
  for (int i = 0; i < n; ++i) {
506✔
2304
    if (RegularMesh::mesh_type == type) {
253✔
2305
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2306
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2307
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2308
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2309
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2310
    } else if (SphericalMesh::mesh_type == type) {
22!
2311
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2312
    } else {
UNCOV
2313
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2314
    }
2315
  }
2316
  if (index_end)
253!
UNCOV
2317
    *index_end = model::meshes.size() - 1;
×
2318

2319
  return 0;
253✔
2320
}
253✔
2321

2322
//! Adds a new unstructured mesh to OpenMC
UNCOV
2323
extern "C" int openmc_add_unstructured_mesh(
×
2324
  const char filename[], const char library[], int* id)
2325
{
2326
  std::string lib_name(library);
×
2327
  std::string mesh_file(filename);
×
UNCOV
2328
  bool valid_lib = false;
×
2329

2330
#ifdef OPENMC_DAGMC_ENABLED
2331
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2332
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2333
    valid_lib = true;
2334
  }
2335
#endif
2336

2337
#ifdef OPENMC_LIBMESH_ENABLED
2338
  if (lib_name == LibMesh::mesh_lib_type) {
×
2339
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2340
    valid_lib = true;
2341
  }
2342
#endif
2343

2344
  if (!valid_lib) {
×
UNCOV
2345
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2346
                           "by this build of OpenMC",
2347
      lib_name));
UNCOV
2348
    return OPENMC_E_INVALID_ARGUMENT;
×
2349
  }
2350

2351
  // auto-assign new ID
2352
  model::meshes.back()->set_id(-1);
×
UNCOV
2353
  *id = model::meshes.back()->id_;
×
2354

2355
  return 0;
×
UNCOV
2356
}
×
2357

2358
//! Return the index in the meshes array of a mesh with a given ID
2359
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2360
{
2361
  auto pair = model::mesh_map.find(id);
429✔
2362
  if (pair == model::mesh_map.end()) {
429!
2363
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
UNCOV
2364
    return OPENMC_E_INVALID_ID;
×
2365
  }
2366
  *index = pair->second;
429✔
2367
  return 0;
429✔
2368
}
2369

2370
//! Return the ID of a mesh
2371
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,794✔
2372
{
2373
  if (int err = check_mesh(index))
2,794!
UNCOV
2374
    return err;
×
2375
  *id = model::meshes[index]->id_;
2,794✔
2376
  return 0;
2,794✔
2377
}
2378

2379
//! Set the ID of a mesh
2380
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2381
{
2382
  if (int err = check_mesh(index))
253!
UNCOV
2383
    return err;
×
2384
  model::meshes[index]->id_ = id;
253✔
2385
  model::mesh_map[id] = index;
253✔
2386
  return 0;
253✔
2387
}
2388

2389
//! Get the number of elements in a mesh
2390
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
264✔
2391
{
2392
  if (int err = check_mesh(index))
264!
UNCOV
2393
    return err;
×
2394
  *n = model::meshes[index]->n_bins();
264✔
2395
  return 0;
264✔
2396
}
2397

2398
//! Get the volume of each element in the mesh
2399
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2400
{
2401
  if (int err = check_mesh(index))
88!
UNCOV
2402
    return err;
×
2403
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2404
    volumes[i] = model::meshes[index]->volume(i);
880✔
2405
  }
2406
  return 0;
88✔
2407
}
2408

2409
//! Get the bounding box of a mesh
2410
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
154✔
2411
{
2412
  if (int err = check_mesh(index))
154!
UNCOV
2413
    return err;
×
2414

2415
  BoundingBox bbox = model::meshes[index]->bounding_box();
154✔
2416

2417
  // set lower left corner values
2418
  ll[0] = bbox.xmin;
154✔
2419
  ll[1] = bbox.ymin;
154✔
2420
  ll[2] = bbox.zmin;
154✔
2421

2422
  // set upper right corner values
2423
  ur[0] = bbox.xmax;
154✔
2424
  ur[1] = bbox.ymax;
154✔
2425
  ur[2] = bbox.zmax;
154✔
2426
  return 0;
154✔
2427
}
2428

2429
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
176✔
2430
  int nz, int table_size, int32_t* materials, double* volumes)
2431
{
2432
  if (int err = check_mesh(index))
176!
UNCOV
2433
    return err;
×
2434

2435
  try {
2436
    model::meshes[index]->material_volumes(
176✔
2437
      nx, ny, nz, table_size, materials, volumes);
2438
  } catch (const std::exception& e) {
11!
2439
    set_errmsg(e.what());
11✔
2440
    if (starts_with(e.what(), "Mesh")) {
11!
2441
      return OPENMC_E_GEOMETRY;
11✔
2442
    } else {
UNCOV
2443
      return OPENMC_E_ALLOCATE;
×
2444
    }
2445
  }
11✔
2446

2447
  return 0;
165✔
2448
}
2449

2450
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2451
  Position width, int basis, int* pixels, int32_t* data)
2452
{
2453
  if (int err = check_mesh(index))
44!
UNCOV
2454
    return err;
×
2455
  const auto& mesh = model::meshes[index].get();
44✔
2456

2457
  int pixel_width = pixels[0];
44✔
2458
  int pixel_height = pixels[1];
44✔
2459

2460
  // get pixel size
2461
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2462
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2463

2464
  // setup basis indices and initial position centered on pixel
2465
  int in_i, out_i;
2466
  Position xyz = origin;
44✔
2467
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
2468
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2469
  switch (basis_enum) {
44!
2470
  case PlotBasis::xy:
44✔
2471
    in_i = 0;
44✔
2472
    out_i = 1;
44✔
2473
    break;
44✔
2474
  case PlotBasis::xz:
×
2475
    in_i = 0;
×
2476
    out_i = 2;
×
2477
    break;
×
2478
  case PlotBasis::yz:
×
2479
    in_i = 1;
×
2480
    out_i = 2;
×
2481
    break;
×
2482
  default:
×
UNCOV
2483
    UNREACHABLE();
×
2484
  }
2485

2486
  // set initial position
2487
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2488
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2489

2490
#pragma omp parallel
24✔
2491
  {
2492
    Position r = xyz;
20✔
2493

2494
#pragma omp for
2495
    for (int y = 0; y < pixel_height; y++) {
420✔
2496
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2497
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2498
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2499
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2500
      }
2501
    }
2502
  }
2503

2504
  return 0;
44✔
2505
}
2506

2507
//! Get the dimension of a regular mesh
2508
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2509
  int32_t index, int** dims, int* n)
2510
{
2511
  if (int err = check_mesh_type<RegularMesh>(index))
11!
UNCOV
2512
    return err;
×
2513
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2514
  *dims = mesh->shape_.data();
11✔
2515
  *n = mesh->n_dimension_;
11✔
2516
  return 0;
11✔
2517
}
2518

2519
//! Set the dimension of a regular mesh
2520
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2521
  int32_t index, int n, const int* dims)
2522
{
2523
  if (int err = check_mesh_type<RegularMesh>(index))
187!
UNCOV
2524
    return err;
×
2525
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2526

2527
  // Copy dimension
2528
  mesh->n_dimension_ = n;
187✔
2529
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2530
  return 0;
187✔
2531
}
2532

2533
//! Get the regular mesh parameters
2534
extern "C" int openmc_regular_mesh_get_params(
209✔
2535
  int32_t index, double** ll, double** ur, double** width, int* n)
2536
{
2537
  if (int err = check_mesh_type<RegularMesh>(index))
209!
UNCOV
2538
    return err;
×
2539
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2540

2541
  if (m->lower_left_.dimension() == 0) {
209!
2542
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2543
    return OPENMC_E_ALLOCATE;
×
2544
  }
2545

2546
  *ll = m->lower_left_.data();
209✔
2547
  *ur = m->upper_right_.data();
209✔
2548
  *width = m->width_.data();
209✔
2549
  *n = m->n_dimension_;
209✔
2550
  return 0;
209✔
2551
}
2552

2553
//! Set the regular mesh parameters
2554
extern "C" int openmc_regular_mesh_set_params(
220✔
2555
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2556
{
2557
  if (int err = check_mesh_type<RegularMesh>(index))
220!
UNCOV
2558
    return err;
×
2559
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2560

2561
  if (m->n_dimension_ == -1) {
220!
2562
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
UNCOV
2563
    return OPENMC_E_UNASSIGNED;
×
2564
  }
2565

2566
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2567
  if (ll && ur) {
220✔
2568
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
198✔
2569
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
198✔
2570
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
198✔
2571
  } else if (ll && width) {
22!
2572
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
11✔
2573
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
11✔
2574
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
11✔
2575
  } else if (ur && width) {
11!
2576
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
11✔
2577
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
11✔
2578
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
11✔
2579
  } else {
2580
    set_errmsg("At least two parameters must be specified.");
×
UNCOV
2581
    return OPENMC_E_INVALID_ARGUMENT;
×
2582
  }
2583

2584
  // Set material volumes
2585

2586
  // TODO: incorporate this into method in RegularMesh that can be called from
2587
  // here and from constructor
2588
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
220✔
2589
  m->element_volume_ = 1.0;
220✔
2590
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2591
    m->element_volume_ *= m->width_[i];
660✔
2592
  }
2593

2594
  return 0;
220✔
2595
}
220✔
2596

2597
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2598
template<class C>
2599
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2600
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2601
  const int nz)
2602
{
2603
  if (int err = check_mesh_type<C>(index))
88!
UNCOV
2604
    return err;
×
2605

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

2608
  m->n_dimension_ = 3;
88✔
2609

2610
  m->grid_[0].reserve(nx);
88✔
2611
  m->grid_[1].reserve(ny);
88✔
2612
  m->grid_[2].reserve(nz);
88✔
2613

2614
  for (int i = 0; i < nx; i++) {
572✔
2615
    m->grid_[0].push_back(grid_x[i]);
484✔
2616
  }
2617
  for (int i = 0; i < ny; i++) {
341✔
2618
    m->grid_[1].push_back(grid_y[i]);
253✔
2619
  }
2620
  for (int i = 0; i < nz; i++) {
319✔
2621
    m->grid_[2].push_back(grid_z[i]);
231✔
2622
  }
2623

2624
  int err = m->set_grid();
88✔
2625
  return err;
88✔
2626
}
2627

2628
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2629
template<class C>
2630
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2631
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2632
{
2633
  if (int err = check_mesh_type<C>(index))
385!
UNCOV
2634
    return err;
×
2635
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2636

2637
  if (m->lower_left_.dimension() == 0) {
385!
2638
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2639
    return OPENMC_E_ALLOCATE;
×
2640
  }
2641

2642
  *grid_x = m->grid_[0].data();
385✔
2643
  *nx = m->grid_[0].size();
385✔
2644
  *grid_y = m->grid_[1].data();
385✔
2645
  *ny = m->grid_[1].size();
385✔
2646
  *grid_z = m->grid_[2].data();
385✔
2647
  *nz = m->grid_[2].size();
385✔
2648

2649
  return 0;
385✔
2650
}
2651

2652
//! Get the rectilinear mesh grid
2653
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2654
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2655
{
2656
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2657
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2658
}
2659

2660
//! Set the rectilienar mesh parameters
2661
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2662
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2663
  const double* grid_z, const int nz)
2664
{
2665
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2666
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2667
}
2668

2669
//! Get the cylindrical mesh grid
2670
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2671
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2672
{
2673
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2674
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2675
}
2676

2677
//! Set the cylindrical mesh parameters
2678
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2679
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2680
  const double* grid_z, const int nz)
2681
{
2682
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2683
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2684
}
2685

2686
//! Get the spherical mesh grid
2687
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2688
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2689
{
2690

2691
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2692
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2693
  ;
2694
}
2695

2696
//! Set the spherical mesh parameters
2697
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2698
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2699
  const double* grid_z, const int nz)
2700
{
2701
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2702
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2703
}
2704

2705
#ifdef OPENMC_DAGMC_ENABLED
2706

2707
const std::string MOABMesh::mesh_lib_type = "moab";
2708

2709
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2710
{
2711
  initialize();
24✔
2712
}
24✔
2713

2714
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2715
{
2716
  initialize();
×
2717
}
2718

2719
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2720
  : UnstructuredMesh()
×
2721
{
2722
  n_dimension_ = 3;
2723
  filename_ = filename;
×
2724
  set_length_multiplier(length_multiplier);
×
2725
  initialize();
×
2726
}
2727

2728
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2729
{
2730
  mbi_ = external_mbi;
1✔
2731
  filename_ = "unknown (external file)";
1✔
2732
  this->initialize();
1✔
2733
}
1✔
2734

2735
void MOABMesh::initialize()
25✔
2736
{
2737

2738
  // Create the MOAB interface and load data from file
2739
  this->create_interface();
25✔
2740

2741
  // Initialise MOAB error code
2742
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2743

2744
  // Set the dimension
2745
  n_dimension_ = 3;
25✔
2746

2747
  // set member range of tetrahedral entities
2748
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2749
  if (rval != moab::MB_SUCCESS) {
25!
2750
    fatal_error("Failed to get all tetrahedral elements");
2751
  }
2752

2753
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2754
    warning("Non-tetrahedral elements found in unstructured "
×
2755
            "mesh file: " +
2756
            filename_);
2757
  }
2758

2759
  // set member range of vertices
2760
  int vertex_dim = 0;
25✔
2761
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2762
  if (rval != moab::MB_SUCCESS) {
25!
2763
    fatal_error("Failed to get all vertex handles");
2764
  }
2765

2766
  // make an entity set for all tetrahedra
2767
  // this is used for convenience later in output
2768
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2769
  if (rval != moab::MB_SUCCESS) {
25!
2770
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2771
  }
2772

2773
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2774
  if (rval != moab::MB_SUCCESS) {
25!
2775
    fatal_error("Failed to add tetrahedra to an entity set.");
2776
  }
2777

2778
  if (length_multiplier_ > 0.0) {
25!
2779
    // get the connectivity of all tets
2780
    moab::Range adj;
×
2781
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2782
    if (rval != moab::MB_SUCCESS) {
×
2783
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2784
    }
2785
    // scale all vertex coords by multiplier (done individually so not all
2786
    // coordinates are in memory twice at once)
2787
    for (auto vert : adj) {
×
2788
      // retrieve coords
2789
      std::array<double, 3> coord;
2790
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2791
      if (rval != moab::MB_SUCCESS) {
×
2792
        fatal_error("Could not get coordinates of vertex.");
2793
      }
2794
      // scale coords
2795
      for (auto& c : coord) {
×
2796
        c *= length_multiplier_;
2797
      }
2798
      // set new coords
2799
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2800
      if (rval != moab::MB_SUCCESS) {
×
2801
        fatal_error("Failed to set new vertex coordinates");
2802
      }
2803
    }
2804
  }
2805

2806
  // Determine bounds of mesh
2807
  this->determine_bounds();
25✔
2808
}
25✔
2809

2810
void MOABMesh::prepare_for_point_location()
21✔
2811
{
2812
  // if the KDTree has already been constructed, do nothing
2813
  if (kdtree_)
21!
2814
    return;
2815

2816
  // build acceleration data structures
2817
  compute_barycentric_data(ehs_);
21✔
2818
  build_kdtree(ehs_);
21✔
2819
}
2820

2821
void MOABMesh::create_interface()
25✔
2822
{
2823
  // Do not create a MOAB instance if one is already in memory
2824
  if (mbi_)
25✔
2825
    return;
1✔
2826

2827
  // create MOAB instance
2828
  mbi_ = std::make_shared<moab::Core>();
24✔
2829

2830
  // load unstructured mesh file
2831
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2832
  if (rval != moab::MB_SUCCESS) {
24!
2833
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2834
  }
2835
}
2836

2837
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
2838
{
2839
  moab::Range all_tris;
21✔
2840
  int adj_dim = 2;
21✔
2841
  write_message("Getting tet adjacencies...", 7);
21✔
2842
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
2843
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2844
  if (rval != moab::MB_SUCCESS) {
21!
2845
    fatal_error("Failed to get adjacent triangles for tets");
2846
  }
2847

2848
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
2849
    warning("Non-triangle elements found in tet adjacencies in "
×
2850
            "unstructured mesh file: " +
2851
            filename_);
×
2852
  }
2853

2854
  // combine into one range
2855
  moab::Range all_tets_and_tris;
21✔
2856
  all_tets_and_tris.merge(all_tets);
21✔
2857
  all_tets_and_tris.merge(all_tris);
21✔
2858

2859
  // create a kd-tree instance
2860
  write_message(
21✔
2861
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
2862
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
2863

2864
  // Determine what options to use
2865
  std::ostringstream options_stream;
21✔
2866
  if (options_.empty()) {
21✔
2867
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
2868
  } else {
2869
    options_stream << options_;
16✔
2870
  }
2871
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
2872

2873
  // Build the k-d tree
2874
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
2875
  if (rval != moab::MB_SUCCESS) {
21!
2876
    fatal_error("Failed to construct KDTree for the "
2877
                "unstructured mesh file: " +
2878
                filename_);
×
2879
  }
2880
}
21✔
2881

2882
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
2883
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2884
{
2885
  hits.clear();
1,543,584✔
2886

2887
  moab::ErrorCode rval;
2888
  vector<moab::EntityHandle> tris;
1,543,584✔
2889
  // get all intersections with triangles in the tet mesh
2890
  // (distances are relative to the start point, not the previous
2891
  // intersection)
2892
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
2893
    dir.array(), start.array(), tris, hits, 0, track_len);
2894
  if (rval != moab::MB_SUCCESS) {
1,543,584!
2895
    fatal_error(
2896
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
2897
  }
2898

2899
  // remove duplicate intersection distances
2900
  std::unique(hits.begin(), hits.end());
1,543,584✔
2901

2902
  // sorts by first component of std::pair by default
2903
  std::sort(hits.begin(), hits.end());
1,543,584✔
2904
}
1,543,584✔
2905

2906
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
2907
  vector<int>& bins, vector<double>& lengths) const
2908
{
2909
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
2910
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
2911
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
2912
  dir.normalize();
1,543,584✔
2913

2914
  double track_len = (end - start).length();
1,543,584✔
2915
  if (track_len == 0.0)
1,543,584!
2916
    return;
721,692✔
2917

2918
  start -= TINY_BIT * dir;
1,543,584✔
2919
  end += TINY_BIT * dir;
1,543,584✔
2920

2921
  vector<double> hits;
1,543,584✔
2922
  intersect_track(start, dir, track_len, hits);
1,543,584✔
2923

2924
  bins.clear();
1,543,584✔
2925
  lengths.clear();
1,543,584✔
2926

2927
  // if there are no intersections the track may lie entirely
2928
  // within a single tet. If this is the case, apply entire
2929
  // score to that tet and return.
2930
  if (hits.size() == 0) {
1,543,584✔
2931
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
2932
    int bin = this->get_bin(midpoint);
721,692✔
2933
    if (bin != -1) {
721,692✔
2934
      bins.push_back(bin);
242,866✔
2935
      lengths.push_back(1.0);
242,866✔
2936
    }
2937
    return;
721,692✔
2938
  }
2939

2940
  // for each segment in the set of tracks, try to look up a tet
2941
  // at the midpoint of the segment
2942
  Position current = r0;
821,892✔
2943
  double last_dist = 0.0;
821,892✔
2944
  for (const auto& hit : hits) {
5,516,161✔
2945
    // get the segment length
2946
    double segment_length = hit - last_dist;
4,694,269✔
2947
    last_dist = hit;
4,694,269✔
2948
    // find the midpoint of this segment
2949
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
2950
    // try to find a tet for this position
2951
    int bin = this->get_bin(midpoint);
4,694,269✔
2952

2953
    // determine the start point for this segment
2954
    current = r0 + u * hit;
4,694,269✔
2955

2956
    if (bin == -1) {
4,694,269✔
2957
      continue;
20,522✔
2958
    }
2959

2960
    bins.push_back(bin);
4,673,747✔
2961
    lengths.push_back(segment_length / track_len);
4,673,747✔
2962
  }
2963

2964
  // tally remaining portion of track after last hit if
2965
  // the last segment of the track is in the mesh but doesn't
2966
  // reach the other side of the tet
2967
  if (hits.back() < track_len) {
821,892!
2968
    Position segment_start = r0 + u * hits.back();
821,892✔
2969
    double segment_length = track_len - hits.back();
821,892✔
2970
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
2971
    int bin = this->get_bin(midpoint);
821,892✔
2972
    if (bin != -1) {
821,892✔
2973
      bins.push_back(bin);
766,509✔
2974
      lengths.push_back(segment_length / track_len);
766,509✔
2975
    }
2976
  }
2977
};
1,543,584✔
2978

2979
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,172✔
2980
{
2981
  moab::CartVect pos(r.x, r.y, r.z);
7,317,172✔
2982
  // find the leaf of the kd-tree for this position
2983
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,172✔
2984
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,172✔
2985
  if (rval != moab::MB_SUCCESS) {
7,317,172✔
2986
    return 0;
1,011,897✔
2987
  }
2988

2989
  // retrieve the tet elements of this leaf
2990
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,275✔
2991
  moab::Range tets;
6,305,275✔
2992
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,275✔
2993
  if (rval != moab::MB_SUCCESS) {
6,305,275!
2994
    warning("MOAB error finding tets.");
×
2995
  }
2996

2997
  // loop over the tets in this leaf, returning the containing tet if found
2998
  for (const auto& tet : tets) {
260,209,886✔
2999
    if (point_in_tet(pos, tet)) {
260,207,039✔
3000
      return tet;
6,302,428✔
3001
    }
3002
  }
3003

3004
  // if no tet is found, return an invalid handle
3005
  return 0;
2,847✔
3006
}
7,317,172✔
3007

3008
double MOABMesh::volume(int bin) const
167,880✔
3009
{
3010
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3011
}
3012

3013
std::string MOABMesh::library() const
34✔
3014
{
3015
  return mesh_lib_type;
34✔
3016
}
3017

3018
// Sample position within a tet for MOAB type tets
3019
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3020
{
3021

3022
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3023

3024
  // Get vertex coordinates for MOAB tet
3025
  const moab::EntityHandle* conn1;
3026
  int conn1_size;
3027
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3028
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3029
    fatal_error(fmt::format(
×
3030
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3031
      conn1_size));
3032
  }
3033
  moab::CartVect p[4];
1,002,050✔
3034
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3035
  if (rval != moab::MB_SUCCESS) {
200,410!
3036
    fatal_error("Failed to get tet coords");
3037
  }
3038

3039
  std::array<Position, 4> tet_verts;
200,410✔
3040
  for (int i = 0; i < 4; i++) {
1,002,050✔
3041
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3042
  }
3043
  // Samples position within tet using Barycentric stuff
3044
  return this->sample_tet(tet_verts, seed);
400,820✔
3045
}
3046

3047
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3048
{
3049
  vector<moab::EntityHandle> conn;
167,880✔
3050
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3051
  if (rval != moab::MB_SUCCESS) {
167,880!
3052
    fatal_error("Failed to get tet connectivity");
3053
  }
3054

3055
  moab::CartVect p[4];
839,400✔
3056
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3057
  if (rval != moab::MB_SUCCESS) {
167,880!
3058
    fatal_error("Failed to get tet coords");
3059
  }
3060

3061
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
335,760✔
3062
}
167,880✔
3063

3064
int MOABMesh::get_bin(Position r) const
7,317,172✔
3065
{
3066
  moab::EntityHandle tet = get_tet(r);
7,317,172✔
3067
  if (tet == 0) {
7,317,172✔
3068
    return -1;
1,014,744✔
3069
  } else {
3070
    return get_bin_from_ent_handle(tet);
6,302,428✔
3071
  }
3072
}
3073

3074
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3075
{
3076
  moab::ErrorCode rval;
3077

3078
  baryc_data_.clear();
21✔
3079
  baryc_data_.resize(tets.size());
21✔
3080

3081
  // compute the barycentric data for each tet element
3082
  // and store it as a 3x3 matrix
3083
  for (auto& tet : tets) {
239,757✔
3084
    vector<moab::EntityHandle> verts;
239,736✔
3085
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3086
    if (rval != moab::MB_SUCCESS) {
239,736!
3087
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3088
    }
3089

3090
    moab::CartVect p[4];
1,198,680✔
3091
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3092
    if (rval != moab::MB_SUCCESS) {
239,736!
3093
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3094
    }
3095

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

3098
    // invert now to avoid this cost later
3099
    a = a.transpose().inverse();
239,736✔
3100
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3101
  }
239,736✔
3102
}
21✔
3103

3104
bool MOABMesh::point_in_tet(
260,207,039✔
3105
  const moab::CartVect& r, moab::EntityHandle tet) const
3106
{
3107

3108
  moab::ErrorCode rval;
3109

3110
  // get tet vertices
3111
  vector<moab::EntityHandle> verts;
260,207,039✔
3112
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,207,039✔
3113
  if (rval != moab::MB_SUCCESS) {
260,207,039!
3114
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3115
    return false;
3116
  }
3117

3118
  // first vertex is used as a reference point for the barycentric data -
3119
  // retrieve its coordinates
3120
  moab::CartVect p_zero;
260,207,039✔
3121
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,207,039✔
3122
  if (rval != moab::MB_SUCCESS) {
260,207,039!
3123
    warning("Failed to get coordinates of a vertex in "
×
3124
            "unstructured mesh: " +
3125
            filename_);
×
3126
    return false;
3127
  }
3128

3129
  // look up barycentric data
3130
  int idx = get_bin_from_ent_handle(tet);
260,207,039✔
3131
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,207,039✔
3132

3133
  moab::CartVect bary_coords = a_inv * (r - p_zero);
260,207,039✔
3134

3135
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
421,415,065✔
3136
          bary_coords[2] >= 0.0 &&
443,103,099✔
3137
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
281,895,073✔
3138
}
260,207,039✔
3139

3140
int MOABMesh::get_bin_from_index(int idx) const
3141
{
3142
  if (idx >= n_bins()) {
×
3143
    fatal_error(fmt::format("Invalid bin index: {}", idx));
×
3144
  }
3145
  return ehs_[idx] - ehs_[0];
3146
}
3147

3148
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3149
{
3150
  int bin = get_bin(r);
3151
  *in_mesh = bin != -1;
3152
  return bin;
3153
}
3154

3155
int MOABMesh::get_index_from_bin(int bin) const
3156
{
3157
  return bin;
3158
}
3159

3160
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3161
  Position plot_ll, Position plot_ur) const
3162
{
3163
  // TODO: Implement mesh lines
3164
  return {};
3165
}
3166

3167
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3168
{
3169
  int idx = vert - verts_[0];
815,520✔
3170
  if (idx >= n_vertices()) {
815,520!
3171
    fatal_error(
3172
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3173
  }
3174
  return idx;
815,520✔
3175
}
3176

3177
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,749,203✔
3178
{
3179
  int bin = eh - ehs_[0];
266,749,203✔
3180
  if (bin >= n_bins()) {
266,749,203!
3181
    fatal_error(fmt::format("Invalid bin: {}", bin));
×
3182
  }
3183
  return bin;
266,749,203✔
3184
}
3185

3186
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3187
{
3188
  if (bin >= n_bins()) {
572,170!
3189
    fatal_error(fmt::format("Invalid bin index: ", bin));
×
3190
  }
3191
  return ehs_[0] + bin;
572,170✔
3192
}
3193

3194
int MOABMesh::n_bins() const
267,525,326✔
3195
{
3196
  return ehs_.size();
267,525,326✔
3197
}
3198

3199
int MOABMesh::n_surface_bins() const
3200
{
3201
  // collect all triangles in the set of tets for this mesh
3202
  moab::Range tris;
×
3203
  moab::ErrorCode rval;
3204
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3205
  if (rval != moab::MB_SUCCESS) {
×
3206
    warning("Failed to get all triangles in the mesh instance");
×
3207
    return -1;
3208
  }
3209
  return 2 * tris.size();
×
3210
}
3211

3212
Position MOABMesh::centroid(int bin) const
3213
{
3214
  moab::ErrorCode rval;
3215

3216
  auto tet = this->get_ent_handle_from_bin(bin);
×
3217

3218
  // look up the tet connectivity
3219
  vector<moab::EntityHandle> conn;
3220
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3221
  if (rval != moab::MB_SUCCESS) {
×
3222
    warning("Failed to get connectivity of a mesh element.");
×
3223
    return {};
3224
  }
3225

3226
  // get the coordinates
3227
  vector<moab::CartVect> coords(conn.size());
×
3228
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3229
  if (rval != moab::MB_SUCCESS) {
×
3230
    warning("Failed to get the coordinates of a mesh element.");
×
3231
    return {};
3232
  }
3233

3234
  // compute the centroid of the element vertices
3235
  moab::CartVect centroid(0.0, 0.0, 0.0);
3236
  for (const auto& coord : coords) {
×
3237
    centroid += coord;
3238
  }
3239
  centroid /= double(coords.size());
3240

3241
  return {centroid[0], centroid[1], centroid[2]};
3242
}
3243

3244
int MOABMesh::n_vertices() const
845,874✔
3245
{
3246
  return verts_.size();
845,874✔
3247
}
3248

3249
Position MOABMesh::vertex(int id) const
86,227✔
3250
{
3251

3252
  moab::ErrorCode rval;
3253

3254
  moab::EntityHandle vert = verts_[id];
86,227✔
3255

3256
  moab::CartVect coords;
86,227✔
3257
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3258
  if (rval != moab::MB_SUCCESS) {
86,227!
3259
    fatal_error("Failed to get the coordinates of a vertex.");
3260
  }
3261

3262
  return {coords[0], coords[1], coords[2]};
172,454✔
3263
}
3264

3265
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3266
{
3267
  moab::ErrorCode rval;
3268

3269
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3270

3271
  // look up the tet connectivity
3272
  vector<moab::EntityHandle> conn;
203,880✔
3273
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3274
  if (rval != moab::MB_SUCCESS) {
203,880!
3275
    fatal_error("Failed to get connectivity of a mesh element.");
3276
    return {};
3277
  }
3278

3279
  std::vector<int> verts(4);
203,880✔
3280
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3281
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3282
  }
3283

3284
  return verts;
203,880✔
3285
}
203,880✔
3286

3287
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3288
  std::string score) const
3289
{
3290
  moab::ErrorCode rval;
3291
  // add a tag to the mesh
3292
  // all scores are treated as a single value
3293
  // with an uncertainty
3294
  moab::Tag value_tag;
3295

3296
  // create the value tag if not present and get handle
3297
  double default_val = 0.0;
3298
  auto val_string = score + "_mean";
×
3299
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3300
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3301
  if (rval != moab::MB_SUCCESS) {
×
3302
    auto msg =
3303
      fmt::format("Could not create or retrieve the value tag for the score {}"
3304
                  " on unstructured mesh {}",
3305
        score, id_);
×
3306
    fatal_error(msg);
3307
  }
3308

3309
  // create the std dev tag if not present and get handle
3310
  moab::Tag error_tag;
3311
  std::string err_string = score + "_std_dev";
×
3312
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3313
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3314
  if (rval != moab::MB_SUCCESS) {
×
3315
    auto msg =
3316
      fmt::format("Could not create or retrieve the error tag for the score {}"
3317
                  " on unstructured mesh {}",
3318
        score, id_);
×
3319
    fatal_error(msg);
3320
  }
3321

3322
  // return the populated tag handles
3323
  return {value_tag, error_tag};
3324
}
3325

3326
void MOABMesh::add_score(const std::string& score)
3327
{
3328
  auto score_tags = get_score_tags(score);
×
3329
  tag_names_.push_back(score);
×
3330
}
3331

3332
void MOABMesh::remove_scores()
3333
{
3334
  for (const auto& name : tag_names_) {
×
3335
    auto value_name = name + "_mean";
×
3336
    moab::Tag tag;
3337
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3338
    if (rval != moab::MB_SUCCESS)
×
3339
      return;
3340

3341
    rval = mbi_->tag_delete(tag);
×
3342
    if (rval != moab::MB_SUCCESS) {
×
3343
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3344
                             " on unstructured mesh {}",
3345
        name, id_);
×
3346
      fatal_error(msg);
3347
    }
3348

3349
    auto std_dev_name = name + "_std_dev";
×
3350
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3351
    if (rval != moab::MB_SUCCESS) {
×
3352
      auto msg =
3353
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3354
                    " on unstructured mesh {}",
3355
          name, id_);
×
3356
    }
3357

3358
    rval = mbi_->tag_delete(tag);
×
3359
    if (rval != moab::MB_SUCCESS) {
×
3360
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3361
                             " on unstructured mesh {}",
3362
        name, id_);
×
3363
      fatal_error(msg);
3364
    }
3365
  }
×
3366
  tag_names_.clear();
3367
}
3368

3369
void MOABMesh::set_score_data(const std::string& score,
3370
  const vector<double>& values, const vector<double>& std_dev)
3371
{
3372
  auto score_tags = this->get_score_tags(score);
×
3373

3374
  moab::ErrorCode rval;
3375
  // set the score value
3376
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
×
3377
  if (rval != moab::MB_SUCCESS) {
×
3378
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3379
                           "on unstructured mesh {}",
3380
      score, id_);
×
3381
    warning(msg);
×
3382
  }
3383

3384
  // set the error value
3385
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
×
3386
  if (rval != moab::MB_SUCCESS) {
×
3387
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3388
                           "on unstructured mesh {}",
3389
      score, id_);
×
3390
    warning(msg);
×
3391
  }
3392
}
3393

3394
void MOABMesh::write(const std::string& base_filename) const
3395
{
3396
  // add extension to the base name
3397
  auto filename = base_filename + ".vtk";
×
3398
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3399
  filename = settings::path_output + filename;
×
3400

3401
  // write the tetrahedral elements of the mesh only
3402
  // to avoid clutter from zero-value data on other
3403
  // elements during visualization
3404
  moab::ErrorCode rval;
3405
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3406
  if (rval != moab::MB_SUCCESS) {
×
3407
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3408
    warning(msg);
×
3409
  }
3410
}
3411

3412
#endif
3413

3414
#ifdef OPENMC_LIBMESH_ENABLED
3415

3416
const std::string LibMesh::mesh_lib_type = "libmesh";
3417

3418
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
3419
{
3420
  // filename_ and length_multiplier_ will already be set by the
3421
  // UnstructuredMesh constructor
3422
  set_mesh_pointer_from_filename(filename_);
23✔
3423
  set_length_multiplier(length_multiplier_);
23✔
3424
  initialize();
23✔
3425
}
23✔
3426

3427
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3428
{
3429
  // filename_ and length_multiplier_ will already be set by the
3430
  // UnstructuredMesh constructor
3431
  set_mesh_pointer_from_filename(filename_);
×
3432
  set_length_multiplier(length_multiplier_);
×
3433
  initialize();
×
3434
}
3435

3436
// create the mesh from a pointer to a libMesh Mesh
3437
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3438
{
3439
  if (!input_mesh.is_replicated()) {
×
3440
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3441
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3442
  }
3443

3444
  m_ = &input_mesh;
3445
  set_length_multiplier(length_multiplier);
×
3446
  initialize();
×
3447
}
3448

3449
// create the mesh from an input file
3450
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3451
{
3452
  n_dimension_ = 3;
3453
  set_mesh_pointer_from_filename(filename);
×
3454
  set_length_multiplier(length_multiplier);
×
3455
  initialize();
×
3456
}
3457

3458
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23✔
3459
{
3460
  filename_ = filename;
23✔
3461
  unique_m_ =
3462
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23✔
3463
  m_ = unique_m_.get();
23✔
3464
  m_->read(filename_);
23✔
3465
}
23✔
3466

3467
// build a libMesh equation system for storing values
3468
void LibMesh::build_eqn_sys()
15✔
3469
{
3470
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
30✔
3471
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15✔
3472
  libMesh::ExplicitSystem& eq_sys =
3473
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15✔
3474
}
15✔
3475

3476
// intialize from mesh file
3477
void LibMesh::initialize()
23✔
3478
{
3479
  if (!settings::libmesh_comm) {
23!
3480
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3481
                "communicator.");
3482
  }
3483

3484
  // assuming that unstructured meshes used in OpenMC are 3D
3485
  n_dimension_ = 3;
23✔
3486

3487
  if (length_multiplier_ > 0.0) {
23!
3488
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
×
3489
  }
3490
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3491
  // Otherwise assume that it is prepared by its owning application
3492
  if (unique_m_) {
23!
3493
    m_->prepare_for_use();
23✔
3494
  }
3495

3496
  // ensure that the loaded mesh is 3 dimensional
3497
  if (m_->mesh_dimension() != n_dimension_) {
23!
3498
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3499
                            "mesh is not a 3D mesh.",
3500
      filename_));
3501
  }
3502

3503
  for (int i = 0; i < num_threads(); i++) {
69✔
3504
    pl_.emplace_back(m_->sub_point_locator());
46✔
3505
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3506
    pl_.back()->enable_out_of_mesh_mode();
46✔
3507
  }
3508

3509
  // store first element in the mesh to use as an offset for bin indices
3510
  auto first_elem = *m_->elements_begin();
23✔
3511
  first_element_id_ = first_elem->id();
23✔
3512

3513
  // bounding box for the mesh for quick rejection checks
3514
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23✔
3515
  libMesh::Point ll = bbox_.min();
23✔
3516
  libMesh::Point ur = bbox_.max();
23✔
3517
  lower_left_ = {ll(0), ll(1), ll(2)};
23✔
3518
  upper_right_ = {ur(0), ur(1), ur(2)};
23✔
3519
}
23✔
3520

3521
// Sample position within a tet for LibMesh type tets
3522
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3523
{
3524
  const auto& elem = get_element_from_bin(bin);
400,820✔
3525
  // Get tet vertex coordinates from LibMesh
3526
  std::array<Position, 4> tet_verts;
400,820✔
3527
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3528
    auto node_ref = elem.node_ref(i);
1,603,280✔
3529
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3530
  }
1,603,280✔
3531
  // Samples position within tet using Barycentric coordinates
3532
  return this->sample_tet(tet_verts, seed);
801,640✔
3533
}
3534

3535
Position LibMesh::centroid(int bin) const
3536
{
3537
  const auto& elem = this->get_element_from_bin(bin);
×
3538
  auto centroid = elem.vertex_average();
×
3539
  return {centroid(0), centroid(1), centroid(2)};
3540
}
3541

3542
int LibMesh::n_vertices() const
39,978✔
3543
{
3544
  return m_->n_nodes();
39,978✔
3545
}
3546

3547
Position LibMesh::vertex(int vertex_id) const
39,942✔
3548
{
3549
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3550
  return {node_ref(0), node_ref(1), node_ref(2)};
79,884✔
3551
}
39,942✔
3552

3553
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
3554
{
3555
  std::vector<int> conn;
265,856✔
3556
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
3557
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
3558
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
3559
  }
3560
  return conn;
265,856✔
3561
}
3562

3563
std::string LibMesh::library() const
33✔
3564
{
3565
  return mesh_lib_type;
33✔
3566
}
3567

3568
int LibMesh::n_bins() const
1,784,287✔
3569
{
3570
  return m_->n_elem();
1,784,287✔
3571
}
3572

3573
int LibMesh::n_surface_bins() const
3574
{
3575
  int n_bins = 0;
3576
  for (int i = 0; i < this->n_bins(); i++) {
×
3577
    const libMesh::Elem& e = get_element_from_bin(i);
3578
    n_bins += e.n_faces();
3579
    // if this is a boundary element, it will only be visited once,
3580
    // the number of surface bins is incremented to
3581
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3582
      // null neighbor pointer indicates a boundary face
3583
      if (!neighbor_ptr) {
×
3584
        n_bins++;
3585
      }
3586
    }
3587
  }
3588
  return n_bins;
3589
}
3590

3591
void LibMesh::add_score(const std::string& var_name)
15✔
3592
{
3593
  if (!equation_systems_) {
15!
3594
    build_eqn_sys();
15✔
3595
  }
3596

3597
  // check if this is a new variable
3598
  std::string value_name = var_name + "_mean";
15✔
3599
  if (!variable_map_.count(value_name)) {
15!
3600
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3601
    auto var_num =
3602
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3603
    variable_map_[value_name] = var_num;
15✔
3604
  }
3605

3606
  std::string std_dev_name = var_name + "_std_dev";
15✔
3607
  // check if this is a new variable
3608
  if (!variable_map_.count(std_dev_name)) {
15!
3609
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3610
    auto var_num =
3611
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3612
    variable_map_[std_dev_name] = var_num;
15✔
3613
  }
3614
}
15✔
3615

3616
void LibMesh::remove_scores()
15✔
3617
{
3618
  if (equation_systems_) {
15!
3619
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3620
    eqn_sys.clear();
15✔
3621
    variable_map_.clear();
15✔
3622
  }
3623
}
15✔
3624

3625
void LibMesh::set_score_data(const std::string& var_name,
15✔
3626
  const vector<double>& values, const vector<double>& std_dev)
3627
{
3628
  if (!equation_systems_) {
15!
3629
    build_eqn_sys();
×
3630
  }
3631

3632
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3633

3634
  if (!eqn_sys.is_initialized()) {
15!
3635
    equation_systems_->init();
15✔
3636
  }
3637

3638
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3639

3640
  // look up the value variable
3641
  std::string value_name = var_name + "_mean";
15✔
3642
  unsigned int value_num = variable_map_.at(value_name);
15✔
3643
  // look up the std dev variable
3644
  std::string std_dev_name = var_name + "_std_dev";
15✔
3645
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15✔
3646

3647
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
97,871✔
3648
       it++) {
3649
    if (!(*it)->active()) {
97,856!
3650
      continue;
3651
    }
3652

3653
    auto bin = get_bin_from_element(*it);
97,856✔
3654

3655
    // set value
3656
    vector<libMesh::dof_id_type> value_dof_indices;
97,856✔
3657
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856✔
3658
    assert(value_dof_indices.size() == 1);
3659
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856✔
3660

3661
    // set std dev
3662
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
3663
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
3664
    assert(std_dev_dof_indices.size() == 1);
3665
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
3666
  }
97,871✔
3667
}
15✔
3668

3669
void LibMesh::write(const std::string& filename) const
15✔
3670
{
3671
  write_message(fmt::format(
15✔
3672
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15✔
3673
  libMesh::ExodusII_IO exo(*m_);
15✔
3674
  std::set<std::string> systems_out = {eq_system_name_};
45✔
3675
  exo.write_discontinuous_exodusII(
15✔
3676
    filename + ".e", *equation_systems_, &systems_out);
30✔
3677
}
15✔
3678

3679
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3680
  vector<int>& bins, vector<double>& lengths) const
3681
{
3682
  // TODO: Implement triangle crossings here
3683
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3684
}
3685

3686
int LibMesh::get_bin(Position r) const
2,340,484✔
3687
{
3688
  // look-up a tet using the point locator
3689
  libMesh::Point p(r.x, r.y, r.z);
2,340,484✔
3690

3691
  // quick rejection check
3692
  if (!bbox_.contains_point(p)) {
2,340,484✔
3693
    return -1;
918,796✔
3694
  }
3695

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

3698
  const auto elem_ptr = (*point_locator)(p);
1,421,688✔
3699
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,688✔
3700
}
2,340,484✔
3701

3702
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,314✔
3703
{
3704
  int bin = elem->id() - first_element_id_;
1,518,314✔
3705
  if (bin >= n_bins() || bin < 0) {
1,518,314!
3706
    fatal_error(fmt::format("Invalid bin: {}", bin));
3707
  }
3708
  return bin;
1,518,314✔
3709
}
3710

3711
std::pair<vector<double>, vector<double>> LibMesh::plot(
3712
  Position plot_ll, Position plot_ur) const
3713
{
3714
  return {};
3715
}
3716

3717
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3718
{
3719
  return m_->elem_ref(bin);
765,460✔
3720
}
3721

3722
double LibMesh::volume(int bin) const
364,640✔
3723
{
3724
  return this->get_element_from_bin(bin).volume();
364,640✔
3725
}
3726

3727
AdaptiveLibMesh::AdaptiveLibMesh(
3728
  libMesh::MeshBase& input_mesh, double length_multiplier)
3729
  : LibMesh(input_mesh, length_multiplier), num_active_(m_->n_active_elem())
×
3730
{
3731
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3732
  // contiguous in ID space, so we need to map from bin indices (defined over
3733
  // active elements) to global dof ids
3734
  bin_to_elem_map_.reserve(num_active_);
×
3735
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3736
  for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
×
3737
       it++) {
3738
    auto elem = *it;
×
3739

3740
    bin_to_elem_map_.push_back(elem->id());
×
3741
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3742
  }
3743
}
3744

3745
int AdaptiveLibMesh::n_bins() const
3746
{
3747
  return num_active_;
3748
}
3749

3750
void AdaptiveLibMesh::add_score(const std::string& var_name)
3751
{
3752
  warning(fmt::format(
×
3753
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3754
    this->id_));
3755
}
3756

3757
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3758
  const vector<double>& values, const vector<double>& std_dev)
3759
{
3760
  warning(fmt::format(
×
3761
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3762
    this->id_));
3763
}
3764

3765
void AdaptiveLibMesh::write(const std::string& filename) const
3766
{
3767
  warning(fmt::format(
×
3768
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3769
    this->id_));
3770
}
3771

3772
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3773
{
3774
  int bin = elem_to_bin_map_[elem->id()];
×
3775
  if (bin >= n_bins() || bin < 0) {
×
3776
    fatal_error(fmt::format("Invalid bin: {}", bin));
3777
  }
3778
  return bin;
3779
}
3780

3781
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3782
{
3783
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3784
}
3785

3786
#endif // OPENMC_LIBMESH_ENABLED
3787

3788
//==============================================================================
3789
// Non-member functions
3790
//==============================================================================
3791

3792
void read_meshes(pugi::xml_node root)
11,781✔
3793
{
3794
  std::unordered_set<int> mesh_ids;
11,781✔
3795

3796
  for (auto node : root.children("mesh")) {
14,656✔
3797
    // Check to make sure multiple meshes in the same file don't share IDs
3798
    int id = std::stoi(get_node_value(node, "id"));
2,875✔
3799
    if (contains(mesh_ids, id)) {
2,875!
UNCOV
3800
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
3801
                              "'{}' in the same input file",
3802
        id));
3803
    }
3804
    mesh_ids.insert(id);
2,875✔
3805

3806
    // If we've already read a mesh with the same ID in a *different* file,
3807
    // assume it is the same here
3808
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,875!
3809
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
UNCOV
3810
      continue;
×
3811
    }
3812

3813
    std::string mesh_type;
2,875✔
3814
    if (check_for_node(node, "type")) {
2,875✔
3815
      mesh_type = get_node_value(node, "type", true, true);
956✔
3816
    } else {
3817
      mesh_type = "regular";
1,919✔
3818
    }
3819

3820
    // determine the mesh library to use
3821
    std::string mesh_lib;
2,875✔
3822
    if (check_for_node(node, "library")) {
2,875✔
3823
      mesh_lib = get_node_value(node, "library", true, true);
47!
3824
    }
3825

3826
    Mesh::create(node, mesh_type, mesh_lib);
2,875✔
3827
  }
2,875✔
3828
}
11,781✔
3829

3830
void read_meshes(hid_t group)
22✔
3831
{
3832
  std::unordered_set<int> mesh_ids;
22✔
3833

3834
  std::vector<int> ids;
22✔
3835
  read_attribute(group, "ids", ids);
22✔
3836

3837
  for (auto id : ids) {
55✔
3838

3839
    // Check to make sure multiple meshes in the same file don't share IDs
3840
    if (contains(mesh_ids, id)) {
33!
UNCOV
3841
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
3842
                              "'{}' in the same HDF5 input file",
3843
        id));
3844
    }
3845
    mesh_ids.insert(id);
33✔
3846

3847
    // If we've already read a mesh with the same ID in a *different* file,
3848
    // assume it is the same here
3849
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
3850
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
3851
      continue;
33✔
3852
    }
3853

3854
    std::string name = fmt::format("mesh {}", id);
×
UNCOV
3855
    hid_t mesh_group = open_group(group, name.c_str());
×
3856

3857
    std::string mesh_type;
×
3858
    if (object_exists(mesh_group, "type")) {
×
UNCOV
3859
      read_dataset(mesh_group, "type", mesh_type);
×
3860
    } else {
UNCOV
3861
      mesh_type = "regular";
×
3862
    }
3863

3864
    // determine the mesh library to use
3865
    std::string mesh_lib;
×
3866
    if (object_exists(mesh_group, "library")) {
×
UNCOV
3867
      read_dataset(mesh_group, "library", mesh_lib);
×
3868
    }
3869

3870
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
UNCOV
3871
  }
×
3872
}
22✔
3873

3874
void meshes_to_hdf5(hid_t group)
6,566✔
3875
{
3876
  // Write number of meshes
3877
  hid_t meshes_group = create_group(group, "meshes");
6,566✔
3878
  int32_t n_meshes = model::meshes.size();
6,566✔
3879
  write_attribute(meshes_group, "n_meshes", n_meshes);
6,566✔
3880

3881
  if (n_meshes > 0) {
6,566✔
3882
    // Write IDs of meshes
3883
    vector<int> ids;
2,060✔
3884
    for (const auto& m : model::meshes) {
4,699✔
3885
      m->to_hdf5(meshes_group);
2,639✔
3886
      ids.push_back(m->id_);
2,639✔
3887
    }
3888
    write_attribute(meshes_group, "ids", ids);
2,060✔
3889
  }
2,060✔
3890

3891
  close_group(meshes_group);
6,566✔
3892
}
6,566✔
3893

3894
void free_memory_mesh()
7,723✔
3895
{
3896
  model::meshes.clear();
7,723✔
3897
  model::mesh_map.clear();
7,723✔
3898
}
7,723✔
3899

3900
extern "C" int n_meshes()
308✔
3901
{
3902
  return model::meshes.size();
308✔
3903
}
3904

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

© 2026 Coveralls, Inc