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

openmc-dev / openmc / 15568616621

10 Jun 2025 07:34PM UTC coverage: 85.154% (-0.004%) from 85.158%
15568616621

Pull #3423

github

web-flow
Merge 1a7e5c8cc into f796fa04e
Pull Request #3423: Fix raytrace infinite loop.

2 of 3 new or added lines in 1 file covered. (66.67%)

114 existing lines in 1 file now uncovered.

52352 of 61479 relevant lines covered (85.15%)

36651425.29 hits per line

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

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

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

168
    // Found the desired material; accumulate volume
169
    if (current_val == index_material) {
2,416,997✔
170
#pragma omp atomic
1,318,023✔
171
      this->volumes(index_elem, slot) += volume;
2,415,647✔
172
      return;
2,415,647✔
173
    }
174

175
    // Slot appears to be empty; attempt to claim
176
    if (current_val == EMPTY) {
1,350✔
177
      // Attempt compare-and-swap from EMPTY to index_material
178
      int32_t expected_val = EMPTY;
1,350✔
179
      bool claimed_slot =
180
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,350✔
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,350✔
185
#pragma omp atomic
742✔
186
        this->volumes(index_elem, slot) += volume;
1,350✔
187
        return;
1,350✔
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,673✔
234
{
235
  // Read mesh id
236
  id_ = std::stoi(get_node_value(node, "id"));
2,673✔
237
  if (check_for_node(node, "name"))
2,673✔
238
    name_ = get_node_value(node, "name");
16✔
239
}
2,673✔
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,
154✔
281
  int32_t* materials, double* volumes) const
282
{
283
  if (mpi::master) {
154✔
284
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
154✔
285
  }
286
  write_message(7, "Number of mesh elements = {}", n_bins());
154✔
287
  write_message(7, "Number of rays (x) = {}", nx);
154✔
288
  write_message(7, "Number of rays (y) = {}", ny);
154✔
289
  write_message(7, "Number of rays (z) = {}", nz);
154✔
290
  int64_t n_total = static_cast<int64_t>(nx) * ny +
154✔
291
                    static_cast<int64_t>(ny) * nz +
154✔
292
                    static_cast<int64_t>(nx) * nz;
154✔
293
  write_message(7, "Total number of rays = {}", n_total);
154✔
294
  write_message(7, "Table size per mesh element = {}", table_size);
154✔
295

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

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

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

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

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

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

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

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

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

333
      // Determine width of rays and number of rays in other directions
334
      int ax1 = (axis + 1) % 3;
210✔
335
      int ax2 = (axis + 2) % 3;
210✔
336
      double min1 = bbox.min()[ax1];
210✔
337
      double min2 = bbox.min()[ax2];
210✔
338
      double d1 = width[ax1];
210✔
339
      double d2 = width[ax2];
210✔
340
      int n1 = n_rays[ax1];
210✔
341
      int n2 = n_rays[ax2];
210✔
342
      if (n1 == 0 || n2 == 0) {
210✔
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;
160✔
349
      int remainder = n1 % mpi::n_procs;
160✔
350
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
160✔
351
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
160✔
352
      int i1_end = i1_start + n1_local;
160✔
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) {
8,395✔
357
        for (int i2 = 0; i2 < n2; ++i2) {
470,510✔
358
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
462,275✔
359
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
462,275✔
360

361
          p.from_source(&site);
462,275✔
362

363
          // Determine particle's location
364
          if (!exhaustive_find_cell(p)) {
462,275✔
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)
422,345✔
371
            p.cell_born() = p.lowest_coord().cell;
422,345✔
372

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

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

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

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

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

396
            // Add volumes to any mesh elements that were crossed
397
            int i_material = p.material();
869,285✔
398
            if (i_material != C_NONE) {
869,285✔
399
              i_material = model::materials[i_material]->id();
840,855✔
400
            }
401
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
1,967,920✔
402
              int mesh_index = bins[i_bin];
1,098,635✔
403
              double length = distance * length_fractions[i_bin];
1,098,635✔
404

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

409
            if (distance == max_distance)
869,285✔
410
              break;
422,345✔
411

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

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

422
            if (boundary.lattice_translation[0] != 0 ||
446,940✔
423
                boundary.lattice_translation[1] != 0 ||
893,880✔
424
                boundary.lattice_translation[2] != 0) {
446,940✔
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()};
446,940✔
430
              p.cross_surface(*surf);
446,940✔
431
            }
432
          }
446,940✔
433
        }
434
      }
435
    }
436
  }
70✔
437

438
  // Check for errors
439
  if (out_of_model) {
154✔
440
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
441
  } else if (result.table_full()) {
143✔
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();
143✔
448

449
#ifdef OPENMC_MPI
450
  // Combine results from multiple MPI processes
451
  if (mpi::n_procs > 1) {
65✔
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;
65✔
486
#else
487
  double t_mpi = 0.0;
78✔
488
#endif
489

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

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

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

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

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

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

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

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

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

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

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

554
  if (n_dimension_ > 2) {
5,118,856✔
555
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,207,880✔
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,323✔
564
{
565
  // because method is const, shape_ is const as well and can't be adapted
566
  auto tmp_shape = shape_;
2,323✔
567
  return xt::adapt(tmp_shape, {n_dimension_});
4,646✔
568
}
569

570
Position StructuredMesh::sample_element(
1,413,951✔
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,951✔
575
  double x_max = positive_grid_boundary(ijk, 0);
1,413,951✔
576

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

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

583
  return {x_min + (x_max - x_min) * prn(seed),
1,413,951✔
584
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,413,951✔
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,136,988,869✔
779
  Position r, bool& in_mesh) const
780
{
781
  MeshIndex ijk;
782
  in_mesh = true;
1,136,988,869✔
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;
99,948,864✔
788
  }
789
  return ijk;
1,136,988,869✔
790
}
791

792
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,675,258,843✔
793
{
794
  switch (n_dimension_) {
1,675,258,843✔
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,595,449,773✔
800
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,595,449,773✔
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,075,040✔
807
{
808
  MeshIndex ijk;
809
  if (n_dimension_ == 1) {
14,075,040✔
810
    ijk[0] = bin + 1;
275✔
811
  } else if (n_dimension_ == 2) {
14,074,765✔
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,060,124✔
815
    ijk[0] = bin % shape_[0] + 1;
14,060,124✔
816
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
14,060,124✔
817
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
14,060,124✔
818
  }
819
  return ijk;
14,075,040✔
820
}
821

822
int StructuredMesh::get_bin(Position r) const
241,916,643✔
823
{
824
  // Determine indices
825
  bool in_mesh;
826
  MeshIndex ijk = get_indices(r, in_mesh);
241,916,643✔
827
  if (!in_mesh)
241,916,643✔
828
    return -1;
20,441,094✔
829

830
  // Convert indices to bin
831
  return get_bin_from_indices(ijk);
221,475,549✔
832
}
833

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

840
int StructuredMesh::n_surface_bins() const
384✔
841
{
842
  return 4 * n_dimension_ * n_bins();
384✔
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(
897,581,973✔
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();
897,581,973✔
915
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
897,581,973✔
916
    return;
8,725,900✔
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;
888,856,073✔
921
  Position local_r = local_coords(r0);
888,856,073✔
922

923
  const int n = n_dimension_;
888,856,073✔
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};
888,856,073✔
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);
888,856,073✔
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) {
888,856,073✔
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,776,419,580✔
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) {
739,569,656✔
952

953
    if (in_mesh) {
1,627,779,446✔
954

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

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

964
      // update position and leave, if we have reached end position
965
      traveled_distance = distances[k].distance;
1,542,273,285✔
966
      if (traveled_distance >= total_distance)
1,542,273,285✔
967
        return;
808,919,782✔
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);
733,353,503✔
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;
733,353,503✔
976
      distances[k] =
733,353,503✔
977
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
733,353,503✔
978

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

982
      // If we are still inside the mesh, tally inward current for the next
983
      // cell
984
      if (in_mesh)
733,353,503✔
985
        tally.surface(ijk, k, !distances[k].max_surface, true);
718,647,452✔
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 {-1};
85,506,161✔
993
      for (int k = 0; k < n; ++k) {
339,878,388✔
994
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
347,822,826✔
995
            (distances[k].distance > traveled_distance)) {
93,450,599✔
996
          traveled_distance = distances[k].distance;
88,503,165✔
997
          k_max = k;
88,503,165✔
998
        }
999
      }
1000
      // Assure some distance is traveled
1001
      if (k_max == -1)
85,506,161✔
NEW
1002
        traveled_distance += TINY_BIT;
×
1003
      // If r1 is not inside the mesh, exit here
1004
      if (traveled_distance >= total_distance)
85,506,161✔
1005
        return;
79,290,008✔
1006

1007
      // Calculate the new cell index and update all distances to next
1008
      // surfaces.
1009
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,216,153✔
1010
      for (int k = 0; k < n; ++k) {
24,654,457✔
1011
        distances[k] =
18,438,304✔
1012
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
18,438,304✔
1013
      }
1014

1015
      // If inside the mesh, Tally inward current
1016
      if (in_mesh)
6,216,153✔
1017
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
6,003,204✔
1018
    }
1019
  }
1020
}
1021

121,600,200✔
1022
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1023
  vector<int>& bins, vector<double>& lengths) const
