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

openmc-dev / openmc / 18664724877

20 Oct 2025 08:57PM UTC coverage: 81.802% (-0.1%) from 81.917%
18664724877

Pull #3598

github

web-flow
Merge 1784abcac into 3ac5d6f8f
Pull Request #3598: load mesh objects from weight_windows.h5 file

16647 of 23259 branches covered (71.57%)

Branch coverage included in aggregate %.

82 of 129 new or added lines in 3 files covered. (63.57%)

18 existing lines in 2 files now uncovered.

53789 of 62847 relevant lines covered (85.59%)

42691485.83 hits per line

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

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

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

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

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

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

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

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

60
namespace openmc {
61

62
//==============================================================================
63
// Global variables
64
//==============================================================================
65

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

90
//==============================================================================
91
// Helper functions
92
//==============================================================================
93

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

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

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

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

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

142
namespace detail {
143

144
//==============================================================================
145
// MaterialVolumes implementation
146
//==============================================================================
147

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

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

165
    // Non-atomic read of current material
166
    int32_t current_val = *slot_ptr;
2,659,073✔
167

168
    // Found the desired material; accumulate volume
169
    if (current_val == index_material) {
2,659,073✔
170
#pragma omp atomic
1,447,026✔
171
      this->volumes(index_elem, slot) += volume;
2,651,996✔
172
      return;
2,651,996✔
173
    }
174

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

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

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

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

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

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

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

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

227
} // namespace detail
228

229
//==============================================================================
230
// Mesh implementation
231
//==============================================================================
232

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

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

266
  return model::meshes.back();
2,711✔
267
}
268

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

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

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

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

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

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

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

313
  // Update ID and entry in the mesh map
314
  id_ = id;
1✔
315
  model::mesh_map[id] = model::meshes.size() - 1;
1✔
316
}
1✔
317

318
vector<double> Mesh::volumes() const
252✔
319
{
320
  vector<double> volumes(n_bins());
252✔
321
  for (int i = 0; i < n_bins(); i++) {
1,125,127✔
322
    volumes[i] = this->volume(i);
1,124,875✔
323
  }
324
  return volumes;
252✔
325
}
×
326

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

343
  Timer timer;
165✔
344
  timer.start();
165✔
345

346
  // Create object for keeping track of materials/volumes
347
  detail::MaterialVolumes result(materials, volumes, table_size);
165✔
348

349
  // Determine bounding box
350
  auto bbox = this->bounding_box();
165✔
351

352
  std::array<int, 3> n_rays = {nx, ny, nz};
165✔
353

354
  // Determine effective width of rays
355
  Position width((nx > 0) ? (bbox.xmax - bbox.xmin) / nx : 0.0,
297✔
356
    (ny > 0) ? (bbox.ymax - bbox.ymin) / ny : 0.0,
319✔
357
    (nz > 0) ? (bbox.zmax - bbox.zmin) / nz : 0.0);
165✔
358

359
  // Set flag for mesh being contained within model
360
  bool out_of_model = false;
165✔
361

