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

openmc-dev / openmc / 14609772425

23 Apr 2025 04:09AM UTC coverage: 85.202% (-0.2%) from 85.414%
14609772425

Pull #3377

github

web-flow
Merge d2e663342 into 5dd6ff652
Pull Request #3377: using reduce chain level to remove need for reduce chain

3 of 5 new or added lines in 1 file covered. (60.0%)

313 existing lines in 27 files now uncovered.

52222 of 61292 relevant lines covered (85.2%)

37246474.52 hits per line

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

87.37
/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 LIBMESH
51
#include "libmesh/mesh_modification.h"
52
#include "libmesh/mesh_tools.h"
53
#include "libmesh/numeric_vector.h"
54
#endif
55

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

60
namespace openmc {
61

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

66
#ifdef LIBMESH
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 LIBMESH
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,259✔
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,259✔
128
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
1,259✔
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,268,893✔
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,268,893✔
159
    // Determine slot to check, making sure it is positive
160
    int slot = (index_material + attempt) % table_size_;
2,268,893✔
161
    if (slot < 0)
2,268,893✔
162
      slot += table_size_;
62,546✔
163
    int32_t* slot_ptr = &this->materials(index_elem, slot);
2,268,893✔
164

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

168
    // Found the desired material; accumulate volume
169
    if (current_val == index_material) {
2,268,893✔
170
#pragma omp atomic
1,237,265✔
171
      this->volumes(index_elem, slot) += volume;
2,267,634✔
172
      return;
2,267,634✔
173
    }
174

175
    // Slot appears to be empty; attempt to claim
176
    if (current_val == EMPTY) {
1,259✔
177
      // Attempt compare-and-swap from EMPTY to index_material
178
      int32_t expected_val = EMPTY;
1,259✔
179
      bool claimed_slot =
180
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,259✔
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,259✔
185
#pragma omp atomic
690✔
186
        this->volumes(index_elem, slot) += volume;
1,259✔
187
        return;
1,259✔
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
Mesh::Mesh(pugi::xml_node node)
2,577✔
234
{
235
  // Read mesh id
236
  id_ = std::stoi(get_node_value(node, "id"));
2,577✔
237
  if (check_for_node(node, "name"))
2,577✔
238
    name_ = get_node_value(node, "name");
16✔
239
}
2,577✔
240

241
void Mesh::set_id(int32_t id)
1✔
242
{
243
  assert(id >= 0 || id == C_NONE);
1✔
244

245
  // Clear entry in mesh map in case one was already assigned
246
  if (id_ != C_NONE) {
1✔
247
    model::mesh_map.erase(id_);
×
248
    id_ = C_NONE;
×
249
  }
250

251
  // Ensure no other mesh has the same ID
252
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
1✔
253
    throw std::runtime_error {
×
254
      fmt::format("Two meshes have the same ID: {}", id)};
×
255
  }
256

257
  // If no ID is specified, auto-assign the next ID in the sequence
258
  if (id == C_NONE) {
1✔
259
    id = 0;
1✔
260
    for (const auto& m : model::meshes) {
3✔
261
      id = std::max(id, m->id_);
2✔
262
    }
263
    ++id;
1✔
264
  }
265

266
  // Update ID and entry in the mesh map
267
  id_ = id;
1✔
268
  model::mesh_map[id] = model::meshes.size() - 1;
1✔
269
}
1✔
270

271
vector<double> Mesh::volumes() const
2,394✔
272
{
273
  vector<double> volumes(n_bins());
2,394✔
274
  for (int i = 0; i < n_bins(); i++) {
7,453,349✔
275
    volumes[i] = this->volume(i);
7,450,955✔
276
  }
277
  return volumes;
2,394✔
278
}
×
279

280
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
143✔
281
  int32_t* materials, double* volumes) const
282
{
283
  if (mpi::master) {
143✔
284
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
143✔
285
  }
286
  write_message(7, "Number of mesh elements = {}", n_bins());
143✔
287
  write_message(7, "Number of rays (x) = {}", nx);
143✔
288
  write_message(7, "Number of rays (y) = {}", ny);
143✔
289
  write_message(7, "Number of rays (z) = {}", nz);
143✔
290
  int64_t n_total = static_cast<int64_t>(nx) * ny +
143✔
291
                    static_cast<int64_t>(ny) * nz +
143✔
292
                    static_cast<int64_t>(nx) * nz;
143✔
293
  write_message(7, "Total number of rays = {}", n_total);
143✔
294
  write_message(7, "Table size per mesh element = {}", table_size);
143✔
295

296
  Timer timer;
143✔
297
  timer.start();
143✔
298

299
  // Create object for keeping track of materials/volumes
300
  detail::MaterialVolumes result(materials, volumes, table_size);
143✔
301

302
  // Determine bounding box
303
  auto bbox = this->bounding_box();
143✔
304

305
  std::array<int, 3> n_rays = {nx, ny, nz};
143✔
306

307
  // Determine effective width of rays
308
  Position width((nx > 0) ? (bbox.xmax - bbox.xmin) / nx : 0.0,
264✔
309
    (ny > 0) ? (bbox.ymax - bbox.ymin) / ny : 0.0,
275✔
310
    (nz > 0) ? (bbox.zmax - bbox.zmin) / nz : 0.0);
143✔
311

312
  // Set flag for mesh being contained within model
313
  bool out_of_model = false;
143✔
314

315
#pragma omp parallel
78✔
316
  {
317
    // Preallocate vector for mesh indices and length fractions and particle
318
    std::vector<int> bins;
65✔
319
    std::vector<double> length_fractions;
65✔
320
    Particle p;
65✔
321

322
    SourceSite site;
65✔
323
    site.E = 1.0;
65✔
324
    site.particle = ParticleType::neutron;
65✔
325

326
    for (int axis = 0; axis < 3; ++axis) {
260✔
327
      // Set starting position and direction
328
      site.r = {0.0, 0.0, 0.0};
195✔
329
      site.r[axis] = bbox.min()[axis];
195✔
330
      site.u = {0.0, 0.0, 0.0};
195✔
331
      site.u[axis] = 1.0;
195✔
332

333
      // Determine width of rays and number of rays in other directions
334
      int ax1 = (axis + 1) % 3;
195✔
335
      int ax2 = (axis + 2) % 3;
195✔
336
      double min1 = bbox.min()[ax1];
195✔
337
      double min2 = bbox.min()[ax2];
195✔
338
      double d1 = width[ax1];
195✔
339
      double d2 = width[ax2];
195✔
340
      int n1 = n_rays[ax1];
195✔
341
      int n2 = n_rays[ax2];
195✔
342
      if (n1 == 0 || n2 == 0) {
195✔
343
        continue;
50✔
344
      }
345

346
      // Divide rays in first direction over MPI processes by computing starting
347
      // and ending indices
348
      int min_work = n1 / mpi::n_procs;
145✔
349
      int remainder = n1 % mpi::n_procs;
145✔
350
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
145✔
351
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
145✔
352
      int i1_end = i1_start + n1_local;
145✔
353

354
      // Loop over rays on face of bounding box
355
#pragma omp for collapse(2)
356
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
7,070✔
357
        for (int i2 = 0; i2 < n2; ++i2) {
418,820✔
358
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
411,895✔
359
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
411,895✔
360

361
          p.from_source(&site);
411,895✔
362

363
          // Determine particle's location
364
          if (!exhaustive_find_cell(p)) {
411,895✔
365
            out_of_model = true;
39,930✔
366
            continue;
39,930✔
367
          }
368

369
          // Set birth cell attribute
370
          if (p.cell_born() == C_NONE)
371,965✔
371
            p.cell_born() = p.lowest_coord().cell;
371,965✔
372

373
          // Initialize last cells from current cell
374
          for (int j = 0; j < p.n_coord(); ++j) {
743,930✔
375
            p.cell_last(j) = p.coord(j).cell;
371,965✔
376
          }
377
          p.n_coord_last() = p.n_coord();
371,965✔
378

379
          while (true) {
380
            // Ray trace from r_start to r_end
381
            Position r0 = p.r();
811,645✔
382
            double max_distance = bbox.max()[axis] - r0[axis];
811,645✔
383

384
            // Find the distance to the nearest boundary
385
            BoundaryInfo boundary = distance_to_boundary(p);
811,645✔
386

387
            // Advance particle forward
388
            double distance = std::min(boundary.distance, max_distance);
811,645✔
389
            p.move_distance(distance);
811,645✔
390

391
            // Determine what mesh elements were crossed by particle
392
            bins.clear();
811,645✔
393
            length_fractions.clear();
811,645✔
394
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
811,645✔
395

396
            // Add volumes to any mesh elements that were crossed
397
            int i_material = p.material();
811,645✔
398
            if (i_material != C_NONE) {
811,645✔
399
              i_material = model::materials[i_material]->id();
783,215✔
400
            }
401
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
1,842,960✔
402
              int mesh_index = bins[i_bin];
1,031,315✔
403
              double length = distance * length_fractions[i_bin];
1,031,315✔
404

405
              // Add volume to result
406
              result.add_volume(mesh_index, i_material, length * d1 * d2);
1,031,315✔
407
            }
408

409
            if (distance == max_distance)
811,645✔
410
              break;
371,965✔
411

412
            // cross next geometric surface
413
            for (int j = 0; j < p.n_coord(); ++j) {
879,360✔
414
              p.cell_last(j) = p.coord(j).cell;
439,680✔
415
            }
416
            p.n_coord_last() = p.n_coord();
439,680✔
417

418
            // Set surface that particle is on and adjust coordinate levels
419
            p.surface() = boundary.surface;
439,680✔
420
            p.n_coord() = boundary.coord_level;
439,680✔
421

422
            if (boundary.lattice_translation[0] != 0 ||
439,680✔
423
                boundary.lattice_translation[1] != 0 ||
879,360✔
424
                boundary.lattice_translation[2] != 0) {
439,680✔
425
              // Particle crosses lattice boundary
426
              cross_lattice(p, boundary);
427
            } else {
428
              // Particle crosses surface
429
              const auto& surf {model::surfaces[p.surface_index()].get()};
439,680✔
430
              p.cross_surface(*surf);
439,680✔
431
            }
432
          }
439,680✔
433
        }
434
      }
435
    }
436
  }
65✔
437

438
  // Check for errors
439
  if (out_of_model) {
143✔
440
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
441
  } else if (result.table_full()) {
132✔
442
    throw std::runtime_error("Maximum number of materials for mesh material "
×
443
                             "volume calculation insufficient.");
×
444
  }
445

446
  // Compute time for raytracing
447
  double t_raytrace = timer.elapsed();
132✔
448

449
#ifdef OPENMC_MPI
450
  // Combine results from multiple MPI processes
451
  if (mpi::n_procs > 1) {
60✔
452
    int total = this->n_bins() * table_size;
453
    if (mpi::master) {
454
      // Allocate temporary buffer for receiving data
455
      std::vector<int32_t> mats(total);
456
      std::vector<double> vols(total);
457

458
      for (int i = 1; i < mpi::n_procs; ++i) {
459
        // Receive material indices and volumes from process i
460
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
461
          MPI_STATUS_IGNORE);
462
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
463
          MPI_STATUS_IGNORE);
464

465
        // Combine with existing results; we can call thread unsafe version of
466
        // add_volume because each thread is operating on a different element
467
#pragma omp for
468
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
469
          for (int k = 0; k < table_size; ++k) {
470
            int index = index_elem * table_size + k;
471
            if (mats[index] != EMPTY) {
472
              result.add_volume_unsafe(index_elem, mats[index], vols[index]);
473
            }
474
          }
475
        }
476
      }
477
    } else {
478
      // Send material indices and volumes to process 0
479
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
480
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
481
    }
482
  }
483

484
  // Report time for MPI communication
485
  double t_mpi = timer.elapsed() - t_raytrace;
60✔
486
#else
487
  double t_mpi = 0.0;
72✔
488
#endif
489

490
  // Normalize based on known volumes of elements
491
  for (int i = 0; i < this->n_bins(); ++i) {
935✔
492
    // Estimated total volume in element i
493
    double volume = 0.0;
803✔
494
    for (int j = 0; j < table_size; ++j) {
7,227✔
495
      volume += result.volumes(i, j);
6,424✔
496
    }
497
    // Renormalize volumes based on known volume of element i
498
    double norm = this->volume(i) / volume;
803✔
499
    for (int j = 0; j < table_size; ++j) {
7,227✔
500
      result.volumes(i, j) *= norm;
6,424✔
501
    }
502
  }
503

504
  // Get total time and normalization time
505
  timer.stop();
132✔
506
  double t_total = timer.elapsed();
132✔
507
  double t_norm = t_total - t_raytrace - t_mpi;
132✔
508

509
  // Show timing statistics
510
  if (settings::verbosity < 7 || !mpi::master)
132✔
511
    return;
44✔
512
  header("Timing Statistics", 7);
88✔
513
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
88✔
514
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
88✔
515
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
88✔
516
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
72✔
517
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
72✔
518
    n_total / t_raytrace);
88✔
519
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
72✔
520
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
88✔
521
  std::fflush(stdout);
88✔
522
}
523

524
void Mesh::to_hdf5(hid_t group) const
2,568✔
525
{
526
  // Create group for mesh
527
  std::string group_name = fmt::format("mesh {}", id_);
4,650✔
528
  hid_t mesh_group = create_group(group, group_name.c_str());
2,568✔
529

530
  // Write mesh type
531
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,568✔
532

533
  // Write mesh ID
534
  write_attribute(mesh_group, "id", id_);
2,568✔
535

536
  // Write mesh name
537
  write_dataset(mesh_group, "name", name_);
2,568✔
538

539
  // Write mesh data
540
  this->to_hdf5_inner(mesh_group);
2,568✔
541

542
  // Close group
543
  close_group(mesh_group);
2,568✔
544
}
2,568✔
545

546
//==============================================================================
547
// Structured Mesh implementation
548
//==============================================================================
549

550
std::string StructuredMesh::bin_label(int bin) const
5,115,917✔
551
{
552
  MeshIndex ijk = get_indices_from_bin(bin);
5,115,917✔
553

554
  if (n_dimension_ > 2) {
5,115,917✔
555
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,202,002✔
556
  } else if (n_dimension_ > 1) {
14,916✔
557
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
29,282✔
558
  } else {
559
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
560
  }
561
}
562

563
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,240✔
564
{
565
  // because method is const, shape_ is const as well and can't be adapted
566
  auto tmp_shape = shape_;
2,240✔
567
  return xt::adapt(tmp_shape, {n_dimension_});
4,480✔
568
}
569

570
Position StructuredMesh::sample_element(
1,413,841✔
571
  const MeshIndex& ijk, uint64_t* seed) const