1024
{
1025

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

121,600,200✔
1041
    const StructuredMesh* mesh;
1042
    vector<int>& bins;
1043
    vector<double>& lengths;
1044
  };
1045

1046
  // Perform the mesh raytrace with the helper class.
121,600,200✔
1047
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1048
}
1049

1050
void StructuredMesh::surface_bins_crossed(
121,600,200✔
1051
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1052
{
1053

1054
  // Helper tally class.
121,600,200✔
1055
  // stores a pointer to the mesh class and a reference to the bins parameter.
×
1056
  // Performs the actual tally through the surface method.
×
1057
  struct SurfaceAggregator {
1058
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
×
1059
      : mesh(_mesh), bins(_bins)
1060
    {}
1061
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
1062
    {
243,200,400✔
1063
      int i_bin =
484,717,668✔
1064
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
363,117,468✔
1065
      if (max)
1066
        i_bin += 2;
1067
      if (inward)
1068
        i_bin += 1;
32,023,288✔
1069
      bins.push_back(i_bin);
1070
    }
153,623,488✔
1071
    void track(const MeshIndex& idx, double l) const {}
1072

1073
    const StructuredMesh* mesh;
151,657,653✔
1074
    vector<int>& bins;
151,657,653✔
1075
  };
1076

1077
  // Perform the mesh raytrace with the helper class.
151,657,653✔
1078
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
151,657,653✔
1079
}
1080

1081
//==============================================================================
1082
// RegularMesh implementation
151,657,653✔
1083
//==============================================================================
151,657,653✔
1084

119,857,654✔
1085
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1086
{
1087
  // Determine number of dimensions for mesh
1088
  if (!check_for_node(node, "dimension")) {
31,799,999✔
1089
    fatal_error("Must specify <dimension> on a regular mesh.");
1090
  }
1091

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

1099
  // Check that dimensions are all greater than zero
1100
  if (xt::any(shape <= 0)) {
1101
    fatal_error("All entries on the <dimension> element for a tally "
31,799,999✔
1102
                "mesh must be positive.");
30,521,015✔
1103
  }
1104

1105
  // Check for lower-left coordinates
1106
  if (check_for_node(node, "lower_left")) {
1107
    // Read mesh lower-left corner location
1108
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1109
  } else {
1,965,835✔
1110
    fatal_error("Must specify <lower_left> on a mesh.");
7,541,315✔
1111
  }
7,684,821✔
1112

2,109,341✔
1113
  // Make sure lower_left and dimension match
2,050,249✔
1114
  if (shape.size() != lower_left_.size()) {
2,050,249✔
1115
    fatal_error("Number of entries on <lower_left> must be the same "
1116
                "as the number of entries on <dimension>.");
1117
  }
1118

1,965,835✔
UNCOV
1119
  if (check_for_node(node, "width")) {
×
1120
    // Make sure one of upper-right or width were specified
1121
    if (check_for_node(node, "upper_right")) {
1,965,835✔
1122
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
1,742,546✔
1123
    }
1124

1125
    width_ = get_node_xarray<double>(node, "width");
1126

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

223,289✔
1134
    // Check for negative widths
200,376✔
1135
    if (xt::any(width_ < 0.0)) {
1136
      fatal_error("Cannot have a negative <width> on a tally mesh.");
1137
    }
1138

775,981,773✔
1139
    // Set width and upper right coordinate
1140
    upper_right_ = xt::eval(lower_left_ + shape * width_);
1141

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

1145
    // Check to ensure width has same dimensions
1146
    auto n = upper_right_.size();
1147
    if (n != lower_left_.size()) {
1148
      fatal_error("Number of entries on <upper_right> must be the "
775,981,773✔
1149
                  "same as the number of entries on <lower_left>.");
775,981,773✔
1150
    }
8,725,900✔
1151

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

767,255,873✔
1158
    // Set width
1159
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1160
  } else {
1161
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
1162
  }
1163

767,255,873✔
1164
  // Set material volumes
1165
  volume_frac_ = 1.0 / xt::prod(shape)();
1166

1167
  element_volume_ = 1.0;
767,255,873✔
1168
  for (int i = 0; i < n_dimension_; i++) {
1169
    element_volume_ *= width_[i];
1170
  }
1171
}
767,255,873✔
1172

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

1178
const std::string RegularMesh::mesh_type = "regular";
1179

1,533,219,180✔
1180
std::string RegularMesh::get_mesh_type() const
2,147,483,647✔
1181
{
2,147,483,647✔
1182
  return mesh_type;
1183
}
1184

1185
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
707,546,368✔
1186
{
1187
  return lower_left_[i] + ijk[i] * width_[i];
1,474,155,958✔
1188
}
1189

1190
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,390,615,632✔
1191
{
1,390,615,632✔
1192
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1193
}
1194

1,390,615,632✔
1195
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1,390,615,632✔
1196
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1197
  double l) const
1198
{
1199
  MeshDistance d;
1,390,615,632✔
1200
  d.next_index = ijk[i];
1,390,615,632✔
1201
  if (std::abs(u[i]) < FP_PRECISION)
689,062,128✔
1202
    return d;
1203

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

701,553,504✔
1215
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1216
  Position plot_ll, Position plot_ur) const
