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

openmc-dev / openmc / 20163164157

12 Dec 2025 10:01AM UTC coverage: 81.832% (-0.04%) from 81.872%
20163164157

Pull #3279

github

web-flow
Merge c32841e75 into bbfa18d72
Pull Request #3279: Hexagonal mesh model

17271 of 24053 branches covered (71.8%)

Branch coverage included in aggregate %.

602 of 876 new or added lines in 9 files covered. (68.72%)

1836 existing lines in 44 files now uncovered.

55648 of 65055 relevant lines covered (85.54%)

42918761.78 hits per line

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

71.98
/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/hex_mesh.h"
34
#include "openmc/material.h"
35
#include "openmc/memory.h"
36
#include "openmc/message_passing.h"
37
#include "openmc/openmp_interface.h"
38
#include "openmc/output.h"
39
#include "openmc/particle_data.h"
40
#include "openmc/plot.h"
41
#include "openmc/random_dist.h"
42
#include "openmc/search.h"
43
#include "openmc/settings.h"
44
#include "openmc/string_utils.h"
45
#include "openmc/tallies/filter.h"
46
#include "openmc/tallies/tally.h"
47
#include "openmc/timer.h"
48
#include "openmc/volume_calc.h"
49
#include "openmc/xml_interface.h"
50

51
#ifdef OPENMC_LIBMESH_ENABLED
52
#include "libmesh/mesh_modification.h"
53
#include "libmesh/mesh_tools.h"
54
#include "libmesh/numeric_vector.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,421✔
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,421✔
129
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
1,421✔
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,816✔
172
      this->volumes(index_elem, slot) += volume;
2,799,982✔
173
      return;
2,799,982✔
174
    }
175

176
    // Slot appears to be empty; attempt to claim
177
    if (current_val == EMPTY) {
7,107✔
178
      // Attempt compare-and-swap from EMPTY to index_material
179
      int32_t expected_val = EMPTY;
1,421✔
180
      bool claimed_slot =
181
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,421✔
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,421!
186
#pragma omp atomic
785✔
187
        this->volumes(index_elem, slot) += volume;
1,421✔
188
        return;
1,421✔
189
      }
190
    }
191
  }
192

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

197
void MaterialVolumes::add_volume_unsafe(
×
198
  int index_elem, int index_material, double volume)
199
{
200
  // Linear probe
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)
×
205
      slot += table_size_;
×
206

207
    // Read current material
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;
×
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;
×
220
      return;
×
221
    }
222
  }
223

224
  // If table is full, set a flag that can be checked later
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,859✔
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,859✔
240
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
1,957!
241
  } else if (mesh_type == RectilinearMesh::mesh_type) {
902✔
242
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
114!
243
  } else if (mesh_type == CylindricalMesh::mesh_type) {
788✔
244
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
390!
245
  } else if (mesh_type == SphericalMesh::mesh_type) {
398✔
246
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
335!
247
  } else if (mesh_type == HexagonalMesh::mesh_type) {
63✔
248
    model::meshes.push_back(make_unique<HexagonalMesh>(dataset));
16!
249
#ifdef OPENMC_DAGMC_ENABLED
250
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
48!
251
             mesh_library == MOABMesh::mesh_lib_type) {
24✔
252
    model::meshes.push_back(make_unique<MOABMesh>(dataset));
24!
253
#endif
254
#ifdef OPENMC_LIBMESH_ENABLED
255
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
46!
256
             mesh_library == LibMesh::mesh_lib_type) {
23✔
257
    model::meshes.push_back(make_unique<LibMesh>(dataset));
23!
258
#endif
259
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
260
    fatal_error("Unstructured mesh support is not enabled or the mesh "
×
261
                "library is invalid.");
262
  } else {
263
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
264
  }
265

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

269
  return model::meshes.back();
2,859✔
270
}
271

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

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

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

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

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

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

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

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

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

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

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

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

352
  Timer timer;
176✔
353
  timer.start();
176✔
354

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

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

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

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

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

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

378
    SourceSite site;
80✔
379
    site.E = 1.0;
80✔
380
    site.particle = ParticleType::neutron;
80✔
381

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

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

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

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

417
          p.from_source(&site);
562,735✔
418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

586
  // Write mesh type
587
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,806✔
588

589
  // Write mesh ID
590
  write_attribute(mesh_group, "id", id_);
2,806✔
591

592
  // Write mesh name
593
  write_dataset(mesh_group, "name", name_);
2,806✔
594

595
  // Write mesh data
596
  this->to_hdf5_inner(mesh_group);
2,806✔
597

598
  // Close group
599
  close_group(mesh_group);
2,806✔
600
}
2,806✔
601

602
//==============================================================================
603
// Structured Mesh implementation
604
//==============================================================================
605

606
std::string StructuredMesh::bin_label(int bin) const
5,127,863✔
607
{
608
  MeshIndex ijk = get_indices_from_bin(bin);
5,127,863✔
609

610
  if (n_dimension_ > 2) {
5,127,863✔
611
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,226,224✔
612
  } else if (n_dimension_ > 1) {
14,751✔
613
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
28,952✔
614
  } else {
615
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
616
  }
617
}
618

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

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