362
#pragma omp parallel
90✔
363
  {
364
    // Preallocate vector for mesh indices and length fractions and particle
365
    std::vector<int> bins;
75✔
366
    std::vector<double> length_fractions;
75✔
367
    Particle p;
75✔
368

369
    SourceSite site;
75✔
370
    site.E = 1.0;
75✔
371
    site.particle = ParticleType::neutron;
75✔
372

373
    for (int axis = 0; axis < 3; ++axis) {
300✔
374
      // Set starting position and direction
375
      site.r = {0.0, 0.0, 0.0};
225✔
376
      site.r[axis] = bbox.min()[axis];
225✔
377
      site.u = {0.0, 0.0, 0.0};
225✔
378
      site.u[axis] = 1.0;
225✔
379

380
      // Determine width of rays and number of rays in other directions
381
      int ax1 = (axis + 1) % 3;
225✔
382
      int ax2 = (axis + 2) % 3;
225✔
383
      double min1 = bbox.min()[ax1];
225✔
384
      double min2 = bbox.min()[ax2];
225✔
385
      double d1 = width[ax1];
225✔
386
      double d2 = width[ax2];
225✔
387
      int n1 = n_rays[ax1];
225✔
388
      int n2 = n_rays[ax2];
225✔
389
      if (n1 == 0 || n2 == 0) {
225✔
390
        continue;
60✔
391
      }
392

393
      // Divide rays in first direction over MPI processes by computing starting
394
      // and ending indices
395
      int min_work = n1 / mpi::n_procs;
165✔
396
      int remainder = n1 % mpi::n_procs;
165✔
397
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
165!
398
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
165✔
399
      int i1_end = i1_start + n1_local;
165✔
400

401
      // Loop over rays on face of bounding box
402
#pragma omp for collapse(2)
403
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
8,900✔
404
        for (int i2 = 0; i2 < n2; ++i2) {
521,010✔
405
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
512,275✔
406
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
512,275✔
407

408
          p.from_source(&site);
512,275✔
409

410
          // Determine particle's location
411
          if (!exhaustive_find_cell(p)) {
512,275✔
412
            out_of_model = true;
39,930✔
413
            continue;
39,930✔
414
          }
415

416
          // Set birth cell attribute
417
          if (p.cell_born() == C_NONE)
472,345!
418
            p.cell_born() = p.lowest_coord().cell();
472,345✔
419

420
          // Initialize last cells from current cell
421
          for (int j = 0; j < p.n_coord(); ++j) {
944,690✔
422
            p.cell_last(j) = p.coord(j).cell();
472,345✔
423
          }
424
          p.n_coord_last() = p.n_coord();
472,345✔
425

426
          while (true) {
427
            // Ray trace from r_start to r_end
428
            Position r0 = p.r();
987,435✔
429
            double max_distance = bbox.max()[axis] - r0[axis];
987,435✔
430

431
            // Find the distance to the nearest boundary
432
            BoundaryInfo boundary = distance_to_boundary(p);
987,435✔
433

434
            // Advance particle forward
435
            double distance = std::min(boundary.distance(), max_distance);
987,435✔
436
            p.move_distance(distance);
987,435✔
437

438
            // Determine what mesh elements were crossed by particle
439
            bins.clear();
987,435✔
440
            length_fractions.clear();
987,435✔
441
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
987,435✔
442

443
            // Add volumes to any mesh elements that were crossed
444
            int i_material = p.material();
987,435✔
445
            if (i_material != C_NONE) {
987,435✔
446
              i_material = model::materials[i_material]->id();
881,745✔
447
            }
448
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,193,520✔
449
              int mesh_index = bins[i_bin];
1,206,085✔
450
              double length = distance * length_fractions[i_bin];
1,206,085✔
451

452
              // Add volume to result
453
              result.add_volume(mesh_index, i_material, length * d1 * d2);
1,206,085✔
454
            }
455

456
            if (distance == max_distance)
987,435✔
457
              break;
472,345✔
458

459
            // cross next geometric surface
460
            for (int j = 0; j < p.n_coord(); ++j) {
1,030,180✔
461
              p.cell_last(j) = p.coord(j).cell();
515,090✔
462
            }
463
            p.n_coord_last() = p.n_coord();
515,090✔
464

465
            // Set surface that particle is on and adjust coordinate levels
466
            p.surface() = boundary.surface();
515,090✔
467
            p.n_coord() = boundary.coord_level();
515,090✔
468

469
            if (boundary.lattice_translation()[0] != 0 ||
515,090✔
470
                boundary.lattice_translation()[1] != 0 ||
1,030,180!
471
                boundary.lattice_translation()[2] != 0) {
515,090!
472
              // Particle crosses lattice boundary
473
              cross_lattice(p, boundary);
×
474
            } else {
475
              // Particle crosses surface
476
              const auto& surf {model::surfaces[p.surface_index()].get()};
515,090✔
477
              p.cross_surface(*surf);
515,090✔
478
            }
479
          }
515,090✔
480
        }
481
      }
482
    }
483
  }
75✔
484

485
  // Check for errors
486
  if (out_of_model) {
165✔
487
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
488
  } else if (result.table_full()) {
154!
489
    throw std::runtime_error("Maximum number of materials for mesh material "
×
490
                             "volume calculation insufficient.");
×
491
  }
492

493
  // Compute time for raytracing
494
  double t_raytrace = timer.elapsed();
154✔
495

496
#ifdef OPENMC_MPI
497
  // Combine results from multiple MPI processes
498
  if (mpi::n_procs > 1) {
70!
499
    int total = this->n_bins() * table_size;
×
500
    if (mpi::master) {
×
501
      // Allocate temporary buffer for receiving data
502
      std::vector<int32_t> mats(total);
×
503
      std::vector<double> vols(total);
×
504

505
      for (int i = 1; i < mpi::n_procs; ++i) {
×
506
        // Receive material indices and volumes from process i
507
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
508
          MPI_STATUS_IGNORE);
509
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
510
          MPI_STATUS_IGNORE);
511

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

531
  // Report time for MPI communication
532
  double t_mpi = timer.elapsed() - t_raytrace;
70✔
533
#else
534
  double t_mpi = 0.0;
84✔
535
#endif
536

537
  // Normalize based on known volumes of elements
538
  for (int i = 0; i < this->n_bins(); ++i) {
1,023✔
539
    // Estimated total volume in element i
540
    double volume = 0.0;
869✔
541
    for (int j = 0; j < table_size; ++j) {
7,821✔
542
      volume += result.volumes(i, j);
6,952✔
543
    }
544
    // Renormalize volumes based on known volume of element i
545
    double norm = this->volume(i) / volume;
869✔
546
    for (int j = 0; j < table_size; ++j) {
7,821✔
547
      result.volumes(i, j) *= norm;
6,952✔
548
    }
549
  }
550

551
  // Get total time and normalization time
552
  timer.stop();
154✔
553
  double t_total = timer.elapsed();
154✔
554
  double t_norm = t_total - t_raytrace - t_mpi;
154✔
555

556
  // Show timing statistics
557
  if (settings::verbosity < 7 || !mpi::master)
154!
558
    return;
44✔
559
  header("Timing Statistics", 7);
110✔
560
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
110✔
561
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
110✔
562
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
110✔
563
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
90✔
564
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
90✔
565
    n_total / t_raytrace);
110✔
566
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
90✔
567
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
110✔
568
  std::fflush(stdout);
110✔
569
}
570