1217
{
1218
  // Figure out which axes lie in the plane of the plot.
701,553,504✔
1219
  array<int, 2> axes {-1, -1};
688,126,437✔
1220
  if (plot_ur.z == plot_ll.z) {
1221
    axes[0] = 0;
1222
    if (n_dimension_ > 1)
1223
      axes[1] = 1;
1224
  } else if (plot_ur.y == plot_ll.y) {
1225
    axes[0] = 0;
1226
    if (n_dimension_ > 2)
83,540,326✔
1227
      axes[1] = 2;
332,337,073✔
1228
  } else if (plot_ur.x == plot_ll.x) {
340,138,005✔
1229
    if (n_dimension_ > 1)
91,341,258✔
1230
      axes[0] = 1;
86,452,916✔
1231
    if (n_dimension_ > 2)
86,452,916✔
1232
      axes[1] = 2;
1233
  } else {
1234
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1235
  }
83,540,326✔
UNCOV
1236

×
1237
  // Get the coordinates of the mesh lines along both of the axes.
1238
  array<vector<double>, 2> axis_lines;
83,540,326✔
1239
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
77,547,462✔
1240
    int axis = axes[i_ax];
1241
    if (axis == -1)
1242
      continue;
1243
    auto& lines {axis_lines[i_ax]};
5,992,864✔
1244

23,865,889✔
1245
    double coord = lower_left_[axis];
17,873,025✔
1246
    for (int i = 0; i < shape_[axis] + 1; ++i) {
17,873,025✔
1247
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1248
        lines.push_back(coord);
1249
      coord += width_[axis];
1250
    }
5,992,864✔
1251
  }
5,802,828✔
1252

1253
  return {axis_lines[0], axis_lines[1]};
1254
}
1255

1256
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
775,981,773✔
1257
{
1258
  write_dataset(mesh_group, "dimension", get_x_shape());
1259
  write_dataset(mesh_group, "lower_left", lower_left_);
1260
  write_dataset(mesh_group, "upper_right", upper_right_);
1261
  write_dataset(mesh_group, "width", width_);
1262
}
1263

1264
xt::xtensor<double, 1> RegularMesh::count_sites(
775,981,773✔
1265
  const SourceSite* bank, int64_t length, bool* outside) const
1266
{
775,981,773✔
1267
  // Determine shape of array for counts
775,981,773✔
1268
  std::size_t m = this->n_bins();
1,395,482,769✔
1269
  vector<std::size_t> shape = {m};
1,391,261,904✔
1270

1271
  // Create array of zeros
1,391,261,904✔
1272
  xt::xarray<double> cnt {shape, 0.0};
1,391,261,904✔
1273
  bool outside_ = false;
1,391,261,904✔
1274

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

1278
    // determine scoring bin for entropy mesh
1279
    int mesh_bin = get_bin(site.r);
1280

1281
    // if outside mesh, skip particle
775,981,773✔
1282
    if (mesh_bin < 0) {
775,981,773✔
1283
      outside_ = true;
1284
      continue;
121,600,200✔
1285
    }
1286

1287
    // Add to appropriate bin
1288
    cnt(mesh_bin) += site.wgt;
1289
  }
1290

1291
  // Create copy of count data. Since ownership will be acquired by xtensor,
1292
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
121,600,200✔
1293
  // warnings.
121,600,200✔
1294
  int total = cnt.size();
121,600,200✔
1295
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
62,521,390✔
1296

1297
#ifdef OPENMC_MPI
1298
  // collect values from all processors
62,521,390✔
1299
  MPI_Reduce(
62,521,390✔
1300
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
31,225,479✔
1301

62,521,390✔
1302
  // Check if there were sites outside the mesh for any processor
30,721,391✔
1303
  if (outside) {
62,521,390✔
1304
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
62,521,390✔
1305
  }
151,657,653✔
1306
#else
1307
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1308
  if (outside)
1309
    *outside = outside_;
1310
#endif
1311

1312
  // Adapt reduced values in array back into an xarray
121,600,200✔
1313
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
121,600,200✔
1314
  xt::xarray<double> counts = arr;
1315

1316
  return counts;
1317
}
1318

1319
double RegularMesh::volume(const MeshIndex& ijk) const
1,821✔
1320
{
1321
  return element_volume_;
1322
}
1,821✔
UNCOV
1323

×
1324
//==============================================================================
1325
// RectilinearMesh implementation
1326
//==============================================================================
1,821✔
1327

1,821✔
1328
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
1,821✔
UNCOV
1329
{
×
1330
  n_dimension_ = 3;
1331

1,821✔
1332
  grid_[0] = get_node_array<double>(node, "x_grid");
1333
  grid_[1] = get_node_array<double>(node, "y_grid");
1334
  grid_[2] = get_node_array<double>(node, "z_grid");
1,821✔
UNCOV
1335

×
1336
  if (int err = set_grid()) {
1337
    fatal_error(openmc_err_msg);
1338
  }
1339
}
1340

1,821✔
1341
const std::string RectilinearMesh::mesh_type = "rectilinear";
1342

1,821✔
1343
std::string RectilinearMesh::get_mesh_type() const
UNCOV
1344
{
×
1345
  return mesh_type;
1346
}
1347

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

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

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

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

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

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

1,821✔
1400
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
1401
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
1,821✔
1402

6,921✔
1403
  return 0;
5,100✔
1404
}
1405

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

1411
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
1412
  Position plot_ll, Position plot_ur) const
1413
{
1414
  // Figure out which axes lie in the plane of the plot.
3,000✔
1415
  array<int, 2> axes {-1, -1};
1416
  if (plot_ur.z == plot_ll.z) {
3,000✔
1417
    axes = {0, 1};
1418
  } else if (plot_ur.y == plot_ll.y) {
1419
    axes = {0, 2};
1,440,839,920✔
1420
  } else if (plot_ur.x == plot_ll.x) {
1421
    axes = {1, 2};
1,440,839,920✔
1422
  } else {
1423
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1424
  }
1,377,957,792✔
1425

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

1432
    for (auto coord : grid_[axis]) {
1433
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
2,147,483,647✔
1434
        lines.push_back(coord);
2,147,483,647✔
1435
    }
2,147,483,647✔
1436
  }
1,458,182✔
1437

1438
  return {axis_lines[0], axis_lines[1]};
2,147,483,647✔
1439
}
2,147,483,647✔
1440

1,436,598,067✔
1441
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
1,436,598,067✔
1442
{
1,395,624,805✔
1443
  write_dataset(mesh_group, "x_grid", grid_[0]);
1,373,715,939✔
1444
  write_dataset(mesh_group, "y_grid", grid_[1]);
1,373,715,939✔
1445
  write_dataset(mesh_group, "z_grid", grid_[2]);
1446
}
2,147,483,647✔
1447

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

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

22✔
1458
//==============================================================================
×
1459
// CylindricalMesh implementation
×
1460
//==============================================================================
×
1461

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

1471
  if (int err = set_grid()) {
1472
    fatal_error(openmc_err_msg);
22✔
1473
  }
66✔
1474
}
44✔
1475

44✔
UNCOV
1476
const std::string CylindricalMesh::mesh_type = "cylindrical";
×
1477