633
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,537,791!
634
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,537,791!
635

636
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,537,791!
637
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,537,791!
638

639
  return {x_min + (x_max - x_min) * prn(seed),
1,537,791✔
640
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,537,791✔
641
}
642

643
//==============================================================================
644
// Unstructured Mesh implementation
645
//==============================================================================
646

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

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

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

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

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

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

686
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
687
{
688
  n_dimension_ = 3;
×
689

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

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

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

715
  if (attribute_exists(group, "options")) {
×
716
    read_attribute(group, "options", options_);
×
717
  }
718

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

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

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

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

778
const std::string UnstructuredMesh::mesh_type = "unstructured";
779

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

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

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

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

804
  if (length_multiplier_ > 0.0)
32!
805
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
806

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

815
  int num_elem_skipped = 0;
32✔
816

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

824
    volumes.emplace_back(this->volume(i));
349,736!
825

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

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

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

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

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

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

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

884
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
885
      in_mesh = false;
102,400,563✔
886
  }
887
  return ijk;
1,140,700,421✔
888
}
889

890
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,688,170,390✔
891
{
892
  switch (n_dimension_) {
1,688,170,390!
893
  case 1:
880,605✔
894
    return ijk[0] - 1;
880,605✔
895
  case 2:
96,174,804✔
896
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
96,174,804✔
897
  case 3:
1,591,114,981✔
898
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,591,114,981✔
899
  default:
×
900
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
901
  }
902
}
903

904
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,881,829✔
905
{
906
  MeshIndex ijk;
907
  if (n_dimension_ == 1) {
7,881,829✔
908
    ijk[0] = bin + 1;
275✔
909
  } else if (n_dimension_ == 2) {
7,881,554✔
910
    ijk[0] = bin % shape_[0] + 1;
14,476✔
911
    ijk[1] = bin / shape_[0] + 1;
14,476✔
912
  } else if (n_dimension_ == 3) {
7,867,078!
913
    ijk[0] = bin % shape_[0] + 1;
7,867,078✔
914
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,867,078✔
915
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,867,078✔
916
  }
917
  return ijk;
7,881,829✔
918
}
919

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

928
  // Convert indices to bin
929
  return get_bin_from_indices(ijk);
226,911,912✔
930
}
931

932
int StructuredMesh::n_bins() const
1,139,375✔
933
{
934
  return std::accumulate(
1,139,375✔
935
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,278,750✔
936
}
937

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

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

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

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

957
    // determine scoring bin for entropy mesh
958
    int mesh_bin = get_bin(site.r);
×
959

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

966
    // Add to appropriate bin
967
    cnt(mesh_bin) += site.wgt;
×
968
  }
969

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

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

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

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

995
  return counts;
×
996
}
×
997

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

1011
  // Compute the length of the entire track.
1012
  double total_distance = (r1 - r0).norm();
897,775,718✔
1013
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
897,775,718✔
1014
    return;
11,634,659✔
1015

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

1021
  const int n = n_dimension_;
886,141,059✔
1022

1023
  // Flag if position is inside the mesh
1024
  bool in_mesh;
1025

1026
  // Position is r = r0 + u * traveled_distance, start at r0
1027
  double traveled_distance {0.0};
886,141,059✔
1028

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

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

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

1048
  // Loop until r = r1 is eventually reached
1049
  while (true) {
742,876,177✔
1050

1051
    if (in_mesh) {
1,628,685,709✔
1052

1053
      // find surface with minimal distance to current position
1054
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,542,812,810✔
1055
                     distances.begin();
1,542,812,810✔
1056

1057
      // Tally track length delta since last step
1058
      tally.track(ijk,
1,542,812,810✔
1059
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,542,812,810✔
1060
          total_distance);
1061

1062
      // update position and leave, if we have reached end position
1063
      traveled_distance = distances[k].distance;
1,542,812,810✔
1064
      if (traveled_distance >= total_distance)
1,542,812,810✔
1065
        return;
806,579,203✔
1066

1067
      // If we have not reached r1, we have hit a surface. Tally outward
1068
      // current
1069
      tally.surface(ijk, k, distances[k].max_surface, false);
736,233,607✔
1070

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

1077
      // Check if we have left the interior of the mesh
1078
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
736,233,607✔
1079

1080
      // If we are still inside the mesh, tally inward current for the next
1081
      // cell
1082
      if (in_mesh)
736,233,607✔
1083
        tally.surface(ijk, k, !distances[k].max_surface, true);
723,056,725✔
1084

1085
    } else { // not inside mesh
1086

1087
      // For all directions outside the mesh, find the distance that we need
1088
      // to travel to reach the next surface. Use the largest distance, as
1089
      // only this will cross all outer surfaces.
1090
      int k_max {-1};
85,872,899✔
1091
      for (int k = 0; k < n; ++k) {
342,047,230✔
1092
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
350,038,447✔
1093
            (distances[k].distance > traveled_distance)) {
93,864,116✔
1094
          traveled_distance = distances[k].distance;
88,886,004✔
1095
          k_max = k;
88,886,004✔
1096
        }
1097
      }
1098
      // Assure some distance is traveled
1099
      if (k_max == -1) {
85,872,899✔
1100
        traveled_distance += TINY_BIT;
110✔
1101
      }
1102

1103
      // If r1 is not inside the mesh, exit here
1104
      if (traveled_distance >= total_distance)
85,872,899✔
1105
        return;
79,230,329✔
1106

1107
      // Calculate the new cell index and update all distances to next
1108
      // surfaces.
1109
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,642,570✔
1110
      for (int k = 0; k < n; ++k) {
26,361,742✔
1111
        distances[k] =
19,719,172✔
1112
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
19,719,172✔
1113
      }
1114

1115
      // If inside the mesh, Tally inward current
1116
      if (in_mesh && k_max >= 0)
6,642,570!
1117
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
6,223,255✔
1118
    }