572
{
573
  // lookup the lower/upper bounds for the mesh element
574
  double x_min = negative_grid_boundary(ijk, 0);
1,413,841✔
575
  double x_max = positive_grid_boundary(ijk, 0);
1,413,841✔
576

577
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,413,841✔
578
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,413,841✔
579

580
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,413,841✔
581
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,413,841✔
582

583
  return {x_min + (x_max - x_min) * prn(seed),
1,413,841✔
584
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,413,841✔
585
}
586

587
//==============================================================================
588
// Unstructured Mesh implementation
589
//==============================================================================
590

591
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
46✔
592
{
593
  // check the mesh type
594
  if (check_for_node(node, "type")) {
46✔
595
    auto temp = get_node_value(node, "type", true, true);
46✔
596
    if (temp != mesh_type) {
46✔
597
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
598
    }
599
  }
46✔
600

601
  // check if a length unit multiplier was specified
602
  if (check_for_node(node, "length_multiplier")) {
46✔
603
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
604
  }
605

606
  // get the filename of the unstructured mesh to load
607
  if (check_for_node(node, "filename")) {
46✔
608
    filename_ = get_node_value(node, "filename");
46✔
609
    if (!file_exists(filename_)) {
46✔
610
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
611
    }
612
  } else {
613
    fatal_error(fmt::format(
×
614
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
615
  }
616

617
  if (check_for_node(node, "options")) {
46✔
618
    options_ = get_node_value(node, "options");
16✔
619
  }
620

621
  // check if mesh tally data should be written with
622
  // statepoint files
623
  if (check_for_node(node, "output")) {
46✔
624
    output_ = get_node_value_bool(node, "output");
×
625
  }
626
}
46✔
627

628
void UnstructuredMesh::determine_bounds()
24✔
629
{
630
  double xmin = INFTY;
24✔
631
  double ymin = INFTY;
24✔
632
  double zmin = INFTY;
24✔
633
  double xmax = -INFTY;
24✔
634
  double ymax = -INFTY;
24✔
635
  double zmax = -INFTY;
24✔
636
  int n = this->n_vertices();
24✔
637
  for (int i = 0; i < n; ++i) {
55,936✔
638
    auto v = this->vertex(i);
55,912✔
639
    xmin = std::min(v.x, xmin);
55,912✔
640
    ymin = std::min(v.y, ymin);
55,912✔
641
    zmin = std::min(v.z, zmin);
55,912✔
642
    xmax = std::max(v.x, xmax);
55,912✔
643
    ymax = std::max(v.y, ymax);
55,912✔
644
    zmax = std::max(v.z, zmax);
55,912✔
645
  }
646
  lower_left_ = {xmin, ymin, zmin};
24✔
647
  upper_right_ = {xmax, ymax, zmax};
24✔
648
}
24✔
649

650
Position UnstructuredMesh::sample_tet(
601,230✔
651
  std::array<Position, 4> coords, uint64_t* seed) const
652
{
653
  // Uniform distribution
654
  double s = prn(seed);
601,230✔
655
  double t = prn(seed);
601,230✔
656
  double u = prn(seed);
601,230✔
657

658
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
659
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
660
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
661
  if (s + t > 1) {
601,230✔
662
    s = 1.0 - s;
301,245✔
663
    t = 1.0 - t;
301,245✔
664
  }
665
  if (s + t + u > 1) {
601,230✔
666
    if (t + u > 1) {
400,908✔
667
      double old_t = t;
199,920✔
668
      t = 1.0 - u;
199,920✔
669
      u = 1.0 - s - old_t;
199,920✔
670
    } else if (t + u <= 1) {
200,988✔
671
      double old_s = s;
200,988✔
672
      s = 1.0 - t - u;
200,988✔
673
      u = old_s + t + u - 1;
200,988✔
674
    }
675
  }
676
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
677
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
678
}
679

680
const std::string UnstructuredMesh::mesh_type = "unstructured";
681

682
std::string UnstructuredMesh::get_mesh_type() const
31✔
683
{
684
  return mesh_type;
31✔
685
}
686

687
void UnstructuredMesh::surface_bins_crossed(
×
688
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
689
{
690
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
691
}
692

693
std::string UnstructuredMesh::bin_label(int bin) const
205,712✔
694
{
695
  return fmt::format("Mesh Index ({})", bin);
205,712✔
696
};
697

698
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
31✔
699
{
700
  write_dataset(mesh_group, "filename", filename_);
31✔
701
  write_dataset(mesh_group, "library", this->library());
31✔
702
  if (!options_.empty()) {
31✔
703
    write_attribute(mesh_group, "options", options_);
8✔
704
  }
705

706
  if (length_multiplier_ > 0.0)
31✔
707
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
708

709
  // write vertex coordinates
710
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
31✔
711
  for (int i = 0; i < this->n_vertices(); i++) {
70,260✔
712
    auto v = this->vertex(i);
70,229✔
713
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
70,229✔
714
  }
715
  write_dataset(mesh_group, "vertices", vertices);
31✔
716

717
  int num_elem_skipped = 0;
31✔
718

719
  // write element types and connectivity
720
  vector<double> volumes;
31✔
721
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
31✔
722
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
31✔
723
  for (int i = 0; i < this->n_bins(); i++) {
349,743✔
724
    auto conn = this->connectivity(i);
349,712✔
725

726
    volumes.emplace_back(this->volume(i));
349,712✔
727

728
    // write linear tet element
729
    if (conn.size() == 4) {
349,712✔
730
      xt::view(elem_types, i, xt::all()) =
695,424✔
731
        static_cast<int>(ElementType::LINEAR_TET);
695,424✔
732
      xt::view(connectivity, i, xt::all()) =
695,424✔
733
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,043,136✔
734
      // write linear hex element
735
    } else if (conn.size() == 8) {
2,000✔
736
      xt::view(elem_types, i, xt::all()) =
4,000✔
737
        static_cast<int>(ElementType::LINEAR_HEX);
4,000✔
738
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000✔
739
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000✔
740
    } else {
741
      num_elem_skipped++;
×
742
      xt::view(elem_types, i, xt::all()) =
×
743
        static_cast<int>(ElementType::UNSUPPORTED);
744
      xt::view(connectivity, i, xt::all()) = -1;
×
745
    }
746
  }
349,712✔
747

748
  // warn users that some elements were skipped
749
  if (num_elem_skipped > 0) {
31✔
750
    warning(fmt::format("The connectivity of {} elements "
×
751
                        "on mesh {} were not written "
752
                        "because they are not of type linear tet/hex.",
753
      num_elem_skipped, this->id_));
×
754
  }
755

756
  write_dataset(mesh_group, "volumes", volumes);
31✔
757
  write_dataset(mesh_group, "connectivity", connectivity);
31✔
758
  write_dataset(mesh_group, "element_types", elem_types);
31✔
759
}
31✔
760

761
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
762
{
763
  length_multiplier_ = length_multiplier;
23✔
764
}
23✔
765

766
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
767
{
768
  auto conn = connectivity(bin);
120,000✔
769

770
  if (conn.size() == 4)
120,000✔
771
    return ElementType::LINEAR_TET;
120,000✔
772
  else if (conn.size() == 8)
×
773
    return ElementType::LINEAR_HEX;
×
774
  else
775
    return ElementType::UNSUPPORTED;
×
776
}
120,000✔
777

778
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,103,015,560✔
779
  Position r, bool& in_mesh) const
780
{
781
  MeshIndex ijk;
782
  in_mesh = true;
1,103,015,560✔
783
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
784
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
785

786
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
787
      in_mesh = false;
83,780,151✔
788
  }
789
  return ijk;
1,103,015,560✔
790
}
791

792
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,655,239,205✔
793
{
794
  switch (n_dimension_) {
1,655,239,205✔
795
  case 1:
877,008✔
796
    return ijk[0] - 1;
877,008✔
797
  case 2:
78,932,062✔
798
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
78,932,062✔
799
  case 3:
1,575,430,135✔
800
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,575,430,135✔
801
  default:
×
802
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
803
  }
804
}
805

806
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
14,070,396✔
807
{
808
  MeshIndex ijk;
809
  if (n_dimension_ == 1) {
14,070,396✔
810
    ijk[0] = bin + 1;
275✔
811
  } else if (n_dimension_ == 2) {
14,070,121✔
812
    ijk[0] = bin % shape_[0] + 1;
14,641✔
813
    ijk[1] = bin / shape_[0] + 1;
14,641✔
814
  } else if (n_dimension_ == 3) {
14,055,480✔
815
    ijk[0] = bin % shape_[0] + 1;
14,055,480✔
816
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
14,055,480✔
817
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
14,055,480✔
818
  }
819
  return ijk;
14,070,396✔
820
}
821

822
int StructuredMesh::get_bin(Position r) const
235,853,352✔
823
{
824
  // Determine indices
825
  bool in_mesh;
826
  MeshIndex ijk = get_indices(r, in_mesh);
235,853,352✔
827
  if (!in_mesh)
235,853,352✔
828
    return -1;
20,436,463✔
829

830
  // Convert indices to bin
831
  return get_bin_from_indices(ijk);
215,416,889✔
832
}
833

834
int StructuredMesh::n_bins() const
7,469,367✔
835
{
836
  return std::accumulate(
7,469,367✔
837
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
14,938,734✔
838
}
839

840
int StructuredMesh::n_surface_bins() const
369✔
841
{
842
  return 4 * n_dimension_ * n_bins();
369✔
843
}
844

845
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
846
  const SourceSite* bank, int64_t length, bool* outside) const
847
{
848
  // Determine shape of array for counts
849
  std::size_t m = this->n_bins();
×
850
  vector<std::size_t> shape = {m};
×
851

852
  // Create array of zeros
853
  xt::xarray<double> cnt {shape, 0.0};
×
854
  bool outside_ = false;
×
855

856
  for (int64_t i = 0; i < length; i++) {
×
857
    const auto& site = bank[i];
×
858

859
    // determine scoring bin for entropy mesh
860
    int mesh_bin = get_bin(site.r);
×
861

862
    // if outside mesh, skip particle
863
    if (mesh_bin < 0) {
×
864
      outside_ = true;
×
865
      continue;
×
866
    }
867

868
    // Add to appropriate bin
869
    cnt(mesh_bin) += site.wgt;
×
870
  }
871

872
  // Create copy of count data. Since ownership will be acquired by xtensor,
873
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
874
  // warnings.
875
  int total = cnt.size();
×
876
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
877

878
#ifdef OPENMC_MPI
879
  // collect values from all processors
880
  MPI_Reduce(
881
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
882

883
  // Check if there were sites outside the mesh for any processor
884
  if (outside) {
885
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
886
  }
887
#else
888
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
889
  if (outside)
890
    *outside = outside_;
891
#endif
892

893
  // Adapt reduced values in array back into an xarray
894
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
895
  xt::xarray<double> counts = arr;
×
896

897
  return counts;
×
898
}
899

900
// raytrace through the mesh. The template class T will do the tallying.
901
// A modern optimizing compiler can recognize the noop method of T and
902
// eliminate that call entirely.
903
template<class T>
904
void StructuredMesh::raytrace_mesh(
870,243,229✔
905
  Position r0, Position r1, const Direction& u, T tally) const
906
{
907
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
908
  // enable/disable tally calls for now, T template type needs to provide both
909
  // surface and track methods, which might be empty. modern optimizing
910
  // compilers will (hopefully) eliminate the complete code (including
911
  // calculation of parameters) but for the future: be explicit
912

913
  // Compute the length of the entire track.
914
  double total_distance = (r1 - r0).norm();
870,243,229✔
915
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
870,243,229✔
916
    return;
9,064,744✔
917

918
  // keep a copy of the original global position to pass to get_indices,
919
  // which performs its own transformation to local coordinates
920
  Position global_r = r0;
861,178,485✔
921
  Position local_r = local_coords(r0);
861,178,485✔
922

923
  const int n = n_dimension_;
861,178,485✔
924

925
  // Flag if position is inside the mesh
926
  bool in_mesh;
927

928
  // Position is r = r0 + u * traveled_distance, start at r0
929
  double traveled_distance {0.0};
861,178,485✔
930

931
  // Calculate index of current cell. Offset the position a tiny bit in
932
  // direction of flight
933
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
861,178,485✔
934

935
  // if track is very short, assume that it is completely inside one cell.
936
  // Only the current cell will score and no surfaces
937
  if (total_distance < 2 * TINY_BIT) {
861,178,485✔
938
    if (in_mesh) {
646,283✔
939
      tally.track(ijk, 1.0);
646,272✔
940
    }
941
    return;
646,283✔
942
  }
943

944
  // Calculate initial distances to next surfaces in all three dimensions
945
  std::array<MeshDistance, 3> distances;
1,721,064,404✔
946
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
947
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
948
  }
949

950
  // Loop until r = r1 is eventually reached
951
  while (true) {
735,167,018✔
952

953
    if (in_mesh) {
1,595,699,220✔
954

955
      // find surface with minimal distance to current position
956
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,520,661,074✔
957
                     distances.begin();
1,520,661,074✔
958

959
      // Tally track length delta since last step
960
      tally.track(ijk,
1,520,661,074✔
961
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,520,661,074✔
962
          total_distance);
963

964
      // update position and leave, if we have reached end position
965
      traveled_distance = distances[k].distance;
1,520,661,074✔
966
      if (traveled_distance >= total_distance)
1,520,661,074✔
967
        return;
791,477,779✔
968

969
      // If we have not reached r1, we have hit a surface. Tally outward
970
      // current
971
      tally.surface(ijk, k, distances[k].max_surface, false);
729,183,295✔
972

973
      // Update cell and calculate distance to next surface in k-direction.
974
      // The two other directions are still valid!
975
      ijk[k] = distances[k].next_index;
729,183,295✔
976
      distances[k] =
729,183,295✔
977
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
729,183,295✔
978

979
      // Check if we have left the interior of the mesh
980
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
729,183,295✔
981

982
      // If we are still inside the mesh, tally inward current for the next
983
      // cell
984
      if (in_mesh)
729,183,295✔
985
        tally.surface(ijk, k, !distances[k].max_surface, true);
715,487,239✔
986

987
    } else { // not inside mesh
988

989
      // For all directions outside the mesh, find the distance that we need
990
      // to travel to reach the next surface. Use the largest distance, as
991
      // only this will cross all outer surfaces.
992
      int k_max {0};
75,038,146✔
993
      for (int k = 0; k < n; ++k) {
298,006,328✔
994
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
299,244,704✔
995
            (distances[k].distance > traveled_distance)) {
76,276,522✔
996
          traveled_distance = distances[k].distance;
75,548,534✔
997
          k_max = k;
75,548,534✔
998
        }
999
      }
1000

1001
      // If r1 is not inside the mesh, exit here
1002
      if (traveled_distance >= total_distance)
75,038,146✔
1003
        return;
69,054,423✔
1004

1005
      // Calculate the new cell index and update all distances to next
1006
      // surfaces.
1007
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
5,983,723✔
1008
      for (int k = 0; k < n; ++k) {
23,724,737✔
1009
        distances[k] =
17,741,014✔
1010
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
17,741,014✔
1011
      }
1012

1013
      // If inside the mesh, Tally inward current
1014
      if (in_mesh)
5,983,723✔
1015
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
5,901,014✔
1016
    }
1017
  }
1018
}
1019

111,687,202✔
1020
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1021
  vector<int>& bins, vector<double>& lengths) const