44✔
1478
std::string CylindricalMesh::get_mesh_type() const
1479
{
44✔
1480
  return mesh_type;
286✔
1481
}
242✔
1482

242✔
1483
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
242✔
1484
  Position r, bool& in_mesh) const
1485
{
1486
  r = local_coords(r);
1487

44✔
1488
  Position mapped_r;
22✔
1489
  mapped_r[0] = std::hypot(r.x, r.y);
1490
  mapped_r[2] = r[2];
1,857✔
1491

1492
  if (mapped_r[0] < FP_PRECISION) {
1,857✔
1493
    mapped_r[1] = 0.0;
1,857✔
1494
  } else {
1,857✔
1495
    mapped_r[1] = std::atan2(r.y, r.x);
1,857✔
1496
    if (mapped_r[1] < 0)
1,857✔
1497
      mapped_r[1] += 2 * M_PI;
1498
  }
8,124✔
1499

1500
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1501

1502
  idx[1] = sanitize_phi(idx[1]);
8,124✔
1503

8,124✔
1504
  return idx;
1505
}
1506

8,124✔
1507
Position CylindricalMesh::sample_element(
8,124✔
1508
  const MeshIndex& ijk, uint64_t* seed) const
1509
{
7,968,133✔
1510
  double r_min = this->r(ijk[0] - 1);
7,960,009✔
1511
  double r_max = this->r(ijk[0]);
1512

1513
  double phi_min = this->phi(ijk[1] - 1);
7,960,009✔
1514
  double phi_max = this->phi(ijk[1]);
1515

1516
  double z_min = this->z(ijk[2] - 1);
7,960,009✔
UNCOV
1517
  double z_max = this->z(ijk[2]);
×
UNCOV
1518

×
1519
  double r_min_sq = r_min * r_min;
1520
  double r_max_sq = r_max * r_max;
1521
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
1522
  double phi = uniform_distribution(phi_min, phi_max, seed);
7,960,009✔
1523
  double z = uniform_distribution(z_min, z_max, seed);
1524

1525
  double x = r * std::cos(phi);
1526
  double y = r * std::sin(phi);
1527

1528
  return origin_ + Position(x, y, z);
8,124✔
1529
}
8,124✔
1530

1531
double CylindricalMesh::find_r_crossing(
1532
  const Position& r, const Direction& u, double l, int shell) const
1533
{
3,900✔
1534

3,900✔
1535
  if ((shell < 0) || (shell > shape_[0]))
1536
    return INFTY;
1537

3,900✔
1538
  // solve r.x^2 + r.y^2 == r0^2
3,900✔
1539
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1540
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1541

4,224✔
1542
  const double r0 = grid_[0][shell];
4,224✔
1543
  if (r0 == 0.0)
4,224✔
1544
    return INFTY;
1545

1546
  const double denominator = u.x * u.x + u.y * u.y;
1547

8,124✔
1548
  // Direction of flight is in z-direction. Will never intersect r.
8,124✔
1549
  if (std::abs(denominator) < FP_PRECISION)
1550
    return INFTY;
16,248✔
1551

8,124✔
1552
  // inverse of dominator to help the compiler to speed things up
1553
  const double inv_denominator = 1.0 / denominator;
7,452,165✔
1554

1555
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
7,452,165✔
1556
  double c = r.x * r.x + r.y * r.y - r0 * r0;
1557
  double D = p * p - c * inv_denominator;
1558

1559
  if (D < 0.0)
1560
    return INFTY;
1561

1562
  D = std::sqrt(D);
103✔
1563

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

103✔
1568
  if (-p - D > l)
103✔
1569
    return -p - D;
1570
  if (-p + D > l)
103✔
UNCOV
1571
    return -p + D;
×
1572

1573
  return INFTY;
103✔
1574
}
1575

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

28,486,579✔
1583
  shell = sanitize_phi(shell);
1584

1585
  const double p0 = grid_[1][shell];
28,486,579✔
1586

1587
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1588
  // => x(s) * cos(p0) = y(s) * sin(p0)
27,738,792✔
1589
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1590
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1591

27,738,792✔
1592
  const double c0 = std::cos(p0);
1593
  const double s0 = std::sin(p0);
1594

57,597,406✔
1595
  const double denominator = (u.x * s0 - u.y * c0);
1596

1597
  // Check if direction of flight is not parallel to phi surface
1598
  if (std::abs(denominator) > FP_PRECISION) {
57,597,406✔
1599
    const double s = -(r.x * s0 - r.y * c0) / denominator;
57,597,406✔
1600
    // Check if solution is in positive direction of flight and crosses the
57,597,406✔
1601
    // correct phi surface (not -phi)
571,824✔
1602
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
1603
      return s;
57,025,582✔
1604
  }
57,025,582✔
1605

28,486,579✔
1606
  return INFTY;
28,486,579✔
1607
}
28,539,003✔
1608

27,738,792✔
1609
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
27,738,792✔
1610
  const Position& r, const Direction& u, double l, int shell) const
1611
{
57,025,582✔
1612
  MeshDistance d;
1613
  d.next_index = shell;
1614

149✔
1615
  // Direction of flight is within xy-plane. Will never intersect z.
1616
  if (std::abs(u.z) < FP_PRECISION)
149✔
1617
    return d;
149✔
1618

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

UNCOV
1630
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
×
1631
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1632
  double l) const
1633
{
1634
  if (i == 0) {
149✔
1635

149✔
1636
    return std::min(
1637
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
149✔
1638
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
1639

1640
  } else if (i == 1) {
80,100,765✔
1641

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

1647
  } else {
1648
    return find_z_crossing(r0, u, l, ijk[i]);
1649
  }
11✔
1650
}
11✔
1651

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

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

132✔
1685
    return OPENMC_E_INVALID_ARGUMENT;
1686
  }
528✔
1687

396✔
1688
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
1689

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

1695
  return 0;
1696
}
390✔
1697

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

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

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

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

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

1726
  double phi_i = grid_[1][ijk[1] - 1];
47,366,451✔
UNCOV
1727
  double phi_o = grid_[1][ijk[1]];
×
1728

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

23,697,839✔
1732
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
1733
}
1734

47,366,451✔
1735
//==============================================================================
1736
// SphericalMesh implementation
47,366,451✔
1737
//==============================================================================
1738

47,366,451✔
1739
SphericalMesh::SphericalMesh(pugi::xml_node node)
1740
  : PeriodicStructuredMesh {node}
1741
{
88,110✔
1742
  n_dimension_ = 3;
1743

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

88,110✔
1749
  if (int err = set_grid()) {
1750
    fatal_error(openmc_err_msg);
88,110✔
1751
  }
88,110✔
1752
}
1753

88,110✔
1754
const std::string SphericalMesh::mesh_type = "spherical";
88,110✔
1755

88,110✔
1756
std::string SphericalMesh::get_mesh_type() const
88,110✔
1757
{
88,110✔
1758
  return mesh_type;
1759
}
88,110✔
1760

88,110✔
1761
StructuredMesh::MeshIndex SphericalMesh::get_indices(
1762
  Position r, bool& in_mesh) const