571
void Mesh::to_hdf5(hid_t group) const
2,694✔
572
{
573
  // Create group for mesh
574
  std::string group_name = fmt::format("mesh {}", id_);
4,880✔
575
  hid_t mesh_group = create_group(group, group_name.c_str());
2,694✔
576

577
  // Write mesh type
578
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,694✔
579

580
  // Write mesh ID
581
  write_attribute(mesh_group, "id", id_);
2,694✔
582

583
  // Write mesh name
584
  write_dataset(mesh_group, "name", name_);
2,694✔
585

586
  // Write mesh data
587
  this->to_hdf5_inner(mesh_group);
2,694✔
588

589
  // Close group
590
  close_group(mesh_group);
2,694✔
591
}
2,694✔
592

593
//==============================================================================
594
// Structured Mesh implementation
595
//==============================================================================
596

597
std::string StructuredMesh::bin_label(int bin) const
5,127,555✔
598
{
599
  MeshIndex ijk = get_indices_from_bin(bin);
5,127,555✔
600

601
  if (n_dimension_ > 2) {
5,127,555✔
602
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,225,608✔
603
  } else if (n_dimension_ > 1) {
14,751✔
604
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
28,952✔
605
  } else {
606
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
607
  }
608
}
609

610
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,311✔
611
{
612
  // because method is const, shape_ is const as well and can't be adapted
613
  auto tmp_shape = shape_;
2,311✔
614
  return xt::adapt(tmp_shape, {n_dimension_});
4,622✔
615
}
616

617
Position StructuredMesh::sample_element(
1,416,830✔
618
  const MeshIndex& ijk, uint64_t* seed) const