1022
{
1023

1024
  // Helper tally class.
1025
  // stores a pointer to the mesh class and references to bins and lengths
1026
  // parameters. Performs the actual tally through the track method.
1027
  struct TrackAggregator {
1028
    TrackAggregator(
1029
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
111,687,202✔
1030
      : mesh(_mesh), bins(_bins), lengths(_lengths)
111,687,202✔
UNCOV
1031
    {}
×
1032
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1033
    void track(const MeshIndex& ijk, double l) const
1034
    {
1035
      bins.push_back(mesh->get_bin_from_indices(ijk));
111,687,202✔
1036
      lengths.push_back(l);
111,687,202✔
1037
    }
1038

111,687,202✔
1039
    const StructuredMesh* mesh;
1040
    vector<int>& bins;
1041
    vector<double>& lengths;
1042
  };
1043

1044
  // Perform the mesh raytrace with the helper class.
111,687,202✔
1045
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1046
}
1047

1048
void StructuredMesh::surface_bins_crossed(
111,687,202✔
1049
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1050
{
1051

1052
  // Helper tally class.
111,687,202✔
UNCOV
1053
  // stores a pointer to the mesh class and a reference to the bins parameter.
×
UNCOV
1054
  // Performs the actual tally through the surface method.
×
1055
  struct SurfaceAggregator {
UNCOV
1056
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
×
1057
      : mesh(_mesh), bins(_bins)
1058
    {}
1059
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
1060
    {
223,374,404✔
1061
      int i_bin =
445,065,676✔
1062
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
333,378,474✔
1063
      if (max)
1064
        i_bin += 2;
1065
      if (inward)
1066
        i_bin += 1;
29,761,523✔
1067
      bins.push_back(i_bin);
1068
    }
141,448,725✔
1069
    void track(const MeshIndex& idx, double l) const {}
1070

1071
    const StructuredMesh* mesh;
139,558,705✔
1072
    vector<int>& bins;
139,558,705✔
1073
  };
1074

1075
  // Perform the mesh raytrace with the helper class.
139,558,705✔
1076
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
139,558,705✔
1077
}
1078

1079
//==============================================================================
1080
// RegularMesh implementation
139,558,705✔
1081
//==============================================================================
139,558,705✔
1082

110,020,471✔
1083
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1084
{
1085
  // Determine number of dimensions for mesh
1086
  if (!check_for_node(node, "dimension")) {
29,538,234✔
1087
    fatal_error("Must specify <dimension> on a regular mesh.");
1088
  }
1089

1090
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
29,538,234✔
1091
  int n = n_dimension_ = shape.size();
29,538,234✔
1092
  if (n != 1 && n != 2 && n != 3) {
29,538,234✔
1093
    fatal_error("Mesh must be one, two, or three dimensions.");
1094
  }
1095
  std::copy(shape.begin(), shape.end(), shape_.begin());
29,538,234✔
1096

1097
  // Check that dimensions are all greater than zero
1098
  if (xt::any(shape <= 0)) {
1099
    fatal_error("All entries on the <dimension> element for a tally "
29,538,234✔
1100
                "mesh must be positive.");
28,335,065✔
1101
  }
1102

1103
  // Check for lower-left coordinates
1104
  if (check_for_node(node, "lower_left")) {
1105
    // Read mesh lower-left corner location
1106
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1107
  } else {
1,890,020✔
1108
    fatal_error("Must specify <lower_left> on a mesh.");
7,238,055✔
1109
  }
7,381,561✔
1110

2,033,526✔
1111
  // Make sure lower_left and dimension match
1,974,434✔
1112
  if (shape.size() != lower_left_.size()) {
1,974,434✔
1113
    fatal_error("Number of entries on <lower_left> must be the same "
1114
                "as the number of entries on <dimension>.");
1115
  }
1116

1117
  if (check_for_node(node, "width")) {
1,890,020✔
1118
    // Make sure one of upper-right or width were specified
1,666,731✔
1119
    if (check_for_node(node, "upper_right")) {
1120
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
1121
    }
1122

223,289✔
1123
    width_ = get_node_xarray<double>(node, "width");
788,568✔
1124

565,279✔
1125
    // Check to ensure width has same dimensions
565,279✔
1126
    auto n = width_.size();
1127
    if (n != lower_left_.size()) {
1128
      fatal_error("Number of entries on <width> must be the same as "
1129
                  "the number of entries on <lower_left>.");
223,289✔
1130
    }
200,376✔
1131

1132
    // Check for negative widths
1133
    if (xt::any(width_ < 0.0)) {
1134
      fatal_error("Cannot have a negative <width> on a tally mesh.");
758,556,027✔
1135
    }
1136

1137
    // Set width and upper right coordinate
1138
    upper_right_ = xt::eval(lower_left_ + shape * width_);
1139

1140
  } else if (check_for_node(node, "upper_right")) {
1141
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1142

1143
    // Check to ensure width has same dimensions
1144
    auto n = upper_right_.size();
758,556,027✔
1145
    if (n != lower_left_.size()) {
758,556,027✔
1146
      fatal_error("Number of entries on <upper_right> must be the "
9,064,744✔
1147
                  "same as the number of entries on <lower_left>.");
1148
    }
1149

1150
    // Check that upper-right is above lower-left
749,491,283✔
1151
    if (xt::any(upper_right_ < lower_left_)) {
749,491,283✔
1152
      fatal_error("The <upper_right> coordinates must be greater than "
1153
                  "the <lower_left> coordinates on a tally mesh.");
749,491,283✔
1154
    }
1155

1156
    // Set width
1157
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1158
  } else {
1159
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
749,491,283✔
1160
  }
1161

1162
  // Set material volumes
1163
  volume_frac_ = 1.0 / xt::prod(shape)();
749,491,283✔
1164

1165
  element_volume_ = 1.0;
1166
  for (int i = 0; i < n_dimension_; i++) {
1167
    element_volume_ *= width_[i];
749,491,283✔
1168
  }
646,283✔
1169
}
646,272✔
1170

1171
int RegularMesh::get_index_in_direction(double r, int i) const
646,283✔
1172
{
1173
  return std::ceil((r - lower_left_[i]) / width_[i]);
1174
}
1175

1,497,690,000✔
1176
const std::string RegularMesh::mesh_type = "regular";
2,147,483,647✔
1177

2,147,483,647✔
1178
std::string RegularMesh::get_mesh_type() const
1179
{
1180
  return mesh_type;
1181
}
705,405,495✔
1182

1183
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,454,250,495✔
1184
{
1185
  return lower_left_[i] + ijk[i] * width_[i];
1186
}
1,381,102,369✔
1187

1,381,102,369✔
1188
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1189
{
1190
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,381,102,369✔
1191
}
1,381,102,369✔
1192

1193
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1194
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1195
  double l) const
1,381,102,369✔
1196
{
1,381,102,369✔
1197
  MeshDistance d;
681,457,308✔
1198
  d.next_index = ijk[i];
1199
  if (std::abs(u[i]) < FP_PRECISION)
1200
    return d;
1201

699,645,061✔
1202
  d.max_surface = (u[i] > 0);
1203
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1204
    d.next_index++;
1205
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
699,645,061✔
1206
  } else if (!d.max_surface && (ijk[i] >= 1)) {
699,645,061✔
1207
    d.next_index--;
699,645,061✔
1208
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1209
  }
1210
  return d;
699,645,061✔
1211
}
1212

1213
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1214
  Position plot_ll, Position plot_ur) const
699,645,061✔
1215
{
687,152,174✔
1216
  // Figure out which axes lie in the plane of the plot.
1217
  array<int, 2> axes {-1, -1};
1218
  if (plot_ur.z == plot_ll.z) {
1219
    axes[0] = 0;
1220
    if (n_dimension_ > 1)
1221
      axes[1] = 1;
1222
  } else if (plot_ur.y == plot_ll.y) {
73,148,126✔
1223
    axes[0] = 0;
290,768,273✔
1224
    if (n_dimension_ > 2)
291,863,143✔
1225
      axes[1] = 2;
74,242,996✔
1226
  } else if (plot_ur.x == plot_ll.x) {
73,574,100✔
1227
    if (n_dimension_ > 1)
73,574,100✔
1228
      axes[0] = 1;
1229
    if (n_dimension_ > 2)
1230
      axes[1] = 2;
1231
  } else {
1232
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
73,148,126✔
1233
  }
67,387,692✔
1234

1235
  // Get the coordinates of the mesh lines along both of the axes.
1236
  array<vector<double>, 2> axis_lines;
1237
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
5,760,434✔
1238
    int axis = axes[i_ax];
22,936,169✔
1239
    if (axis == -1)
17,175,735✔
1240
      continue;
17,175,735✔
1241
    auto& lines {axis_lines[i_ax]};
1242

1243
    double coord = lower_left_[axis];
1244
    for (int i = 0; i < shape_[axis] + 1; ++i) {
5,760,434✔
1245
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
5,700,638✔
1246
        lines.push_back(coord);
1247
      coord += width_[axis];
1248
    }
1249
  }
1250

758,556,027✔
1251
  return {axis_lines[0], axis_lines[1]};
1252
}
1253

1254
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1255
{
1256
  write_dataset(mesh_group, "dimension", get_x_shape());
1257
  write_dataset(mesh_group, "lower_left", lower_left_);
1258
  write_dataset(mesh_group, "upper_right", upper_right_);
758,556,027✔
1259
  write_dataset(mesh_group, "width", width_);
1260
}
758,556,027✔
1261

758,556,027✔
1262
xt::xtensor<double, 1> RegularMesh::count_sites(
1,392,497,873✔
1263
  const SourceSite* bank, int64_t length, bool* outside) const
1,381,748,641✔
1264
{
1265
  // Determine shape of array for counts
1,381,748,641✔
1266
  std::size_t m = this->n_bins();
1,381,748,641✔
1267
  vector<std::size_t> shape = {m};
1,381,748,641✔
1268

1269
  // Create array of zeros
1270
  xt::xarray<double> cnt {shape, 0.0};
1271
  bool outside_ = false;
1272

1273
  for (int64_t i = 0; i < length; i++) {
1274
    const auto& site = bank[i];
1275

758,556,027✔
1276
    // determine scoring bin for entropy mesh
758,556,027✔
1277
    int mesh_bin = get_bin(site.r);
1278

111,687,202✔
1279
    // if outside mesh, skip particle
1280
    if (mesh_bin < 0) {
1281
      outside_ = true;
1282
      continue;
1283
    }
1284

1285
    // Add to appropriate bin
1286
    cnt(mesh_bin) += site.wgt;
111,687,202✔
1287
  }
111,687,202✔
1288

111,687,202✔
1289
  // Create copy of count data. Since ownership will be acquired by xtensor,
58,073,675✔
1290
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
1291
  // warnings.
1292
  int total = cnt.size();
58,073,675✔
1293
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
58,073,675✔
1294

29,002,149✔
1295
#ifdef OPENMC_MPI
58,073,675✔
1296
  // collect values from all processors
28,535,441✔
1297
  MPI_Reduce(
58,073,675✔
1298
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
58,073,675✔
1299

139,558,705✔
1300
  // Check if there were sites outside the mesh for any processor
1301
  if (outside) {
1302
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1303
  }
1304
#else
1305
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1306
  if (outside)
111,687,202✔
1307
    *outside = outside_;
111,687,202✔
1308
#endif
1309

1310
  // Adapt reduced values in array back into an xarray
1311
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
1312
  xt::xarray<double> counts = arr;
1313

1,758✔
1314
  return counts;
1315
}
1316

1,758✔
UNCOV
1317
double RegularMesh::volume(const MeshIndex& ijk) const
×
1318
{
1319
  return element_volume_;
1320
}
1,758✔
1321

1,758✔
1322
//==============================================================================
1,758✔
UNCOV
1323
// RectilinearMesh implementation
×
1324
//==============================================================================
1325

1,758✔
1326
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
1327
{
1328
  n_dimension_ = 3;
1,758✔
UNCOV
1329

×
1330
  grid_[0] = get_node_array<double>(node, "x_grid");
1331
  grid_[1] = get_node_array<double>(node, "y_grid");
1332
  grid_[2] = get_node_array<double>(node, "z_grid");
1333

1334
  if (int err = set_grid()) {
1,758✔
1335
    fatal_error(openmc_err_msg);
1336
  }
1,758✔
1337
}
UNCOV
1338

×
1339
const std::string RectilinearMesh::mesh_type = "rectilinear";
1340

1341
std::string RectilinearMesh::get_mesh_type() const
1342
{
1,758✔
UNCOV
1343
  return mesh_type;
×
1344
}
1345

1346
double RectilinearMesh::positive_grid_boundary(
1347
  const MeshIndex& ijk, int i) const
1,758✔
1348
{
1349
  return grid_[i][ijk[i]];
48✔
UNCOV
1350
}
×
1351

1352
double RectilinearMesh::negative_grid_boundary(
1353
  const MeshIndex& ijk, int i) const
48✔
1354
{
1355
  return grid_[i][ijk[i] - 1];
1356
}
48✔
1357

48✔
UNCOV
1358
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
×
1359
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1360
  double l) const
1361
{
1362
  MeshDistance d;
1363
  d.next_index = ijk[i];
48✔
UNCOV
1364
  if (std::abs(u[i]) < FP_PRECISION)
×
1365
    return d;
1366

1367
  d.max_surface = (u[i] > 0);
1368
  if (d.max_surface && (ijk[i] <= shape_[i])) {
48✔
1369
    d.next_index++;
1370
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,710✔
1371
  } else if (!d.max_surface && (ijk[i] > 0)) {
1,710✔
1372
    d.next_index--;
1373
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1374
  }
1,710✔
1375
  return d;
1,710✔
UNCOV
1376
}
×
1377

1378
int RectilinearMesh::set_grid()
1379
{
1380
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1381
    static_cast<int>(grid_[1].size()) - 1,
1,710✔
UNCOV
1382
    static_cast<int>(grid_[2].size()) - 1};
×
1383

1384
  for (const auto& g : grid_) {
1385
    if (g.size() < 2) {
1386
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
1387
                 "must each have at least 2 points");
1,710✔
1388
      return OPENMC_E_INVALID_ARGUMENT;
UNCOV
1389
    }
×
1390
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1391
        g.end()) {
1392
      set_errmsg("Values in for x-, y-, and z- grids for "
1393
                 "rectilinear meshes must be sorted and unique.");
1,758✔
1394
      return OPENMC_E_INVALID_ARGUMENT;
1395
    }
1,758✔
1396
  }
6,669✔
1397

4,911✔
1398
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
1399
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
1,758✔
1400

1401
  return 0;
2,147,483,647✔
1402
}
1403

2,147,483,647✔
1404
int RectilinearMesh::get_index_in_direction(double r, int i) const
1405
{
1406
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1407
}
1408

2,889✔
1409
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
1410
  Position plot_ll, Position plot_ur) const
2,889✔
1411
{
1412
  // Figure out which axes lie in the plane of the plot.
1413
  array<int, 2> axes {-1, -1};
1,403,697,019✔
1414
  if (plot_ur.z == plot_ll.z) {
1415
    axes = {0, 1};
1,403,697,019✔
1416
  } else if (plot_ur.y == plot_ll.y) {
1417
    axes = {0, 2};
1418
  } else if (plot_ur.x == plot_ll.x) {
1,340,810,765✔
1419
    axes = {1, 2};
1420
  } else {
1,340,810,765✔
1421
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1422
  }
1423

2,147,483,647✔
1424
  // Get the coordinates of the mesh lines along both of the axes.
1425
  array<vector<double>, 2> axis_lines;
1426
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1427
    int axis = axes[i_ax];
2,147,483,647✔
1428
    vector<double>& lines {axis_lines[i_ax]};
2,147,483,647✔
1429

2,147,483,647✔
1430
    for (auto coord : grid_[axis]) {
1,204,566✔
1431
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1432
        lines.push_back(coord);
2,147,483,647✔
1433
    }
2,147,483,647✔
1434
  }
1,399,455,496✔
1435

1,399,455,496✔
1436
  return {axis_lines[0], axis_lines[1]};
1,349,303,654✔
1437
}
1,336,569,242✔
1438

1,336,569,242✔
1439
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
1440
{
2,147,483,647✔
1441
  write_dataset(mesh_group, "x_grid", grid_[0]);
1442
  write_dataset(mesh_group, "y_grid", grid_[1]);
1443
  write_dataset(mesh_group, "z_grid", grid_[2]);
22✔
1444
}
1445

1446
double RectilinearMesh::volume(const MeshIndex& ijk) const
1447
{
22✔
1448
  double vol {1.0};
22✔
1449

22✔
1450
  for (int i = 0; i < n_dimension_; i++) {
22✔
1451
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
22✔
UNCOV
1452
  }
×
UNCOV
1453
  return vol;
×
UNCOV
1454
}
×
1455

×
1456
//==============================================================================
×
1457
// CylindricalMesh implementation
×
1458
//==============================================================================
×
1459

×
1460
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
×
1461
  : PeriodicStructuredMesh {node}
1462
{
×
1463
  n_dimension_ = 3;
1464
  grid_[0] = get_node_array<double>(node, "r_grid");
1465
  grid_[1] = get_node_array<double>(node, "phi_grid");
1466
  grid_[2] = get_node_array<double>(node, "z_grid");
22✔
1467
  origin_ = get_node_position(node, "origin");
66✔
1468

44✔
1469
  if (int err = set_grid()) {
44✔
UNCOV
1470
    fatal_error(openmc_err_msg);
×
1471
  }
44✔
1472
}
1473

44✔
1474
const std::string CylindricalMesh::mesh_type = "cylindrical";
286✔
1475

242✔
1476
std::string CylindricalMesh::get_mesh_type() const
242✔
1477
{
242✔
1478
  return mesh_type;
1479
}
1480

1481
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
44✔
1482
  Position r, bool& in_mesh) const