1119
  }
1120
}
1121

1122
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
785,648,153✔
1123
  vector<int>& bins, vector<double>& lengths) const
1124
{
1125

1126
  // Helper tally class.
1127
  // stores a pointer to the mesh class and references to bins and lengths
1128
  // parameters. Performs the actual tally through the track method.
1129
  struct TrackAggregator {
1130
    TrackAggregator(
785,648,153✔
1131
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1132
      : mesh(_mesh), bins(_bins), lengths(_lengths)
785,648,153✔
1133
    {}
785,648,153✔
1134
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1,407,354,398✔
1135
    void track(const MeshIndex& ijk, double l) const
1,403,099,289✔
1136
    {
1137
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,403,099,289✔
1138
      lengths.push_back(l);
1,403,099,289✔
1139
    }
1,403,099,289✔
1140

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

1146
  // Perform the mesh raytrace with the helper class.
1147
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
785,648,153✔
1148
}
785,648,153✔
1149

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

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

1173
    const StructuredMesh* mesh;
1174
    vector<int>& bins;
1175
  };
1176

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

1181
//==============================================================================
1182
// RegularMesh implementation
1183
//==============================================================================
1184

1185
int RegularMesh::set_grid()
1,979✔
1186
{
1187
  auto shape = xt::adapt(shape_, {n_dimension_});
1,979✔
1188

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

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

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

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

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

1220
  } else if (upper_right_.size() > 0) {
1,930!
1221

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

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

1237
    // Set width
1238
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1,930✔
1239
  }
1240

1241
  // Set material volumes
1242
  volume_frac_ = 1.0 / xt::prod(shape)();
1,979✔
1243

1244
  element_volume_ = 1.0;
1,979✔
1245
  for (int i = 0; i < n_dimension_; i++) {
7,478✔
1246
    element_volume_ *= width_[i];
5,499✔
1247
  }
1248
  return 0;
1,979✔
1249
}
1,979✔
1250

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

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

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

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

1279
    width_ = get_node_xarray<double>(node, "width");
49✔
1280

1281
  } else if (check_for_node(node, "upper_right")) {
1,919!
1282

1283
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1,919✔
1284

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

1289
  if (int err = set_grid()) {
1,968!
1290
    fatal_error(openmc_err_msg);
×
1291
  }
1292
}
1,968✔
1293

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

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

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

1317
  if (object_exists(group, "upper_right")) {
11!
1318

1319
    read_dataset(group, "upper_right", upper_right_);
11✔
1320

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

1325
  if (int err = set_grid()) {
11!
1326
    fatal_error(openmc_err_msg);
×
1327
  }
1328
}
11✔
1329

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

1335
const std::string RegularMesh::mesh_type = "regular";
1336

1337
std::string RegularMesh::get_mesh_type() const
45,883✔
1338
{
1339
  return mesh_type;
45,883✔
1340
}
1341

1342
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,433,160,101✔
1343
{
1344
  return lower_left_[i] + ijk[i] * width_[i];
1,433,160,101✔
1345
}
1346

1347
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,371,430,987✔
1348
{
1349
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,371,430,987✔
1350
}
1351

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

1361
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1362
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1363
    d.next_index++;
1,428,546,728✔
1364
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,428,546,728✔
1365
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,387,999,363✔
1366
    d.next_index--;
1,366,817,614✔
1367
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,366,817,614✔
1368
  }
1369

1370
  return d;
2,147,483,647✔
1371
}
1372

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

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

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

1411
  return {axis_lines[0], axis_lines[1]};
44✔
1412
}
22✔
1413

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

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

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

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

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

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

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

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

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

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

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

1474
  return counts;
15,678✔
1475
}
7,839✔
1476

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

1482
//==============================================================================
1483
// RectilinearMesh implementation
1484
//==============================================================================
1485

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

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

1494
  if (int err = set_grid()) {
125!
1495
    fatal_error(openmc_err_msg);
×
1496
  }
1497
}
125✔
1498

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

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

1507
  if (int err = set_grid()) {
11!
1508
    fatal_error(openmc_err_msg);
×
1509
  }
1510
}
11✔
1511

1512
const std::string RectilinearMesh::mesh_type = "rectilinear";
1513

1514
std::string RectilinearMesh::get_mesh_type() const
384,923✔
1515
{
1516
  return mesh_type;
384,923✔
1517
}
1518

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

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

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

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

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

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

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