88,110✔
1763
{
1764
  r = local_coords(r);
1765

141,838,246✔
1766
  Position mapped_r;
1767
  mapped_r[0] = r.norm();
1768

1769
  if (mapped_r[0] < FP_PRECISION) {
141,838,246✔
1770
    mapped_r[1] = 0.0;
17,677,528✔
1771
    mapped_r[2] = 0.0;
1772
  } else {
1773
    mapped_r[1] = std::acos(r.z / mapped_r.x);
1774
    mapped_r[2] = std::atan2(r.y, r.x);
1775
    if (mapped_r[2] < 0)
1776
      mapped_r[2] += 2 * M_PI;
124,160,718✔
1777
  }
124,160,718✔
1778

7,015,096✔
1779
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1780

117,145,622✔
1781
  idx[1] = sanitize_theta(idx[1]);
1782
  idx[2] = sanitize_phi(idx[2]);
1783

117,145,622✔
1784
  return idx;
58,960✔
1785
}
1786

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

1793
  double theta_min = this->theta(ijk[1] - 1);
117,086,662✔
1794
  double theta_max = this->theta(ijk[1]);
9,633,712✔
1795

1796
  double phi_min = this->phi(ijk[2] - 1);
107,452,950✔
1797
  double phi_max = this->phi(ijk[2]);
1798

1799
  double cos_theta =
107,452,950✔
1800
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
6,469,408✔
1801
  double sin_theta = std::sin(std::acos(cos_theta));
1802
  double phi = uniform_distribution(phi_min, phi_max, seed);
100,983,542✔
1803
  double r_min_cub = std::pow(r_min, 3);
20,133,047✔
1804
  double r_max_cub = std::pow(r_max, 3);
80,850,495✔
1805
  // might be faster to do rejection here?
50,032,807✔
1806
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
1807

30,817,688✔
1808
  double x = r * std::cos(phi) * sin_theta;
1809
  double y = r * std::sin(phi) * sin_theta;
1810
  double z = r * cos_theta;
73,733,814✔
1811

1812
  return origin_ + Position(x, y, z);
1813
}
1814

73,733,814✔
1815
double SphericalMesh::find_r_crossing(
29,760,896✔
1816
  const Position& r, const Direction& u, double l, int shell) const
1817
{
43,972,918✔
1818
  if ((shell < 0) || (shell > shape_[0]))
1819
    return INFTY;
43,972,918✔
1820

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

43,972,918✔
1830
  if (std::abs(c) <= RADIAL_MESH_TOL)
1831
    return INFTY;
1832

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

1842
  return INFTY;
1843
}
36,340,216✔
1844

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

1,118,216✔
1852
  shell = sanitize_theta(shell);
1853

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

1861
  const double cos_t = std::cos(grid_[1][shell]);
35,222,000✔
1862
  const bool sgn = std::signbit(cos_t);
1863
  const double cos_t_2 = cos_t * cos_t;
1864

144,126,246✔
1865
  const double a = cos_t_2 - u.z * u.z;
1866
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1867
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
1868

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

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

36,340,216✔
1883
    // no crossing is possible
1884
    return INFTY;
1885
  }
1886

412✔
1887
  const double p = b / a;
1888
  double D = p * p - c / a;
412✔
1889

412✔
1890
  if (D < 0.0)
412✔
1891
    return INFTY;
1892

1,648✔
1893
  D = std::sqrt(D);
1,236✔
UNCOV
1894

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

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

412✔
UNCOV
1906
  return INFTY;
×
1907
}
UNCOV
1908

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

412✔
UNCOV
1916
  shell = sanitize_phi(shell);
×
1917

1918
  const double p0 = grid_[2][shell];
UNCOV
1919

×
1920
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1921
  // => x(s) * cos(p0) = y(s) * sin(p0)
1922
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
412✔
1923
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1924

824✔
1925
  const double c0 = std::cos(p0);
824✔
1926
  const double s0 = std::sin(p0);
824✔
1927

824✔
1928
  const double denominator = (u.x * s0 - u.y * c0);
1929

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

1939
  return INFTY;
UNCOV
1940
}
×
1941

1942
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
1943
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1944
  double l) const
1945
{
1946

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

363✔
1952
  } else if (i == 1) {
363✔
1953
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
363✔
1954
                      find_theta_crossing(r0, u, l, ijk[i])),
1955
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
792✔
1956
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
1957

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

1966
int SphericalMesh::set_grid()
792✔
1967
{
1968
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1969
    static_cast<int>(grid_[1].size()) - 1,
1970
    static_cast<int>(grid_[2].size()) - 1};
1971

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

1994
    return OPENMC_E_INVALID_ARGUMENT;
1995
  }
67,739,463✔
1996
  if (grid_[2].back() > 2 * PI) {
1997
    set_errmsg("phi-grids for "
1998
               "spherical meshes must end with phi <= 2*pi.");
67,739,463✔
1999
    return OPENMC_E_INVALID_ARGUMENT;
2000
  }
67,739,463✔
2001

67,739,463✔
2002
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
2003
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
67,739,463✔
UNCOV
2004

×
UNCOV
2005
  double r = grid_[0].back();
×
2006
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
2007
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
67,739,463✔
2008

67,739,463✔
2009
  return 0;
67,739,463✔
2010
}
33,878,218✔
2011

2012
int SphericalMesh::get_index_in_direction(double r, int i) const
2013
{
67,739,463✔
2014
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
2015
}
67,739,463✔
2016

67,739,463✔
2017
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
2018
  Position plot_ll, Position plot_ur) const
67,739,463✔
2019
{
2020
  fatal_error("Plot of spherical Mesh not implemented");
2021

110✔
2022
  // Figure out which axes lie in the plane of the plot.
2023
  array<vector<double>, 2> axis_lines;
2024
  return {axis_lines[0], axis_lines[1]};
110✔
2025
}
110✔
2026

2027
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
2028
{
110✔
2029
  write_dataset(mesh_group, "r_grid", grid_[0]);
2030
  write_dataset(mesh_group, "theta_grid", grid_[1]);
110✔
2031
  write_dataset(mesh_group, "phi_grid", grid_[2]);
110✔
2032
  write_dataset(mesh_group, "origin", origin_);
2033
}
2034

110✔
2035
double SphericalMesh::volume(const MeshIndex& ijk) const
110✔
2036
{
110✔
2037
  double r_i = grid_[0][ijk[0] - 1];
110✔
2038
  double r_o = grid_[0][ijk[0]];
110✔
2039

2040
  double theta_i = grid_[1][ijk[1] - 1];
110✔
2041
  double theta_o = grid_[1][ijk[1]];
2042

110✔
2043
  double phi_i = grid_[2][ijk[2] - 1];
110✔
2044
  double phi_o = grid_[2][ijk[2]];
110✔
2045

2046
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
110✔
2047
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
2048
}
2049

441,926,232✔
2050
//==============================================================================
2051
// Helper functions for the C API
2052
//==============================================================================
441,926,232✔
2053

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

395,564,059✔
2063
template<class T>
2064
int check_mesh_type(int32_t index)
395,564,059✔
2065
{
10,586,180✔
2066
  if (int err = check_mesh(index))
2067
    return err;
384,977,879✔
2068

357,140,443✔
2069
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2070
  if (!mesh) {
357,140,443✔
2071
    set_errmsg("This function is not valid for input mesh.");
64,176,541✔
2072
    return OPENMC_E_INVALID_TYPE;
292,963,902✔
2073
  }
176,563,519✔
2074
  return 0;
2075
}
2076