22✔
1483
{
1484
  r = local_coords(r);
1,800✔
1485

1486
  Position mapped_r;
1,800✔
1487
  mapped_r[0] = std::hypot(r.x, r.y);
1,800✔
1488
  mapped_r[2] = r[2];
1,800✔
1489

1,800✔
1490
  if (mapped_r[0] < FP_PRECISION) {
1,800✔
1491
    mapped_r[1] = 0.0;
1492
  } else {
7,839✔
1493
    mapped_r[1] = std::atan2(r.y, r.x);
1494
    if (mapped_r[1] < 0)
1495
      mapped_r[1] += 2 * M_PI;
1496
  }
7,839✔
1497

7,839✔
1498
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1499

1500
  idx[1] = sanitize_phi(idx[1]);
7,839✔
1501

7,839✔
1502
  return idx;
1503
}
7,688,787✔
1504

7,680,948✔
1505
Position CylindricalMesh::sample_element(
1506
  const MeshIndex& ijk, uint64_t* seed) const
1507
{
7,680,948✔
1508
  double r_min = this->r(ijk[0] - 1);
1509
  double r_max = this->r(ijk[0]);
1510

7,680,948✔
UNCOV
1511
  double phi_min = this->phi(ijk[1] - 1);
×
UNCOV
1512
  double phi_max = this->phi(ijk[1]);
×
1513

1514
  double z_min = this->z(ijk[2] - 1);
1515
  double z_max = this->z(ijk[2]);
1516

7,680,948✔
1517
  double r_min_sq = r_min * r_min;
1518
  double r_max_sq = r_max * r_max;
1519
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
1520
  double phi = uniform_distribution(phi_min, phi_max, seed);
1521
  double z = uniform_distribution(z_min, z_max, seed);
1522

7,839✔
1523
  double x = r * std::cos(phi);
7,839✔
1524
  double y = r * std::sin(phi);
1525

1526
  return origin_ + Position(x, y, z);
1527
}
3,615✔
1528

3,615✔
1529
double CylindricalMesh::find_r_crossing(
1530
  const Position& r, const Direction& u, double l, int shell) const
1531
{
3,615✔
1532

3,615✔
1533
  if ((shell < 0) || (shell > shape_[0]))
1534
    return INFTY;
1535

4,224✔
1536
  // solve r.x^2 + r.y^2 == r0^2
4,224✔
1537
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
4,224✔
1538
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1539

1540
  const double r0 = grid_[0][shell];
1541
  if (r0 == 0.0)
7,839✔
1542
    return INFTY;
7,839✔
1543

1544
  const double denominator = u.x * u.x + u.y * u.y;
15,678✔
1545

7,839✔
1546
  // Direction of flight is in z-direction. Will never intersect r.
1547
  if (std::abs(denominator) < FP_PRECISION)
7,451,670✔
1548
    return INFTY;
1549

7,451,670✔
1550
  // inverse of dominator to help the compiler to speed things up
1551
  const double inv_denominator = 1.0 / denominator;
1552

1553
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
1554
  double c = r.x * r.x + r.y * r.y - r0 * r0;
1555
  double D = p * p - c * inv_denominator;
1556

103✔
1557
  if (D < 0.0)
1558
    return INFTY;
103✔
1559

1560
  D = std::sqrt(D);
103✔
1561

103✔
1562
  // the solution -p - D is always smaller as -p + D : Check this one first
103✔
1563
  if (std::abs(c) <= RADIAL_MESH_TOL)
1564
    return INFTY;
103✔
UNCOV
1565

×
1566
  if (-p - D > l)
1567
    return -p - D;
103✔
1568
  if (-p + D > l)
1569
    return -p + D;
1570

1571
  return INFTY;
253✔
1572
}
1573

253✔
1574
double CylindricalMesh::find_phi_crossing(
1575
  const Position& r, const Direction& u, double l, int shell) const
1576
{
26,400,033✔
1577
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1578
  if (full_phi_ && (shape_[1] == 1))
1579
    return INFTY;
26,400,033✔
1580

1581
  shell = sanitize_phi(shell);
1582

25,654,849✔
1583
  const double p0 = grid_[1][shell];
1584

1585
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
25,654,849✔
1586
  // => x(s) * cos(p0) = y(s) * sin(p0)
1587
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1588
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
53,414,482✔
1589

1590
  const double c0 = std::cos(p0);
1591
  const double s0 = std::sin(p0);
1592

53,414,482✔
1593
  const double denominator = (u.x * s0 - u.y * c0);
53,414,482✔
1594

53,414,482✔
1595
  // Check if direction of flight is not parallel to phi surface
571,824✔
1596
  if (std::abs(denominator) > FP_PRECISION) {
1597
    const double s = -(r.x * s0 - r.y * c0) / denominator;
52,842,658✔
1598
    // Check if solution is in positive direction of flight and crosses the
52,842,658✔
1599
    // correct phi surface (not -phi)
26,400,033✔
1600
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
26,400,033✔
1601
      return s;
26,442,625✔
1602
  }
25,654,849✔
1603

25,654,849✔
1604
  return INFTY;
1605
}
52,842,658✔
1606

1607
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
1608
  const Position& r, const Direction& u, double l, int shell) const
147✔
1609
{
1610
  MeshDistance d;
147✔
1611
  d.next_index = shell;
147✔
1612

147✔
1613
  // Direction of flight is within xy-plane. Will never intersect z.
1614
  if (std::abs(u.z) < FP_PRECISION)
588✔
1615
    return d;
441✔
UNCOV
1616

×
1617
  d.max_surface = (u.z > 0.0);
UNCOV
1618
  if (d.max_surface && (shell <= shape_[2])) {
×
1619
    d.next_index += 1;
1620
    d.distance = (grid_[2][shell] - r.z) / u.z;
441✔
1621
  } else if (!d.max_surface && (shell > 0)) {
882✔
UNCOV
1622
    d.next_index -= 1;
×
1623
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
UNCOV
1624
  }
×
1625
  return d;
1626
}
1627

1628
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
147✔
1629
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
147✔
1630
  double l) const
1631
{
147✔
1632
  if (i == 0) {
1633

1634
    return std::min(
73,891,983✔
1635
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
1636
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
73,891,983✔
1637

1638
  } else if (i == 1) {
1639

11✔
1640
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
1641
                      find_phi_crossing(r0, u, l, ijk[i])),
1642
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
1643
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
11✔
1644

11✔
UNCOV
1645
  } else {
×
1646
    return find_z_crossing(r0, u, l, ijk[i]);
11✔
1647
  }
11✔
1648
}
×
UNCOV
1649

×
1650
int CylindricalMesh::set_grid()
1651
{
×
1652
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1653
    static_cast<int>(grid_[1].size()) - 1,
1654
    static_cast<int>(grid_[2].size()) - 1};
1655

11✔
1656
  for (const auto& g : grid_) {
33✔
1657
    if (g.size() < 2) {
22✔
1658
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
22✔
1659
                 "must each have at least 2 points");
1660
      return OPENMC_E_INVALID_ARGUMENT;
110✔
1661
    }
88✔
1662
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
88✔
1663
        g.end()) {
1664
      set_errmsg("Values in for r-, phi-, and z- grids for "
1665
                 "cylindrical meshes must be sorted and unique.");
1666
      return OPENMC_E_INVALID_ARGUMENT;
22✔
1667
    }
11✔
1668
  }
1669
  if (grid_[0].front() < 0.0) {
88✔
1670
    set_errmsg("r-grid for "
1671
               "cylindrical meshes must start at r >= 0.");
88✔
1672
    return OPENMC_E_INVALID_ARGUMENT;
88✔
1673
  }
88✔
1674
  if (grid_[1].front() < 0.0) {
88✔
1675
    set_errmsg("phi-grid for "
1676
               "cylindrical meshes must start at phi >= 0.");
132✔
1677
    return OPENMC_E_INVALID_ARGUMENT;
1678
  }
132✔
1679
  if (grid_[1].back() > 2.0 * PI) {
1680
    set_errmsg("phi-grids for "
528✔
1681
               "cylindrical meshes must end with theta <= 2*pi.");
396✔
1682

1683
    return OPENMC_E_INVALID_ARGUMENT;
132✔
1684
  }
1685

1686
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
1687

1688
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
1689
    origin_[2] + grid_[2].front()};
1690
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
379✔
1691
    origin_[2] + grid_[2].back()};
379✔
1692

1693
  return 0;
379✔
1694
}
379✔
1695

379✔
1696
int CylindricalMesh::get_index_in_direction(double r, int i) const
379✔
1697
{
379✔
1698
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1699
}
379✔
UNCOV
1700

×
1701
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
1702
  Position plot_ll, Position plot_ur) const
379✔
1703
{
1704
  fatal_error("Plot of cylindrical Mesh not implemented");
1705

1706
  // Figure out which axes lie in the plane of the plot.
473✔
1707
  array<vector<double>, 2> axis_lines;
1708
  return {axis_lines[0], axis_lines[1]};
473✔
1709
}
1710

1711
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
47,366,451✔
1712
{
1713
  write_dataset(mesh_group, "r_grid", grid_[0]);
1714
  write_dataset(mesh_group, "phi_grid", grid_[1]);
47,366,451✔
1715
  write_dataset(mesh_group, "z_grid", grid_[2]);
1716
  write_dataset(mesh_group, "origin", origin_);
47,366,451✔
1717
}
47,366,451✔
1718

47,366,451✔
1719
double CylindricalMesh::volume(const MeshIndex& ijk) const
1720
{
47,366,451✔
UNCOV
1721
  double r_i = grid_[0][ijk[0] - 1];
×
1722
  double r_o = grid_[0][ijk[0]];
1723

47,366,451✔
1724
  double phi_i = grid_[1][ijk[1] - 1];
47,366,451✔
1725
  double phi_o = grid_[1][ijk[1]];
23,697,839✔
1726

1727
  double z_i = grid_[2][ijk[2] - 1];
1728
  double z_o = grid_[2][ijk[2]];
47,366,451✔
1729

1730
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
47,366,451✔
1731
}
1732

47,366,451✔
1733
//==============================================================================
1734
// SphericalMesh implementation
1735
//==============================================================================
88,000✔
1736

1737
SphericalMesh::SphericalMesh(pugi::xml_node node)
1738
  : PeriodicStructuredMesh {node}
88,000✔
1739
{
88,000✔
1740
  n_dimension_ = 3;
1741

88,000✔
1742
  grid_[0] = get_node_array<double>(node, "r_grid");
88,000✔
1743
  grid_[1] = get_node_array<double>(node, "theta_grid");
1744
  grid_[2] = get_node_array<double>(node, "phi_grid");
88,000✔
1745
  origin_ = get_node_position(node, "origin");
88,000✔
1746

1747
  if (int err = set_grid()) {
88,000✔
1748
    fatal_error(openmc_err_msg);
88,000✔
1749
  }
88,000✔
1750
}
88,000✔
1751

88,000✔
1752
const std::string SphericalMesh::mesh_type = "spherical";
1753

88,000✔
1754
std::string SphericalMesh::get_mesh_type() const
88,000✔
1755
{
1756
  return mesh_type;
88,000✔
1757
}
1758

1759
StructuredMesh::MeshIndex SphericalMesh::get_indices(
141,838,246✔
1760
  Position r, bool& in_mesh) const
1761
{
1762
  r = local_coords(r);
1763

141,838,246✔
1764
  Position mapped_r;
17,677,528✔
1765
  mapped_r[0] = r.norm();
1766

1767
  if (mapped_r[0] < FP_PRECISION) {
1768
    mapped_r[1] = 0.0;
1769
    mapped_r[2] = 0.0;
1770
  } else {
124,160,718✔
1771
    mapped_r[1] = std::acos(r.z / mapped_r.x);
124,160,718✔
1772
    mapped_r[2] = std::atan2(r.y, r.x);
7,015,096✔
1773
    if (mapped_r[2] < 0)
1774
      mapped_r[2] += 2 * M_PI;
117,145,622✔
1775
  }
1776

1777
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
117,145,622✔
1778

58,960✔
1779
  idx[1] = sanitize_theta(idx[1]);
1780
  idx[2] = sanitize_phi(idx[2]);
1781

117,086,662✔
1782
  return idx;
1783
}
117,086,662✔
1784

117,086,662✔
1785
Position SphericalMesh::sample_element(
117,086,662✔
1786
  const MeshIndex& ijk, uint64_t* seed) const
1787
{
117,086,662✔
1788
  double r_min = this->r(ijk[0] - 1);
9,633,712✔
1789
  double r_max = this->r(ijk[0]);
1790

107,452,950✔
1791
  double theta_min = this->theta(ijk[1] - 1);
1792
  double theta_max = this->theta(ijk[1]);
1793

107,452,950✔
1794
  double phi_min = this->phi(ijk[2] - 1);
6,469,408✔
1795
  double phi_max = this->phi(ijk[2]);
1796

100,983,542✔
1797
  double cos_theta = uniform_distribution(theta_min, theta_max, seed);
20,133,047✔
1798
  double sin_theta = std::sin(std::acos(cos_theta));
80,850,495✔
1799
  double phi = uniform_distribution(phi_min, phi_max, seed);
50,032,807✔
1800
  double r_min_cub = std::pow(r_min, 3);
1801
  double r_max_cub = std::pow(r_max, 3);
30,817,688✔
1802
  // might be faster to do rejection here?
1803
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
1804

73,733,814✔
1805
  double x = r * std::cos(phi) * sin_theta;
1806
  double y = r * std::sin(phi) * sin_theta;
1807
  double z = r * cos_theta;
1808

73,733,814✔
1809
  return origin_ + Position(x, y, z);
29,760,896✔
1810
}
1811

43,972,918✔
1812
double SphericalMesh::find_r_crossing(
1813
  const Position& r, const Direction& u, double l, int shell) const
43,972,918✔
1814
{
1815
  if ((shell < 0) || (shell > shape_[0]))
1816
    return INFTY;
1817

1818
  // solve |r+s*u| = r0
1819
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
1820
  const double r0 = grid_[0][shell];
43,972,918✔
1821
  if (r0 == 0.0)
43,972,918✔
1822
    return INFTY;
1823
  const double p = r.dot(u);
43,972,918✔
1824
  double c = r.dot(r) - r0 * r0;
1825
  double D = p * p - c;
1826

43,972,918✔
1827
  if (std::abs(c) <= RADIAL_MESH_TOL)
43,712,174✔
1828
    return INFTY;
1829

1830
  if (D >= 0.0) {
43,712,174✔
1831
    D = std::sqrt(D);
20,218,363✔
1832
    // the solution -p - D is always smaller as -p + D : Check this one first
1833
    if (-p - D > l)
1834
      return -p - D;
23,754,555✔
1835
    if (-p + D > l)
1836
      return -p + D;
1837
  }
36,340,216✔
1838

1839
  return INFTY;
1840
}
36,340,216✔
1841

36,340,216✔
1842
double SphericalMesh::find_theta_crossing(
1843
  const Position& r, const Direction& u, double l, int shell) const
1844
{
36,340,216✔
1845
  // Theta grid is [0, π], thus there is no real surface to cross
1,118,216✔
1846
  if (full_theta_ && (shape_[1] == 1))
1847
    return INFTY;
35,222,000✔
1848

35,222,000✔
1849
  shell = sanitize_theta(shell);
16,558,091✔
1850

16,558,091✔
1851
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
18,663,909✔
1852
  // yields
16,810,321✔
1853
  // a*s^2 + 2*b*s + c == 0 with
16,810,321✔
1854
  // a = cos(theta)^2 - u.z * u.z
1855
  // b = r*u * cos(theta)^2 - u.z * r.z
35,222,000✔
1856
  // c = r*r * cos(theta)^2 - r.z^2
1857

1858
  const double cos_t = std::cos(grid_[1][shell]);
144,126,246✔
1859
  const bool sgn = std::signbit(cos_t);
1860
  const double cos_t_2 = cos_t * cos_t;
1861

1862
  const double a = cos_t_2 - u.z * u.z;
144,126,246✔
1863
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1864
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
70,919,123✔
1865

70,919,123✔
1866
  // if factor of s^2 is zero, direction of flight is parallel to theta
141,838,246✔
1867
  // surface
1868
  if (std::abs(a) < FP_PRECISION) {
73,207,123✔
1869
    // if b vanishes, direction of flight is within theta surface and crossing
1870
    // is not possible
36,866,907✔
1871
    if (std::abs(b) < FP_PRECISION)
36,866,907✔
1872
      return INFTY;
36,866,907✔
1873

73,733,814✔
1874
    const double s = -0.5 * c / b;
1875
    // Check if solution is in positive direction of flight and has correct
1876
    // sign
36,340,216✔
1877
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1878
      return s;
1879

1880
    // no crossing is possible
401✔
1881
    return INFTY;
1882
  }
401✔
1883

401✔
1884
  const double p = b / a;
401✔
1885
  double D = p * p - c / a;
1886

1,604✔
1887
  if (D < 0.0)
1,203✔
UNCOV
1888
    return INFTY;
×
1889

UNCOV
1890
  D = std::sqrt(D);
×
1891

1892
  // the solution -p-D is always smaller as -p+D : Check this one first
1,203✔
1893
  double s = -p - D;
2,406✔
UNCOV
1894
  // Check if solution is in positive direction of flight and has correct sign
×
1895
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
UNCOV
1896
    return s;
×
1897

1898
  s = -p + D;
1899
  // Check if solution is in positive direction of flight and has correct sign
401✔
UNCOV
1900
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
1901
    return s;
UNCOV
1902

×
1903
  return INFTY;
1904
}
401✔
1905