1574
  return 0;
180✔
1575
}
1576

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

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

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

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

1609
  return {axis_lines[0], axis_lines[1]};
22✔
1610
}
11✔
1611

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

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

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

1629
//==============================================================================
1630
// CylindricalMesh implementation
1631
//==============================================================================
1632

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

1642
  if (int err = set_grid()) {
401!
1643
    fatal_error(openmc_err_msg);
×
1644
  }
1645
}
401✔
1646

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

1655
  if (int err = set_grid()) {
11!
1656
    fatal_error(openmc_err_msg);
×
1657
  }
1658
}
11✔
1659

1660
const std::string CylindricalMesh::mesh_type = "cylindrical";
1661

1662
std::string CylindricalMesh::get_mesh_type() const
646,756✔
1663
{
1664
  return mesh_type;
646,756✔
1665
}
1666

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

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

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

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

1686
  idx[1] = sanitize_phi(idx[1]);
47,726,668✔
1687

1688
  return idx;
47,726,668✔
1689
}
1690

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

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

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

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

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

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

1715
double CylindricalMesh::find_r_crossing(
142,568,516✔
1716
  const Position& r, const Direction& u, double l, int shell) const
1717
{
1718

1719
  if ((shell < 0) || (shell > shape_[0]))
142,568,516!
1720
    return INFTY;
17,913,907✔
1721

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

1726
  const double r0 = grid_[0][shell];
124,654,609✔
1727
  if (r0 == 0.0)
124,654,609✔
1728
    return INFTY;
7,130,651✔
1729

1730
  const double denominator = u.x * u.x + u.y * u.y;
117,523,958✔
1731

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

1736
  // inverse of dominator to help the compiler to speed things up
1737
  const double inv_denominator = 1.0 / denominator;
117,464,998✔
1738

1739
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,464,998✔
1740
  double c = r.x * r.x + r.y * r.y - r0 * r0;
117,464,998✔
1741
  double D = p * p - c * inv_denominator;
117,464,998✔
1742

1743
  if (D < 0.0)
117,464,998✔
1744
    return INFTY;
9,733,570✔
1745

1746
  D = std::sqrt(D);
107,731,428✔
1747

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

1752
  if (-p - D > l)
101,120,054✔
1753
    return -p - D;
20,205,998✔
1754
  if (-p + D > l)
80,914,056✔
1755
    return -p + D;
50,090,580✔
1756

1757
  return INFTY;
30,823,476✔
1758
}
1759

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

1767
  shell = sanitize_phi(shell);
43,970,718✔
1768

1769
  const double p0 = grid_[1][shell];
43,970,718✔
1770

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

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

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

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

1790
  return INFTY;
23,750,859✔
1791
}
1792

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

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

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

1814
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,197,361✔
1815
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1816
  double l) const
1817
{
1818
  if (i == 0) {
145,197,361✔
1819

1820
    return std::min(
71,284,258✔
1821
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,284,258✔
1822
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,568,516✔
1823

1824
  } else if (i == 1) {
73,913,103✔
1825

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

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

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

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

1869
    return OPENMC_E_INVALID_ARGUMENT;
×
1870
  }
1871

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

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

1879
  return 0;
434✔
1880
}
1881

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

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

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

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

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

1910
  double phi_i = grid_[1][ijk[1] - 1];
792✔
1911
  double phi_o = grid_[1][ijk[1]];
792✔
1912

1913
  double z_i = grid_[2][ijk[2] - 1];
792✔
1914
  double z_o = grid_[2][ijk[2]];
792✔
1915

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

1919
//==============================================================================
1920
// SphericalMesh implementation
1921
//==============================================================================
1922

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

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

1933
  if (int err = set_grid()) {
346!
1934
    fatal_error(openmc_err_msg);
×
1935
  }
1936
}
346✔
1937

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

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

1947
  if (int err = set_grid()) {
11!
1948
    fatal_error(openmc_err_msg);
×
1949
  }
1950
}
11✔
1951

1952
const std::string SphericalMesh::mesh_type = "spherical";
1953

1954
std::string SphericalMesh::get_mesh_type() const
323,521✔
1955
{
1956
  return mesh_type;
323,521✔
1957
}
1958

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

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

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

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

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

1982
  return idx;
68,175,250✔
1983
}
1984

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

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

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

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

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

2010
  return origin_ + Position(x, y, z);
110✔
2011
}
2012

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

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

2028
  if (std::abs(c) <= RADIAL_MESH_TOL)
396,198,528✔
2029
    return INFTY;
10,598,654✔
2030

2031
  if (D >= 0.0) {
385,599,874✔
2032
    D = std::sqrt(D);
357,722,926✔
2033
    // the solution -p - D is always smaller as -p + D : Check this one first
2034
    if (-p - D > l)
357,722,926✔
2035
      return -p - D;
64,279,325✔
2036
    if (-p + D > l)
293,443,601✔
2037
      return -p + D;
176,902,198✔
2038
  }
2039

2040
  return INFTY;
144,418,351✔
2041
}
2042

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

2050
  shell = sanitize_theta(shell);