144,237,819✔
2077
template<class T>
2078
bool is_mesh_type(int32_t index)
2079
{
108,467,832✔
2080
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2081
  return mesh;
2082
}
2083

108,467,832✔
2084
//==============================================================================
70,123,416✔
2085
// C API functions
2086
//==============================================================================
38,344,416✔
2087

2088
// Return the type of mesh as a C string
2089
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
2090
{
2091
  if (int err = check_mesh(index))
2092
    return err;
2093

2094
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
2095

38,344,416✔
2096
  return 0;
38,344,416✔
2097
}
38,344,416✔
2098

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

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

37,861,868✔
2123
  return 0;
2124
}
37,861,868✔
2125

10,945,825✔
2126
//! Adds a new unstructured mesh to OpenMC
2127
extern "C" int openmc_add_unstructured_mesh(
26,916,043✔
2128
  const char filename[], const char library[], int* id)
2129
{
2130
  std::string lib_name(library);
26,916,043✔
2131
  std::string mesh_file(filename);
2132
  bool valid_lib = false;
26,916,043✔
2133

5,283,102✔
2134
#ifdef DAGMC
2135
  if (lib_name == MOABMesh::mesh_lib_type) {
21,632,941✔
2136
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
2137
    valid_lib = true;
21,632,941✔
2138
  }
10,154,661✔
2139
#endif
2140

11,478,280✔
2141
#ifdef LIBMESH
2142
  if (lib_name == LibMesh::mesh_lib_type) {
2143
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
110,058,036✔
2144
    valid_lib = true;
2145
  }
2146
#endif
2147

110,058,036✔
2148
  if (!valid_lib) {
70,123,416✔
2149
    set_errmsg(fmt::format("Mesh library {} is not supported "
2150
                           "by this build of OpenMC",
39,934,620✔
2151
      lib_name));
2152
    return OPENMC_E_INVALID_ARGUMENT;
39,934,620✔
2153
  }
2154

2155
  // auto-assign new ID
2156
  model::meshes.back()->set_id(-1);
2157
  *id = model::meshes.back()->id_;
2158

2159
  return 0;
39,934,620✔
2160
}
39,934,620✔
2161

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

22,358,490✔
2174
//! Return the ID of a mesh
2175
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2176
{
330,226,050✔
2177
  if (int err = check_mesh(index))
2178
    return err;
2179
  *id = model::meshes[index]->id_;
2180
  return 0;
2181
}
330,226,050✔
2182

220,963,116✔
2183
//! Set the ID of a mesh
220,963,116✔
2184
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
441,926,232✔
2185
{
2186
  if (int err = check_mesh(index))
109,262,934✔
2187
    return err;
54,233,916✔
2188
  model::meshes[index]->id_ = id;
54,233,916✔
2189
  model::mesh_map[id] = index;
54,233,916✔
2190
  return 0;
108,467,832✔
2191
}
2192

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

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

1,005✔
2213
//! Get the bounding box of a mesh
2,010✔
UNCOV
2214
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
×
2215
{
UNCOV
2216
  if (int err = check_mesh(index))
×
2217
    return err;
2218

1,005✔
UNCOV
2219
  BoundingBox bbox = model::meshes[index]->bounding_box();
×
2220

2221
  // set lower left corner values
×
2222
  ll[0] = bbox.xmin;
2223
  ll[1] = bbox.ymin;
2224
  ll[2] = bbox.zmin;
335✔
UNCOV
2225

×
2226
  // set upper right corner values
2227
  ur[0] = bbox.xmax;
UNCOV
2228
  ur[1] = bbox.ymax;
×
2229
  ur[2] = bbox.zmax;
2230
  return 0;
335✔
UNCOV
2231
}
×
2232

UNCOV
2233
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
×
2234
  int nz, int table_size, int32_t* materials, double* volumes)
2235
{
2236
  if (int err = check_mesh(index))
335✔
2237
    return err;
335✔
2238

2239
  try {
335✔
2240
    model::meshes[index]->material_volumes(
335✔
2241
      nx, ny, nz, table_size, materials, volumes);
335✔
2242
  } catch (const std::exception& e) {
2243
    set_errmsg(e.what());
335✔
2244
    if (starts_with(e.what(), "Mesh")) {
2245
      return OPENMC_E_GEOMETRY;
2246
    } else {
203,218,389✔
2247
      return OPENMC_E_ALLOCATE;
2248
    }
203,218,389✔
2249
  }
2250

UNCOV
2251
  return 0;
×
2252
}
2253

UNCOV
2254
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
×
2255
  Position width, int basis, int* pixels, int32_t* data)
2256
{
2257
  if (int err = check_mesh(index))
2258
    return err;
2259
  const auto& mesh = model::meshes[index].get();
2260

2261
  int pixel_width = pixels[0];
297✔
2262
  int pixel_height = pixels[1];
2263

297✔
2264
  // get pixel size
297✔
2265
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
297✔
2266
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
297✔
2267

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

2290
  // set initial position
6,423✔
UNCOV
2291
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
×
UNCOV
2292
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
×
2293

2294
#pragma omp parallel
6,423✔
2295
  {
2296
    Position r = xyz;
2297

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

2308
  return 0;
1,143✔
2309
}
2310

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

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

×
2331
  // Copy dimension
2332
  mesh->n_dimension_ = n;
143✔
2333
  std::copy(dims, dims + n, mesh->shape_.begin());
2334
  return 0;
191✔
2335
}
2336

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

191✔
2345
  if (m->lower_left_.dimension() == 0) {
2346
    set_errmsg("Mesh parameters have not been set.");
666✔
2347
    return OPENMC_E_ALLOCATE;
2348
  }
666✔
2349

×
2350
  *ll = m->lower_left_.data();
2351
  *ur = m->upper_right_.data();
666✔
2352
  *width = m->width_.data();
666✔
UNCOV
2353
  *n = m->n_dimension_;
×
UNCOV
2354
  return 0;
×
2355
}
2356

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

2365
  if (m->n_dimension_ == -1) {
2366
    set_errmsg("Need to set mesh dimension before setting parameters.");
2367
    return OPENMC_E_UNASSIGNED;
2368
  }
2369

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

268✔
2388
  // Set material volumes
2389

536✔
2390
  // TODO: incorporate this into method in RegularMesh that can be called from
268✔
2391
  // here and from constructor
178✔
2392
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
90✔
2393
  m->element_volume_ = 1.0;
46✔
2394
  for (int i = 0; i < m->n_dimension_; i++) {
44✔
2395
    m->element_volume_ *= m->width_[i];
22✔
2396
  }
22✔
2397

22✔
2398
  return 0;
2399
}
×
2400

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

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

UNCOV
2412
  m->n_dimension_ = 3;
×
UNCOV
2413

×
UNCOV
2414
  m->grid_[0].reserve(nx);
×
2415
  m->grid_[1].reserve(ny);
2416
  m->grid_[2].reserve(nz);
2417

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

2428
  int err = m->set_grid();
2429
  return err;
2430
}
×
UNCOV
2431

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