×
1906
double SphericalMesh::find_phi_crossing(
1907
  const Position& r, const Direction& u, double l, int shell) const
×
1908
{
1909
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
401✔
1910
  if (full_phi_ && (shape_[2] == 1))
×
1911
    return INFTY;
1912

UNCOV
1913
  shell = sanitize_phi(shell);
×
1914

1915
  const double p0 = grid_[2][shell];
1916

401✔
1917
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1918
  // => x(s) * cos(p0) = y(s) * sin(p0)
802✔
1919
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
802✔
1920
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
802✔
1921

802✔
1922
  const double c0 = std::cos(p0);
1923
  const double s0 = std::sin(p0);
401✔
1924

1925
  const double denominator = (u.x * s0 - u.y * c0);
1926

142,099,353✔
1927
  // Check if direction of flight is not parallel to phi surface
1928
  if (std::abs(denominator) > FP_PRECISION) {
142,099,353✔
1929
    const double s = -(r.x * s0 - r.y * c0) / denominator;
1930
    // Check if solution is in positive direction of flight and crosses the
UNCOV
1931
    // correct phi surface (not -phi)
×
1932
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
1933
      return s;
UNCOV
1934
  }
×
1935

1936
  return INFTY;
1937
}
1938

1939
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
1940
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1941
  double l) const
363✔
1942
{
1943

363✔
1944
  if (i == 0) {
363✔
1945
    return std::min(
363✔
1946
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
363✔
1947
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
363✔
1948

1949
  } else if (i == 1) {
352✔
1950
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
1951
                      find_theta_crossing(r0, u, l, ijk[i])),
352✔
1952
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
352✔
1953
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
1954

352✔
1955
  } else {
352✔
1956
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
1957
                      find_phi_crossing(r0, u, l, ijk[i])),
352✔
1958
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
352✔
1959
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
1960
  }
352✔
1961
}
1962

1963
int SphericalMesh::set_grid()
1964
{
1965
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1966
    static_cast<int>(grid_[1].size()) - 1,
1967
    static_cast<int>(grid_[2].size()) - 1};
291✔
1968

291✔
1969
  for (const auto& g : grid_) {
1970
    if (g.size() < 2) {
291✔
1971
      set_errmsg("x-, y-, and z- grids for spherical meshes "
1972
                 "must each have at least 2 points");
291✔
1973
      return OPENMC_E_INVALID_ARGUMENT;
291✔
1974
    }
291✔
1975
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
291✔
1976
        g.end()) {
1977
      set_errmsg("Values in for r-, theta-, and phi- grids for "
291✔
UNCOV
1978
                 "spherical meshes must be sorted and unique.");
×
1979
      return OPENMC_E_INVALID_ARGUMENT;
1980
    }
291✔
1981
    if (g.front() < 0.0) {
1982
      set_errmsg("r-, theta-, and phi- grids for "
1983
                 "spherical meshes must start at v >= 0.");
1984
      return OPENMC_E_INVALID_ARGUMENT;
341✔
1985
    }
1986
  }
341✔
1987
  if (grid_[1].back() > PI) {
1988
    set_errmsg("theta-grids for "
1989
               "spherical meshes must end with theta <= pi.");
67,412,510✔
1990

1991
    return OPENMC_E_INVALID_ARGUMENT;
1992
  }
67,412,510✔
1993
  if (grid_[2].back() > 2 * PI) {
1994
    set_errmsg("phi-grids for "
67,412,510✔
1995
               "spherical meshes must end with phi <= 2*pi.");
67,412,510✔
1996
    return OPENMC_E_INVALID_ARGUMENT;
1997
  }
67,412,510✔
UNCOV
1998

×
UNCOV
1999
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
×
2000
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
2001

67,412,510✔
2002
  double r = grid_[0].back();
67,412,510✔
2003
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
67,412,510✔
2004
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
33,712,800✔
2005

2006
  return 0;
2007
}
67,412,510✔
2008

2009
int SphericalMesh::get_index_in_direction(double r, int i) const
67,412,510✔
2010
{
67,412,510✔
2011
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
2012
}
67,412,510✔
2013

2014
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
UNCOV
2015
  Position plot_ll, Position plot_ur) const
×
2016
{
2017
  fatal_error("Plot of spherical Mesh not implemented");
UNCOV
2018

×
UNCOV
2019
  // Figure out which axes lie in the plane of the plot.
×
2020
  array<vector<double>, 2> axis_lines;
UNCOV
2021
  return {axis_lines[0], axis_lines[1]};
×
UNCOV
2022
}
×
2023

2024
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
×
UNCOV
2025
{
×
2026
  write_dataset(mesh_group, "r_grid", grid_[0]);
2027
  write_dataset(mesh_group, "theta_grid", grid_[1]);
×
UNCOV
2028
  write_dataset(mesh_group, "phi_grid", grid_[2]);
×
2029
  write_dataset(mesh_group, "origin", origin_);
×
2030
}
×
UNCOV
2031

×
2032
double SphericalMesh::volume(const MeshIndex& ijk) const
2033
{
×
2034
  double r_i = grid_[0][ijk[0] - 1];
2035
  double r_o = grid_[0][ijk[0]];
×
2036

×
UNCOV
2037
  double theta_i = grid_[1][ijk[1] - 1];
×
2038
  double theta_o = grid_[1][ijk[1]];
UNCOV
2039

×
2040
  double phi_i = grid_[2][ijk[2] - 1];
2041
  double phi_o = grid_[2][ijk[2]];
2042

441,926,232✔
2043
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
2044
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
2045
}
441,926,232✔
2046

39,388,107✔
2047
//==============================================================================
2048
// Helper functions for the C API
2049
//==============================================================================
2050

402,538,125✔
2051
int check_mesh(int32_t index)
402,538,125✔
2052
{
6,974,066✔
2053
  if (index < 0 || index >= model::meshes.size()) {
395,564,059✔
2054
    set_errmsg("Index in meshes array is out of bounds.");
395,564,059✔
2055
    return OPENMC_E_OUT_OF_BOUNDS;
395,564,059✔
2056
  }
2057
  return 0;
395,564,059✔
2058
}
10,586,180✔
2059

2060
template<class T>
384,977,879✔
2061
int check_mesh_type(int32_t index)
357,140,443✔
2062
{
2063
  if (int err = check_mesh(index))
357,140,443✔
2064
    return err;
64,176,541✔
2065

292,963,902✔
2066
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
176,563,519✔
2067
  if (!mesh) {
2068
    set_errmsg("This function is not valid for input mesh.");
2069
    return OPENMC_E_INVALID_TYPE;
144,237,819✔
2070
  }
2071
  return 0;
2072
}
108,467,832✔
2073

2074
template<class T>
2075
bool is_mesh_type(int32_t index)
2076
{
108,467,832✔
2077
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
70,123,416✔
2078
  return mesh;
2079
}
38,344,416✔
2080

2081
//==============================================================================
2082
// C API functions
2083
//==============================================================================
2084

2085
// Return the type of mesh as a C string
2086
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
2087
{
2088
  if (int err = check_mesh(index))
38,344,416✔
2089
    return err;
38,344,416✔
2090

38,344,416✔
2091
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
2092

38,344,416✔
2093
  return 0;
38,344,416✔
2094
}
38,344,416✔
2095

2096
//! Extend the meshes array by n elements
2097
extern "C" int openmc_extend_meshes(
2098
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
38,344,416✔
2099
{
2100
  if (index_start)
2101
    *index_start = model::meshes.size();
482,548✔
2102
  std::string mesh_type;
482,548✔
2103

UNCOV
2104
  for (int i = 0; i < n; ++i) {
×
2105
    if (RegularMesh::mesh_type == type) {
2106
      model::meshes.push_back(make_unique<RegularMesh>());
UNCOV
2107
    } else if (RectilinearMesh::mesh_type == type) {
×
UNCOV
2108
      model::meshes.push_back(make_unique<RectilinearMesh>());
×
2109
    } else if (CylindricalMesh::mesh_type == type) {
2110
      model::meshes.push_back(make_unique<CylindricalMesh>());
UNCOV
2111
    } else if (SphericalMesh::mesh_type == type) {
×
2112
      model::meshes.push_back(make_unique<SphericalMesh>());
2113
    } else {
2114
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
37,861,868✔
2115
    }
37,861,868✔
2116
  }
2117
  if (index_end)
37,861,868✔
2118
    *index_end = model::meshes.size() - 1;
10,945,825✔
2119

2120
  return 0;
26,916,043✔
2121
}
2122

2123
//! Adds a new unstructured mesh to OpenMC
26,916,043✔
2124
extern "C" int openmc_add_unstructured_mesh(
2125
  const char filename[], const char library[], int* id)
26,916,043✔
2126
{
5,283,102✔
2127
  std::string lib_name(library);
2128
  std::string mesh_file(filename);
21,632,941✔
2129
  bool valid_lib = false;
2130

21,632,941✔
2131
#ifdef DAGMC
10,154,661✔
2132
  if (lib_name == MOABMesh::mesh_lib_type) {
2133
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
11,478,280✔
2134
    valid_lib = true;
2135
  }
2136
#endif
110,058,036✔
2137

2138
#ifdef LIBMESH
2139
  if (lib_name == LibMesh::mesh_lib_type) {
2140
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
110,058,036✔
2141
    valid_lib = true;
70,123,416✔
2142
  }
2143
#endif
39,934,620✔
2144

2145
  if (!valid_lib) {
39,934,620✔
2146
    set_errmsg(fmt::format("Mesh library {} is not supported "
2147
                           "by this build of OpenMC",
2148
      lib_name));
2149
    return OPENMC_E_INVALID_ARGUMENT;
2150
  }
2151

2152
  // auto-assign new ID
39,934,620✔
2153
  model::meshes.back()->set_id(-1);
39,934,620✔
2154
  *id = model::meshes.back()->id_;
2155

39,934,620✔
2156
  return 0;
2157
}
2158

39,934,620✔
2159
//! Return the index in the meshes array of a mesh with a given ID
39,700,628✔
2160
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
2161
{
2162
  auto pair = model::mesh_map.find(id);
39,700,628✔
2163
  if (pair == model::mesh_map.end()) {
17,576,130✔
2164
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
2165
    return OPENMC_E_INVALID_ID;
2166
  }
22,358,490✔
2167
  *index = pair->second;
2168
  return 0;
2169
}
330,226,050✔
2170

2171
//! Return the ID of a mesh
2172
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2173
{
2174
  if (int err = check_mesh(index))
330,226,050✔
2175
    return err;
220,963,116✔
2176
  *id = model::meshes[index]->id_;
220,963,116✔
2177
  return 0;
441,926,232✔
2178
}
2179

109,262,934✔
2180
//! Set the ID of a mesh
54,233,916✔
2181
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
54,233,916✔
2182
{
54,233,916✔
2183
  if (int err = check_mesh(index))
108,467,832✔
2184
    return err;
2185
  model::meshes[index]->id_ = id;
2186
  model::mesh_map[id] = index;
55,029,018✔
2187
  return 0;
55,029,018✔
2188
}
55,029,018✔
2189

110,058,036✔
2190
//! Get the number of elements in a mesh
2191
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
2192
{
2193
  if (int err = check_mesh(index))
313✔
2194
    return err;
2195
  *n = model::meshes[index]->n_bins();
313✔
2196
  return 0;
313✔
2197
}
313✔
2198

2199
//! Get the volume of each element in the mesh
1,252✔
2200
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
939✔
UNCOV
2201
{
×
2202
  if (int err = check_mesh(index))
UNCOV
2203
    return err;
×
2204
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
2205
    volumes[i] = model::meshes[index]->volume(i);
939✔
2206
  }
1,878✔
UNCOV
2207
  return 0;
×
2208
}
UNCOV
2209

×
2210
//! Get the bounding box of a mesh
2211
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
939✔
2212
{
×
2213
  if (int err = check_mesh(index))
2214
    return err;
×
2215

2216
  BoundingBox bbox = model::meshes[index]->bounding_box();
2217

313✔
UNCOV
2218
  // set lower left corner values
×
2219
  ll[0] = bbox.xmin;
2220
  ll[1] = bbox.ymin;
UNCOV
2221
  ll[2] = bbox.zmin;
×
2222

2223
  // set upper right corner values
313✔
UNCOV
2224
  ur[0] = bbox.xmax;
×
2225
  ur[1] = bbox.ymax;
2226
  ur[2] = bbox.zmax;
×
2227
  return 0;
2228
}
2229

313✔
2230
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
313✔
2231
  int nz, int table_size, int32_t* materials, double* volumes)
2232
{
313✔
2233
  if (int err = check_mesh(index))
313✔
2234
    return err;
313✔
2235

2236
  try {
313✔
2237
    model::meshes[index]->material_volumes(
2238
      nx, ny, nz, table_size, materials, volumes);
2239
  } catch (const std::exception& e) {
202,237,530✔
2240
    set_errmsg(e.what());
2241
    if (starts_with(e.what(), "Mesh")) {
202,237,530✔
2242
      return OPENMC_E_GEOMETRY;
2243
    } else {
UNCOV
2244
      return OPENMC_E_ALLOCATE;
×
2245
    }
2246
  }
UNCOV
2247

×
2248
  return 0;
2249
}
2250

2251
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
2252
  Position width, int basis, int* pixels, int32_t* data)
2253
{
2254
  if (int err = check_mesh(index))
286✔
2255
    return err;
2256
  const auto& mesh = model::meshes[index].get();
286✔
2257

286✔
2258
  int pixel_width = pixels[0];
286✔
2259
  int pixel_height = pixels[1];
286✔
2260

286✔
2261
  // get pixel size
2262
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
484✔
2263
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
2264

484✔
2265
  // setup basis indices and initial position centered on pixel
484✔
2266
  int in_i, out_i;
2267
  Position xyz = origin;
484✔
2268
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
484✔
2269
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
2270
  switch (basis_enum) {
484✔
2271
  case PlotBasis::xy:
484✔
2272
    in_i = 0;
2273
    out_i = 1;
484✔
2274
    break;
484✔
2275
  case PlotBasis::xz:
2276
    in_i = 0;
2277
    out_i = 2;
2278
    break;
2279
  case PlotBasis::yz:
2280
    in_i = 1;
2281
    out_i = 2;
6,160✔
2282
    break;
2283
  default:
6,160✔
UNCOV
2284
    UNREACHABLE();
×
UNCOV
2285
  }
×
2286

2287
  // set initial position
6,160✔
2288
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
2289
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
2290

2291
#pragma omp parallel
1,100✔
2292
  {
2293
    Position r = xyz;
1,100✔
UNCOV
2294

×
2295
#pragma omp for
2296
    for (int y = 0; y < pixel_height; y++) {
1,100✔
2297
      r[out_i] = xyz[out_i] - out_pixel * y;
1,100✔
UNCOV
2298
      for (int x = 0; x < pixel_width; x++) {
×
2299
        r[in_i] = xyz[in_i] + in_pixel * x;
×
2300
        data[pixel_width * y + x] = mesh->get_bin(r);
2301
      }
1,100✔
2302
    }
2303
  }
143✔
2304

2305
  return 0;
143✔
UNCOV
2306
}
×
2307