38,358,540✔
2051

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

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

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

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

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

2081
    // no crossing is possible
2082
    return INFTY;
×
2083
  }
2084

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

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

2091
  D = std::sqrt(D);
26,921,004✔
2092

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

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

2104
  return INFTY;
11,475,101✔
2105
}
2106

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

2114
  shell = sanitize_phi(shell);
39,948,018✔
2115

2116
  const double p0 = grid_[2][shell];
39,948,018✔
2117

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

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

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

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

2137
  return INFTY;
22,368,566✔
2138
}
2139

2140
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
331,662,573✔
2141
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2142
  double l) const
2143
{
2144

2145
  if (i == 0) {
331,662,573✔
2146
    return std::min(
221,540,242✔
2147
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,540,242✔
2148
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,080,484✔
2149

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

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

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

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

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

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

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

2207
  return 0;
379✔
2208
}
2209

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

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

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

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

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

2238
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2239
  double theta_o = grid_[1][ijk[1]];
935✔
2240

2241
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2242
  double phi_o = grid_[2][ijk[2]];
935✔
2243

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

2248
//==============================================================================
2249
// Helper functions for the C API
2250
//==============================================================================
2251

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

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

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

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

2282
//==============================================================================
2283
// C API functions
2284
//==============================================================================
2285

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

2292
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,452✔
2293

2294
  return 0;
1,452✔
2295
}
2296

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

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

2323
  return 0;
253✔
2324
}
253✔
2325

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

2334
#ifdef OPENMC_DAGMC_ENABLED
2335
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2336
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2337
    valid_lib = true;
2338
  }
2339
#endif
2340

2341
#ifdef OPENMC_LIBMESH_ENABLED
2342
  if (lib_name == LibMesh::mesh_lib_type) {
×
2343
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2344
    valid_lib = true;
2345
  }
2346
#endif
2347

2348
  if (!valid_lib) {
×
2349
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2350
                           "by this build of OpenMC",
2351
      lib_name));
2352
    return OPENMC_E_INVALID_ARGUMENT;
×
2353
  }
2354

2355
  // auto-assign new ID
2356
  model::meshes.back()->set_id(-1);
×
2357
  *id = model::meshes.back()->id_;
×
2358

2359
  return 0;
×
2360
}
×
2361

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

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

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

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

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

2413
//! Get the bounding box of a mesh
2414
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
154✔
2415
{
2416
  if (int err = check_mesh(index))
154!
2417
    return err;
×
2418

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

2421
  // set lower left corner values
2422
  ll[0] = bbox.xmin;
154✔
2423
  ll[1] = bbox.ymin;
154✔
2424
  ll[2] = bbox.zmin;
154✔
2425

2426
  // set upper right corner values
2427
  ur[0] = bbox.xmax;
154✔
2428
  ur[1] = bbox.ymax;
154✔
2429
  ur[2] = bbox.zmax;
154✔
2430
  return 0;
154✔
2431
}
2432

2433
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
176✔
2434
  int nz, int table_size, int32_t* materials, double* volumes)
2435
{
2436
  if (int err = check_mesh(index))
176!
2437
    return err;
×
2438

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

2451
  return 0;
165✔
2452
}
2453

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

2461
  int pixel_width = pixels[0];
44✔
2462
  int pixel_height = pixels[1];
44✔
2463

2464
  // get pixel size
2465
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2466
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2467

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

2490
  // set initial position
2491
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2492
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2493

2494
#pragma omp parallel
24✔
2495
  {
2496
    Position r = xyz;
20✔
2497

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

2508
  return 0;
44✔
2509
}
2510

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

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

2531
  // Copy dimension
2532
  mesh->n_dimension_ = n;
187✔
2533
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2534
  return 0;
187✔
2535
}
2536

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

2545
  if (m->lower_left_.dimension() == 0) {
209!
2546
    set_errmsg("Mesh parameters have not been set.");
×
2547
    return OPENMC_E_ALLOCATE;
×
2548
  }
2549

2550
  *ll = m->lower_left_.data();
209✔
2551
  *ur = m->upper_right_.data();
209✔
2552
  *width = m->width_.data();
209✔
2553
  *n = m->n_dimension_;
209✔
2554
  return 0;
209✔
2555
}
2556

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

2565
  if (m->n_dimension_ == -1) {
220!
2566
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2567
    return OPENMC_E_UNASSIGNED;
×
2568
  }
2569

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

2588
  // Set material volumes
2589

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

2598
  return 0;
220✔
2599
}
220✔
2600

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

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

2612
  m->n_dimension_ = 3;
88✔
2613

2614
  m->grid_[0].reserve(nx);
88✔
2615
  m->grid_[1].reserve(ny);
88✔
2616
  m->grid_[2].reserve(nz);
88✔
2617

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

2628
  int err = m->set_grid();
88✔
2629
  return err;
88✔
2630
}
2631

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

2641
  if (m->lower_left_.dimension() == 0) {
385!
2642
    set_errmsg("Mesh parameters have not been set.");
×
2643
    return OPENMC_E_ALLOCATE;
×
2644
  }
2645

2646
  *grid_x = m->grid_[0].data();