619
{
620
  // lookup the lower/upper bounds for the mesh element
621
  double x_min = negative_grid_boundary(ijk, 0);
1,416,830✔
622
  double x_max = positive_grid_boundary(ijk, 0);
1,416,830✔
623

624
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,416,830!
625
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,416,830!
626

627
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,416,830!
628
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,416,830!
629

630
  return {x_min + (x_max - x_min) * prn(seed),
1,416,830✔
631
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,416,830✔
632
}
633

634
//==============================================================================
635
// Unstructured Mesh implementation
636
//==============================================================================
637

638
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
46✔
639
{
640
  n_dimension_ = 3;
46✔
641

642
  // check the mesh type
643
  if (check_for_node(node, "type")) {
46!
644
    auto temp = get_node_value(node, "type", true, true);
46!
645
    if (temp != mesh_type) {
46!
646
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
647
    }
648
  }
46✔
649

650
  // check if a length unit multiplier was specified
651
  if (check_for_node(node, "length_multiplier")) {
46!
652
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
653
  }
654

655
  // get the filename of the unstructured mesh to load
656
  if (check_for_node(node, "filename")) {
46!
657
    filename_ = get_node_value(node, "filename");
46!
658
    if (!file_exists(filename_)) {
46!
659
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
660
    }
661
  } else {
662
    fatal_error(fmt::format(
×
663
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
664
  }
665

666
  if (check_for_node(node, "options")) {
46!
667
    options_ = get_node_value(node, "options");
16!
668
  }
669

670
  // check if mesh tally data should be written with
671
  // statepoint files
672
  if (check_for_node(node, "output")) {
46!
673
    output_ = get_node_value_bool(node, "output");
×
674
  }
675
}
46✔
676

NEW
677
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
678
{
NEW
679
  n_dimension_ = 3;
×
680

681
  // check the mesh type
NEW
682
  if (object_exists(group, "type")) {
×
NEW
683
    std::string temp;
×
NEW
684
    read_dataset(group, "type", temp);
×
NEW
685
    if (temp != mesh_type) {
×
NEW
686
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
687
    }
NEW
688
  }
×
689

690
  // check if a length unit multiplier was specified
NEW
691
  if (object_exists(group, "length_multiplier")) {
×
NEW
692
    read_dataset(group, "length_multiplier", length_multiplier_);
×
693
  }
694

695
  // get the filename of the unstructured mesh to load
NEW
696
  if (object_exists(group, "filename")) {
×
NEW
697
    read_dataset(group, "filename", filename_);
×
NEW
698
    if (!file_exists(filename_)) {
×
NEW
699
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
700
    }
701
  } else {
NEW
702
    fatal_error(fmt::format(
×
NEW
703
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
704
  }
705

NEW
706
  if (attribute_exists(group, "options")) {
×
NEW
707
    read_attribute(group, "options", options_);
×
708
  }
709

710
  // check if mesh tally data should be written with
711
  // statepoint files
NEW
712
  if (attribute_exists(group, "output")) {
×
NEW
713
    read_attribute(group, "output", output_);
×
714
  }
NEW
715
}
×
716

717
void UnstructuredMesh::determine_bounds()
24✔
718
{
719
  double xmin = INFTY;
24✔
720
  double ymin = INFTY;
24✔
721
  double zmin = INFTY;
24✔
722
  double xmax = -INFTY;
24✔
723
  double ymax = -INFTY;
24✔
724
  double zmax = -INFTY;
24✔
725
  int n = this->n_vertices();
24!
726
  for (int i = 0; i < n; ++i) {
55,936✔
727
    auto v = this->vertex(i);
55,912!
728
    xmin = std::min(v.x, xmin);
55,912✔
729
    ymin = std::min(v.y, ymin);
55,912✔
730
    zmin = std::min(v.z, zmin);
55,912✔
731
    xmax = std::max(v.x, xmax);
55,912✔
732
    ymax = std::max(v.y, ymax);
55,912✔
733
    zmax = std::max(v.z, zmax);
55,912✔
734
  }
735
  lower_left_ = {xmin, ymin, zmin};
24!
736
  upper_right_ = {xmax, ymax, zmax};
24!
737
}
24✔
738

739
Position UnstructuredMesh::sample_tet(
601,230✔
740
  std::array<Position, 4> coords, uint64_t* seed) const
741
{
742
  // Uniform distribution
743
  double s = prn(seed);
601,230✔
744
  double t = prn(seed);
601,230✔
745
  double u = prn(seed);
601,230✔
746

747
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
748
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
749
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
750
  if (s + t > 1) {
601,230✔
751
    s = 1.0 - s;
300,619✔
752
    t = 1.0 - t;
300,619✔
753
  }
754
  if (s + t + u > 1) {
601,230✔
755
    if (t + u > 1) {
400,816✔
756
      double old_t = t;
200,327✔
757
      t = 1.0 - u;
200,327✔
758
      u = 1.0 - s - old_t;
200,327✔
759
    } else if (t + u <= 1) {
200,489!
760
      double old_s = s;
200,489✔
761
      s = 1.0 - t - u;
200,489✔
762
      u = old_s + t + u - 1;
200,489✔
763
    }
764
  }
765
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
766
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
767
}
768

769
const std::string UnstructuredMesh::mesh_type = "unstructured";
770

771
std::string UnstructuredMesh::get_mesh_type() const
31✔
772
{
773
  return mesh_type;
31✔
774
}
775

776
void UnstructuredMesh::surface_bins_crossed(
×
777
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
778
{
779
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
780
}
781

782
std::string UnstructuredMesh::bin_label(int bin) const
205,712✔
783
{
784
  return fmt::format("Mesh Index ({})", bin);
205,712!
785
};
786

787
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
31✔
788
{
789
  write_dataset(mesh_group, "filename", filename_);
31!
790
  write_dataset(mesh_group, "library", this->library());
31!
791
  if (!options_.empty()) {
31✔
792
    write_attribute(mesh_group, "options", options_);
8!
793
  }
794

795
  if (length_multiplier_ > 0.0)
31!
796
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
797

798
  // write vertex coordinates
799
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
31!
800
  for (int i = 0; i < this->n_vertices(); i++) {
70,260!
801
    auto v = this->vertex(i);
70,229!
802
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
70,229!
803
  }
804
  write_dataset(mesh_group, "vertices", vertices);
31!
805

806
  int num_elem_skipped = 0;
31✔
807

808
  // write element types and connectivity
809
  vector<double> volumes;
31✔
810
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
31!
811
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
31!
812
  for (int i = 0; i < this->n_bins(); i++) {
349,743!
813
    auto conn = this->connectivity(i);
349,712!
814

815
    volumes.emplace_back(this->volume(i));
349,712!
816

817
    // write linear tet element
818
    if (conn.size() == 4) {
349,712✔
819
      xt::view(elem_types, i, xt::all()) =
695,424!
820
        static_cast<int>(ElementType::LINEAR_TET);
695,424!
821
      xt::view(connectivity, i, xt::all()) =
695,424!
822
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,043,136!
823
      // write linear hex element
824
    } else if (conn.size() == 8) {
2,000!
825
      xt::view(elem_types, i, xt::all()) =
4,000!
826
        static_cast<int>(ElementType::LINEAR_HEX);
4,000!
827
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000!
828
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000!
829
    } else {
830
      num_elem_skipped++;
×
831
      xt::view(elem_types, i, xt::all()) =
×
832
        static_cast<int>(ElementType::UNSUPPORTED);
×
833
      xt::view(connectivity, i, xt::all()) = -1;
×
834
    }
835
  }
349,712✔
836

837
  // warn users that some elements were skipped
838
  if (num_elem_skipped > 0) {
31!
839
    warning(fmt::format("The connectivity of {} elements "
×
840
                        "on mesh {} were not written "
841
                        "because they are not of type linear tet/hex.",
842
      num_elem_skipped, this->id_));
×
843
  }
844

845
  write_dataset(mesh_group, "volumes", volumes);
31!
846
  write_dataset(mesh_group, "connectivity", connectivity);
31!
847
  write_dataset(mesh_group, "element_types", elem_types);
31!
848
}
31✔
849

850
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
851
{
852
  length_multiplier_ = length_multiplier;
23✔
853
}
23✔
854

855
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
856
{
857
  auto conn = connectivity(bin);
120,000!
858

859
  if (conn.size() == 4)
120,000!
860
    return ElementType::LINEAR_TET;
120,000✔
861
  else if (conn.size() == 8)
×
862
    return ElementType::LINEAR_HEX;
×
863
  else
864
    return ElementType::UNSUPPORTED;
×
865
}
120,000✔
866

867
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,118,192,252✔
868
  Position r, bool& in_mesh) const
869
{
870
  MeshIndex ijk;
871
  in_mesh = true;
1,118,192,252✔
872
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
873
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
874

875
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
876
      in_mesh = false;
102,385,917✔
877
  }
878
  return ijk;
1,118,192,252✔
879
}
880

881
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,659,410,463✔
882
{
883
  switch (n_dimension_) {
1,659,410,463!
884
  case 1:
880,605✔
885
    return ijk[0] - 1;
880,605✔
886
  case 2:
70,207,324✔
887
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
70,207,324✔
888
  case 3:
1,588,322,534✔
889
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,588,322,534✔
890
  default:
×
891
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
892
  }
893
}
894

895
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,760,549✔
896
{
897
  MeshIndex ijk;
898
  if (n_dimension_ == 1) {
7,760,549✔
899
    ijk[0] = bin + 1;
275✔
900
  } else if (n_dimension_ == 2) {
7,760,274✔
901
    ijk[0] = bin % shape_[0] + 1;
14,476✔
902
    ijk[1] = bin / shape_[0] + 1;
14,476✔
903
  } else if (n_dimension_ == 3) {
7,745,798!
904
    ijk[0] = bin % shape_[0] + 1;
7,745,798✔
905
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,745,798✔
906
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,745,798✔
907
  }
908
  return ijk;
7,760,549✔
909
}
910

911
int StructuredMesh::get_bin(Position r) const
247,687,884✔
912
{
913
  // Determine indices
914
  bool in_mesh;
915
  MeshIndex ijk = get_indices(r, in_mesh);
247,687,884✔
916
  if (!in_mesh)
247,687,884✔
917
    return -1;
20,990,292✔
918

919
  // Convert indices to bin
920
  return get_bin_from_indices(ijk);
226,697,592✔
921
}
922

923
int StructuredMesh::n_bins() const
1,139,306✔
924
{
925
  return std::accumulate(
1,139,306✔
926
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,278,612✔
927
}
928

929
int StructuredMesh::n_surface_bins() const
380✔
930
{
931
  return 4 * n_dimension_ * n_bins();
380✔
932
}
933

934
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
935
  const SourceSite* bank, int64_t length, bool* outside) const
936
{
937
  // Determine shape of array for counts
938
  std::size_t m = this->n_bins();
×
939
  vector<std::size_t> shape = {m};
×
940

941
  // Create array of zeros
942
  xt::xarray<double> cnt {shape, 0.0};
×
943
  bool outside_ = false;
×
944

945
  for (int64_t i = 0; i < length; i++) {
×
946
    const auto& site = bank[i];
×
947

948
    // determine scoring bin for entropy mesh
949
    int mesh_bin = get_bin(site.r);
×
950

951
    // if outside mesh, skip particle
952
    if (mesh_bin < 0) {
×
953
      outside_ = true;
×
954
      continue;
×
955
    }
956

957
    // Add to appropriate bin
958
    cnt(mesh_bin) += site.wgt;
×
959
  }
960

961
  // Create copy of count data. Since ownership will be acquired by xtensor,
962
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
963
  // warnings.
964
  int total = cnt.size();
×
965
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
966

967
#ifdef OPENMC_MPI
968
  // collect values from all processors
969
  MPI_Reduce(
×
970
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
971

972
  // Check if there were sites outside the mesh for any processor
973
  if (outside) {
×
974
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
975
  }
976
#else
977
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
×
978
  if (outside)
×
979
    *outside = outside_;
980
#endif
981

982
  // Adapt reduced values in array back into an xarray
983
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
984
  xt::xarray<double> counts = arr;
×
985

986
  return counts;
×
987
}
×
988

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

1002
  // Compute the length of the entire track.
1003
  double total_distance = (r1 - r0).norm();
875,497,692✔
1004
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
875,497,692✔
1005
    return;
11,635,894✔
1006

1007
  // keep a copy of the original global position to pass to get_indices,
1008
  // which performs its own transformation to local coordinates
1009
  Position global_r = r0;
863,861,798✔
1010
  Position local_r = local_coords(r0);
863,861,798✔
1011

1012
  const int n = n_dimension_;
863,861,798✔
1013

1014
  // Flag if position is inside the mesh
1015
  bool in_mesh;
1016

1017
  // Position is r = r0 + u * traveled_distance, start at r0
1018
  double traveled_distance {0.0};
863,861,798✔
1019

1020
  // Calculate index of current cell. Offset the position a tiny bit in
1021
  // direction of flight
1022
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
863,861,798✔
1023

1024
  // if track is very short, assume that it is completely inside one cell.
1025
  // Only the current cell will score and no surfaces
1026
  if (total_distance < 2 * TINY_BIT) {
863,861,798✔
1027
    if (in_mesh) {
331,527✔
1028
      tally.track(ijk, 1.0);
331,043✔
1029
    }
1030
    return;
331,527✔
1031
  }
1032

1033
  // Calculate initial distances to next surfaces in all three dimensions
1034
  std::array<MeshDistance, 3> distances;
1,727,060,542✔
1035
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1036
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1037
  }
1038

1039
  // Loop until r = r1 is eventually reached
1040
  while (true) {
736,588,755✔
1041

1042
    if (in_mesh) {
1,600,119,026✔
1043

1044
      // find surface with minimal distance to current position
1045
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,514,267,203✔
1046
                     distances.begin();
1,514,267,203✔
1047

1048
      // Tally track length delta since last step
1049
      tally.track(ijk,
1,514,267,203✔
1050
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,514,267,203✔
1051
          total_distance);
1052

1053
      // update position and leave, if we have reached end position
1054
      traveled_distance = distances[k].distance;
1,514,267,203✔
1055
      if (traveled_distance >= total_distance)
1,514,267,203✔
1056
        return;
784,321,018✔
1057

1058
      // If we have not reached r1, we have hit a surface. Tally outward
1059
      // current
1060
      tally.surface(ijk, k, distances[k].max_surface, false);
729,946,185✔
1061

1062
      // Update cell and calculate distance to next surface in k-direction.
1063
      // The two other directions are still valid!
1064
      ijk[k] = distances[k].next_index;
729,946,185✔
1065
      distances[k] =
729,946,185✔
1066
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
729,946,185✔
1067

1068
      // Check if we have left the interior of the mesh
1069
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
729,946,185✔
1070

1071
      // If we are still inside the mesh, tally inward current for the next
1072
      // cell
1073
      if (in_mesh)
729,946,185✔
1074
        tally.surface(ijk, k, !distances[k].max_surface, true);
716,790,379✔
1075

1076
    } else { // not inside mesh
1077

1078
      // For all directions outside the mesh, find the distance that we need
1079
      // to travel to reach the next surface. Use the largest distance, as
1080
      // only this will cross all outer surfaces.
1081
      int k_max {-1};
85,851,823✔
1082
      for (int k = 0; k < n; ++k) {
341,962,926✔
1083
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
349,954,143✔
1084
            (distances[k].distance > traveled_distance)) {
93,843,040✔
1085
          traveled_distance = distances[k].distance;
88,864,928✔
1086
          k_max = k;
88,864,928✔
1087
        }
1088
      }
1089
      // Assure some distance is traveled
1090
      if (k_max == -1) {
85,851,823✔
1091
        traveled_distance += TINY_BIT;
110✔
1092
      }
1093

1094
      // If r1 is not inside the mesh, exit here
1095
      if (traveled_distance >= total_distance)
85,851,823✔
1096
        return;
79,209,253✔
1097

1098
      // Calculate the new cell index and update all distances to next
1099
      // surfaces.
1100
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,642,570✔
1101
      for (int k = 0; k < n; ++k) {
26,361,742✔
1102
        distances[k] =
19,719,172✔
1103
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
19,719,172✔
1104
      }
1105

1106
      // If inside the mesh, Tally inward current
1107
      if (in_mesh && k_max >= 0)
6,642,570!
1108
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
6,223,255✔
1109
    }
1110
  }
1111
}
1112

1113
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
763,370,127✔
1114
  vector<int>& bins, vector<double>& lengths) const
1115
{
1116

1117
  // Helper tally class.
1118
  // stores a pointer to the mesh class and references to bins and lengths
1119
  // parameters. Performs the actual tally through the track method.
1120
  struct TrackAggregator {
1121
    TrackAggregator(
763,370,127✔
1122
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1123
      : mesh(_mesh), bins(_bins), lengths(_lengths)
763,370,127✔
1124
    {}
763,370,127✔
1125
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1,394,800,630✔
1126
    void track(const MeshIndex& ijk, double l) const
1,374,553,682✔
1127
    {
1128
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,374,553,682✔
1129
      lengths.push_back(l);
1,374,553,682✔
1130
    }
1,374,553,682✔
1131

1132
    const StructuredMesh* mesh;
1133
    vector<int>& bins;
1134
    vector<double>& lengths;
1135
  };
1136

1137
  // Perform the mesh raytrace with the helper class.
1138
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
763,370,127✔
1139
}
763,370,127✔
1140

1141
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1142
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1143
{
1144

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

1164
    const StructuredMesh* mesh;
1165
    vector<int>& bins;
1166
  };
1167

1168
  // Perform the mesh raytrace with the helper class.
1169
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1170
}
112,127,565✔
1171

1172
//==============================================================================
1173
// RegularMesh implementation
1174
//==============================================================================
1175

1176
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1,848✔
1177
{
1178
  // Determine number of dimensions for mesh
1179
  if (!check_for_node(node, "dimension")) {
1,848!
1180
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1181
  }
1182

1183
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
1,848✔
1184
  int n = n_dimension_ = shape.size();
1,848✔
1185
  if (n != 1 && n != 2 && n != 3) {
1,848!
1186
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1187
  }
1188
  std::copy(shape.begin(), shape.end(), shape_.begin());
1,848✔
1189

1190
  // Check that dimensions are all greater than zero
1191
  if (xt::any(shape <= 0)) {
1,848!
1192
    fatal_error("All entries on the <dimension> element for a tally "
×
1193
                "mesh must be positive.");
1194
  }
1195

1196
  // Check for lower-left coordinates
1197
  if (check_for_node(node, "lower_left")) {
1,848!
1198
    // Read mesh lower-left corner location
1199
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1,848✔
1200
  } else {
1201
    fatal_error("Must specify <lower_left> on a mesh.");
×
1202
  }
1203

1204
  // Make sure lower_left and dimension match
1205
  if (shape.size() != lower_left_.size()) {
1,848!
1206
    fatal_error("Number of entries on <lower_left> must be the same "
×
1207
                "as the number of entries on <dimension>.");
1208
  }
1209

1210
  if (check_for_node(node, "width")) {
1,848✔
1211
    // Make sure one of upper-right or width were specified
1212
    if (check_for_node(node, "upper_right")) {
49!
1213
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1214
    }
1215

1216
    width_ = get_node_xarray<double>(node, "width");
49✔
1217

1218
    // Check to ensure width has same dimensions
1219
    auto n = width_.size();
49✔
1220
    if (n != lower_left_.size()) {
49!
1221
      fatal_error("Number of entries on <width> must be the same as "
×
1222
                  "the number of entries on <lower_left>.");
1223
    }
1224

1225
    // Check for negative widths
1226
    if (xt::any(width_ < 0.0)) {
49!
1227
      fatal_error("Cannot have a negative <width> on a tally mesh.");
×
1228
    }
1229

1230
    // Set width and upper right coordinate
1231
    upper_right_ = xt::eval(lower_left_ + shape * width_);
49✔
1232

1233
  } else if (check_for_node(node, "upper_right")) {
1,799!
1234
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1,799✔
1235

1236
    // Check to ensure width has same dimensions
1237
    auto n = upper_right_.size();
1,799✔
1238
    if (n != lower_left_.size()) {
1,799!
1239
      fatal_error("Number of entries on <upper_right> must be the "
×
1240
                  "same as the number of entries on <lower_left>.");
1241
    }
1242

1243
    // Check that upper-right is above lower-left
1244
    if (xt::any(upper_right_ < lower_left_)) {
1,799!
1245
      fatal_error("The <upper_right> coordinates must be greater than "
×
1246
                  "the <lower_left> coordinates on a tally mesh.");
1247
    }
1248

1249
    // Set width
1250
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1,799✔
1251
  } else {
1252
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1253
  }
1254

1255
  // Set material volumes
1256
  volume_frac_ = 1.0 / xt::prod(shape)();
1,848✔
1257

1258
  element_volume_ = 1.0;
1,848✔
1259
  for (int i = 0; i < n_dimension_; i++) {
7,018✔
1260
    element_volume_ *= width_[i];
5,170✔
1261
  }
1262
}
1,848✔
1263

1264
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
11✔
1265
{
1266
  // Determine number of dimensions for mesh
1267
  if (!object_exists(group, "dimension")) {
11!
NEW
1268
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1269
  }
1270

1271
  xt::xtensor<int, 1> shape;
11✔
1272
  read_dataset(group, "dimension", shape);
11✔
1273
  int n = n_dimension_ = shape.size();
11✔
1274
  if (n != 1 && n != 2 && n != 3) {
11!
NEW
1275
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1276
  }
1277
  std::copy(shape.begin(), shape.end(), shape_.begin());
11✔
1278

1279
  // Check that dimensions are all greater than zero
1280
  if (xt::any(shape <= 0)) {
11!
NEW
1281
    fatal_error("All entries on the <dimension> element for a tally "
×
1282
                "mesh must be positive.");
1283
  }
1284

1285
  // Check for lower-left coordinates
1286
  if (object_exists(group, "lower_left")) {
11!
1287
    // Read mesh lower-left corner location
1288
    read_dataset(group, "lower_left", lower_left_);
11✔
1289
  } else {
NEW
1290
    fatal_error("Must specify <lower_left> on a mesh.");
×
1291
  }
1292

1293
  // Make sure lower_left and dimension match
1294
  if (shape.size() != lower_left_.size()) {
11!
NEW
1295
    fatal_error("Number of entries on <lower_left> must be the same "
×
1296
                "as the number of entries on <dimension>.");
1297
  }
1298

1299
  if (object_exists(group, "upper_right")) {
11!
1300

1301
    read_dataset(group, "upper_right", upper_right_);
11✔
1302

1303
    // Check to ensure width has same dimensions
1304
    auto n = upper_right_.size();
11✔
1305
    if (n != lower_left_.size()) {
11!
NEW
1306
      fatal_error("Number of entries on <upper_right> must be the "
×
1307
                  "same as the number of entries on <lower_left>.");
1308
    }
1309

1310
    // Check that upper-right is above lower-left
1311
    if (xt::any(upper_right_ < lower_left_)) {
11!
NEW
1312
      fatal_error("The <upper_right> coordinates must be greater than "
×
1313
                  "the <lower_left> coordinates on a tally mesh.");
1314
    }
1315

1316
    // Set width
1317
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
11✔
1318
  } else {
NEW
1319
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1320
  }
1321

1322
  // Set material volumes
1323
  volume_frac_ = 1.0 / xt::prod(shape)();
11✔
1324

1325
  element_volume_ = 1.0;
11✔
1326
  for (int i = 0; i < n_dimension_; i++) {
44✔
1327
    element_volume_ *= width_[i];
33✔
1328
  }
1329
}
11✔
1330

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

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

1338
std::string RegularMesh::get_mesh_type() const
2,971✔
1339
{
1340
  return mesh_type;
2,971✔
1341
}
1342

1343
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,406,215,419✔
1344
{
1345
  return lower_left_[i] + ijk[i] * width_[i];
1,406,215,419✔
1346
}
1347

1348
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,344,498,234✔
1349
{
1350
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,344,498,234✔
1351
}
1352

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

1362
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1363
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1364
    d.next_index++;
1,401,964,929✔
1365
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,401,964,929✔
1366
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,361,408,417✔
1367
    d.next_index--;
1,340,247,744✔
1368
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,340,247,744✔
1369
  }