2308
//! Get the dimension of a regular mesh
143✔
2309
extern "C" int openmc_regular_mesh_get_dimension(
143✔
UNCOV
2310
  int32_t index, int** dims, int* n)
×
2311
{
×
2312
  if (int err = check_mesh_type<RegularMesh>(index))
2313
    return err;
143✔
2314
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2315
  *dims = mesh->shape_.data();
143✔
2316
  *n = mesh->n_dimension_;
2317
  return 0;
143✔
UNCOV
2318
}
×
2319

2320
//! Set the dimension of a regular mesh
143✔
2321
extern "C" int openmc_regular_mesh_set_dimension(
143✔
UNCOV
2322
  int32_t index, int n, const int* dims)
×
2323
{
×
2324
  if (int err = check_mesh_type<RegularMesh>(index))
2325
    return err;
143✔
2326
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2327

187✔
2328
  // Copy dimension
2329
  mesh->n_dimension_ = n;
187✔
UNCOV
2330
  std::copy(dims, dims + n, mesh->shape_.begin());
×
2331
  return 0;
2332
}
187✔
2333

187✔
UNCOV
2334
//! Get the regular mesh parameters
×
2335
extern "C" int openmc_regular_mesh_get_params(
×
2336
  int32_t index, double** ll, double** ur, double** width, int* n)
2337
{
187✔
2338
  if (int err = check_mesh_type<RegularMesh>(index))
2339
    return err;
627✔
2340
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2341

627✔
UNCOV
2342
  if (m->lower_left_.dimension() == 0) {
×
2343
    set_errmsg("Mesh parameters have not been set.");
2344
    return OPENMC_E_ALLOCATE;
627✔
2345
  }
627✔
UNCOV
2346

×
2347
  *ll = m->lower_left_.data();
×
2348
  *ur = m->upper_right_.data();
2349
  *width = m->width_.data();
627✔
2350
  *n = m->n_dimension_;
2351
  return 0;
2352
}
2353

2354
//! Set the regular mesh parameters
2355
extern "C" int openmc_regular_mesh_set_params(
2356
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2357
{
2358
  if (int err = check_mesh_type<RegularMesh>(index))
2359
    return err;
2360
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2361

2362
  if (m->n_dimension_ == -1) {
2363
    set_errmsg("Need to set mesh dimension before setting parameters.");
2364
    return OPENMC_E_UNASSIGNED;
1,419✔
2365
  }
2366

1,419✔
UNCOV
2367
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
×
2368
  if (ll && ur) {
2369
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
1,419✔
2370
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
2371
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
1,419✔
2372
  } else if (ll && width) {
2373
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
2374
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
2375
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
253✔
2376
  } else if (ur && width) {
2377
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
2378
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
253✔
2379
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
253✔
2380
  } else {
253✔
2381
    set_errmsg("At least two parameters must be specified.");
2382
    return OPENMC_E_INVALID_ARGUMENT;
506✔
2383
  }
253✔
2384

165✔
2385
  // Set material volumes
88✔
2386

44✔
2387
  // TODO: incorporate this into method in RegularMesh that can be called from
44✔
2388
  // here and from constructor
22✔
2389
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
22✔
2390
  m->element_volume_ = 1.0;
22✔
2391
  for (int i = 0; i < m->n_dimension_; i++) {
UNCOV
2392
    m->element_volume_ *= m->width_[i];
×
2393
  }
2394

2395
  return 0;
253✔
UNCOV
2396
}
×
2397

2398
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
253✔
2399
template<class C>
253✔
2400
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
2401
  const int nx, const double* grid_y, const int ny, const double* grid_z,
UNCOV
2402
  const int nz)
×
2403
{
2404
  if (int err = check_mesh_type<C>(index))
UNCOV
2405
    return err;
×
UNCOV
2406

×
2407
  C* m = dynamic_cast<C*>(model::meshes[index].get());
×
2408

2409
  m->n_dimension_ = 3;
2410

2411
  m->grid_[0].reserve(nx);
2412
  m->grid_[1].reserve(ny);
2413
  m->grid_[2].reserve(nz);
2414

2415
  for (int i = 0; i < nx; i++) {
2416
    m->grid_[0].push_back(grid_x[i]);
2417
  }
2418
  for (int i = 0; i < ny; i++) {
2419
    m->grid_[1].push_back(grid_y[i]);
2420
  }
2421
  for (int i = 0; i < nz; i++) {
2422
    m->grid_[2].push_back(grid_z[i]);
UNCOV
2423
  }
×
UNCOV
2424

×
2425
  int err = m->set_grid();
2426
  return err;
UNCOV
2427
}
×
2428

2429
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2430
template<class C>
UNCOV
2431
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
×
2432
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
×
2433
{
UNCOV
2434
  if (int err = check_mesh_type<C>(index))
×
2435
    return err;
2436
  C* m = dynamic_cast<C*>(model::meshes[index].get());
2437

2438
  if (m->lower_left_.dimension() == 0) {
429✔
2439
    set_errmsg("Mesh parameters have not been set.");
2440
    return OPENMC_E_ALLOCATE;
429✔
2441
  }
429✔
UNCOV
2442

×
UNCOV
2443
  *grid_x = m->grid_[0].data();
×
2444
  *nx = m->grid_[0].size();
2445
  *grid_y = m->grid_[1].data();
429✔
2446
  *ny = m->grid_[1].size();
429✔
2447
  *grid_z = m->grid_[2].data();
2448
  *nz = m->grid_[2].size();
2449

2450
  return 0;
2,750✔
2451
}
2452

2,750✔
UNCOV
2453
//! Get the rectilinear mesh grid
×
2454
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
2,750✔
2455
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2,750✔
2456
{
2457
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
2458
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2459
}
253✔
2460

2461
//! Set the rectilienar mesh parameters
253✔
UNCOV
2462
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
×
2463
  const double* grid_x, const int nx, const double* grid_y, const int ny,
253✔
2464
  const double* grid_z, const int nz)
253✔
2465
{
253✔
2466
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
2467
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2468
}
2469

231✔
2470
//! Get the cylindrical mesh grid
2471
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
231✔
UNCOV
2472
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
×
2473
{
231✔
2474
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
231✔
2475
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2476
}
2477

2478
//! Set the cylindrical mesh parameters
88✔
2479
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
2480
  const double* grid_x, const int nx, const double* grid_y, const int ny,
88✔
UNCOV
2481
  const double* grid_z, const int nz)
×
2482
{
968✔
2483
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
880✔
2484
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2485
}
88✔
2486

2487
//! Get the spherical mesh grid
2488
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
2489
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
132✔
2490
{
2491

132✔
UNCOV
2492
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
×
2493
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2494
  ;
132✔
2495
}
2496

2497
//! Set the spherical mesh parameters
132✔
2498
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
132✔
2499
  const double* grid_x, const int nx, const double* grid_y, const int ny,
132✔
2500
  const double* grid_z, const int nz)
2501
{
2502
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
132✔
2503
    index, grid_x, nx, grid_y, ny, grid_z, nz);
132✔
2504
}
132✔
2505

132✔
2506
#ifdef DAGMC
2507

2508
const std::string MOABMesh::mesh_lib_type = "moab";
143✔
2509

2510
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2511
{
143✔
UNCOV
2512
  initialize();
×
2513
}
2514

2515
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
143✔
2516
{
2517
  filename_ = filename;
11✔
2518
  set_length_multiplier(length_multiplier);
11✔
2519
  initialize();
11✔
2520
}
11✔
2521

UNCOV
2522
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
×
2523
{
2524
  mbi_ = external_mbi;
11✔
2525
  filename_ = "unknown (external file)";
2526
  this->initialize();
132✔
2527
}
2528

2529
void MOABMesh::initialize()
44✔
2530
{
2531

2532
  // Create the MOAB interface and load data from file
44✔
UNCOV
2533
  this->create_interface();
×
2534

44✔
2535
  // Initialise MOAB error code
2536
  moab::ErrorCode rval = moab::MB_SUCCESS;
44✔
2537

44✔
2538
  // Set the dimension
2539
  n_dimension_ = 3;
2540

44✔
2541
  // set member range of tetrahedral entities
44✔
2542
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2543
  if (rval != moab::MB_SUCCESS) {
2544
    fatal_error("Failed to get all tetrahedral elements");
2545
  }
44✔
2546

2547
  if (!ehs_.all_of_type(moab::MBTET)) {
44✔
2548
    warning("Non-tetrahedral elements found in unstructured "
44✔
2549
            "mesh file: " +
44✔
2550
            filename_);
44✔
2551
  }
44✔
2552

44✔
UNCOV
2553
  // set member range of vertices
×
UNCOV
2554
  int vertex_dim = 0;
×
UNCOV
2555
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
×
UNCOV
2556
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2557
    fatal_error("Failed to get all vertex handles");
×
2558
  }
×
2559

×
2560
  // make an entity set for all tetrahedra
×
2561
  // this is used for convenience later in output
×
2562
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
×
2563
  if (rval != moab::MB_SUCCESS) {
2564
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2565
  }
2566

44✔
2567
  rval = mbi_->add_entities(tetset_, ehs_);
44✔
2568
  if (rval != moab::MB_SUCCESS) {
2569
    fatal_error("Failed to add tetrahedra to an entity set.");
24✔
2570
  }
2571

20✔
2572
  if (length_multiplier_ > 0.0) {
2573
    // get the connectivity of all tets
2574
    moab::Range adj;
420✔
2575
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
400✔
2576
    if (rval != moab::MB_SUCCESS) {
8,400✔
2577
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
8,000✔
2578
    }
8,000✔
2579
    // scale all vertex coords by multiplier (done individually so not all
2580
    // coordinates are in memory twice at once)
2581
    for (auto vert : adj) {
2582
      // retrieve coords
2583
      std::array<double, 3> coord;
44✔
2584
      rval = mbi_->get_coords(&vert, 1, coord.data());
2585
      if (rval != moab::MB_SUCCESS) {
2586
        fatal_error("Could not get coordinates of vertex.");
2587
      }
11✔
2588
      // scale coords
2589
      for (auto& c : coord) {
2590
        c *= length_multiplier_;
11✔
UNCOV
2591
      }
×
2592
      // set new coords
11✔
2593
      rval = mbi_->set_coords(&vert, 1, coord.data());
11✔
2594
      if (rval != moab::MB_SUCCESS) {
11✔
2595
        fatal_error("Failed to set new vertex coordinates");
11✔
2596
      }
2597
    }
2598
  }
2599

187✔
2600
  // Determine bounds of mesh
2601
  this->determine_bounds();
2602
}
187✔
UNCOV
2603

×
2604
void MOABMesh::prepare_for_point_location()
187✔
2605
{
2606
  // if the KDTree has already been constructed, do nothing
2607
  if (kdtree_)
187✔
2608
    return;
187✔
2609

187✔
2610
  // build acceleration data structures
2611
  compute_barycentric_data(ehs_);
2612
  build_kdtree(ehs_);
2613
}
209✔
2614

2615
void MOABMesh::create_interface()
2616
{
209✔
UNCOV
2617
  // Do not create a MOAB instance if one is already in memory
×
2618
  if (mbi_)
209✔
2619
    return;
2620

209✔
UNCOV
2621
  // create MOAB instance
×
2622
  mbi_ = std::make_shared<moab::Core>();
×
2623

2624
  // load unstructured mesh file
2625
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
209✔
2626
  if (rval != moab::MB_SUCCESS) {
209✔
2627
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
209✔
2628
  }
209✔
2629
}
209✔
2630

2631
void MOABMesh::build_kdtree(const moab::Range& all_tets)
2632
{
2633
  moab::Range all_tris;
220✔
2634
  int adj_dim = 2;
2635
  write_message("Getting tet adjacencies...", 7);
2636
  moab::ErrorCode rval = mbi_->get_adjacencies(
220✔
UNCOV
2637
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
×
2638
  if (rval != moab::MB_SUCCESS) {
220✔
2639
    fatal_error("Failed to get adjacent triangles for tets");
2640
  }
220✔
UNCOV
2641

×
2642
  if (!all_tris.all_of_type(moab::MBTRI)) {
×
2643
    warning("Non-triangle elements found in tet adjacencies in "
2644
            "unstructured mesh file: " +
2645
            filename_);
220✔
2646
  }
220✔
2647

198✔
2648
  // combine into one range
198✔
2649
  moab::Range all_tets_and_tris;
198✔
2650
  all_tets_and_tris.merge(all_tets);
22✔
2651
  all_tets_and_tris.merge(all_tris);
11✔
2652

11✔
2653
  // create a kd-tree instance
11✔
2654
  write_message(
11✔
2655
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
11✔
2656
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
11✔
2657

11✔
2658
  // Determine what options to use
UNCOV
2659
  std::ostringstream options_stream;
×
UNCOV
2660
  if (options_.empty()) {
×
2661
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
2662
  } else {
2663
    options_stream << options_;
2664
  }
2665
  moab::FileOptions file_opts(options_stream.str().c_str());
2666

2667
  // Build the k-d tree
220✔
2668
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
220✔
2669
  if (rval != moab::MB_SUCCESS) {
880✔
2670
    fatal_error("Failed to construct KDTree for the "
660✔
2671
                "unstructured mesh file: " +
2672
                filename_);
2673
  }
220✔
2674
}
220✔
2675

2676
void MOABMesh::intersect_track(const moab::CartVect& start,
2677
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2678
{
88✔
2679
  hits.clear();
2680

2681
  moab::ErrorCode rval;
2682
  vector<moab::EntityHandle> tris;
88✔
UNCOV
2683
  // get all intersections with triangles in the tet mesh
×
2684
  // (distances are relative to the start point, not the previous
2685
  // intersection)
88✔
2686
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
2687
    dir.array(), start.array(), tris, hits, 0, track_len);
88✔
2688
  if (rval != moab::MB_SUCCESS) {
2689
    fatal_error(
88✔
2690
      "Failed to compute intersections on unstructured mesh: " + filename_);
88✔
2691
  }
88✔
2692

2693
  // remove duplicate intersection distances
572✔
2694
  std::unique(hits.begin(), hits.end());
484✔
2695

2696
  // sorts by first component of std::pair by default
341✔
2697
  std::sort(hits.begin(), hits.end());
253✔
2698
}
2699

319✔
2700
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
231✔
2701
  vector<int>& bins, vector<double>& lengths) const
2702
{
2703
  moab::CartVect start(r0.x, r0.y, r0.z);
88✔
2704
  moab::CartVect end(r1.x, r1.y, r1.z);
88✔
2705
  moab::CartVect dir(u.x, u.y, u.z);
2706
  dir.normalize();
22✔
2707

2708
  double track_len = (end - start).length();
2709
  if (track_len == 0.0)
2710
    return;
22✔
UNCOV
2711

×
2712
  start -= TINY_BIT * dir;
2713
  end += TINY_BIT * dir;
22✔
2714

2715
  vector<double> hits;
22✔
2716
  intersect_track(start, dir, track_len, hits);
2717

22✔
2718
  bins.clear();
22✔
2719
  lengths.clear();
22✔
2720

2721
  // if there are no intersections the track may lie entirely
88✔
2722
  // within a single tet. If this is the case, apply entire
66✔
2723
  // score to that tet and return.
2724
  if (hits.size() == 0) {
88✔
2725
    Position midpoint = r0 + u * (track_len * 0.5);
66✔
2726
    int bin = this->get_bin(midpoint);
2727
    if (bin != -1) {
99✔
2728
      bins.push_back(bin);
77✔
2729
      lengths.push_back(1.0);
2730
    }
2731
    return;
22✔
2732
  }
22✔
2733

2734
  // for each segment in the set of tracks, try to look up a tet
22✔
2735
  // at the midpoint of the segment
2736
  Position current = r0;
2737
  double last_dist = 0.0;
2738
  for (const auto& hit : hits) {
22✔
UNCOV
2739
    // get the segment length
×
2740
    double segment_length = hit - last_dist;
2741
    last_dist = hit;
22✔
2742
    // find the midpoint of this segment
2743
    Position midpoint = current + u * (segment_length * 0.5);
22✔
2744
    // try to find a tet for this position
2745
    int bin = this->get_bin(midpoint);
22✔
2746

22✔
2747
    // determine the start point for this segment
22✔
2748
    current = r0 + u * hit;
2749

88✔
2750
    if (bin == -1) {
66✔
2751
      continue;
2752
    }
99✔
2753

77✔
2754
    bins.push_back(bin);
2755
    lengths.push_back(segment_length / track_len);
77✔
2756
  }
55✔
2757

2758
  // tally remaining portion of track after last hit if
2759
  // the last segment of the track is in the mesh but doesn't
22✔
2760
  // reach the other side of the tet
22✔
2761
  if (hits.back() < track_len) {
2762
    Position segment_start = r0 + u * hits.back();
44✔
2763
    double segment_length = track_len - hits.back();
2764
    Position midpoint = segment_start + u * (segment_length * 0.5);
2765
    int bin = this->get_bin(midpoint);
2766
    if (bin != -1) {
44✔
UNCOV
2767
      bins.push_back(bin);
×
2768
      lengths.push_back(segment_length / track_len);
2769
    }
44✔
2770
  }
2771
};
44✔
2772

2773
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
44✔
2774
{
44✔
2775
  moab::CartVect pos(r.x, r.y, r.z);
44✔
2776
  // find the leaf of the kd-tree for this position
2777
  moab::AdaptiveKDTreeIter kdtree_iter;
396✔
2778
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
352✔
2779
  if (rval != moab::MB_SUCCESS) {
2780
    return 0;
154✔
2781
  }
110✔
2782

2783
  // retrieve the tet elements of this leaf
143✔
2784
  moab::EntityHandle leaf = kdtree_iter.handle();
99✔
2785
  moab::Range tets;
2786
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
2787
  if (rval != moab::MB_SUCCESS) {
44✔
2788
    warning("MOAB error finding tets.");
44✔
2789
  }
2790

2791
  // loop over the tets in this leaf, returning the containing tet if found
2792
  for (const auto& tet : tets) {
2793
    if (point_in_tet(pos, tet)) {
385✔
2794
      return tet;
2795
    }
2796
  }
385✔
UNCOV
2797

×
2798
  // if no tet is found, return an invalid handle
385✔
2799
  return 0;
2800
}
385✔
UNCOV
2801

×
2802
double MOABMesh::volume(int bin) const
×
2803
{
2804
  return tet_volume(get_ent_handle_from_bin(bin));
2805
}
385✔
2806

385✔
2807
std::string MOABMesh::library() const
385✔
2808
{
385✔
2809
  return mesh_lib_type;
385✔
2810
}
385✔
2811

2812
// Sample position within a tet for MOAB type tets
385✔
2813
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
2814
{
121✔
2815

2816
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
2817

121✔
UNCOV
2818
  // Get vertex coordinates for MOAB tet
×
2819
  const moab::EntityHandle* conn1;
121✔
2820
  int conn1_size;
2821
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
121✔
UNCOV
2822
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
×
2823
    fatal_error(fmt::format(
×
2824
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
2825
      conn1_size));
2826
  }
121✔
2827
  moab::CartVect p[4];
121✔
2828
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
121✔
2829
  if (rval != moab::MB_SUCCESS) {
121✔
2830
    fatal_error("Failed to get tet coords");
121✔
2831
  }
121✔
2832

2833
  std::array<Position, 4> tet_verts;
121✔
2834
  for (int i = 0; i < 4; i++) {
2835
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
121✔
2836
  }
2837
  // Samples position within tet using Barycentric stuff
2838
  return this->sample_tet(tet_verts, seed);
121✔
UNCOV
2839
}
×
2840