385✔
2647
  *nx = m->grid_[0].size();
385✔
2648
  *grid_y = m->grid_[1].data();
385✔
2649
  *ny = m->grid_[1].size();
385✔
2650
  *grid_z = m->grid_[2].data();
385✔
2651
  *nz = m->grid_[2].size();
385✔
2652

2653
  return 0;
385✔
2654
}
2655

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

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

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

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

2690
//! Get the spherical mesh grid
2691
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2692
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2693
{
2694

2695
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2696
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2697
  ;
2698
}
2699

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

2709
#ifdef OPENMC_DAGMC_ENABLED
2710

2711
const std::string MOABMesh::mesh_lib_type = "moab";
2712

2713
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2714
{
2715
  initialize();
24✔
2716
}
24✔
2717

2718
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2719
{
2720
  initialize();
×
2721
}
2722

2723
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2724
  : UnstructuredMesh()
×
2725
{
2726
  n_dimension_ = 3;
2727
  filename_ = filename;
×
2728
  set_length_multiplier(length_multiplier);
×
2729
  initialize();
×
2730
}
2731

2732
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2733
{
2734
  mbi_ = external_mbi;
1✔
2735
  filename_ = "unknown (external file)";
1✔
2736
  this->initialize();
1✔
2737
}
1✔
2738

2739
void MOABMesh::initialize()
25✔
2740
{
2741

2742
  // Create the MOAB interface and load data from file
2743
  this->create_interface();
25✔
2744

2745
  // Initialise MOAB error code
2746
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2747

2748
  // Set the dimension
2749
  n_dimension_ = 3;
25✔
2750

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

2757
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2758
    warning("Non-tetrahedral elements found in unstructured "
×
2759
            "mesh file: " +
2760
            filename_);
2761
  }
2762

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

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

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

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

2810
  // Determine bounds of mesh
2811
  this->determine_bounds();
25✔
2812
}
25✔
2813

2814
void MOABMesh::prepare_for_point_location()
21✔
2815
{
2816
  // if the KDTree has already been constructed, do nothing
2817
  if (kdtree_)
21!
2818
    return;
2819

2820
  // build acceleration data structures
2821
  compute_barycentric_data(ehs_);
21✔
2822
  build_kdtree(ehs_);
21✔
2823
}
2824

2825
void MOABMesh::create_interface()
25✔
2826
{
2827
  // Do not create a MOAB instance if one is already in memory
2828
  if (mbi_)
25✔
2829
    return;
1✔
2830

2831
  // create MOAB instance
2832
  mbi_ = std::make_shared<moab::Core>();
24✔
2833

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

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

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

2858
  // combine into one range
2859
  moab::Range all_tets_and_tris;
21✔
2860
  all_tets_and_tris.merge(all_tets);
21✔
2861
  all_tets_and_tris.merge(all_tris);
21✔
2862

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

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

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

2886
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
2887
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2888
{
2889
  hits.clear();
1,543,584✔
2890

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

2903
  // remove duplicate intersection distances
2904
  std::unique(hits.begin(), hits.end());
1,543,584✔
2905

2906
  // sorts by first component of std::pair by default
2907
  std::sort(hits.begin(), hits.end());
1,543,584✔
2908
}
1,543,584✔
2909

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

2918
  double track_len = (end - start).length();
1,543,584✔
2919
  if (track_len == 0.0)
1,543,584!
2920
    return;
721,692✔
2921

2922
  start -= TINY_BIT * dir;
1,543,584✔
2923
  end += TINY_BIT * dir;
1,543,584✔
2924

2925
  vector<double> hits;
1,543,584✔
2926
  intersect_track(start, dir, track_len, hits);
1,543,584✔
2927

2928
  bins.clear();
1,543,584✔
2929
  lengths.clear();
1,543,584✔
2930

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

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

2957
    // determine the start point for this segment
2958
    current = r0 + u * hit;
4,694,269✔
2959

2960
    if (bin == -1) {
4,694,269✔
2961
      continue;
20,522✔
2962
    }
2963

2964
    bins.push_back(bin);
4,673,747✔
2965
    lengths.push_back(segment_length / track_len);
4,673,747✔
2966
  }
2967

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

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

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

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

3008
  // if no tet is found, return an invalid handle
3009
  return 0;
2,847✔
3010
}
7,317,172✔
3011

3012
double MOABMesh::volume(int bin) const
167,880✔
3013
{
3014
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3015
}
3016

3017
std::string MOABMesh::library() const
34✔
3018
{
3019
  return mesh_lib_type;
34✔
3020
}
3021

3022
// Sample position within a tet for MOAB type tets
3023
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3024
{
3025

3026
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3027

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

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

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

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

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

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

3078
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3079
{
3080
  moab::ErrorCode rval;
3081

3082
  baryc_data_.clear();
21✔
3083
  baryc_data_.resize(tets.size());
21✔
3084

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

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

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

3102
    // invert now to avoid this cost later
3103
    a = a.transpose().inverse();
239,736✔
3104
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3105
  }
239,736✔
3106
}
21✔
3107

3108
bool MOABMesh::point_in_tet(
260,207,039✔
3109
  const moab::CartVect& r, moab::EntityHandle tet) const