UNCOV
2441
  if (m->lower_left_.dimension() == 0) {
×
2442
    set_errmsg("Mesh parameters have not been set.");
2443
    return OPENMC_E_ALLOCATE;
2444
  }
2445

444✔
2446
  *grid_x = m->grid_[0].data();
2447
  *nx = m->grid_[0].size();
444✔
2448
  *grid_y = m->grid_[1].data();
444✔
UNCOV
2449
  *ny = m->grid_[1].size();
×
UNCOV
2450
  *grid_z = m->grid_[2].data();
×
2451
  *nz = m->grid_[2].size();
2452

444✔
2453
  return 0;
444✔
2454
}
2455

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

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

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

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

968✔
2490
//! Get the spherical mesh grid
880✔
2491
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
2492
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
88✔
2493
{
2494

2495
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
2496
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2497
  ;
2498
}
143✔
UNCOV
2499

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

2509
#ifdef DAGMC
143✔
2510

143✔
2511
const std::string MOABMesh::mesh_lib_type = "moab";
143✔
2512

143✔
2513
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2514
{
2515
  initialize();
154✔
2516
}
2517

2518
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
154✔
UNCOV
2519
{
×
2520
  filename_ = filename;
2521
  set_length_multiplier(length_multiplier);
2522
  initialize();
154✔
2523
}
2524

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

11✔
2532
void MOABMesh::initialize()
2533
{
143✔
2534

2535
  // Create the MOAB interface and load data from file
2536
  this->create_interface();
44✔
2537

2538
  // Initialise MOAB error code
2539
  moab::ErrorCode rval = moab::MB_SUCCESS;
44✔
UNCOV
2540

×
2541
  // Set the dimension
44✔
2542
  n_dimension_ = 3;
2543

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

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

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

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

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

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

11✔
2603
  // Determine bounds of mesh
2604
  this->determine_bounds();
2605
}
2606

200✔
2607
void MOABMesh::prepare_for_point_location()
2608
{
2609
  // if the KDTree has already been constructed, do nothing
200✔
UNCOV
2610
  if (kdtree_)
×
2611
    return;
200✔
2612

2613
  // build acceleration data structures
2614
  compute_barycentric_data(ehs_);
200✔
2615
  build_kdtree(ehs_);
200✔
2616
}
200✔
2617

2618
void MOABMesh::create_interface()
2619
{
2620
  // Do not create a MOAB instance if one is already in memory
222✔
2621
  if (mbi_)
2622
    return;
2623

222✔
2624
  // create MOAB instance
×
2625
  mbi_ = std::make_shared<moab::Core>();
222✔
2626

2627
  // load unstructured mesh file
222✔
UNCOV
2628
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
×
UNCOV
2629
  if (rval != moab::MB_SUCCESS) {
×
2630
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2631
  }
2632
}
222✔
2633

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

×
2645
  if (!all_tris.all_of_type(moab::MBTRI)) {
233✔
2646
    warning("Non-triangle elements found in tet adjacencies in "
2647
            "unstructured mesh file: " +
233✔
UNCOV
2648
            filename_);
×
UNCOV
2649
  }
×
2650

2651
  // combine into one range
2652
  moab::Range all_tets_and_tris;
233✔
2653
  all_tets_and_tris.merge(all_tets);
233✔
2654
  all_tets_and_tris.merge(all_tris);
211✔
2655

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

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

2670
  // Build the k-d tree
2671
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
2672
  if (rval != moab::MB_SUCCESS) {
2673
    fatal_error("Failed to construct KDTree for the "
2674
                "unstructured mesh file: " +
233✔
2675
                filename_);
233✔
2676
  }
932✔
2677
}
699✔
2678

2679
void MOABMesh::intersect_track(const moab::CartVect& start,
2680
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
233✔
2681
{
233✔
2682
  hits.clear();
2683

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

2696
  // remove duplicate intersection distances
90✔
2697
  std::unique(hits.begin(), hits.end());
90✔
2698

90✔
2699
  // sorts by first component of std::pair by default
2700
  std::sort(hits.begin(), hits.end());
600✔
2701
}
510✔
2702

2703
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
347✔
2704
  vector<int>& bins, vector<double>& lengths) const
257✔
2705
{
2706
  moab::CartVect start(r0.x, r0.y, r0.z);
325✔
2707
  moab::CartVect end(r1.x, r1.y, r1.z);
235✔
2708
  moab::CartVect dir(u.x, u.y, u.z);
2709
  dir.normalize();
2710

90✔
2711
  double track_len = (end - start).length();
90✔
2712
  if (track_len == 0.0)
2713
    return;
22✔
2714

2715
  start -= TINY_BIT * dir;
2716
  end += TINY_BIT * dir;
2717

22✔
UNCOV
2718
  vector<double> hits;
×
2719
  intersect_track(start, dir, track_len, hits);
2720

22✔
2721
  bins.clear();
2722
  lengths.clear();
22✔
2723

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

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

2750
    // determine the start point for this segment
22✔
2751
    current = r0 + u * hit;
2752

22✔
2753
    if (bin == -1) {
22✔
2754
      continue;
22✔
2755
    }
2756

88✔
2757
    bins.push_back(bin);
66✔
2758
    lengths.push_back(segment_length / track_len);
2759
  }
99✔
2760

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

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

378✔
2786
  // retrieve the tet elements of this leaf
2787
  moab::EntityHandle leaf = kdtree_iter.handle();
160✔
2788
  moab::Range tets;
114✔
2789
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
2790
  if (rval != moab::MB_SUCCESS) {
149✔
2791
    warning("MOAB error finding tets.");
103✔
2792
  }
2793

2794
  // loop over the tets in this leaf, returning the containing tet if found
46✔
2795
  for (const auto& tet : tets) {
46✔
2796
    if (point_in_tet(pos, tet)) {
2797
      return tet;
2798
    }
2799
  }
2800

387✔
2801
  // if no tet is found, return an invalid handle
2802
  return 0;
2803
}
387✔
2804

×
2805
double MOABMesh::volume(int bin) const
387✔
2806
{
2807
  return tet_volume(get_ent_handle_from_bin(bin));
387✔
UNCOV
2808
}
×
UNCOV
2809

×
2810
std::string MOABMesh::library() const
2811
{
2812
  return mesh_lib_type;
387✔
2813
}
387✔
2814

387✔
2815
// Sample position within a tet for MOAB type tets
387✔
2816
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
387✔
2817
{
387✔
2818

2819
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
387✔
2820

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

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

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

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

121✔
2858
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
121✔
2859
}
121✔
2860

2861
int MOABMesh::get_bin(Position r) const
121✔
2862
{
2863
  moab::EntityHandle tet = get_tet(r);
145✔
2864
  if (tet == 0) {
2865
    return -1;
2866
  } else {
145✔
2867
    return get_bin_from_ent_handle(tet);
×
2868
  }
145✔
2869
}
2870

145✔
UNCOV
2871
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
×
UNCOV
2872
{
×
2873
  moab::ErrorCode rval;
2874

2875
  baryc_data_.clear();
145✔
2876
  baryc_data_.resize(tets.size());
145✔
2877

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

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

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

46✔
2895
    // invert now to avoid this cost later
2896
    a = a.transpose().inverse();
2897
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
2898
  }
46✔
2899
}
46✔
2900