121✔
2841
double MOABMesh::tet_volume(moab::EntityHandle tet) const
2842
{
121✔
UNCOV
2843
  vector<moab::EntityHandle> conn;
×
2844
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
×
2845
  if (rval != moab::MB_SUCCESS) {
2846
    fatal_error("Failed to get tet connectivity");
2847
  }
121✔
2848

121✔
2849
  moab::CartVect p[4];
121✔
2850
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
121✔
2851
  if (rval != moab::MB_SUCCESS) {
121✔
2852
    fatal_error("Failed to get tet coords");
121✔
2853
  }
2854

121✔
2855
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
2856
}
143✔
2857

2858
int MOABMesh::get_bin(Position r) const
2859
{
143✔
UNCOV
2860
  moab::EntityHandle tet = get_tet(r);
×
2861
  if (tet == 0) {
143✔
2862
    return -1;
2863
  } else {
143✔
UNCOV
2864
    return get_bin_from_ent_handle(tet);
×
2865
  }
×
2866
}
2867

2868
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
143✔
2869
{
143✔
2870
  moab::ErrorCode rval;
143✔
2871

143✔
2872
  baryc_data_.clear();
143✔
2873
  baryc_data_.resize(tets.size());
143✔
2874

2875
  // compute the barycentric data for each tet element
143✔
2876
  // and store it as a 3x3 matrix
2877
  for (auto& tet : tets) {
2878
    vector<moab::EntityHandle> verts;
2879
    rval = mbi_->get_connectivity(&tet, 1, verts);
143✔
2880
    if (rval != moab::MB_SUCCESS) {
2881
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
2882
    }
143✔
2883

143✔
2884
    moab::CartVect p[4];
2885
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
2886
    if (rval != moab::MB_SUCCESS) {
2887
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
44✔
2888
    }
2889

2890
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
2891

44✔
2892
    // invert now to avoid this cost later
44✔
2893
    a = a.transpose().inverse();
2894
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
2895
  }
2896
}
121✔
2897

2898
bool MOABMesh::point_in_tet(
2899
  const moab::CartVect& r, moab::EntityHandle tet) const
121✔
2900
{
121✔
2901

2902
  moab::ErrorCode rval;
2903

2904
  // get tet vertices
22✔
2905
  vector<moab::EntityHandle> verts;
2906
  rval = mbi_->get_connectivity(&tet, 1, verts);
2907
  if (rval != moab::MB_SUCCESS) {
2908
    warning("Failed to get vertices of tet in umesh: " + filename_);
22✔
2909
    return false;
22✔
2910
  }
2911

2912
  // first vertex is used as a reference point for the barycentric data -
2913
  // retrieve its coordinates
121✔
2914
  moab::CartVect p_zero;
2915
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
2916
  if (rval != moab::MB_SUCCESS) {
2917
    warning("Failed to get coordinates of a vertex in "
121✔
2918
            "unstructured mesh: " +
121✔
2919
            filename_);
2920
    return false;
2921
  }
2922

2923
  // look up barycentric data
22✔
2924
  int idx = get_bin_from_ent_handle(tet);
2925
  const moab::Matrix3& a_inv = baryc_data_[idx];
2926

2927
  moab::CartVect bary_coords = a_inv * (r - p_zero);
22✔
2928

22✔
2929
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
2930
          bary_coords[2] >= 0.0 &&
2931
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
2932
}
2933

2934
int MOABMesh::get_bin_from_index(int idx) const
2935
{
23✔
2936
  if (idx >= n_bins()) {
2937
    fatal_error(fmt::format("Invalid bin index: {}", idx));
23✔
2938
  }
23✔
2939
  return ehs_[idx] - ehs_[0];
2940
}
2941

2942
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
2943
{
2944
  int bin = get_bin(r);
2945
  *in_mesh = bin != -1;
2946
  return bin;
2947
}
1✔
2948

2949
int MOABMesh::get_index_from_bin(int bin) const
1✔
2950
{
1✔
2951
  return bin;
1✔
2952
}
1✔
2953

2954
std::pair<vector<double>, vector<double>> MOABMesh::plot(
24✔
2955
  Position plot_ll, Position plot_ur) const
2956
{
2957
  // TODO: Implement mesh lines
2958
  return {};
24✔
2959
}
2960

2961
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
24✔
2962
{
2963
  int idx = vert - verts_[0];
2964
  if (idx >= n_vertices()) {
24✔
2965
    fatal_error(
2966
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
2967
  }
24✔
2968
  return idx;
24✔
2969
}
2970

2971
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
2972
{
24✔
2973
  int bin = eh - ehs_[0];
2974
  if (bin >= n_bins()) {
2975
    fatal_error(fmt::format("Invalid bin: {}", bin));
2976
  }
2977
  return bin;
2978
}
2979

24✔
2980
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
24✔
2981
{
24✔
2982
  if (bin >= n_bins()) {
2983
    fatal_error(fmt::format("Invalid bin index: ", bin));
2984
  }
2985
  return ehs_[0] + bin;
2986
}
2987

24✔
2988
int MOABMesh::n_bins() const
24✔
2989
{
2990
  return ehs_.size();
2991
}
2992

24✔
2993
int MOABMesh::n_surface_bins() const
24✔
2994
{
2995
  // collect all triangles in the set of tets for this mesh
2996
  moab::Range tris;
2997
  moab::ErrorCode rval;
24✔
2998
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
2999
  if (rval != moab::MB_SUCCESS) {
3000
    warning("Failed to get all triangles in the mesh instance");
3001
    return -1;
3002
  }
3003
  return 2 * tris.size();
3004
}
3005

3006
Position MOABMesh::centroid(int bin) const
3007
{
3008
  moab::ErrorCode rval;
3009

3010
  auto tet = this->get_ent_handle_from_bin(bin);
3011

3012
  // look up the tet connectivity
3013
  vector<moab::EntityHandle> conn;
3014
  rval = mbi_->get_connectivity(&tet, 1, conn);
3015
  if (rval != moab::MB_SUCCESS) {
3016
    warning("Failed to get connectivity of a mesh element.");
3017
    return {};
3018
  }
3019

3020
  // get the coordinates
3021
  vector<moab::CartVect> coords(conn.size());
3022
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3023
  if (rval != moab::MB_SUCCESS) {
3024
    warning("Failed to get the coordinates of a mesh element.");
3025
    return {};
3026
  }
24✔
3027

24✔
3028
  // compute the centroid of the element vertices
3029
  moab::CartVect centroid(0.0, 0.0, 0.0);
20✔
3030
  for (const auto& coord : coords) {
3031
    centroid += coord;
3032
  }
20✔
3033
  centroid /= double(coords.size());
3034

3035
  return {centroid[0], centroid[1], centroid[2]};
3036
}
20✔
3037

20✔
3038
int MOABMesh::n_vertices() const
3039
{
3040
  return verts_.size();
24✔
3041
}
3042

3043
Position MOABMesh::vertex(int id) const
24✔
3044
{
1✔
3045

3046
  moab::ErrorCode rval;
3047

23✔
3048
  moab::EntityHandle vert = verts_[id];
3049

3050
  moab::CartVect coords;
23✔
3051
  rval = mbi_->get_coords(&vert, 1, coords.array());
23✔
3052
  if (rval != moab::MB_SUCCESS) {
3053
    fatal_error("Failed to get the coordinates of a vertex.");
3054
  }
3055

3056
  return {coords[0], coords[1], coords[2]};
20✔
3057
}
3058

20✔
3059
std::vector<int> MOABMesh::connectivity(int bin) const
20✔
3060
{
20✔
3061
  moab::ErrorCode rval;
20✔
3062

3063
  auto tet = get_ent_handle_from_bin(bin);
20✔
3064

3065
  // look up the tet connectivity
3066
  vector<moab::EntityHandle> conn;
3067
  rval = mbi_->get_connectivity(&tet, 1, conn);
20✔
3068
  if (rval != moab::MB_SUCCESS) {
3069
    fatal_error("Failed to get connectivity of a mesh element.");
3070
    return {};
3071
  }
3072

3073
  std::vector<int> verts(4);
3074
  for (int i = 0; i < verts.size(); i++) {
20✔
3075
    verts[i] = get_vert_idx_from_handle(conn[i]);
20✔
3076
  }
20✔
3077

3078
  return verts;
3079
}
20✔
3080

20✔
3081
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
20✔
3082
  std::string score) const
3083
{
3084
  moab::ErrorCode rval;
20✔
3085
  // add a tag to the mesh
20✔
3086
  // all scores are treated as a single value
4✔
3087
  // with an uncertainty
3088
  moab::Tag value_tag;
16✔
3089

3090
  // create the value tag if not present and get handle
20✔
3091
  double default_val = 0.0;
3092
  auto val_string = score + "_mean";
3093
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
20✔
3094
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
20✔
3095
  if (rval != moab::MB_SUCCESS) {
3096
    auto msg =
3097
      fmt::format("Could not create or retrieve the value tag for the score {}"
3098
                  " on unstructured mesh {}",
3099
        score, id_);
20✔
3100
    fatal_error(msg);
3101
  }
1,542,122✔
3102

3103
  // create the std dev tag if not present and get handle
3104
  moab::Tag error_tag;
1,542,122✔
3105
  std::string err_string = score + "_std_dev";
3106
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3107
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
1,542,122✔
3108
  if (rval != moab::MB_SUCCESS) {
3109
    auto msg =
3110
      fmt::format("Could not create or retrieve the error tag for the score {}"
3111
                  " on unstructured mesh {}",
1,542,122✔
3112
        score, id_);
3113
    fatal_error(msg);
1,542,122✔
3114
  }
3115

3116
  // return the populated tag handles
3117
  return {value_tag, error_tag};
3118
}
3119

1,542,122✔
3120
void MOABMesh::add_score(const std::string& score)
3121
{
3122
  auto score_tags = get_score_tags(score);
1,542,122✔
3123
  tag_names_.push_back(score);
1,542,122✔
3124
}
3125

1,542,122✔
3126
void MOABMesh::remove_scores()
3127
{
3128
  for (const auto& name : tag_names_) {
1,542,122✔
3129
    auto value_name = name + "_mean";
1,542,122✔
3130
    moab::Tag tag;
1,542,122✔
3131
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
1,542,122✔
3132
    if (rval != moab::MB_SUCCESS)
3133
      return;
1,542,122✔
3134

1,542,122✔
3135
    rval = mbi_->tag_delete(tag);
720,627✔
3136
    if (rval != moab::MB_SUCCESS) {
3137
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
1,542,122✔
3138
                             " on unstructured mesh {}",
1,542,122✔
3139
        name, id_);
3140
      fatal_error(msg);
1,542,122✔
3141
    }
1,542,122✔
3142

3143
    auto std_dev_name = name + "_std_dev";
1,542,122✔
3144
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
1,542,122✔
3145
    if (rval != moab::MB_SUCCESS) {
3146
      auto msg =
3147
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3148
                    " on unstructured mesh {}",
3149
          name, id_);
1,542,122✔
3150
    }
720,627✔
3151

720,627✔
3152
    rval = mbi_->tag_delete(tag);
720,627✔
3153
    if (rval != moab::MB_SUCCESS) {
242,659✔
3154
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
242,659✔
3155
                             " on unstructured mesh {}",
3156
        name, id_);
720,627✔
3157
      fatal_error(msg);
3158
    }
3159
  }
3160
  tag_names_.clear();
3161
}
821,495✔
3162

821,495✔
3163
void MOABMesh::set_score_data(const std::string& score,
5,514,377✔
3164
  const vector<double>& values, const vector<double>& std_dev)
3165
{
4,692,882✔
3166
  auto score_tags = this->get_score_tags(score);
4,692,882✔
3167

3168
  moab::ErrorCode rval;
4,692,882✔
3169
  // set the score value
3170
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
4,692,882✔
3171
  if (rval != moab::MB_SUCCESS) {
3172
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3173
                           "on unstructured mesh {}",
4,692,882✔
3174
      score, id_);
3175
    warning(msg);
4,692,882✔
3176
  }
20,480✔
3177

3178
  // set the error value
3179
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
4,672,402✔
3180
  if (rval != moab::MB_SUCCESS) {
4,672,402✔
3181
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3182
                           "on unstructured mesh {}",
3183
      score, id_);
3184
    warning(msg);
3185
  }
3186
}
821,495✔
3187