3110
{
3111

3112
  moab::ErrorCode rval;
3113

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

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

3133
  // look up barycentric data
3134
  int idx = get_bin_from_ent_handle(tet);
260,207,039✔
3135
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,207,039✔
3136

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

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

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

3152
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3153
{
3154
  int bin = get_bin(r);
3155
  *in_mesh = bin != -1;
3156
  return bin;
3157
}
3158

3159
int MOABMesh::get_index_from_bin(int bin) const
3160
{
3161
  return bin;
3162
}
3163

3164
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3165
  Position plot_ll, Position plot_ur) const
3166
{
3167
  // TODO: Implement mesh lines
3168
  return {};
3169
}
3170

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

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

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

3198
int MOABMesh::n_bins() const
267,525,326✔
3199
{
3200
  return ehs_.size();
267,525,326✔
3201
}
3202

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

3216
Position MOABMesh::centroid(int bin) const
3217
{
3218
  moab::ErrorCode rval;
3219

3220
  auto tet = this->get_ent_handle_from_bin(bin);
×
3221

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

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

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

3245
  return {centroid[0], centroid[1], centroid[2]};
3246
}
3247

3248
int MOABMesh::n_vertices() const
845,874✔
3249
{
3250
  return verts_.size();
845,874✔
3251
}
3252

3253
Position MOABMesh::vertex(int id) const
86,227✔
3254
{
3255

3256
  moab::ErrorCode rval;
3257

3258
  moab::EntityHandle vert = verts_[id];
86,227✔
3259

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

3266
  return {coords[0], coords[1], coords[2]};
172,454✔
3267
}
3268

3269
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3270
{
3271
  moab::ErrorCode rval;
3272

3273
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3274

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

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

3288
  return verts;
203,880✔
3289
}
203,880✔
3290

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

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

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

3326
  // return the populated tag handles
3327
  return {value_tag, error_tag};
3328
}
3329

3330
void MOABMesh::add_score(const std::string& score)
3331
{
3332
  auto score_tags = get_score_tags(score);
×
3333
  tag_names_.push_back(score);
×
3334
}
3335

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

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

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

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

3373
void MOABMesh::set_score_data(const std::string& score,
3374
  const vector<double>& values, const vector<double>& std_dev)
3375
{
3376
  auto score_tags = this->get_score_tags(score);
×
3377

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

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

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

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

3416
#endif
3417

3418
#ifdef OPENMC_LIBMESH_ENABLED
3419

3420
const std::string LibMesh::mesh_lib_type = "libmesh";
3421

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

3431
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3432
{
3433
  // filename_ and length_multiplier_ will already be set by the
3434
  // UnstructuredMesh constructor
3435
  set_mesh_pointer_from_filename(filename_);
×
3436
  set_length_multiplier(length_multiplier_);
×
3437
  initialize();
×
3438
}
3439

3440
// create the mesh from a pointer to a libMesh Mesh
3441
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3442
{
3443
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
×
3444
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3445
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3446
  }
3447

3448
  m_ = &input_mesh;
3449
  set_length_multiplier(length_multiplier);
×
3450
  initialize();
×
3451
}
3452

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

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

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

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

3488
  // assuming that unstructured meshes used in OpenMC are 3D
3489
  n_dimension_ = 3;
23✔
3490

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

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

3507
  for (int i = 0; i < num_threads(); i++) {
69✔
3508
    pl_.emplace_back(m_->sub_point_locator());
46✔
3509
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3510
    pl_.back()->enable_out_of_mesh_mode();
46✔
3511
  }
3512

3513
  // store first element in the mesh to use as an offset for bin indices
3514
  auto first_elem = *m_->elements_begin();
23✔
3515
  first_element_id_ = first_elem->id();
23✔
3516

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

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

3539
Position LibMesh::centroid(int bin) const
3540
{
3541
  const auto& elem = this->get_element_from_bin(bin);
×
3542
  auto centroid = elem.vertex_average();
×
3543
  return {centroid(0), centroid(1), centroid(2)};
3544
}
3545

3546
int LibMesh::n_vertices() const
39,978✔
3547
{
3548
  return m_->n_nodes();
39,978✔
3549
}
3550

3551
Position LibMesh::vertex(int vertex_id) const
39,942✔
3552
{
3553
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3554
  return {node_ref(0), node_ref(1), node_ref(2)};
79,884✔
3555
}
39,942✔
3556

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

3567
std::string LibMesh::library() const
33✔
3568
{
3569
  return mesh_lib_type;
33✔
3570
}
3571

3572
int LibMesh::n_bins() const
1,784,287✔
3573
{
3574
  return m_->n_elem();
1,784,287✔
3575
}
3576

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