2901
bool MOABMesh::point_in_tet(
2902
  const moab::CartVect& r, moab::EntityHandle tet) const
2903
{
121✔
2904

2905
  moab::ErrorCode rval;
2906

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

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

121✔
2926
  // look up barycentric data
2927
  int idx = get_bin_from_ent_handle(tet);
2928
  const moab::Matrix3& a_inv = baryc_data_[idx];
2929

2930
  moab::CartVect bary_coords = a_inv * (r - p_zero);
22✔
2931

2932
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
2933
          bary_coords[2] >= 0.0 &&
2934
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
22✔
2935
}
22✔
2936

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

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

2952
int MOABMesh::get_index_from_bin(int bin) const
2953
{
2954
  return bin;
1✔
2955
}
2956

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

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

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

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

2991
int MOABMesh::n_bins() const
2992
{
2993
  return ehs_.size();
2994
}
24✔
2995

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

3009
Position MOABMesh::centroid(int bin) const
3010
{
3011
  moab::ErrorCode rval;
3012

3013
  auto tet = this->get_ent_handle_from_bin(bin);
3014

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

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

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

3038
  return {centroid[0], centroid[1], centroid[2]};
3039
}
20✔
3040

3041
int MOABMesh::n_vertices() const
3042
{
3043
  return verts_.size();
20✔
3044
}
20✔
3045

3046
Position MOABMesh::vertex(int id) const
3047
{
24✔
3048

3049
  moab::ErrorCode rval;
3050

24✔
3051
  moab::EntityHandle vert = verts_[id];
1✔
3052

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

23✔
3059
  return {coords[0], coords[1], coords[2]};
3060
}
3061

3062
std::vector<int> MOABMesh::connectivity(int bin) const
3063
{
20✔
3064
  moab::ErrorCode rval;
3065

20✔
3066
  auto tet = get_ent_handle_from_bin(bin);
20✔
3067

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

3076
  std::vector<int> verts(4);
3077
  for (int i = 0; i < verts.size(); i++) {
3078
    verts[i] = get_vert_idx_from_handle(conn[i]);
3079
  }
3080

3081
  return verts;
20✔
3082
}
20✔
3083

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

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

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

1,542,122✔
3119
  // return the populated tag handles
3120
  return {value_tag, error_tag};
1,542,122✔
3121
}
3122

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

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

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

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

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

3166
void MOABMesh::set_score_data(const std::string& score,
3167
  const vector<double>& values, const vector<double>& std_dev)
3168
{
821,495✔
3169
  auto score_tags = this->get_score_tags(score);
821,495✔
3170

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

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

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

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

3209
#endif
7,307,001✔
3210

7,307,001✔
3211
#ifdef LIBMESH
7,307,001✔
3212

1,010,077✔
3213
const std::string LibMesh::mesh_lib_type = "libmesh";
3214

3215
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node), adaptive_(false)
3216
{
6,296,924✔
3217
  // filename_ and length_multiplier_ will already be set by the
6,296,924✔
3218
  // UnstructuredMesh constructor
6,296,924✔
3219
  set_mesh_pointer_from_filename(filename_);
6,296,924✔
3220
  set_length_multiplier(length_multiplier_);
3221
  initialize();
3222
}
3223

3224
// create the mesh from a pointer to a libMesh Mesh
260,010,824✔
3225
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
260,007,978✔
3226
  : adaptive_(input_mesh.n_active_elem() != input_mesh.n_elem())
6,294,078✔
3227
{
3228
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
3229
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3230
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3231
  }
2,846✔
3232

7,307,001✔
3233
  m_ = &input_mesh;
3234
  set_length_multiplier(length_multiplier);
167,856✔
3235
  initialize();
3236
}
167,856✔
3237

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

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

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

3265
// intialize from mesh file
200,410✔
3266
void LibMesh::initialize()
1,002,050✔
3267
{
801,640✔
3268
  if (!settings::libmesh_comm) {
3269
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3270
                "communicator.");
400,820✔
3271
  }
3272

3273
  // assuming that unstructured meshes used in OpenMC are 3D
167,856✔
3274
  n_dimension_ = 3;
3275

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

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

3292
  for (int i = 0; i < num_threads(); i++) {
7,307,001✔
3293
    pl_.emplace_back(m_->sub_point_locator());
7,307,001✔
3294
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
1,012,923✔
3295
    pl_.back()->enable_out_of_mesh_mode();
3296
  }
6,294,078✔
3297

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

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

239,712✔
3312
      bin_to_elem_map_.push_back(elem->id());
239,712✔
3313
      elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3314
    }
3315
  }
3316

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

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

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

3346
int LibMesh::n_vertices() const
260,007,978✔
3347
{
260,007,978✔
3348
  return m_->n_nodes();
260,007,978✔
3349
}
3350

3351
Position LibMesh::vertex(int vertex_id) const
3352
{
3353
  const auto node_ref = m_->node_ref(vertex_id);
3354
  return {node_ref(0), node_ref(1), node_ref(2)};
3355
}
3356

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

3367
std::string LibMesh::library() const
3368
{
3369
  return mesh_lib_type;
3370
}
3371

3372
int LibMesh::n_bins() const
3373
{
3374
  return m_->n_active_elem();
3375
}
3376

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

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

3402
    return;
3403
  }
266,541,768✔
3404

3405
  if (!equation_systems_) {
266,541,768✔
3406
    build_eqn_sys();
266,541,768✔
3407
  }
3408

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

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

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

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

3445
    return;
3446
  }
3447

3448
  if (!equation_systems_) {
3449
    build_eqn_sys();
3450
  }
3451

3452
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3453

3454
  if (!eqn_sys.is_initialized()) {
3455
    equation_systems_->init();
3456
  }
3457

3458
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3459

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

3467
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3468
       it++) {
3469
    if (!(*it)->active()) {
3470
      continue;
845,761✔
3471
    }
3472

845,761✔
3473
    auto bin = get_bin_from_element(*it);
3474

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

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

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

203,856✔
3496
    return;
3497
  }
3498

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

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

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

3519
  // quick rejection check
3520
  if (!bbox_.contains_point(p)) {
3521
    return -1;
3522
  }
3523

3524
  const auto& point_locator = pl_.at(thread_num());
3525

3526
  const auto elem_ptr = (*point_locator)(p);
3527
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3528
}
3529

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

3540
std::pair<vector<double>, vector<double>> LibMesh::plot(
3541
  Position plot_ll, Position plot_ur) const
3542
{
3543
  return {};
3544
}
3545

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

3551
double LibMesh::volume(int bin) const
3552
{
3553
  return this->get_element_from_bin(bin).volume();
3554
}
3555

3556
#endif // LIBMESH
3557

3558
//==============================================================================
3559
// Non-member functions
3560
//==============================================================================
3561

3562
void read_meshes(pugi::xml_node root)
3563
{
3564
  std::unordered_set<int> mesh_ids;
3565

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

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

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

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

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

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

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

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

3644
  close_group(meshes_group);
23✔
3645
}
3646

3647
void free_memory_mesh()
3648
{
23✔
3649
  model::meshes.clear();
23✔
3650
  model::mesh_map.clear();
23✔
3651
}
23✔
3652

3653
extern "C" int n_meshes()
3654
{
3655
  return model::meshes.size();
3656
}
3657

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