821,495✔
3188
void MOABMesh::write(const std::string& base_filename) const
821,495✔
3189
{
821,495✔
3190
  // add extension to the base name
821,495✔
3191
  auto filename = base_filename + ".vtk";
821,495✔
3192
  write_message(5, "Writing unstructured mesh {}...", filename);
766,195✔
3193
  filename = settings::path_output + filename;
766,195✔
3194

3195
  // write the tetrahedral elements of the mesh only
3196
  // to avoid clutter from zero-value data on other
1,542,122✔
3197
  // elements during visualization
3198
  moab::ErrorCode rval;
7,307,001✔
3199
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3200
  if (rval != moab::MB_SUCCESS) {
7,307,001✔
3201
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3202
    warning(msg);
7,307,001✔
3203
  }
7,307,001✔
3204
}
7,307,001✔
3205

1,010,077✔
3206
#endif
3207

3208
#ifdef LIBMESH
3209

6,296,924✔
3210
const std::string LibMesh::mesh_lib_type = "libmesh";
6,296,924✔
3211

6,296,924✔
3212
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node), adaptive_(false)
6,296,924✔
3213
{
3214
  // filename_ and length_multiplier_ will already be set by the
3215
  // UnstructuredMesh constructor
3216
  set_mesh_pointer_from_filename(filename_);
3217
  set_length_multiplier(length_multiplier_);
260,010,824✔
3218
  initialize();
260,007,978✔
3219
}
6,294,078✔
3220

3221
// create the mesh from a pointer to a libMesh Mesh
3222
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3223
  : adaptive_(input_mesh.n_active_elem() != input_mesh.n_elem())
3224
{
2,846✔
3225
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
7,307,001✔
3226
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3227
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
167,856✔
3228
  }
3229

167,856✔
3230
  m_ = &input_mesh;
3231
  set_length_multiplier(length_multiplier);
3232
  initialize();
32✔
3233
}
3234

32✔
3235
// create the mesh from an input file
3236
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
3237
  : adaptive_(false)
3238
{
200,410✔
3239
  set_mesh_pointer_from_filename(filename);
3240
  set_length_multiplier(length_multiplier);
3241
  initialize();
200,410✔
3242
}
3243

3244
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3245
{
3246
  filename_ = filename;
200,410✔
3247
  unique_m_ =
200,410✔
3248
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
3249
  m_ = unique_m_.get();
3250
  m_->read(filename_);
3251
}
3252

1,002,050✔
3253
// build a libMesh equation system for storing values
200,410✔
3254
void LibMesh::build_eqn_sys()
200,410✔
3255
{
3256
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
3257
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3258
  libMesh::ExplicitSystem& eq_sys =
200,410✔
3259
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
1,002,050✔
3260
}
801,640✔
3261

3262
// intialize from mesh file
3263
void LibMesh::initialize()
400,820✔
3264
{
3265
  if (!settings::libmesh_comm) {
3266
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
167,856✔
3267
                "communicator.");
3268
  }
167,856✔
3269

167,856✔
3270
  // assuming that unstructured meshes used in OpenMC are 3D
167,856✔
3271
  n_dimension_ = 3;
3272

3273
  if (length_multiplier_ > 0.0) {
3274
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
839,280✔
3275
  }
167,856✔
3276
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
167,856✔
3277
  // Otherwise assume that it is prepared by its owning application
3278
  if (unique_m_) {
3279
    m_->prepare_for_use();
3280
  }
335,712✔
3281

167,856✔
3282
  // ensure that the loaded mesh is 3 dimensional
3283
  if (m_->mesh_dimension() != n_dimension_) {
7,307,001✔
3284
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3285
                            "mesh is not a 3D mesh.",
7,307,001✔
3286
      filename_));
7,307,001✔
3287
  }
1,012,923✔
3288

3289
  for (int i = 0; i < num_threads(); i++) {
6,294,078✔
3290
    pl_.emplace_back(m_->sub_point_locator());
3291
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3292
    pl_.back()->enable_out_of_mesh_mode();
3293
  }
20✔
3294

3295
  // store first element in the mesh to use as an offset for bin indices
3296
  auto first_elem = *m_->elements_begin();
3297
  first_element_id_ = first_elem->id();
20✔
3298

20✔
3299
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3300
  // contiguous in ID space, so we need to map from bin indices (defined over
3301
  // active elements) to global dof ids
3302
  if (adaptive_) {
239,732✔
3303
    bin_to_elem_map_.reserve(m_->n_active_elem());
239,712✔
3304
    elem_to_bin_map_.resize(m_->n_elem(), -1);
239,712✔
3305
    for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
239,712✔
3306
         it++) {
3307
      auto elem = *it;
3308

3309
      bin_to_elem_map_.push_back(elem->id());
1,198,560✔
3310
      elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
239,712✔
3311
    }
239,712✔
3312
  }
3313

3314
  // bounding box for the mesh for quick rejection checks
3315
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
239,712✔
3316
  libMesh::Point ll = bbox_.min();
3317
  libMesh::Point ur = bbox_.max();
3318
  lower_left_ = {ll(0), ll(1), ll(2)};
239,712✔
3319
  upper_right_ = {ur(0), ur(1), ur(2)};
239,712✔
3320
}
239,712✔
3321

20✔
3322
// Sample position within a tet for LibMesh type tets
3323
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
260,007,978✔
3324
{
3325
  const auto& elem = get_element_from_bin(bin);
3326
  // Get tet vertex coordinates from LibMesh
3327
  std::array<Position, 4> tet_verts;
3328
  for (int i = 0; i < elem.n_nodes(); i++) {
3329
    auto node_ref = elem.node_ref(i);
3330
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
260,007,978✔
3331
  }
260,007,978✔
3332
  // Samples position within tet using Barycentric coordinates
260,007,978✔
3333
  return this->sample_tet(tet_verts, seed);
3334
}
3335

3336
Position LibMesh::centroid(int bin) const
3337
{
3338
  const auto& elem = this->get_element_from_bin(bin);
3339
  auto centroid = elem.vertex_average();
260,007,978✔
3340
  return {centroid(0), centroid(1), centroid(2)};
260,007,978✔
3341
}
260,007,978✔
3342

3343
int LibMesh::n_vertices() const
3344
{
3345
  return m_->n_nodes();
3346
}
3347

3348
Position LibMesh::vertex(int vertex_id) const
3349
{
260,007,978✔
3350
  const auto node_ref = m_->node_ref(vertex_id);
260,007,978✔
3351
  return {node_ref(0), node_ref(1), node_ref(2)};
3352
}
260,007,978✔
3353

3354
std::vector<int> LibMesh::connectivity(int elem_id) const
421,084,473✔
3355
{
442,748,125✔
3356
  std::vector<int> conn;
281,671,630✔
3357
  const auto* elem_ptr = m_->elem_ptr(elem_id);
260,007,978✔
3358
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3359
    conn.push_back(elem_ptr->node_id(i));
3360
  }
3361
  return conn;
3362
}
3363

3364
std::string LibMesh::library() const
3365
{
3366
  return mesh_lib_type;
3367
}
3368

3369
int LibMesh::n_bins() const
3370
{
3371
  return m_->n_active_elem();
3372
}
3373

3374
int LibMesh::n_surface_bins() const
3375
{
3376
  int n_bins = 0;
3377
  for (int i = 0; i < this->n_bins(); i++) {
3378
    const libMesh::Elem& e = get_element_from_bin(i);
3379
    n_bins += e.n_faces();
3380
    // if this is a boundary element, it will only be visited once,
3381
    // the number of surface bins is incremented to
3382
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3383
      // null neighbor pointer indicates a boundary face
3384
      if (!neighbor_ptr) {
3385
        n_bins++;
3386
      }
815,424✔
3387
    }
3388
  }
815,424✔
3389
  return n_bins;
815,424✔
3390
}
3391

3392
void LibMesh::add_score(const std::string& var_name)
3393
{
815,424✔
3394
  if (adaptive_) {
3395
    warning(fmt::format(
3396
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
266,541,768✔
3397
      this->id_));
3398

266,541,768✔
3399
    return;
266,541,768✔
3400
  }
3401

3402
  if (!equation_systems_) {
266,541,768✔
3403
    build_eqn_sys();
3404
  }
3405

572,122✔
3406
  // check if this is a new variable
3407
  std::string value_name = var_name + "_mean";
572,122✔
3408
  if (!variable_map_.count(value_name)) {
3409
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3410
    auto var_num =
572,122✔
3411
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3412
    variable_map_[value_name] = var_num;
3413
  }
267,317,815✔
3414

3415
  std::string std_dev_name = var_name + "_std_dev";
267,317,815✔
3416
  // check if this is a new variable
3417
  if (!variable_map_.count(std_dev_name)) {
3418
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3419
    auto var_num =
3420
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3421
    variable_map_[std_dev_name] = var_num;
3422
  }
3423
}
3424

3425
void LibMesh::remove_scores()
3426
{
3427
  if (equation_systems_) {
3428
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3429
    eqn_sys.clear();
3430
    variable_map_.clear();
3431
  }
3432
}
3433

3434
void LibMesh::set_score_data(const std::string& var_name,
3435
  const vector<double>& values, const vector<double>& std_dev)
3436
{
3437
  if (adaptive_) {
3438
    warning(fmt::format(
3439
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3440
      this->id_));
3441

3442
    return;
3443
  }
3444

3445
  if (!equation_systems_) {
3446
    build_eqn_sys();
3447
  }
3448

3449
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3450

3451
  if (!eqn_sys.is_initialized()) {
3452
    equation_systems_->init();
3453
  }
3454

3455
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3456

3457
  // look up the value variable
3458
  std::string value_name = var_name + "_mean";
3459
  unsigned int value_num = variable_map_.at(value_name);
3460
  // look up the std dev variable
3461
  std::string std_dev_name = var_name + "_std_dev";
3462
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3463

845,761✔
3464
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3465
       it++) {
845,761✔
3466
    if (!(*it)->active()) {
3467
      continue;
3468
    }
86,199✔
3469

3470
    auto bin = get_bin_from_element(*it);
3471

3472
    // set value
3473
    vector<libMesh::dof_id_type> value_dof_indices;
86,199✔
3474
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3475
    assert(value_dof_indices.size() == 1);
86,199✔
3476
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
86,199✔
3477

86,199✔
3478
    // set std dev
3479
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3480
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3481
    assert(std_dev_dof_indices.size() == 1);
172,398✔
3482
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3483
  }
3484
}
203,856✔
3485

3486
void LibMesh::write(const std::string& filename) const
3487
{
3488
  if (adaptive_) {
203,856✔
3489
    warning(fmt::format(
3490
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3491
      this->id_));
203,856✔
3492

203,856✔
3493
    return;
203,856✔
3494
  }
3495

3496
  write_message(fmt::format(
3497
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3498
  libMesh::ExodusII_IO exo(*m_);
203,856✔
3499
  std::set<std::string> systems_out = {eq_system_name_};
1,019,280✔
3500
  exo.write_discontinuous_exodusII(
815,424✔
3501
    filename + ".e", *equation_systems_, &systems_out);
3502
}
3503

203,856✔
3504
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
203,856✔
3505
  vector<int>& bins, vector<double>& lengths) const
3506
{
3507
  // TODO: Implement triangle crossings here
3508
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3509
}
3510

3511
int LibMesh::get_bin(Position r) const
3512
{
3513
  // look-up a tet using the point locator
3514
  libMesh::Point p(r.x, r.y, r.z);
3515

3516
  // quick rejection check
3517
  if (!bbox_.contains_point(p)) {
3518
    return -1;
3519
  }
3520

3521
  const auto& point_locator = pl_.at(thread_num());
3522

3523
  const auto elem_ptr = (*point_locator)(p);
3524
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3525
}
3526

3527
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3528
{
3529
  int bin =
3530
    adaptive_ ? elem_to_bin_map_[elem->id()] : elem->id() - first_element_id_;
3531
  if (bin >= n_bins() || bin < 0) {
3532
    fatal_error(fmt::format("Invalid bin: {}", bin));
3533
  }
3534
  return bin;
3535
}
3536

3537
std::pair<vector<double>, vector<double>> LibMesh::plot(
3538
  Position plot_ll, Position plot_ur) const
3539
{
3540
  return {};
3541
}
3542

3543
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3544
{
3545
  return adaptive_ ? m_->elem_ref(bin_to_elem_map_.at(bin)) : m_->elem_ref(bin);
3546
}
3547

3548
double LibMesh::volume(int bin) const
3549
{
3550
  return this->get_element_from_bin(bin).volume();
3551
}
3552

3553
#endif // LIBMESH
3554

3555
//==============================================================================
3556
// Non-member functions
3557
//==============================================================================
3558

3559
void read_meshes(pugi::xml_node root)
3560
{
3561
  std::unordered_set<int> mesh_ids;
3562

3563
  for (auto node : root.children("mesh")) {
3564
    // Check to make sure multiple meshes in the same file don't share IDs
3565
    int id = std::stoi(get_node_value(node, "id"));
3566
    if (contains(mesh_ids, id)) {
3567
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
3568
                              "'{}' in the same input file",
3569
        id));
3570
    }
3571
    mesh_ids.insert(id);
3572

3573
    // If we've already read a mesh with the same ID in a *different* file,
3574
    // assume it is the same here
3575
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3576
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
3577
      continue;
3578
    }
3579

3580
    std::string mesh_type;
3581
    if (check_for_node(node, "type")) {
3582
      mesh_type = get_node_value(node, "type", true, true);
3583
    } else {
3584
      mesh_type = "regular";
3585
    }
3586

3587
    // determine the mesh library to use
3588
    std::string mesh_lib;
3589
    if (check_for_node(node, "library")) {
3590
      mesh_lib = get_node_value(node, "library", true, true);
3591
    }
3592

3593
    // Read mesh and add to vector
3594
    if (mesh_type == RegularMesh::mesh_type) {
3595
      model::meshes.push_back(make_unique<RegularMesh>(node));
3596
    } else if (mesh_type == RectilinearMesh::mesh_type) {
3597
      model::meshes.push_back(make_unique<RectilinearMesh>(node));
3598
    } else if (mesh_type == CylindricalMesh::mesh_type) {
3599
      model::meshes.push_back(make_unique<CylindricalMesh>(node));
3600
    } else if (mesh_type == SphericalMesh::mesh_type) {
3601
      model::meshes.push_back(make_unique<SphericalMesh>(node));
3602
#ifdef DAGMC
3603
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3604
               mesh_lib == MOABMesh::mesh_lib_type) {
3605
      model::meshes.push_back(make_unique<MOABMesh>(node));
3606
#endif
3607
#ifdef LIBMESH
3608
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3609
               mesh_lib == LibMesh::mesh_lib_type) {
3610
      model::meshes.push_back(make_unique<LibMesh>(node));
3611
#endif
3612
    } else if (mesh_type == UnstructuredMesh::mesh_type) {
3613
      fatal_error("Unstructured mesh support is not enabled or the mesh "
3614
                  "library is invalid.");
3615
    } else {
3616
      fatal_error("Invalid mesh type: " + mesh_type);
3617
    }
3618

3619
    // Map ID to position in vector
3620
    model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3621
  }
3622
}
3623

3624
void meshes_to_hdf5(hid_t group)
3625
{
3626
  // Write number of meshes
3627
  hid_t meshes_group = create_group(group, "meshes");
3628
  int32_t n_meshes = model::meshes.size();
3629
  write_attribute(meshes_group, "n_meshes", n_meshes);
3630

3631
  if (n_meshes > 0) {
3632
    // Write IDs of meshes
3633
    vector<int> ids;
3634
    for (const auto& m : model::meshes) {
3635
      m->to_hdf5(meshes_group);
3636
      ids.push_back(m->id_);
3637
    }
23✔
3638
    write_attribute(meshes_group, "ids", ids);
3639
  }
3640

3641
  close_group(meshes_group);
23✔
3642
}
23✔
3643

23✔
3644
void free_memory_mesh()
23✔
3645
{
3646
  model::meshes.clear();
3647
  model::mesh_map.clear();
3648
}
3649

3650
extern "C" int n_meshes()
3651
{
3652
  return model::meshes.size();
3653
}
3654

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

© 2026 Coveralls, Inc