1370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1483
//==============================================================================
1484
// RectilinearMesh implementation
1485
//==============================================================================
1486

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

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

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

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

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

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

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

1515
std::string RectilinearMesh::get_mesh_type() const
275✔
1516
{
1517
  return mesh_type;
275✔
1518
}
1519

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

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

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

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

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

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

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

1575
  return 0;
180✔
1576
}
1577

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

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

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

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

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

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

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

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

1630
//==============================================================================
1631
// CylindricalMesh implementation
1632
//==============================================================================
1633

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

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

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

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

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

1663
std::string CylindricalMesh::get_mesh_type() const
484✔
1664
{
1665
  return mesh_type;
484✔
1666
}
1667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1870
    return OPENMC_E_INVALID_ARGUMENT;
×
1871
  }
1872

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

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

1880
  return 0;
434✔
1881
}
1882

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

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

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

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

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

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

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

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

1920
//==============================================================================
1921
// SphericalMesh implementation
1922
//==============================================================================
1923

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

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

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

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

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

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

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

1955
std::string SphericalMesh::get_mesh_type() const
374✔
1956
{
1957
  return mesh_type;
374✔
1958
}
1959

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2208
  return 0;
368✔
2209
}
2210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2295
  return 0;
1,441✔
2296
}
2297

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

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