3595
void LibMesh::add_score(const std::string& var_name)
15✔
3596
{
3597
  if (!equation_systems_) {
15!
3598
    build_eqn_sys();
15✔
3599
  }
3600

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

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

3620
void LibMesh::remove_scores()
15✔
3621
{
3622
  if (equation_systems_) {
15!
3623
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3624
    eqn_sys.clear();
15✔
3625
    variable_map_.clear();
15✔
3626
  }
3627
}
15✔
3628

3629
void LibMesh::set_score_data(const std::string& var_name,
15✔
3630
  const vector<double>& values, const vector<double>& std_dev)
3631
{
3632
  if (!equation_systems_) {
15!
3633
    build_eqn_sys();
×
3634
  }
3635

3636
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3637

3638
  if (!eqn_sys.is_initialized()) {
15!
3639
    equation_systems_->init();
15✔
3640
  }
3641

3642
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3643

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

3651
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
97,871✔
3652
       it++) {
3653
    if (!(*it)->active()) {
97,856!
3654
      continue;
3655
    }
3656

3657
    auto bin = get_bin_from_element(*it);
97,856✔
3658

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

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

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

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

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

3695
  // quick rejection check
3696
  if (!bbox_.contains_point(p)) {
2,340,484✔
3697
    return -1;
918,796✔
3698
  }
3699

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

3702
  const auto elem_ptr = (*point_locator)(p);
1,421,688✔
3703
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,688✔
3704
}
2,340,484✔
3705

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

3715
std::pair<vector<double>, vector<double>> LibMesh::plot(
3716
  Position plot_ll, Position plot_ur) const
3717
{
3718
  return {};
3719
}
3720

3721
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3722
{
3723
  return m_->elem_ref(bin);
765,460✔
3724
}
3725

3726
double LibMesh::volume(int bin) const
364,640✔
3727
{
3728
  return this->get_element_from_bin(bin).volume();
364,640✔
3729
}
3730

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

3744
    bin_to_elem_map_.push_back(elem->id());
×
3745
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3746
  }
3747
}
3748

3749
int AdaptiveLibMesh::n_bins() const
3750
{
3751
  return num_active_;
3752
}
3753

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

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

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

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

3785
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3786
{
3787
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3788
}
3789

3790
#endif // OPENMC_LIBMESH_ENABLED
3791

3792
//==============================================================================
3793
// Non-member functions
3794
//==============================================================================
3795

3796
void read_meshes(pugi::xml_node root)
11,750✔
3797
{
3798
  std::unordered_set<int> mesh_ids;
11,750✔
3799

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

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

3817
    std::string mesh_type;
2,859✔
3818
    if (check_for_node(node, "type")) {
2,859✔
3819
      mesh_type = get_node_value(node, "type", true, true);
972✔
3820
    } else {
3821
      mesh_type = "regular";
1,887✔
3822
    }
3823

3824
    // determine the mesh library to use
3825
    std::string mesh_lib;
2,859✔
3826
    if (check_for_node(node, "library")) {
2,859✔
3827
      mesh_lib = get_node_value(node, "library", true, true);
47!
3828
    }
3829

3830
    Mesh::create(node, mesh_type, mesh_lib);
2,859✔
3831
  }
2,859✔
3832
}
11,750✔
3833

3834
void read_meshes(hid_t group)
22✔
3835
{
3836
  std::unordered_set<int> mesh_ids;
22✔
3837

3838
  std::vector<int> ids;
22✔
3839
  read_attribute(group, "ids", ids);
22✔
3840

3841
  for (auto id : ids) {
55✔
3842

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

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

3858
    std::string name = fmt::format("mesh {}", id);
×
3859
    hid_t mesh_group = open_group(group, name.c_str());
×
3860

3861
    std::string mesh_type;
×
3862
    if (object_exists(mesh_group, "type")) {
×
3863
      read_dataset(mesh_group, "type", mesh_type);
×
3864
    } else {
3865
      mesh_type = "regular";
×
3866
    }
3867

3868
    // determine the mesh library to use
3869
    std::string mesh_lib;
×
3870
    if (object_exists(mesh_group, "library")) {
×
3871
      read_dataset(mesh_group, "library", mesh_lib);
×
3872
    }
3873

3874
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
3875
  }
×
3876
}
22✔
3877

3878
void meshes_to_hdf5(hid_t group)
6,555✔
3879
{
3880
  // Write number of meshes
3881
  hid_t meshes_group = create_group(group, "meshes");
6,555✔
3882
  int32_t n_meshes = model::meshes.size();
6,555✔
3883
  write_attribute(meshes_group, "n_meshes", n_meshes);
6,555✔
3884

3885
  if (n_meshes > 0) {
6,555✔
3886
    // Write IDs of meshes
3887
    vector<int> ids;
2,049✔
3888
    for (const auto& m : model::meshes) {
4,677✔
3889
      m->to_hdf5(meshes_group);
2,628✔
3890
      ids.push_back(m->id_);
2,628✔
3891
    }
3892
    write_attribute(meshes_group, "ids", ids);
2,049✔
3893
  }
2,049✔
3894

3895
  close_group(meshes_group);
6,555✔
3896
}
6,555✔
3897

3898
void free_memory_mesh()
7,707✔
3899
{
3900
  model::meshes.clear();
7,707✔
3901
  model::mesh_map.clear();
7,707✔
3902
}
7,707✔
3903

3904
extern "C" int n_meshes()
308✔
3905
{
3906
  return model::meshes.size();
308✔
3907
}
3908

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