2322
  return 0;
253✔
2323
}
253✔
2324

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

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

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

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

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

2358
  return 0;
×
2359
}
×
2360

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

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

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

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

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

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

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

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

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

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

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

2450
  return 0;
154✔
2451
}
2452

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

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

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

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

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

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

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

2507
  return 0;
44✔
2508
}
2509

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

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

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

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

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

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

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

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

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

2587
  // Set material volumes
2588

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

2597
  return 0;
220✔
2598
}
220✔
2599

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

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

2611
  m->n_dimension_ = 3;
88✔
2612

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

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

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

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

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

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

2652
  return 0;
385✔
2653
}
2654

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

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

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

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

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

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

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

2708
#ifdef OPENMC_DAGMC_ENABLED
2709

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

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

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

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

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

2738
void MOABMesh::initialize()
24✔
2739
{
2740

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

2744
  // Initialise MOAB error code
2745
  moab::ErrorCode rval = moab::MB_SUCCESS;
24✔
2746

2747
  // Set the dimension
2748
  n_dimension_ = 3;
24✔
2749

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2921
  start -= TINY_BIT * dir;
1,543,564✔
2922
  end += TINY_BIT * dir;
1,543,564✔
2923

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

2927
  bins.clear();
1,543,564✔
2928
  lengths.clear();
1,543,564✔
2929

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

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

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

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

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

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

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

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

3000
  // loop over the tets in this leaf, returning the containing tet if found
3001
  for (const auto& tet : tets) {
260,209,001✔
3002
    if (point_in_tet(pos, tet)) {
260,206,154✔
3003
      return tet;
6,302,306✔
3004
    }
3005
  }
3006

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

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

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

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

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

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

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

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

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

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

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

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

3081
  baryc_data_.clear();
20✔
3082
  baryc_data_.resize(tets.size());
20✔
3083

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

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

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

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

3107
bool MOABMesh::point_in_tet(
260,206,154✔
3108
  const moab::CartVect& r, moab::EntityHandle tet) const
3109
{
3110

3111
  moab::ErrorCode rval;
3112

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

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

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

3136
  moab::CartVect bary_coords = a_inv * (r - p_zero);
260,206,154✔
3137

3138
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
421,413,584✔
3139
          bary_coords[2] >= 0.0 &&
443,101,423✔
3140
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
281,893,993✔
3141
}
260,206,154✔
3142

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

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

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

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

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

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

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

3197
int MOABMesh::n_bins() const
267,524,219✔
3198
{
3199
  return ehs_.size();
267,524,219✔
3200
}
3201

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

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

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

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

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

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

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

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

3252
Position MOABMesh::vertex(int id) const
86,199✔
3253
{
3254

3255
  moab::ErrorCode rval;
3256

3257
  moab::EntityHandle vert = verts_[id];
86,199✔
3258

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

3265
  return {coords[0], coords[1], coords[2]};
172,398✔
3266
}
3267

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

3272
  auto tet = get_ent_handle_from_bin(bin);
203,856✔
3273

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

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

3287
  return verts;
203,856✔
3288
}
203,856✔
3289

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3415
#endif
3416

3417
#ifdef OPENMC_LIBMESH_ENABLED
3418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3789
#endif // OPENMC_LIBMESH_ENABLED
3790

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

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

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

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

3816
    std::string mesh_type;
2,711✔
3817
    if (check_for_node(node, "type")) {
2,711✔
3818
      mesh_type = get_node_value(node, "type", true, true);
944✔
3819
    } else {
3820
      mesh_type = "regular";
1,767✔
3821
    }
3822

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

3829
    Mesh::create(node, mesh_type, mesh_lib);
2,711✔
3830
  }
2,711✔
3831
}
11,694✔
3832

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

3837
  std::array<int, 1> ids;
3838
  read_attribute(group, "ids", ids);
11✔
3839

3840
  for (auto id : ids) {
22✔
3841

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

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

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

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

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

NEW
3873
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
UNCOV
3874
  }
×
3875
}
11✔
3876

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

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

3894
  close_group(meshes_group);
6,739✔
3895
}
6,739✔
3896

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

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

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

© 2025 Coveralls, Inc