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

openmc-dev / openmc / 18538152141

15 Oct 2025 06:02PM UTC coverage: 81.97% (-3.2%) from 85.194%
18538152141

Pull #3417

github

web-flow
Merge 4604e1321 into e9077b137
Pull Request #3417: Addition of a collision tracking feature

16794 of 23357 branches covered (71.9%)

Branch coverage included in aggregate %.

480 of 522 new or added lines in 13 files covered. (91.95%)

457 existing lines in 53 files now uncovered.

54128 of 63165 relevant lines covered (85.69%)

42776927.64 hits per line

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

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

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

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

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

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

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

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

60
namespace openmc {
61

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

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

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

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

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

117
//! Atomic compare-and-swap for signed 32-bit integer
118
//
119
//! \param[in,out] ptr Pointer to value to update
120
//! \param[in,out] expected Value to compare to
121
//! \param[in] desired If comparison is successful, value to update to
122
//! \return True if the comparison was successful and the value was updated
123
inline bool atomic_cas_int32(int32_t* ptr, int32_t& expected, int32_t desired)
1,591✔
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,591✔
128
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
1,591✔
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(
3,051,231✔
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) {
3,056,917!
159
    // Determine slot to check, making sure it is positive
160
    int slot = (index_material + attempt) % table_size_;
3,056,917✔
161
    if (slot < 0)
3,056,917✔
162
      slot += table_size_;
227,976✔
163
    int32_t* slot_ptr = &this->materials(index_elem, slot);
3,056,917✔
164

165
    // Non-atomic read of current material
166
    int32_t current_val = *slot_ptr;
3,056,917✔
167

168
    // Found the desired material; accumulate volume
169
    if (current_val == index_material) {
3,056,917✔
170
#pragma omp atomic
1,447,135✔
171
      this->volumes(index_elem, slot) += volume;
3,049,640✔
172
      return;
3,049,640✔
173
    }
174

175
    // Slot appears to be empty; attempt to claim
176
    if (current_val == EMPTY) {
7,277✔
177
      // Attempt compare-and-swap from EMPTY to index_material
178
      int32_t expected_val = EMPTY;
1,591✔
179
      bool claimed_slot =
180
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,591✔
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,591!
185
#pragma omp atomic
771✔
186
        this->volumes(index_elem, slot) += volume;
1,591✔
187
        return;
1,591✔
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,779✔
234
{
235
  // Read mesh id
236
  id_ = std::stoi(get_node_value(node, "id"));
2,779✔
237
  if (check_for_node(node, "name"))
2,779✔
238
    name_ = get_node_value(node, "name");
16✔
239
}
2,779✔
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
263✔
272
{
273
  vector<double> volumes(n_bins());
263✔
274
  for (int i = 0; i < n_bins(); i++) {
1,204,998✔
275
    volumes[i] = this->volume(i);
1,204,735✔
276
  }
277
  return volumes;
263✔
278
}
×
279

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

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

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

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

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

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

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

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

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

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

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

361
          p.from_source(&site);
674,841✔
362

363
          // Determine particle's location
364
          if (!exhaustive_find_cell(p)) {
674,841✔
365
            out_of_model = true;
55,902✔
366
            continue;
55,902✔
367
          }
368

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

373
          // Initialize last cells from current cell
374
          for (int j = 0; j < p.n_coord(); ++j) {
1,237,878✔
375
            p.cell_last(j) = p.coord(j).cell();
618,939✔
376
          }
377
          p.n_coord_last() = p.n_coord();
618,939✔
378

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

384
            // Find the distance to the nearest boundary
385
            BoundaryInfo boundary = distance_to_boundary(p);
1,317,043✔
386

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

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

396
            // Add volumes to any mesh elements that were crossed
397
            int i_material = p.material();
1,317,043✔
398
            if (i_material != C_NONE) {
1,317,043✔
399
              i_material = model::materials[i_material]->id();
1,190,215✔
400
            }
401
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,920,972✔
402
              int mesh_index = bins[i_bin];
1,603,929✔
403
              double length = distance * length_fractions[i_bin];
1,603,929✔
404

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

409
            if (distance == max_distance)
1,317,043✔
410
              break;
618,939✔
411

412
            // cross next geometric surface
413
            for (int j = 0; j < p.n_coord(); ++j) {
1,396,208✔
414
              p.cell_last(j) = p.coord(j).cell();
698,104✔
415
            }
416
            p.n_coord_last() = p.n_coord();
698,104✔
417

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

554
  if (n_dimension_ > 2) {
5,353,323✔
555
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,677,144✔
556
  } else if (n_dimension_ > 1) {
14,751✔
557
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
28,952✔
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,430✔
564
{
565
  // because method is const, shape_ is const as well and can't be adapted
566
  auto tmp_shape = shape_;
2,430✔
567
  return xt::adapt(tmp_shape, {n_dimension_});
4,860✔
568
}
569

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

577
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,534,222!
578
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,534,222!
579

580
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,534,222!
581
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,534,222!
582

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

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

591
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
46✔
592
{
593
  n_dimension_ = 3;
46✔
594

595
  // check the mesh type
596
  if (check_for_node(node, "type")) {
46!
597
    auto temp = get_node_value(node, "type", true, true);
46!
598
    if (temp != mesh_type) {
46!
599
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
600
    }
601
  }
46✔
602

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

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

619
  if (check_for_node(node, "options")) {
46!
620
    options_ = get_node_value(node, "options");
16!
621
  }
622

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

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

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

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

682
const std::string UnstructuredMesh::mesh_type = "unstructured";
683

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

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

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

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

708
  if (length_multiplier_ > 0.0)
31!
709
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
710

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

719
  int num_elem_skipped = 0;
31✔
720

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

728
    volumes.emplace_back(this->volume(i));
349,712!
729

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

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

758
  write_dataset(mesh_group, "volumes", volumes);
31!
759
  write_dataset(mesh_group, "connectivity", connectivity);
31!
760
  write_dataset(mesh_group, "element_types", elem_types);
31!
761
}
31✔
762

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

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

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

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

788
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
789
      in_mesh = false;
102,465,381✔
790
  }
791
  return ijk;
1,148,014,152✔
792
}
793

794
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,685,391,194✔
795
{
796
  switch (n_dimension_) {
1,685,391,194!
797
  case 1:
880,605✔
798
    return ijk[0] - 1;
880,605✔
799
  case 2:
70,207,324✔
800
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
70,207,324✔
801
  case 3:
1,614,303,265✔
802
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,614,303,265✔
803
  default:
×
804
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
805
  }
806
}
807

808
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,183,979✔
809
{
810
  MeshIndex ijk;
811
  if (n_dimension_ == 1) {
8,183,979✔
812
    ijk[0] = bin + 1;
275✔
813
  } else if (n_dimension_ == 2) {
8,183,704✔
814
    ijk[0] = bin % shape_[0] + 1;
14,476✔
815
    ijk[1] = bin / shape_[0] + 1;
14,476✔
816
  } else if (n_dimension_ == 3) {
8,169,228!
817
    ijk[0] = bin % shape_[0] + 1;
8,169,228✔
818
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,169,228✔
819
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,169,228✔
820
  }
821
  return ijk;
8,183,979✔
822
}
823

824
int StructuredMesh::get_bin(Position r) const
256,617,655✔
825
{
826
  // Determine indices
827
  bool in_mesh;
828
  MeshIndex ijk = get_indices(r, in_mesh);
256,617,655✔
829
  if (!in_mesh)
256,617,655✔
830
    return -1;
20,991,092✔
831

832
  // Convert indices to bin
833
  return get_bin_from_indices(ijk);
235,626,563✔
834
}
835

836
int StructuredMesh::n_bins() const
1,220,263✔
837
{
838
  return std::accumulate(
1,220,263✔
839
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,440,526✔
840
}
841

842
int StructuredMesh::n_surface_bins() const
403✔
843
{
844
  return 4 * n_dimension_ * n_bins();
403✔
845
}
846

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

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

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

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

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

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

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

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

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

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

899
  return counts;
×
UNCOV
900
}
×
901

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

915
  // Compute the length of the entire track.
916
  double total_distance = (r1 - r0).norm();
896,337,702✔
917
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
896,337,702✔
918
    return;
11,630,955✔
919

920
  // keep a copy of the original global position to pass to get_indices,
921
  // which performs its own transformation to local coordinates
922
  Position global_r = r0;
884,706,747✔
923
  Position local_r = local_coords(r0);
884,706,747✔
924

925
  const int n = n_dimension_;
884,706,747✔
926

927
  // Flag if position is inside the mesh
928
  bool in_mesh;
929

930
  // Position is r = r0 + u * traveled_distance, start at r0
931
  double traveled_distance {0.0};
884,706,747✔
932

933
  // Calculate index of current cell. Offset the position a tiny bit in
934
  // direction of flight
935
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
884,706,747✔
936

937
  // if track is very short, assume that it is completely inside one cell.
938
  // Only the current cell will score and no surfaces
939
  if (total_distance < 2 * TINY_BIT) {
884,706,747✔
940
    if (in_mesh) {
331,527✔
941
      tally.track(ijk, 1.0);
331,043✔
942
    }
943
    return;
331,527✔
944
  }
945

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

952
  // Loop until r = r1 is eventually reached
953
  while (true) {
741,404,368✔
954

955
    if (in_mesh) {
1,625,779,588✔
956

957
      // find surface with minimal distance to current position
958
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,539,004,494✔
959
                     distances.begin();
1,539,004,494✔
960

961
      // Tally track length delta since last step
962
      tally.track(ijk,
1,539,004,494✔
963
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,539,004,494✔
964
          total_distance);
965

966
      // update position and leave, if we have reached end position
967
      traveled_distance = distances[k].distance;
1,539,004,494✔
968
      if (traveled_distance >= total_distance)
1,539,004,494✔
969
        return;
804,289,876✔
970

971
      // If we have not reached r1, we have hit a surface. Tally outward
972
      // current
973
      tally.surface(ijk, k, distances[k].max_surface, false);
734,714,618✔
974

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

981
      // Check if we have left the interior of the mesh
982
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
734,714,618✔
983

984
      // If we are still inside the mesh, tally inward current for the next
985
      // cell
986
      if (in_mesh)
734,714,618✔
987
        tally.surface(ijk, k, !distances[k].max_surface, true);
720,713,405✔
988

989
    } else { // not inside mesh
990

991
      // For all directions outside the mesh, find the distance that we need
992
      // to travel to reach the next surface. Use the largest distance, as
993
      // only this will cross all outer surfaces.
994
      int k_max {-1};
86,775,094✔
995
      for (int k = 0; k < n; ++k) {
345,656,010✔
996
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
353,647,227✔
997
            (distances[k].distance > traveled_distance)) {
94,766,311✔
998
          traveled_distance = distances[k].distance;
89,788,199✔
999
          k_max = k;
89,788,199✔
1000
        }
1001
      }
1002
      // Assure some distance is traveled
1003
      if (k_max == -1) {
86,775,094✔
1004
        traveled_distance += TINY_BIT;
110✔
1005
      }
1006

1007
      // If r1 is not inside the mesh, exit here
1008
      if (traveled_distance >= total_distance)
86,775,094✔
1009
        return;
80,085,344✔
1010

1011
      // Calculate the new cell index and update all distances to next
1012
      // surfaces.
1013
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,689,750✔
1014
      for (int k = 0; k < n; ++k) {
26,550,462✔
1015
        distances[k] =
19,860,712✔
1016
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
19,860,712✔
1017
      }
1018

1019
      // If inside the mesh, Tally inward current
1020
      if (in_mesh && k_max >= 0)
6,689,750!
1021
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
6,270,435✔
1022
    }
1023
  }
1024
}
1025

1026
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
774,257,882✔
1027
  vector<int>& bins, vector<double>& lengths) const
1028
{
1029

1030
  // Helper tally class.
1031
  // stores a pointer to the mesh class and references to bins and lengths
1032
  // parameters. Performs the actual tally through the track method.
1033
  struct TrackAggregator {
1034
    TrackAggregator(
774,257,882✔
1035
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1036
      : mesh(_mesh), bins(_bins), lengths(_lengths)
774,257,882✔
1037
    {}
774,257,882✔
1038
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1,399,080,813✔
1039
    void track(const MeshIndex& ijk, double l) const
1,387,146,986✔
1040
    {
1041
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,387,146,986✔
1042
      lengths.push_back(l);
1,387,146,986✔
1043
    }
1,387,146,986✔
1044

1045
    const StructuredMesh* mesh;
1046
    vector<int>& bins;
1047
    vector<double>& lengths;
1048
  };
1049

1050
  // Perform the mesh raytrace with the helper class.
1051
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
774,257,882✔
1052
}
774,257,882✔
1053

1054
void StructuredMesh::surface_bins_crossed(
122,079,820✔
1055
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1056
{
1057

1058
  // Helper tally class.
1059
  // stores a pointer to the mesh class and a reference to the bins parameter.
1060
  // Performs the actual tally through the surface method.
1061
  struct SurfaceAggregator {
1062
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
122,079,820✔
1063
      : mesh(_mesh), bins(_bins)
122,079,820✔
1064
    {}
122,079,820✔
1065
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
62,617,645✔
1066
    {
1067
      int i_bin =
1068
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
62,617,645✔
1069
      if (max)
62,617,645✔
1070
        i_bin += 2;
31,280,564✔
1071
      if (inward)
62,617,645✔
1072
        i_bin += 1;
30,774,022✔
1073
      bins.push_back(i_bin);
62,617,645✔
1074
    }
62,617,645✔
1075
    void track(const MeshIndex& idx, double l) const {}
152,188,551✔
1076

1077
    const StructuredMesh* mesh;
1078
    vector<int>& bins;
1079
  };
1080

1081
  // Perform the mesh raytrace with the helper class.
1082
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
122,079,820✔
1083
}
122,079,820✔
1084

1085
//==============================================================================
1086
// RegularMesh implementation
1087
//==============================================================================
1088

1089
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1,900✔
1090
{
1091
  // Determine number of dimensions for mesh
1092
  if (!check_for_node(node, "dimension")) {
1,900!
UNCOV
1093
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1094
  }
1095

1096
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
1,900✔
1097
  int n = n_dimension_ = shape.size();
1,900✔
1098
  if (n != 1 && n != 2 && n != 3) {
1,900!
UNCOV
1099
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1100
  }
1101
  std::copy(shape.begin(), shape.end(), shape_.begin());
1,900✔
1102

1103
  // Check that dimensions are all greater than zero
1104
  if (xt::any(shape <= 0)) {
1,900!
UNCOV
1105
    fatal_error("All entries on the <dimension> element for a tally "
×
1106
                "mesh must be positive.");
1107
  }
1108

1109
  // Check for lower-left coordinates
1110
  if (check_for_node(node, "lower_left")) {
1,900!
1111
    // Read mesh lower-left corner location
1112
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1,900✔
1113
  } else {
UNCOV
1114
    fatal_error("Must specify <lower_left> on a mesh.");
×
1115
  }
1116

1117
  // Make sure lower_left and dimension match
1118
  if (shape.size() != lower_left_.size()) {
1,900!
UNCOV
1119
    fatal_error("Number of entries on <lower_left> must be the same "
×
1120
                "as the number of entries on <dimension>.");
1121
  }
1122

1123
  if (check_for_node(node, "width")) {
1,900✔
1124
    // Make sure one of upper-right or width were specified
1125
    if (check_for_node(node, "upper_right")) {
49!
UNCOV
1126
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1127
    }
1128

1129
    width_ = get_node_xarray<double>(node, "width");
49✔
1130

1131
    // Check to ensure width has same dimensions
1132
    auto n = width_.size();
49✔
1133
    if (n != lower_left_.size()) {
49!
UNCOV
1134
      fatal_error("Number of entries on <width> must be the same as "
×
1135
                  "the number of entries on <lower_left>.");
1136
    }
1137

1138
    // Check for negative widths
1139
    if (xt::any(width_ < 0.0)) {
49!
UNCOV
1140
      fatal_error("Cannot have a negative <width> on a tally mesh.");
×
1141
    }
1142

1143
    // Set width and upper right coordinate
1144
    upper_right_ = xt::eval(lower_left_ + shape * width_);
49✔
1145

1146
  } else if (check_for_node(node, "upper_right")) {
1,851!
1147
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1,851✔
1148

1149
    // Check to ensure width has same dimensions
1150
    auto n = upper_right_.size();
1,851✔
1151
    if (n != lower_left_.size()) {
1,851!
UNCOV
1152
      fatal_error("Number of entries on <upper_right> must be the "
×
1153
                  "same as the number of entries on <lower_left>.");
1154
    }
1155

1156
    // Check that upper-right is above lower-left
1157
    if (xt::any(upper_right_ < lower_left_)) {
1,851!
UNCOV
1158
      fatal_error("The <upper_right> coordinates must be greater than "
×
1159
                  "the <lower_left> coordinates on a tally mesh.");
1160
    }
1161

1162
    // Set width
1163
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1,851✔
1164
  } else {
UNCOV
1165
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1166
  }
1167

1168
  // Set material volumes
1169
  volume_frac_ = 1.0 / xt::prod(shape)();
1,900✔
1170

1171
  element_volume_ = 1.0;
1,900✔
1172
  for (int i = 0; i < n_dimension_; i++) {
7,226✔
1173
    element_volume_ *= width_[i];
5,326✔
1174
  }
1175
}
1,900✔
1176

1177
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1178
{
1179
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1180
}
1181

1182
const std::string RegularMesh::mesh_type = "regular";
1183

1184
std::string RegularMesh::get_mesh_type() const
3,156✔
1185
{
1186
  return mesh_type;
3,156✔
1187
}
1188

1189
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,437,300,087✔
1190
{
1191
  return lower_left_[i] + ijk[i] * width_[i];
1,437,300,087✔
1192
}
1193

1194
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,375,432,489✔
1195
{
1196
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,375,432,489✔
1197
}
1198

1199
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1200
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1201
  double l) const
1202
{
1203
  MeshDistance d;
2,147,483,647✔
1204
  d.next_index = ijk[i];
2,147,483,647✔
1205
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1206
    return d;
1,669,834✔
1207

1208
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1209
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1210
    d.next_index++;
1,432,697,421✔
1211
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,432,697,421✔
1212
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,392,776,465✔
1213
    d.next_index--;
1,370,829,823✔
1214
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,370,829,823✔
1215
  }
1216

1217
  return d;
2,147,483,647✔
1218
}
1219

1220
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1221
  Position plot_ll, Position plot_ur) const
1222
{
1223
  // Figure out which axes lie in the plane of the plot.
1224
  array<int, 2> axes {-1, -1};
22✔
1225
  if (plot_ur.z == plot_ll.z) {
22!
1226
    axes[0] = 0;
22✔
1227
    if (n_dimension_ > 1)
22!
1228
      axes[1] = 1;
22✔
UNCOV
1229
  } else if (plot_ur.y == plot_ll.y) {
×
UNCOV
1230
    axes[0] = 0;
×
UNCOV
1231
    if (n_dimension_ > 2)
×
UNCOV
1232
      axes[1] = 2;
×
UNCOV
1233
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1234
    if (n_dimension_ > 1)
×
UNCOV
1235
      axes[0] = 1;
×
UNCOV
1236
    if (n_dimension_ > 2)
×
UNCOV
1237
      axes[1] = 2;
×
1238
  } else {
UNCOV
1239
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1240
  }
1241

1242
  // Get the coordinates of the mesh lines along both of the axes.
1243
  array<vector<double>, 2> axis_lines;
22✔
1244
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1245
    int axis = axes[i_ax];
44✔
1246
    if (axis == -1)
44!
UNCOV
1247
      continue;
×
1248
    auto& lines {axis_lines[i_ax]};
44✔
1249

1250
    double coord = lower_left_[axis];
44✔
1251
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1252
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1253
        lines.push_back(coord);
242✔
1254
      coord += width_[axis];
242✔
1255
    }
1256
  }
1257

1258
  return {axis_lines[0], axis_lines[1]};
44✔
1259
}
22✔
1260

1261
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1,936✔
1262
{
1263
  write_dataset(mesh_group, "dimension", get_x_shape());
1,936✔
1264
  write_dataset(mesh_group, "lower_left", lower_left_);
1,936✔
1265
  write_dataset(mesh_group, "upper_right", upper_right_);
1,936✔
1266
  write_dataset(mesh_group, "width", width_);
1,936✔
1267
}
1,936✔
1268

1269
xt::xtensor<double, 1> RegularMesh::count_sites(
8,424✔
1270
  const SourceSite* bank, int64_t length, bool* outside) const
1271
{
1272
  // Determine shape of array for counts
1273
  std::size_t m = this->n_bins();
8,424✔
1274
  vector<std::size_t> shape = {m};
8,424✔
1275

1276
  // Create array of zeros
1277
  xt::xarray<double> cnt {shape, 0.0};
8,424✔
1278
  bool outside_ = false;
8,424✔
1279

1280
  for (int64_t i = 0; i < length; i++) {
8,254,695✔
1281
    const auto& site = bank[i];
8,246,271✔
1282

1283
    // determine scoring bin for entropy mesh
1284
    int mesh_bin = get_bin(site.r);
8,246,271✔
1285

1286
    // if outside mesh, skip particle
1287
    if (mesh_bin < 0) {
8,246,271!
UNCOV
1288
      outside_ = true;
×
UNCOV
1289
      continue;
×
1290
    }
1291

1292
    // Add to appropriate bin
1293
    cnt(mesh_bin) += site.wgt;
8,246,271✔
1294
  }
1295

1296
  // Create copy of count data. Since ownership will be acquired by xtensor,
1297
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
1298
  // warnings.
1299
  int total = cnt.size();
8,424✔
1300
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
8,424✔
1301

1302
#ifdef OPENMC_MPI
1303
  // collect values from all processors
1304
  MPI_Reduce(
4,200✔
1305
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
4,200✔
1306

1307
  // Check if there were sites outside the mesh for any processor
1308
  if (outside) {
4,200!
1309
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
4,200✔
1310
  }
1311
#else
1312
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
4,224✔
1313
  if (outside)
4,224!
1314
    *outside = outside_;
4,224✔
1315
#endif
1316

1317
  // Adapt reduced values in array back into an xarray
1318
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
8,424✔
1319
  xt::xarray<double> counts = arr;
8,424✔
1320

1321
  return counts;
16,848✔
1322
}
8,424✔
1323

1324
double RegularMesh::volume(const MeshIndex& ijk) const
1,206,088✔
1325
{
1326
  return element_volume_;
1,206,088✔
1327
}
1328

1329
//==============================================================================
1330
// RectilinearMesh implementation
1331
//==============================================================================
1332

1333
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
115✔
1334
{
1335
  n_dimension_ = 3;
115✔
1336

1337
  grid_[0] = get_node_array<double>(node, "x_grid");
115✔
1338
  grid_[1] = get_node_array<double>(node, "y_grid");
115✔
1339
  grid_[2] = get_node_array<double>(node, "z_grid");
115✔
1340

1341
  if (int err = set_grid()) {
115!
UNCOV
1342
    fatal_error(openmc_err_msg);
×
1343
  }
1344
}
115✔
1345

1346
const std::string RectilinearMesh::mesh_type = "rectilinear";
1347

1348
std::string RectilinearMesh::get_mesh_type() const
295✔
1349
{
1350
  return mesh_type;
295✔
1351
}
1352

1353
double RectilinearMesh::positive_grid_boundary(
28,663,409✔
1354
  const MeshIndex& ijk, int i) const
1355
{
1356
  return grid_[i][ijk[i]];
28,663,409✔
1357
}
1358

1359
double RectilinearMesh::negative_grid_boundary(
27,830,868✔
1360
  const MeshIndex& ijk, int i) const
1361
{
1362
  return grid_[i][ijk[i] - 1];
27,830,868✔
1363
}
1364

1365
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
57,967,221✔
1366
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1367
  double l) const
1368
{
1369
  MeshDistance d;
57,967,221✔
1370
  d.next_index = ijk[i];
57,967,221✔
1371
  if (std::abs(u[i]) < FP_PRECISION)
57,967,221✔
1372
    return d;
675,792✔
1373

1374
  d.max_surface = (u[i] > 0);
57,291,429✔
1375
  if (d.max_surface && (ijk[i] <= shape_[i])) {
57,291,429✔
1376
    d.next_index++;
28,663,409✔
1377
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
28,663,409✔
1378
  } else if (!d.max_surface && (ijk[i] > 0)) {
28,628,020✔
1379
    d.next_index--;
27,830,868✔
1380
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
27,830,868✔
1381
  }
1382
  return d;
57,291,429✔
1383
}
1384

1385
int RectilinearMesh::set_grid()
165✔
1386
{
1387
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
165✔
1388
    static_cast<int>(grid_[1].size()) - 1,
165✔
1389
    static_cast<int>(grid_[2].size()) - 1};
165✔
1390

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

1405
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
165✔
1406
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
165✔
1407

1408
  return 0;
165✔
1409
}
1410

1411
int RectilinearMesh::get_index_in_direction(double r, int i) const
80,492,670✔
1412
{
1413
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
80,492,670✔
1414
}
1415

1416
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1417
  Position plot_ll, Position plot_ur) const
1418
{
1419
  // Figure out which axes lie in the plane of the plot.
1420
  array<int, 2> axes {-1, -1};
11✔
1421
  if (plot_ur.z == plot_ll.z) {
11!
UNCOV
1422
    axes = {0, 1};
×
1423
  } else if (plot_ur.y == plot_ll.y) {
11!
1424
    axes = {0, 2};
11✔
UNCOV
1425
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1426
    axes = {1, 2};
×
1427
  } else {
UNCOV
1428
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1429
  }
1430

1431
  // Get the coordinates of the mesh lines along both of the axes.
1432
  array<vector<double>, 2> axis_lines;
11✔
1433
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1434
    int axis = axes[i_ax];
22✔
1435
    vector<double>& lines {axis_lines[i_ax]};
22✔
1436

1437
    for (auto coord : grid_[axis]) {
110✔
1438
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1439
        lines.push_back(coord);
88✔
1440
    }
1441
  }
1442

1443
  return {axis_lines[0], axis_lines[1]};
22✔
1444
}
11✔
1445

1446
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
102✔
1447
{
1448
  write_dataset(mesh_group, "x_grid", grid_[0]);
102✔
1449
  write_dataset(mesh_group, "y_grid", grid_[1]);
102✔
1450
  write_dataset(mesh_group, "z_grid", grid_[2]);
102✔
1451
}
102✔
1452

1453
double RectilinearMesh::volume(const MeshIndex& ijk) const
156✔
1454
{
1455
  double vol {1.0};
156✔
1456

1457
  for (int i = 0; i < n_dimension_; i++) {
624✔
1458
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
468✔
1459
  }
1460
  return vol;
156✔
1461
}
1462

1463
//==============================================================================
1464
// CylindricalMesh implementation
1465
//==============================================================================
1466

1467
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
392✔
1468
  : PeriodicStructuredMesh {node}
392✔
1469
{
1470
  n_dimension_ = 3;
392✔
1471
  grid_[0] = get_node_array<double>(node, "r_grid");
392✔
1472
  grid_[1] = get_node_array<double>(node, "phi_grid");
392✔
1473
  grid_[2] = get_node_array<double>(node, "z_grid");
392✔
1474
  origin_ = get_node_position(node, "origin");
392✔
1475

1476
  if (int err = set_grid()) {
392!
1477
    fatal_error(openmc_err_msg);
×
1478
  }
1479
}
392✔
1480

1481
const std::string CylindricalMesh::mesh_type = "cylindrical";
1482

1483
std::string CylindricalMesh::get_mesh_type() const
492✔
1484
{
1485
  return mesh_type;
492✔
1486
}
1487

1488
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,831,708✔
1489
  Position r, bool& in_mesh) const
1490
{
1491
  r = local_coords(r);
47,831,708✔
1492

1493
  Position mapped_r;
47,831,708✔
1494
  mapped_r[0] = std::hypot(r.x, r.y);
47,831,708✔
1495
  mapped_r[2] = r[2];
47,831,708✔
1496

1497
  if (mapped_r[0] < FP_PRECISION) {
47,831,708!
UNCOV
1498
    mapped_r[1] = 0.0;
×
1499
  } else {
1500
    mapped_r[1] = std::atan2(r.y, r.x);
47,831,708✔
1501
    if (mapped_r[1] < 0)
47,831,708✔
1502
      mapped_r[1] += 2 * M_PI;
23,931,679✔
1503
  }
1504

1505
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,831,708✔
1506

1507
  idx[1] = sanitize_phi(idx[1]);
47,831,708✔
1508

1509
  return idx;
47,831,708✔
1510
}
1511

1512
Position CylindricalMesh::sample_element(
88,120✔
1513
  const MeshIndex& ijk, uint64_t* seed) const
1514
{
1515
  double r_min = this->r(ijk[0] - 1);
88,120✔
1516
  double r_max = this->r(ijk[0]);
88,120✔
1517

1518
  double phi_min = this->phi(ijk[1] - 1);
88,120✔
1519
  double phi_max = this->phi(ijk[1]);
88,120✔
1520

1521
  double z_min = this->z(ijk[2] - 1);
88,120✔
1522
  double z_max = this->z(ijk[2]);
88,120✔
1523

1524
  double r_min_sq = r_min * r_min;
88,120✔
1525
  double r_max_sq = r_max * r_max;
88,120✔
1526
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,120✔
1527
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,120✔
1528
  double z = uniform_distribution(z_min, z_max, seed);
88,120✔
1529

1530
  double x = r * std::cos(phi);
88,120✔
1531
  double y = r * std::sin(phi);
88,120✔
1532

1533
  return origin_ + Position(x, y, z);
88,120✔
1534
}
1535

1536
double CylindricalMesh::find_r_crossing(
142,853,348✔
1537
  const Position& r, const Direction& u, double l, int shell) const
1538
{
1539

1540
  if ((shell < 0) || (shell > shape_[0]))
142,853,348!
1541
    return INFTY;
17,962,259✔
1542

1543
  // solve r.x^2 + r.y^2 == r0^2
1544
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1545
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1546

1547
  const double r0 = grid_[0][shell];
124,891,089✔
1548
  if (r0 == 0.0)
124,891,089✔
1549
    return INFTY;
7,153,907✔
1550

1551
  const double denominator = u.x * u.x + u.y * u.y;
117,737,182✔
1552

1553
  // Direction of flight is in z-direction. Will never intersect r.
1554
  if (std::abs(denominator) < FP_PRECISION)
117,737,182✔
1555
    return INFTY;
69,680✔
1556

1557
  // inverse of dominator to help the compiler to speed things up
1558
  const double inv_denominator = 1.0 / denominator;
117,667,502✔
1559

1560
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,667,502✔
1561
  double c = r.x * r.x + r.y * r.y - r0 * r0;
117,667,502✔
1562
  double D = p * p - c * inv_denominator;
117,667,502✔
1563

1564
  if (D < 0.0)
117,667,502✔
1565
    return INFTY;
9,758,626✔
1566

1567
  D = std::sqrt(D);
107,908,876✔
1568

1569
  // the solution -p - D is always smaller as -p + D : Check this one first
1570
  if (std::abs(c) <= RADIAL_MESH_TOL)
107,908,876✔
1571
    return INFTY;
6,611,374✔
1572

1573
  if (-p - D > l)
101,297,502✔
1574
    return -p - D;
20,250,334✔
1575
  if (-p + D > l)
81,047,168✔
1576
    return -p + D;
50,179,356✔
1577

1578
  return INFTY;
30,867,812✔
1579
}
1580

1581
double CylindricalMesh::find_phi_crossing(
74,708,694✔
1582
  const Position& r, const Direction& u, double l, int shell) const
1583
{
1584
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1585
  if (full_phi_ && (shape_[1] == 1))
74,708,694✔
1586
    return INFTY;
30,474,840✔
1587

1588
  shell = sanitize_phi(shell);
44,233,854✔
1589

1590
  const double p0 = grid_[1][shell];
44,233,854✔
1591

1592
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1593
  // => x(s) * cos(p0) = y(s) * sin(p0)
1594
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1595
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1596

1597
  const double c0 = std::cos(p0);
44,233,854✔
1598
  const double s0 = std::sin(p0);
44,233,854✔
1599

1600
  const double denominator = (u.x * s0 - u.y * c0);
44,233,854✔
1601

1602
  // Check if direction of flight is not parallel to phi surface
1603
  if (std::abs(denominator) > FP_PRECISION) {
44,233,854✔
1604
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,932,702✔
1605
    // Check if solution is in positive direction of flight and crosses the
1606
    // correct phi surface (not -phi)
1607
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,932,702✔
1608
      return s;
20,304,175✔
1609
  }
1610

1611
  return INFTY;
23,929,679✔
1612
}
1613

1614
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,795,364✔
1615
  const Position& r, const Direction& u, double l, int shell) const
1616
{
1617
  MeshDistance d;
36,795,364✔
1618
  d.next_index = shell;
36,795,364✔
1619

1620
  // Direction of flight is within xy-plane. Will never intersect z.
1621
  if (std::abs(u.z) < FP_PRECISION)
36,795,364✔
1622
    return d;
1,216,528✔
1623

1624
  d.max_surface = (u.z > 0.0);
35,578,836✔
1625
  if (d.max_surface && (shell <= shape_[2])) {
35,578,836✔
1626
    d.next_index += 1;
16,879,969✔
1627
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,879,969✔
1628
  } else if (!d.max_surface && (shell > 0)) {
18,698,867✔
1629
    d.next_index -= 1;
16,843,453✔
1630
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,843,453✔
1631
  }
1632
  return d;
35,578,836✔
1633
}
1634

1635
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,576,385✔
1636
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1637
  double l) const
1638
{
1639
  if (i == 0) {
145,576,385✔
1640

1641
    return std::min(
71,426,674✔
1642
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,426,674✔
1643
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,853,348✔
1644

1645
  } else if (i == 1) {
74,149,711✔
1646

1647
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,354,347✔
1648
                      find_phi_crossing(r0, u, l, ijk[i])),
37,354,347✔
1649
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,354,347✔
1650
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,708,694✔
1651

1652
  } else {
1653
    return find_z_crossing(r0, u, l, ijk[i]);
36,795,364✔
1654
  }
1655
}
1656

1657
int CylindricalMesh::set_grid()
418✔
1658
{
1659
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
418✔
1660
    static_cast<int>(grid_[1].size()) - 1,
418✔
1661
    static_cast<int>(grid_[2].size()) - 1};
418✔
1662

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

UNCOV
1690
    return OPENMC_E_INVALID_ARGUMENT;
×
1691
  }
1692

1693
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
418!
1694

1695
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
836✔
1696
    origin_[2] + grid_[2].front()};
836✔
1697
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
836✔
1698
    origin_[2] + grid_[2].back()};
836✔
1699

1700
  return 0;
418✔
1701
}
1702

1703
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,495,124✔
1704
{
1705
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,495,124✔
1706
}
1707

UNCOV
1708
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
1709
  Position plot_ll, Position plot_ur) const
1710
{
UNCOV
1711
  fatal_error("Plot of cylindrical Mesh not implemented");
×
1712

1713
  // Figure out which axes lie in the plane of the plot.
1714
  array<vector<double>, 2> axis_lines;
1715
  return {axis_lines[0], axis_lines[1]};
1716
}
1717

1718
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
363✔
1719
{
1720
  write_dataset(mesh_group, "r_grid", grid_[0]);
363✔
1721
  write_dataset(mesh_group, "phi_grid", grid_[1]);
363✔
1722
  write_dataset(mesh_group, "z_grid", grid_[2]);
363✔
1723
  write_dataset(mesh_group, "origin", origin_);
363✔
1724
}
363✔
1725

1726
double CylindricalMesh::volume(const MeshIndex& ijk) const
886✔
1727
{
1728
  double r_i = grid_[0][ijk[0] - 1];
886✔
1729
  double r_o = grid_[0][ijk[0]];
886✔
1730

1731
  double phi_i = grid_[1][ijk[1] - 1];
886✔
1732
  double phi_o = grid_[1][ijk[1]];
886✔
1733

1734
  double z_i = grid_[2][ijk[2] - 1];
886✔
1735
  double z_o = grid_[2][ijk[2]];
886✔
1736

1737
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
886✔
1738
}
1739

1740
//==============================================================================
1741
// SphericalMesh implementation
1742
//==============================================================================
1743

1744
SphericalMesh::SphericalMesh(pugi::xml_node node)
326✔
1745
  : PeriodicStructuredMesh {node}
326✔
1746
{
1747
  n_dimension_ = 3;
326✔
1748

1749
  grid_[0] = get_node_array<double>(node, "r_grid");
326✔
1750
  grid_[1] = get_node_array<double>(node, "theta_grid");
326✔
1751
  grid_[2] = get_node_array<double>(node, "phi_grid");
326✔
1752
  origin_ = get_node_position(node, "origin");
326✔
1753

1754
  if (int err = set_grid()) {
326!
UNCOV
1755
    fatal_error(openmc_err_msg);
×
1756
  }
1757
}
326✔
1758

1759
const std::string SphericalMesh::mesh_type = "spherical";
1760

1761
std::string SphericalMesh::get_mesh_type() const
374✔
1762
{
1763
  return mesh_type;
374✔
1764
}
1765

1766
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,289,188✔
1767
  Position r, bool& in_mesh) const
1768
{
1769
  r = local_coords(r);
68,289,188✔
1770

1771
  Position mapped_r;
68,289,188✔
1772
  mapped_r[0] = r.norm();
68,289,188✔
1773

1774
  if (mapped_r[0] < FP_PRECISION) {
68,289,188!
UNCOV
1775
    mapped_r[1] = 0.0;
×
UNCOV
1776
    mapped_r[2] = 0.0;
×
1777
  } else {
1778
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,289,188✔
1779
    mapped_r[2] = std::atan2(r.y, r.x);
68,289,188✔
1780
    if (mapped_r[2] < 0)
68,289,188✔
1781
      mapped_r[2] += 2 * M_PI;
34,125,258✔
1782
  }
1783

1784
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,289,188✔
1785

1786
  idx[1] = sanitize_theta(idx[1]);
68,289,188✔
1787
  idx[2] = sanitize_phi(idx[2]);
68,289,188✔
1788

1789
  return idx;
68,289,188✔
1790
}
1791

1792
Position SphericalMesh::sample_element(
120✔
1793
  const MeshIndex& ijk, uint64_t* seed) const
1794
{
1795
  double r_min = this->r(ijk[0] - 1);
120✔
1796
  double r_max = this->r(ijk[0]);
120✔
1797

1798
  double theta_min = this->theta(ijk[1] - 1);
120✔
1799
  double theta_max = this->theta(ijk[1]);
120✔
1800

1801
  double phi_min = this->phi(ijk[2] - 1);
120✔
1802
  double phi_max = this->phi(ijk[2]);
120✔
1803

1804
  double cos_theta =
1805
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
120✔
1806
  double sin_theta = std::sin(std::acos(cos_theta));
120✔
1807
  double phi = uniform_distribution(phi_min, phi_max, seed);
120✔
1808
  double r_min_cub = std::pow(r_min, 3);
120✔
1809
  double r_max_cub = std::pow(r_max, 3);
120✔
1810
  // might be faster to do rejection here?
1811
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
120✔
1812

1813
  double x = r * std::cos(phi) * sin_theta;
120✔
1814
  double y = r * std::sin(phi) * sin_theta;
120✔
1815
  double z = r * cos_theta;
120✔
1816

1817
  return origin_ + Position(x, y, z);
120✔
1818
}
1819

1820
double SphericalMesh::find_r_crossing(
443,371,360✔
1821
  const Position& r, const Direction& u, double l, int shell) const
1822
{
1823
  if ((shell < 0) || (shell > shape_[0]))
443,371,360✔
1824
    return INFTY;
39,697,009✔
1825

1826
  // solve |r+s*u| = r0
1827
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
1828
  const double r0 = grid_[0][shell];
403,674,351✔
1829
  if (r0 == 0.0)
403,674,351✔
1830
    return INFTY;
7,287,017✔
1831
  const double p = r.dot(u);
396,387,334✔
1832
  double c = r.dot(r) - r0 * r0;
396,387,334✔
1833
  double D = p * p - c;
396,387,334✔
1834

1835
  if (std::abs(c) <= RADIAL_MESH_TOL)
396,387,334✔
1836
    return INFTY;
10,598,654✔
1837

1838
  if (D >= 0.0) {
385,788,680✔
1839
    D = std::sqrt(D);
357,872,784✔
1840
    // the solution -p - D is always smaller as -p + D : Check this one first
1841
    if (-p - D > l)
357,872,784✔
1842
      return -p - D;
64,319,881✔
1843
    if (-p + D > l)
293,552,903✔
1844
      return -p + D;
176,970,944✔
1845
  }
1846

1847
  return INFTY;
144,497,855✔
1848
}
1849

1850
double SphericalMesh::find_theta_crossing(
109,566,044✔
1851
  const Position& r, const Direction& u, double l, int shell) const
1852
{
1853
  // Theta grid is [0, π], thus there is no real surface to cross
1854
  if (full_theta_ && (shape_[1] == 1))
109,566,044✔
1855
    return INFTY;
71,032,032✔
1856

1857
  shell = sanitize_theta(shell);
38,534,012✔
1858

1859
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
1860
  // yields
1861
  // a*s^2 + 2*b*s + c == 0 with
1862
  // a = cos(theta)^2 - u.z * u.z
1863
  // b = r*u * cos(theta)^2 - u.z * r.z
1864
  // c = r*r * cos(theta)^2 - r.z^2
1865

1866
  const double cos_t = std::cos(grid_[1][shell]);
38,534,012✔
1867
  const bool sgn = std::signbit(cos_t);
38,534,012✔
1868
  const double cos_t_2 = cos_t * cos_t;
38,534,012✔
1869

1870
  const double a = cos_t_2 - u.z * u.z;
38,534,012✔
1871
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,534,012✔
1872
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,534,012✔
1873

1874
  // if factor of s^2 is zero, direction of flight is parallel to theta
1875
  // surface
1876
  if (std::abs(a) < FP_PRECISION) {
38,534,012✔
1877
    // if b vanishes, direction of flight is within theta surface and crossing
1878
    // is not possible
1879
    if (std::abs(b) < FP_PRECISION)
570,284!
1880
      return INFTY;
570,284✔
1881

UNCOV
1882
    const double s = -0.5 * c / b;
×
1883
    // Check if solution is in positive direction of flight and has correct
1884
    // sign
UNCOV
1885
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
UNCOV
1886
      return s;
×
1887

1888
    // no crossing is possible
UNCOV
1889
    return INFTY;
×
1890
  }
1891

1892
  const double p = b / a;
37,963,728✔
1893
  double D = p * p - c / a;
37,963,728✔
1894

1895
  if (D < 0.0)
37,963,728✔
1896
    return INFTY;
11,025,420✔
1897

1898
  D = std::sqrt(D);
26,938,308✔
1899

1900
  // the solution -p-D is always smaller as -p+D : Check this one first
1901
  double s = -p - D;
26,938,308✔
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))
26,938,308✔
1904
    return s;
5,294,623✔
1905

1906
  s = -p + D;
21,643,685✔
1907
  // Check if solution is in positive direction of flight and has correct sign
1908
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
21,643,685✔
1909
    return s;
10,163,296✔
1910

1911
  return INFTY;
11,480,389✔
1912
}
1913

1914
double SphericalMesh::find_phi_crossing(
111,164,682✔
1915
  const Position& r, const Direction& u, double l, int shell) const
1916
{
1917
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1918
  if (full_phi_ && (shape_[2] == 1))
111,164,682✔
1919
    return INFTY;
71,032,032✔
1920

1921
  shell = sanitize_phi(shell);
40,132,650✔
1922

1923
  const double p0 = grid_[2][shell];
40,132,650✔
1924

1925
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1926
  // => x(s) * cos(p0) = y(s) * sin(p0)
1927
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1928
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1929

1930
  const double c0 = std::cos(p0);
40,132,650✔
1931
  const double s0 = std::sin(p0);
40,132,650✔
1932

1933
  const double denominator = (u.x * s0 - u.y * c0);
40,132,650✔
1934

1935
  // Check if direction of flight is not parallel to phi surface
1936
  if (std::abs(denominator) > FP_PRECISION) {
40,132,650✔
1937
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,856,114✔
1938
    // Check if solution is in positive direction of flight and crosses the
1939
    // correct phi surface (not -phi)
1940
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,856,114✔
1941
      return s;
17,628,692✔
1942
  }
1943

1944
  return INFTY;
22,503,958✔
1945
}
1946

1947
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,051,043✔
1948
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1949
  double l) const
1950
{
1951

1952
  if (i == 0) {
332,051,043✔
1953
    return std::min(
221,685,680✔
1954
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,685,680✔
1955
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,371,360✔
1956

1957
  } else if (i == 1) {
110,365,363✔
1958
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
54,783,022✔
1959
                      find_theta_crossing(r0, u, l, ijk[i])),
54,783,022✔
1960
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
54,783,022✔
1961
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
109,566,044✔
1962

1963
  } else {
1964
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,582,341✔
1965
                      find_phi_crossing(r0, u, l, ijk[i])),
55,582,341✔
1966
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,582,341✔
1967
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,164,682✔
1968
  }
1969
}
1970

1971
int SphericalMesh::set_grid()
352✔
1972
{
1973
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
352✔
1974
    static_cast<int>(grid_[1].size()) - 1,
352✔
1975
    static_cast<int>(grid_[2].size()) - 1};
352✔
1976

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

UNCOV
1999
    return OPENMC_E_INVALID_ARGUMENT;
×
2000
  }
2001
  if (grid_[2].back() > 2 * PI) {
352!
UNCOV
2002
    set_errmsg("phi-grids for "
×
2003
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2004
    return OPENMC_E_INVALID_ARGUMENT;
×
2005
  }
2006

2007
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
352!
2008
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
352✔
2009

2010
  double r = grid_[0].back();
352✔
2011
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
352✔
2012
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
352✔
2013

2014
  return 0;
352✔
2015
}
2016

2017
int SphericalMesh::get_index_in_direction(double r, int i) const
204,867,564✔
2018
{
2019
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
204,867,564✔
2020
}
2021

UNCOV
2022
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2023
  Position plot_ll, Position plot_ur) const
2024
{
UNCOV
2025
  fatal_error("Plot of spherical Mesh not implemented");
×
2026

2027
  // Figure out which axes lie in the plane of the plot.
2028
  array<vector<double>, 2> axis_lines;
2029
  return {axis_lines[0], axis_lines[1]};
2030
}
2031

2032
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
297✔
2033
{
2034
  write_dataset(mesh_group, "r_grid", grid_[0]);
297✔
2035
  write_dataset(mesh_group, "theta_grid", grid_[1]);
297✔
2036
  write_dataset(mesh_group, "phi_grid", grid_[2]);
297✔
2037
  write_dataset(mesh_group, "origin", origin_);
297✔
2038
}
297✔
2039

2040
double SphericalMesh::volume(const MeshIndex& ijk) const
1,064✔
2041
{
2042
  double r_i = grid_[0][ijk[0] - 1];
1,064✔
2043
  double r_o = grid_[0][ijk[0]];
1,064✔
2044

2045
  double theta_i = grid_[1][ijk[1] - 1];
1,064✔
2046
  double theta_o = grid_[1][ijk[1]];
1,064✔
2047

2048
  double phi_i = grid_[2][ijk[2] - 1];
1,064✔
2049
  double phi_o = grid_[2][ijk[2]];
1,064✔
2050

2051
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,064✔
2052
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
1,064✔
2053
}
2054

2055
//==============================================================================
2056
// Helper functions for the C API
2057
//==============================================================================
2058

2059
int check_mesh(int32_t index)
7,074✔
2060
{
2061
  if (index < 0 || index >= model::meshes.size()) {
7,074!
UNCOV
2062
    set_errmsg("Index in meshes array is out of bounds.");
×
UNCOV
2063
    return OPENMC_E_OUT_OF_BOUNDS;
×
2064
  }
2065
  return 0;
7,074✔
2066
}
2067

2068
template<class T>
2069
int check_mesh_type(int32_t index)
1,257✔
2070
{
2071
  if (int err = check_mesh(index))
1,257!
UNCOV
2072
    return err;
×
2073

2074
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,257!
2075
  if (!mesh) {
1,257!
UNCOV
2076
    set_errmsg("This function is not valid for input mesh.");
×
UNCOV
2077
    return OPENMC_E_INVALID_TYPE;
×
2078
  }
2079
  return 0;
1,257✔
2080
}
2081

2082
template<class T>
2083
bool is_mesh_type(int32_t index)
2084
{
2085
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2086
  return mesh;
2087
}
2088

2089
//==============================================================================
2090
// C API functions
2091
//==============================================================================
2092

2093
// Return the type of mesh as a C string
2094
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,619✔
2095
{
2096
  if (int err = check_mesh(index))
1,619!
UNCOV
2097
    return err;
×
2098

2099
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,619✔
2100

2101
  return 0;
1,619✔
2102
}
2103

2104
//! Extend the meshes array by n elements
2105
extern "C" int openmc_extend_meshes(
284✔
2106
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2107
{
2108
  if (index_start)
284!
2109
    *index_start = model::meshes.size();
284✔
2110
  std::string mesh_type;
284✔
2111

2112
  for (int i = 0; i < n; ++i) {
568✔
2113
    if (RegularMesh::mesh_type == type) {
284✔
2114
      model::meshes.push_back(make_unique<RegularMesh>());
182✔
2115
    } else if (RectilinearMesh::mesh_type == type) {
102✔
2116
      model::meshes.push_back(make_unique<RectilinearMesh>());
50✔
2117
    } else if (CylindricalMesh::mesh_type == type) {
52✔
2118
      model::meshes.push_back(make_unique<CylindricalMesh>());
26✔
2119
    } else if (SphericalMesh::mesh_type == type) {
26!
2120
      model::meshes.push_back(make_unique<SphericalMesh>());
26✔
2121
    } else {
UNCOV
2122
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2123
    }
2124
  }
2125
  if (index_end)
284!
UNCOV
2126
    *index_end = model::meshes.size() - 1;
×
2127

2128
  return 0;
284✔
2129
}
284✔
2130

2131
//! Adds a new unstructured mesh to OpenMC
UNCOV
2132
extern "C" int openmc_add_unstructured_mesh(
×
2133
  const char filename[], const char library[], int* id)
2134
{
UNCOV
2135
  std::string lib_name(library);
×
UNCOV
2136
  std::string mesh_file(filename);
×
UNCOV
2137
  bool valid_lib = false;
×
2138

2139
#ifdef OPENMC_DAGMC_ENABLED
2140
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2141
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2142
    valid_lib = true;
2143
  }
2144
#endif
2145

2146
#ifdef OPENMC_LIBMESH_ENABLED
2147
  if (lib_name == LibMesh::mesh_lib_type) {
×
2148
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2149
    valid_lib = true;
2150
  }
2151
#endif
2152

UNCOV
2153
  if (!valid_lib) {
×
UNCOV
2154
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2155
                           "by this build of OpenMC",
2156
      lib_name));
UNCOV
2157
    return OPENMC_E_INVALID_ARGUMENT;
×
2158
  }
2159

2160
  // auto-assign new ID
UNCOV
2161
  model::meshes.back()->set_id(-1);
×
UNCOV
2162
  *id = model::meshes.back()->id_;
×
2163

UNCOV
2164
  return 0;
×
UNCOV
2165
}
×
2166

2167
//! Return the index in the meshes array of a mesh with a given ID
2168
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
476✔
2169
{
2170
  auto pair = model::mesh_map.find(id);
476✔
2171
  if (pair == model::mesh_map.end()) {
476!
UNCOV
2172
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
UNCOV
2173
    return OPENMC_E_INVALID_ID;
×
2174
  }
2175
  *index = pair->second;
476✔
2176
  return 0;
476✔
2177
}
2178

2179
//! Return the ID of a mesh
2180
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
3,116✔
2181
{
2182
  if (int err = check_mesh(index))
3,116!
UNCOV
2183
    return err;
×
2184
  *id = model::meshes[index]->id_;
3,116✔
2185
  return 0;
3,116✔
2186
}
2187

2188
//! Set the ID of a mesh
2189
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
284✔
2190
{
2191
  if (int err = check_mesh(index))
284!
UNCOV
2192
    return err;
×
2193
  model::meshes[index]->id_ = id;
284✔
2194
  model::mesh_map[id] = index;
284✔
2195
  return 0;
284✔
2196
}
2197

2198
//! Get the number of elements in a mesh
2199
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
290✔
2200
{
2201
  if (int err = check_mesh(index))
290!
UNCOV
2202
    return err;
×
2203
  *n = model::meshes[index]->n_bins();
290✔
2204
  return 0;
290✔
2205
}
2206

2207
//! Get the volume of each element in the mesh
2208
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
104✔
2209
{
2210
  if (int err = check_mesh(index))
104!
UNCOV
2211
    return err;
×
2212
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
1,144✔
2213
    volumes[i] = model::meshes[index]->volume(i);
1,040✔
2214
  }
2215
  return 0;
104✔
2216
}
2217

2218
//! Get the bounding box of a mesh
2219
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
166✔
2220
{
2221
  if (int err = check_mesh(index))
166!
UNCOV
2222
    return err;
×
2223

2224
  BoundingBox bbox = model::meshes[index]->bounding_box();
166✔
2225

2226
  // set lower left corner values
2227
  ll[0] = bbox.xmin;
166✔
2228
  ll[1] = bbox.ymin;
166✔
2229
  ll[2] = bbox.zmin;
166✔
2230

2231
  // set upper right corner values
2232
  ur[0] = bbox.xmax;
166✔
2233
  ur[1] = bbox.ymax;
166✔
2234
  ur[2] = bbox.zmax;
166✔
2235
  return 0;
166✔
2236
}
2237

2238
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
186✔
2239
  int nz, int table_size, int32_t* materials, double* volumes)
2240
{
2241
  if (int err = check_mesh(index))
186!
2242
    return err;
×
2243

2244
  try {
2245
    model::meshes[index]->material_volumes(
186✔
2246
      nx, ny, nz, table_size, materials, volumes);
2247
  } catch (const std::exception& e) {
13!
2248
    set_errmsg(e.what());
13✔
2249
    if (starts_with(e.what(), "Mesh")) {
13!
2250
      return OPENMC_E_GEOMETRY;
13✔
2251
    } else {
UNCOV
2252
      return OPENMC_E_ALLOCATE;
×
2253
    }
2254
  }
13✔
2255

2256
  return 0;
173✔
2257
}
2258

2259
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
52✔
2260
  Position width, int basis, int* pixels, int32_t* data)
2261
{
2262
  if (int err = check_mesh(index))
52!
2263
    return err;
×
2264
  const auto& mesh = model::meshes[index].get();
52✔
2265

2266
  int pixel_width = pixels[0];
52✔
2267
  int pixel_height = pixels[1];
52✔
2268

2269
  // get pixel size
2270
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
52✔
2271
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
52✔
2272

2273
  // setup basis indices and initial position centered on pixel
2274
  int in_i, out_i;
2275
  Position xyz = origin;
52✔
2276
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
2277
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
52✔
2278
  switch (basis_enum) {
52!
2279
  case PlotBasis::xy:
52✔
2280
    in_i = 0;
52✔
2281
    out_i = 1;
52✔
2282
    break;
52✔
UNCOV
2283
  case PlotBasis::xz:
×
UNCOV
2284
    in_i = 0;
×
UNCOV
2285
    out_i = 2;
×
UNCOV
2286
    break;
×
UNCOV
2287
  case PlotBasis::yz:
×
UNCOV
2288
    in_i = 1;
×
UNCOV
2289
    out_i = 2;
×
UNCOV
2290
    break;
×
UNCOV
2291
  default:
×
UNCOV
2292
    UNREACHABLE();
×
2293
  }
2294

2295
  // set initial position
2296
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
52✔
2297
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
52✔
2298

2299
#pragma omp parallel
24✔
2300
  {
2301
    Position r = xyz;
28✔
2302

2303
#pragma omp for
2304
    for (int y = 0; y < pixel_height; y++) {
588✔
2305
      r[out_i] = xyz[out_i] - out_pixel * y;
560✔
2306
      for (int x = 0; x < pixel_width; x++) {
11,760✔
2307
        r[in_i] = xyz[in_i] + in_pixel * x;
11,200✔
2308
        data[pixel_width * y + x] = mesh->get_bin(r);
11,200✔
2309
      }
2310
    }
2311
  }
2312

2313
  return 0;
52✔
2314
}
2315

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

2328
//! Set the dimension of a regular mesh
2329
extern "C" int openmc_regular_mesh_set_dimension(
208✔
2330
  int32_t index, int n, const int* dims)
2331
{
2332
  if (int err = check_mesh_type<RegularMesh>(index))
208!
UNCOV
2333
    return err;
×
2334
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
208!
2335

2336
  // Copy dimension
2337
  mesh->n_dimension_ = n;
208✔
2338
  std::copy(dims, dims + n, mesh->shape_.begin());
208✔
2339
  return 0;
208✔
2340
}
2341

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

2350
  if (m->lower_left_.dimension() == 0) {
234!
2351
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2352
    return OPENMC_E_ALLOCATE;
×
2353
  }
2354

2355
  *ll = m->lower_left_.data();
234✔
2356
  *ur = m->upper_right_.data();
234✔
2357
  *width = m->width_.data();
234✔
2358
  *n = m->n_dimension_;
234✔
2359
  return 0;
234✔
2360
}
2361

2362
//! Set the regular mesh parameters
2363
extern "C" int openmc_regular_mesh_set_params(
247✔
2364
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2365
{
2366
  if (int err = check_mesh_type<RegularMesh>(index))
247!
UNCOV
2367
    return err;
×
2368
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
247!
2369

2370
  if (m->n_dimension_ == -1) {
247!
UNCOV
2371
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
UNCOV
2372
    return OPENMC_E_UNASSIGNED;
×
2373
  }
2374

2375
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
247✔
2376
  if (ll && ur) {
247✔
2377
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
221✔
2378
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
221✔
2379
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
221✔
2380
  } else if (ll && width) {
26!
2381
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
13✔
2382
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
13✔
2383
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
13✔
2384
  } else if (ur && width) {
13!
2385
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
13✔
2386
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
13✔
2387
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
13✔
2388
  } else {
UNCOV
2389
    set_errmsg("At least two parameters must be specified.");
×
UNCOV
2390
    return OPENMC_E_INVALID_ARGUMENT;
×
2391
  }
2392

2393
  // Set material volumes
2394

2395
  // TODO: incorporate this into method in RegularMesh that can be called from
2396
  // here and from constructor
2397
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
247✔
2398
  m->element_volume_ = 1.0;
247✔
2399
  for (int i = 0; i < m->n_dimension_; i++) {
988✔
2400
    m->element_volume_ *= m->width_[i];
741✔
2401
  }
2402

2403
  return 0;
247✔
2404
}
247✔
2405

2406
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2407
template<class C>
2408
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
102✔
2409
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2410
  const int nz)
2411
{
2412
  if (int err = check_mesh_type<C>(index))
102!
UNCOV
2413
    return err;
×
2414

2415
  C* m = dynamic_cast<C*>(model::meshes[index].get());
102!
2416

2417
  m->n_dimension_ = 3;
102✔
2418

2419
  m->grid_[0].reserve(nx);
102✔
2420
  m->grid_[1].reserve(ny);
102✔
2421
  m->grid_[2].reserve(nz);
102✔
2422

2423
  for (int i = 0; i < nx; i++) {
648✔
2424
    m->grid_[0].push_back(grid_x[i]);
546✔
2425
  }
2426
  for (int i = 0; i < ny; i++) {
397✔
2427
    m->grid_[1].push_back(grid_y[i]);
295✔
2428
  }
2429
  for (int i = 0; i < nz; i++) {
371✔
2430
    m->grid_[2].push_back(grid_z[i]);
269✔
2431
  }
2432

2433
  int err = m->set_grid();
102✔
2434
  return err;
102✔
2435
}
2436

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

2446
  if (m->lower_left_.dimension() == 0) {
453!
2447
    set_errmsg("Mesh parameters have not been set.");
×
2448
    return OPENMC_E_ALLOCATE;
×
2449
  }
2450

2451
  *grid_x = m->grid_[0].data();
453✔
2452
  *nx = m->grid_[0].size();
453✔
2453
  *grid_y = m->grid_[1].data();
453✔
2454
  *ny = m->grid_[1].size();
453✔
2455
  *grid_z = m->grid_[2].data();
453✔
2456
  *nz = m->grid_[2].size();
453✔
2457

2458
  return 0;
453✔
2459
}
2460

2461
//! Get the rectilinear mesh grid
2462
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
167✔
2463
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2464
{
2465
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
167✔
2466
    index, grid_x, nx, grid_y, ny, grid_z, nz);
167✔
2467
}
2468

2469
//! Set the rectilienar mesh parameters
2470
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
50✔
2471
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2472
  const double* grid_z, const int nz)
2473
{
2474
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
50✔
2475
    index, grid_x, nx, grid_y, ny, grid_z, nz);
50✔
2476
}
2477

2478
//! Get the cylindrical mesh grid
2479
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
143✔
2480
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2481
{
2482
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
143✔
2483
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2484
}
2485

2486
//! Set the cylindrical mesh parameters
2487
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
26✔
2488
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2489
  const double* grid_z, const int nz)
2490
{
2491
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
26✔
2492
    index, grid_x, nx, grid_y, ny, grid_z, nz);
26✔
2493
}
2494

2495
//! Get the spherical mesh grid
2496
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
143✔
2497
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2498
{
2499

2500
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
143✔
2501
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2502
  ;
2503
}
2504

2505
//! Set the spherical mesh parameters
2506
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
26✔
2507
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2508
  const double* grid_z, const int nz)
2509
{
2510
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
26✔
2511
    index, grid_x, nx, grid_y, ny, grid_z, nz);
26✔
2512
}
2513

2514
#ifdef OPENMC_DAGMC_ENABLED
2515

2516
const std::string MOABMesh::mesh_lib_type = "moab";
2517

2518
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
2519
{
2520
  initialize();
23✔
2521
}
23✔
2522

2523
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2524
  : UnstructuredMesh()
×
2525
{
2526
  n_dimension_ = 3;
2527
  filename_ = filename;
×
2528
  set_length_multiplier(length_multiplier);
×
2529
  initialize();
×
2530
}
2531

2532
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2533
{
2534
  mbi_ = external_mbi;
1✔
2535
  filename_ = "unknown (external file)";
1✔
2536
  this->initialize();
1✔
2537
}
1✔
2538

2539
void MOABMesh::initialize()
24✔
2540
{
2541

2542
  // Create the MOAB interface and load data from file
2543
  this->create_interface();
24✔
2544

2545
  // Initialise MOAB error code
2546
  moab::ErrorCode rval = moab::MB_SUCCESS;
24✔
2547

2548
  // Set the dimension
2549
  n_dimension_ = 3;
24✔
2550

2551
  // set member range of tetrahedral entities
2552
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
24✔
2553
  if (rval != moab::MB_SUCCESS) {
24!
2554
    fatal_error("Failed to get all tetrahedral elements");
2555
  }
2556

2557
  if (!ehs_.all_of_type(moab::MBTET)) {
24!
2558
    warning("Non-tetrahedral elements found in unstructured "
×
2559
            "mesh file: " +
2560
            filename_);
2561
  }
2562

2563
  // set member range of vertices
2564
  int vertex_dim = 0;
24✔
2565
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
24✔
2566
  if (rval != moab::MB_SUCCESS) {
24!
2567
    fatal_error("Failed to get all vertex handles");
2568
  }
2569

2570
  // make an entity set for all tetrahedra
2571
  // this is used for convenience later in output
2572
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
24✔
2573
  if (rval != moab::MB_SUCCESS) {
24!
2574
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2575
  }
2576

2577
  rval = mbi_->add_entities(tetset_, ehs_);
24✔
2578
  if (rval != moab::MB_SUCCESS) {
24!
2579
    fatal_error("Failed to add tetrahedra to an entity set.");
2580
  }
2581

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

2610
  // Determine bounds of mesh
2611
  this->determine_bounds();
24✔
2612
}
24✔
2613

2614
void MOABMesh::prepare_for_point_location()
20✔
2615
{
2616
  // if the KDTree has already been constructed, do nothing
2617
  if (kdtree_)
20!
2618
    return;
2619

2620
  // build acceleration data structures
2621
  compute_barycentric_data(ehs_);
20✔
2622
  build_kdtree(ehs_);
20✔
2623
}
2624

2625
void MOABMesh::create_interface()
24✔
2626
{
2627
  // Do not create a MOAB instance if one is already in memory
2628
  if (mbi_)
24✔
2629
    return;
1✔
2630

2631
  // create MOAB instance
2632
  mbi_ = std::make_shared<moab::Core>();
23✔
2633

2634
  // load unstructured mesh file
2635
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
23✔
2636
  if (rval != moab::MB_SUCCESS) {
23!
2637
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2638
  }
2639
}
2640

2641
void MOABMesh::build_kdtree(const moab::Range& all_tets)
20✔
2642
{
2643
  moab::Range all_tris;
20✔
2644
  int adj_dim = 2;
20✔
2645
  write_message("Getting tet adjacencies...", 7);
20✔
2646
  moab::ErrorCode rval = mbi_->get_adjacencies(
20✔
2647
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2648
  if (rval != moab::MB_SUCCESS) {
20!
2649
    fatal_error("Failed to get adjacent triangles for tets");
2650
  }
2651

2652
  if (!all_tris.all_of_type(moab::MBTRI)) {
20!
2653
    warning("Non-triangle elements found in tet adjacencies in "
×
2654
            "unstructured mesh file: " +
2655
            filename_);
×
2656
  }
2657

2658
  // combine into one range
2659
  moab::Range all_tets_and_tris;
20✔
2660
  all_tets_and_tris.merge(all_tets);
20✔
2661
  all_tets_and_tris.merge(all_tris);
20✔
2662

2663
  // create a kd-tree instance
2664
  write_message(
20✔
2665
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
20✔
2666
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
20✔
2667

2668
  // Determine what options to use
2669
  std::ostringstream options_stream;
20✔
2670
  if (options_.empty()) {
20✔
2671
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
4✔
2672
  } else {
2673
    options_stream << options_;
16✔
2674
  }
2675
  moab::FileOptions file_opts(options_stream.str().c_str());
20✔
2676

2677
  // Build the k-d tree
2678
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
20✔
2679
  if (rval != moab::MB_SUCCESS) {
20!
2680
    fatal_error("Failed to construct KDTree for the "
2681
                "unstructured mesh file: " +
2682
                filename_);
×
2683
  }
2684
}
20✔
2685

2686
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,564✔
2687
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2688
{
2689
  hits.clear();
1,543,564✔
2690

2691
  moab::ErrorCode rval;
2692
  vector<moab::EntityHandle> tris;
1,543,564✔
2693
  // get all intersections with triangles in the tet mesh
2694
  // (distances are relative to the start point, not the previous
2695
  // intersection)
2696
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,564✔
2697
    dir.array(), start.array(), tris, hits, 0, track_len);
2698
  if (rval != moab::MB_SUCCESS) {
1,543,564!
2699
    fatal_error(
2700
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
2701
  }
2702

2703
  // remove duplicate intersection distances
2704
  std::unique(hits.begin(), hits.end());
1,543,564✔
2705

2706
  // sorts by first component of std::pair by default
2707
  std::sort(hits.begin(), hits.end());
1,543,564✔
2708
}
1,543,564✔
2709

2710
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,564✔
2711
  vector<int>& bins, vector<double>& lengths) const
2712
{
2713
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,564✔
2714
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,564✔
2715
  moab::CartVect dir(u.x, u.y, u.z);
1,543,564✔
2716
  dir.normalize();
1,543,564✔
2717

2718
  double track_len = (end - start).length();
1,543,564✔
2719
  if (track_len == 0.0)
1,543,564!
2720
    return;
721,692✔
2721

2722
  start -= TINY_BIT * dir;
1,543,564✔
2723
  end += TINY_BIT * dir;
1,543,564✔
2724

2725
  vector<double> hits;
1,543,564✔
2726
  intersect_track(start, dir, track_len, hits);
1,543,564✔
2727

2728
  bins.clear();
1,543,564✔
2729
  lengths.clear();
1,543,564✔
2730

2731
  // if there are no intersections the track may lie entirely
2732
  // within a single tet. If this is the case, apply entire
2733
  // score to that tet and return.
2734
  if (hits.size() == 0) {
1,543,564✔
2735
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
2736
    int bin = this->get_bin(midpoint);
721,692✔
2737
    if (bin != -1) {
721,692✔
2738
      bins.push_back(bin);
242,866✔
2739
      lengths.push_back(1.0);
242,866✔
2740
    }
2741
    return;
721,692✔
2742
  }
2743

2744
  // for each segment in the set of tracks, try to look up a tet
2745
  // at the midpoint of the segment
2746
  Position current = r0;
821,872✔
2747
  double last_dist = 0.0;
821,872✔
2748
  for (const auto& hit : hits) {
5,516,019✔
2749
    // get the segment length
2750
    double segment_length = hit - last_dist;
4,694,147✔
2751
    last_dist = hit;
4,694,147✔
2752
    // find the midpoint of this segment
2753
    Position midpoint = current + u * (segment_length * 0.5);
4,694,147✔
2754
    // try to find a tet for this position
2755
    int bin = this->get_bin(midpoint);
4,694,147✔
2756

2757
    // determine the start point for this segment
2758
    current = r0 + u * hit;
4,694,147✔
2759

2760
    if (bin == -1) {
4,694,147✔
2761
      continue;
20,522✔
2762
    }
2763

2764
    bins.push_back(bin);
4,673,625✔
2765
    lengths.push_back(segment_length / track_len);
4,673,625✔
2766
  }
2767

2768
  // tally remaining portion of track after last hit if
2769
  // the last segment of the track is in the mesh but doesn't
2770
  // reach the other side of the tet
2771
  if (hits.back() < track_len) {
821,872!
2772
    Position segment_start = r0 + u * hits.back();
821,872✔
2773
    double segment_length = track_len - hits.back();
821,872✔
2774
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,872✔
2775
    int bin = this->get_bin(midpoint);
821,872✔
2776
    if (bin != -1) {
821,872✔
2777
      bins.push_back(bin);
766,509✔
2778
      lengths.push_back(segment_length / track_len);
766,509✔
2779
    }
2780
  }
2781
};
1,543,564✔
2782

2783
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,030✔
2784
{
2785
  moab::CartVect pos(r.x, r.y, r.z);
7,317,030✔
2786
  // find the leaf of the kd-tree for this position
2787
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,030✔
2788
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,030✔
2789
  if (rval != moab::MB_SUCCESS) {
7,317,030✔
2790
    return 0;
1,011,877✔
2791
  }
2792

2793
  // retrieve the tet elements of this leaf
2794
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,153✔
2795
  moab::Range tets;
6,305,153✔
2796
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,153✔
2797
  if (rval != moab::MB_SUCCESS) {
6,305,153!
2798
    warning("MOAB error finding tets.");
×
2799
  }
2800

2801
  // loop over the tets in this leaf, returning the containing tet if found
2802
  for (const auto& tet : tets) {
260,209,001✔
2803
    if (point_in_tet(pos, tet)) {
260,206,154✔
2804
      return tet;
6,302,306✔
2805
    }
2806
  }
2807

2808
  // if no tet is found, return an invalid handle
2809
  return 0;
2,847✔
2810
}
7,317,030✔
2811

2812
double MOABMesh::volume(int bin) const
167,856✔
2813
{
2814
  return tet_volume(get_ent_handle_from_bin(bin));
167,856✔
2815
}
2816

2817
std::string MOABMesh::library() const
32✔
2818
{
2819
  return mesh_lib_type;
32✔
2820
}
2821

2822
// Sample position within a tet for MOAB type tets
2823
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
2824
{
2825

2826
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
2827

2828
  // Get vertex coordinates for MOAB tet
2829
  const moab::EntityHandle* conn1;
2830
  int conn1_size;
2831
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
2832
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
2833
    fatal_error(fmt::format(
×
2834
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
2835
      conn1_size));
2836
  }
2837
  moab::CartVect p[4];
1,002,050✔
2838
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
2839
  if (rval != moab::MB_SUCCESS) {
200,410!
2840
    fatal_error("Failed to get tet coords");
2841
  }
2842

2843
  std::array<Position, 4> tet_verts;
200,410✔
2844
  for (int i = 0; i < 4; i++) {
1,002,050✔
2845
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
2846
  }
2847
  // Samples position within tet using Barycentric stuff
2848
  return this->sample_tet(tet_verts, seed);
400,820✔
2849
}
2850

2851
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,856✔
2852
{
2853
  vector<moab::EntityHandle> conn;
167,856✔
2854
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,856✔
2855
  if (rval != moab::MB_SUCCESS) {
167,856!
2856
    fatal_error("Failed to get tet connectivity");
2857
  }
2858

2859
  moab::CartVect p[4];
839,280✔
2860
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,856✔
2861
  if (rval != moab::MB_SUCCESS) {
167,856!
2862
    fatal_error("Failed to get tet coords");
2863
  }
2864

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

2868
int MOABMesh::get_bin(Position r) const
7,317,030✔
2869
{
2870
  moab::EntityHandle tet = get_tet(r);
7,317,030✔
2871
  if (tet == 0) {
7,317,030✔
2872
    return -1;
1,014,724✔
2873
  } else {
2874
    return get_bin_from_ent_handle(tet);
6,302,306✔
2875
  }
2876
}
2877

2878
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
20✔
2879
{
2880
  moab::ErrorCode rval;
2881

2882
  baryc_data_.clear();
20✔
2883
  baryc_data_.resize(tets.size());
20✔
2884

2885
  // compute the barycentric data for each tet element
2886
  // and store it as a 3x3 matrix
2887
  for (auto& tet : tets) {
239,732✔
2888
    vector<moab::EntityHandle> verts;
239,712✔
2889
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,712✔
2890
    if (rval != moab::MB_SUCCESS) {
239,712!
2891
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
2892
    }
2893

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

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

2902
    // invert now to avoid this cost later
2903
    a = a.transpose().inverse();
239,712✔
2904
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,712✔
2905
  }
239,712✔
2906
}
20✔
2907

2908
bool MOABMesh::point_in_tet(
260,206,154✔
2909
  const moab::CartVect& r, moab::EntityHandle tet) const
2910
{
2911

2912
  moab::ErrorCode rval;
2913

2914
  // get tet vertices
2915
  vector<moab::EntityHandle> verts;
260,206,154✔
2916
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,206,154✔
2917
  if (rval != moab::MB_SUCCESS) {
260,206,154!
2918
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
2919
    return false;
2920
  }
2921

2922
  // first vertex is used as a reference point for the barycentric data -
2923
  // retrieve its coordinates
2924
  moab::CartVect p_zero;
260,206,154✔
2925
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,206,154✔
2926
  if (rval != moab::MB_SUCCESS) {
260,206,154!
2927
    warning("Failed to get coordinates of a vertex in "
×
2928
            "unstructured mesh: " +
2929
            filename_);
×
2930
    return false;
2931
  }
2932

2933
  // look up barycentric data
2934
  int idx = get_bin_from_ent_handle(tet);
260,206,154✔
2935
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,206,154✔
2936

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

2939
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
421,413,584✔
2940
          bary_coords[2] >= 0.0 &&
443,101,423✔
2941
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
281,893,993✔
2942
}
260,206,154✔
2943

2944
int MOABMesh::get_bin_from_index(int idx) const
2945
{
2946
  if (idx >= n_bins()) {
×
2947
    fatal_error(fmt::format("Invalid bin index: {}", idx));
×
2948
  }
2949
  return ehs_[idx] - ehs_[0];
2950
}
2951

2952
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
2953
{
2954
  int bin = get_bin(r);
2955
  *in_mesh = bin != -1;
2956
  return bin;
2957
}
2958

2959
int MOABMesh::get_index_from_bin(int bin) const
2960
{
2961
  return bin;
2962
}
2963

2964
std::pair<vector<double>, vector<double>> MOABMesh::plot(
2965
  Position plot_ll, Position plot_ur) const
2966
{
2967
  // TODO: Implement mesh lines
2968
  return {};
2969
}
2970

2971
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,424✔
2972
{
2973
  int idx = vert - verts_[0];
815,424✔
2974
  if (idx >= n_vertices()) {
815,424!
2975
    fatal_error(
2976
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
2977
  }
2978
  return idx;
815,424✔
2979
}
2980

2981
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,748,172✔
2982
{
2983
  int bin = eh - ehs_[0];
266,748,172✔
2984
  if (bin >= n_bins()) {
266,748,172!
2985
    fatal_error(fmt::format("Invalid bin: {}", bin));
×
2986
  }
2987
  return bin;
266,748,172✔
2988
}
2989

2990
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,122✔
2991
{
2992
  if (bin >= n_bins()) {
572,122!
2993
    fatal_error(fmt::format("Invalid bin index: ", bin));
×
2994
  }
2995
  return ehs_[0] + bin;
572,122✔
2996
}
2997

2998
int MOABMesh::n_bins() const
267,524,219✔
2999
{
3000
  return ehs_.size();
267,524,219✔
3001
}
3002

3003
int MOABMesh::n_surface_bins() const
3004
{
3005
  // collect all triangles in the set of tets for this mesh
3006
  moab::Range tris;
×
3007
  moab::ErrorCode rval;
3008
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3009
  if (rval != moab::MB_SUCCESS) {
×
3010
    warning("Failed to get all triangles in the mesh instance");
×
3011
    return -1;
3012
  }
3013
  return 2 * tris.size();
×
3014
}
3015

3016
Position MOABMesh::centroid(int bin) const
3017
{
3018
  moab::ErrorCode rval;
3019

3020
  auto tet = this->get_ent_handle_from_bin(bin);
×
3021

3022
  // look up the tet connectivity
3023
  vector<moab::EntityHandle> conn;
3024
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3025
  if (rval != moab::MB_SUCCESS) {
×
3026
    warning("Failed to get connectivity of a mesh element.");
×
3027
    return {};
3028
  }
3029

3030
  // get the coordinates
3031
  vector<moab::CartVect> coords(conn.size());
×
3032
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3033
  if (rval != moab::MB_SUCCESS) {
×
3034
    warning("Failed to get the coordinates of a mesh element.");
×
3035
    return {};
3036
  }
3037

3038
  // compute the centroid of the element vertices
3039
  moab::CartVect centroid(0.0, 0.0, 0.0);
3040
  for (const auto& coord : coords) {
×
3041
    centroid += coord;
3042
  }
3043
  centroid /= double(coords.size());
3044

3045
  return {centroid[0], centroid[1], centroid[2]};
3046
}
3047

3048
int MOABMesh::n_vertices() const
845,761✔
3049
{
3050
  return verts_.size();
845,761✔
3051
}
3052

3053
Position MOABMesh::vertex(int id) const
86,199✔
3054
{
3055

3056
  moab::ErrorCode rval;
3057

3058
  moab::EntityHandle vert = verts_[id];
86,199✔
3059

3060
  moab::CartVect coords;
86,199✔
3061
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,199✔
3062
  if (rval != moab::MB_SUCCESS) {
86,199!
3063
    fatal_error("Failed to get the coordinates of a vertex.");
3064
  }
3065

3066
  return {coords[0], coords[1], coords[2]};
172,398✔
3067
}
3068

3069
std::vector<int> MOABMesh::connectivity(int bin) const
203,856✔
3070
{
3071
  moab::ErrorCode rval;
3072

3073
  auto tet = get_ent_handle_from_bin(bin);
203,856✔
3074

3075
  // look up the tet connectivity
3076
  vector<moab::EntityHandle> conn;
203,856✔
3077
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,856✔
3078
  if (rval != moab::MB_SUCCESS) {
203,856!
3079
    fatal_error("Failed to get connectivity of a mesh element.");
3080
    return {};
3081
  }
3082

3083
  std::vector<int> verts(4);
203,856✔
3084
  for (int i = 0; i < verts.size(); i++) {
1,019,280✔
3085
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,424✔
3086
  }
3087

3088
  return verts;
203,856✔
3089
}
203,856✔
3090

3091
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3092
  std::string score) const
3093
{
3094
  moab::ErrorCode rval;
3095
  // add a tag to the mesh
3096
  // all scores are treated as a single value
3097
  // with an uncertainty
3098
  moab::Tag value_tag;
3099

3100
  // create the value tag if not present and get handle
3101
  double default_val = 0.0;
3102
  auto val_string = score + "_mean";
×
3103
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3104
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3105
  if (rval != moab::MB_SUCCESS) {
×
3106
    auto msg =
3107
      fmt::format("Could not create or retrieve the value tag for the score {}"
3108
                  " on unstructured mesh {}",
3109
        score, id_);
×
3110
    fatal_error(msg);
3111
  }
3112

3113
  // create the std dev tag if not present and get handle
3114
  moab::Tag error_tag;
3115
  std::string err_string = score + "_std_dev";
×
3116
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3117
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3118
  if (rval != moab::MB_SUCCESS) {
×
3119
    auto msg =
3120
      fmt::format("Could not create or retrieve the error tag for the score {}"
3121
                  " on unstructured mesh {}",
3122
        score, id_);
×
3123
    fatal_error(msg);
3124
  }
3125

3126
  // return the populated tag handles
3127
  return {value_tag, error_tag};
3128
}
3129

3130
void MOABMesh::add_score(const std::string& score)
3131
{
3132
  auto score_tags = get_score_tags(score);
×
3133
  tag_names_.push_back(score);
×
3134
}
3135

3136
void MOABMesh::remove_scores()
3137
{
3138
  for (const auto& name : tag_names_) {
×
3139
    auto value_name = name + "_mean";
×
3140
    moab::Tag tag;
3141
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3142
    if (rval != moab::MB_SUCCESS)
×
3143
      return;
3144

3145
    rval = mbi_->tag_delete(tag);
×
3146
    if (rval != moab::MB_SUCCESS) {
×
3147
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3148
                             " on unstructured mesh {}",
3149
        name, id_);
×
3150
      fatal_error(msg);
3151
    }
3152

3153
    auto std_dev_name = name + "_std_dev";
×
3154
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3155
    if (rval != moab::MB_SUCCESS) {
×
3156
      auto msg =
3157
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3158
                    " on unstructured mesh {}",
3159
          name, id_);
×
3160
    }
3161

3162
    rval = mbi_->tag_delete(tag);
×
3163
    if (rval != moab::MB_SUCCESS) {
×
3164
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3165
                             " on unstructured mesh {}",
3166
        name, id_);
×
3167
      fatal_error(msg);
3168
    }
3169
  }
×
3170
  tag_names_.clear();
3171
}
3172

3173
void MOABMesh::set_score_data(const std::string& score,
3174
  const vector<double>& values, const vector<double>& std_dev)
3175
{
3176
  auto score_tags = this->get_score_tags(score);
×
3177

3178
  moab::ErrorCode rval;
3179
  // set the score value
3180
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
×
3181
  if (rval != moab::MB_SUCCESS) {
×
3182
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3183
                           "on unstructured mesh {}",
3184
      score, id_);
×
3185
    warning(msg);
×
3186
  }
3187

3188
  // set the error value
3189
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
×
3190
  if (rval != moab::MB_SUCCESS) {
×
3191
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3192
                           "on unstructured mesh {}",
3193
      score, id_);
×
3194
    warning(msg);
×
3195
  }
3196
}
3197

3198
void MOABMesh::write(const std::string& base_filename) const
3199
{
3200
  // add extension to the base name
3201
  auto filename = base_filename + ".vtk";
×
3202
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3203
  filename = settings::path_output + filename;
×
3204

3205
  // write the tetrahedral elements of the mesh only
3206
  // to avoid clutter from zero-value data on other
3207
  // elements during visualization
3208
  moab::ErrorCode rval;
3209
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3210
  if (rval != moab::MB_SUCCESS) {
×
3211
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3212
    warning(msg);
×
3213
  }
3214
}
3215

3216
#endif
3217

3218
#ifdef OPENMC_LIBMESH_ENABLED
3219

3220
const std::string LibMesh::mesh_lib_type = "libmesh";
3221

3222
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
3223
{
3224
  // filename_ and length_multiplier_ will already be set by the
3225
  // UnstructuredMesh constructor
3226
  set_mesh_pointer_from_filename(filename_);
23✔
3227
  set_length_multiplier(length_multiplier_);
23✔
3228
  initialize();
23✔
3229
}
23✔
3230

3231
// create the mesh from a pointer to a libMesh Mesh
3232
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3233
{
3234
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
×
3235
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3236
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3237
  }
3238

3239
  m_ = &input_mesh;
3240
  set_length_multiplier(length_multiplier);
×
3241
  initialize();
×
3242
}
3243

3244
// create the mesh from an input file
3245
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3246
{
3247
  n_dimension_ = 3;
3248
  set_mesh_pointer_from_filename(filename);
×
3249
  set_length_multiplier(length_multiplier);
×
3250
  initialize();
×
3251
}
3252

3253
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23✔
3254
{
3255
  filename_ = filename;
23✔
3256
  unique_m_ =
3257
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23✔
3258
  m_ = unique_m_.get();
23✔
3259
  m_->read(filename_);
23✔
3260
}
23✔
3261

3262
// build a libMesh equation system for storing values
3263
void LibMesh::build_eqn_sys()
15✔
3264
{
3265
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
30✔
3266
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15✔
3267
  libMesh::ExplicitSystem& eq_sys =
3268
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15✔
3269
}
15✔
3270

3271
// intialize from mesh file
3272
void LibMesh::initialize()
23✔
3273
{
3274
  if (!settings::libmesh_comm) {
23!
3275
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3276
                "communicator.");
3277
  }
3278

3279
  // assuming that unstructured meshes used in OpenMC are 3D
3280
  n_dimension_ = 3;
23✔
3281

3282
  if (length_multiplier_ > 0.0) {
23!
3283
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
×
3284
  }
3285
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3286
  // Otherwise assume that it is prepared by its owning application
3287
  if (unique_m_) {
23!
3288
    m_->prepare_for_use();
23✔
3289
  }
3290

3291
  // ensure that the loaded mesh is 3 dimensional
3292
  if (m_->mesh_dimension() != n_dimension_) {
23!
3293
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3294
                            "mesh is not a 3D mesh.",
3295
      filename_));
3296
  }
3297

3298
  for (int i = 0; i < num_threads(); i++) {
69✔
3299
    pl_.emplace_back(m_->sub_point_locator());
46✔
3300
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3301
    pl_.back()->enable_out_of_mesh_mode();
46✔
3302
  }
3303

3304
  // store first element in the mesh to use as an offset for bin indices
3305
  auto first_elem = *m_->elements_begin();
23✔
3306
  first_element_id_ = first_elem->id();
23✔
3307

3308
  // bounding box for the mesh for quick rejection checks
3309
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23✔
3310
  libMesh::Point ll = bbox_.min();
23✔
3311
  libMesh::Point ur = bbox_.max();
23✔
3312
  lower_left_ = {ll(0), ll(1), ll(2)};
23✔
3313
  upper_right_ = {ur(0), ur(1), ur(2)};
23✔
3314
}
23✔
3315

3316
// Sample position within a tet for LibMesh type tets
3317
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3318
{
3319
  const auto& elem = get_element_from_bin(bin);
400,820✔
3320
  // Get tet vertex coordinates from LibMesh
3321
  std::array<Position, 4> tet_verts;
400,820✔
3322
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3323
    auto node_ref = elem.node_ref(i);
1,603,280✔
3324
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3325
  }
1,603,280✔
3326
  // Samples position within tet using Barycentric coordinates
3327
  return this->sample_tet(tet_verts, seed);
801,640✔
3328
}
3329

3330
Position LibMesh::centroid(int bin) const
3331
{
3332
  const auto& elem = this->get_element_from_bin(bin);
×
3333
  auto centroid = elem.vertex_average();
×
3334
  return {centroid(0), centroid(1), centroid(2)};
3335
}
3336

3337
int LibMesh::n_vertices() const
39,978✔
3338
{
3339
  return m_->n_nodes();
39,978✔
3340
}
3341

3342
Position LibMesh::vertex(int vertex_id) const
39,942✔
3343
{
3344
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3345
  return {node_ref(0), node_ref(1), node_ref(2)};
79,884✔
3346
}
39,942✔
3347

3348
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
3349
{
3350
  std::vector<int> conn;
265,856✔
3351
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
3352
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
3353
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
3354
  }
3355
  return conn;
265,856✔
3356
}
3357

3358
std::string LibMesh::library() const
33✔
3359
{
3360
  return mesh_lib_type;
33✔
3361
}
3362

3363
int LibMesh::n_bins() const
1,784,287✔
3364
{
3365
  return m_->n_elem();
1,784,287✔
3366
}
3367

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

3386
void LibMesh::add_score(const std::string& var_name)
15✔
3387
{
3388
  if (!equation_systems_) {
15!
3389
    build_eqn_sys();
15✔
3390
  }
3391

3392
  // check if this is a new variable
3393
  std::string value_name = var_name + "_mean";
15✔
3394
  if (!variable_map_.count(value_name)) {
15!
3395
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3396
    auto var_num =
3397
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3398
    variable_map_[value_name] = var_num;
15✔
3399
  }
3400

3401
  std::string std_dev_name = var_name + "_std_dev";
15✔
3402
  // check if this is a new variable
3403
  if (!variable_map_.count(std_dev_name)) {
15!
3404
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3405
    auto var_num =
3406
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3407
    variable_map_[std_dev_name] = var_num;
15✔
3408
  }
3409
}
15✔
3410

3411
void LibMesh::remove_scores()
15✔
3412
{
3413
  if (equation_systems_) {
15!
3414
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3415
    eqn_sys.clear();
15✔
3416
    variable_map_.clear();
15✔
3417
  }
3418
}
15✔
3419

3420
void LibMesh::set_score_data(const std::string& var_name,
15✔
3421
  const vector<double>& values, const vector<double>& std_dev)
3422
{
3423
  if (!equation_systems_) {
15!
3424
    build_eqn_sys();
×
3425
  }
3426

3427
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3428

3429
  if (!eqn_sys.is_initialized()) {
15!
3430
    equation_systems_->init();
15✔
3431
  }
3432

3433
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3434

3435
  // look up the value variable
3436
  std::string value_name = var_name + "_mean";
15✔
3437
  unsigned int value_num = variable_map_.at(value_name);
15✔
3438
  // look up the std dev variable
3439
  std::string std_dev_name = var_name + "_std_dev";
15✔
3440
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15✔
3441

3442
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
97,871✔
3443
       it++) {
3444
    if (!(*it)->active()) {
97,856!
3445
      continue;
3446
    }
3447

3448
    auto bin = get_bin_from_element(*it);
97,856✔
3449

3450
    // set value
3451
    vector<libMesh::dof_id_type> value_dof_indices;
97,856✔
3452
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856✔
3453
    assert(value_dof_indices.size() == 1);
3454
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856✔
3455

3456
    // set std dev
3457
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
3458
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
3459
    assert(std_dev_dof_indices.size() == 1);
3460
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
3461
  }
97,871✔
3462
}
15✔
3463

3464
void LibMesh::write(const std::string& filename) const
15✔
3465
{
3466
  write_message(fmt::format(
15✔
3467
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15✔
3468
  libMesh::ExodusII_IO exo(*m_);
15✔
3469
  std::set<std::string> systems_out = {eq_system_name_};
45✔
3470
  exo.write_discontinuous_exodusII(
15✔
3471
    filename + ".e", *equation_systems_, &systems_out);
30✔
3472
}
15✔
3473

3474
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3475
  vector<int>& bins, vector<double>& lengths) const
3476
{
3477
  // TODO: Implement triangle crossings here
3478
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3479
}
3480

3481
int LibMesh::get_bin(Position r) const
2,340,484✔
3482
{
3483
  // look-up a tet using the point locator
3484
  libMesh::Point p(r.x, r.y, r.z);
2,340,484✔
3485

3486
  // quick rejection check
3487
  if (!bbox_.contains_point(p)) {
2,340,484✔
3488
    return -1;
918,796✔
3489
  }
3490

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

3493
  const auto elem_ptr = (*point_locator)(p);
1,421,688✔
3494
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,688✔
3495
}
2,340,484✔
3496

3497
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,314✔
3498
{
3499
  int bin = elem->id() - first_element_id_;
1,518,314✔
3500
  if (bin >= n_bins() || bin < 0) {
1,518,314!
3501
    fatal_error(fmt::format("Invalid bin: {}", bin));
3502
  }
3503
  return bin;
1,518,314✔
3504
}
3505

3506
std::pair<vector<double>, vector<double>> LibMesh::plot(
3507
  Position plot_ll, Position plot_ur) const
3508
{
3509
  return {};
3510
}
3511

3512
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3513
{
3514
  return m_->elem_ref(bin);
765,460✔
3515
}
3516

3517
double LibMesh::volume(int bin) const
364,640✔
3518
{
3519
  return this->get_element_from_bin(bin).volume();
364,640✔
3520
}
3521

3522
AdaptiveLibMesh::AdaptiveLibMesh(
3523
  libMesh::MeshBase& input_mesh, double length_multiplier)
3524
  : LibMesh(input_mesh, length_multiplier), num_active_(m_->n_active_elem())
×
3525
{
3526
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3527
  // contiguous in ID space, so we need to map from bin indices (defined over
3528
  // active elements) to global dof ids
3529
  bin_to_elem_map_.reserve(num_active_);
×
3530
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3531
  for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
×
3532
       it++) {
3533
    auto elem = *it;
×
3534

3535
    bin_to_elem_map_.push_back(elem->id());
×
3536
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3537
  }
3538
}
3539

3540
int AdaptiveLibMesh::n_bins() const
3541
{
3542
  return num_active_;
3543
}
3544

3545
void AdaptiveLibMesh::add_score(const std::string& var_name)
3546
{
3547
  warning(fmt::format(
×
3548
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3549
    this->id_));
3550
}
3551

3552
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3553
  const vector<double>& values, const vector<double>& std_dev)
3554
{
3555
  warning(fmt::format(
×
3556
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3557
    this->id_));
3558
}
3559

3560
void AdaptiveLibMesh::write(const std::string& filename) const
3561
{
3562
  warning(fmt::format(
×
3563
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3564
    this->id_));
3565
}
3566

3567
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3568
{
3569
  int bin = elem_to_bin_map_[elem->id()];
×
3570
  if (bin >= n_bins() || bin < 0) {
×
3571
    fatal_error(fmt::format("Invalid bin: {}", bin));
3572
  }
3573
  return bin;
3574
}
3575

3576
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3577
{
3578
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3579
}
3580

3581
#endif // OPENMC_LIBMESH_ENABLED
3582

3583
//==============================================================================
3584
// Non-member functions
3585
//==============================================================================
3586

3587
void read_meshes(pugi::xml_node root)
11,773✔
3588
{
3589
  std::unordered_set<int> mesh_ids;
11,773✔
3590

3591
  for (auto node : root.children("mesh")) {
14,552✔
3592
    // Check to make sure multiple meshes in the same file don't share IDs
3593
    int id = std::stoi(get_node_value(node, "id"));
2,779✔
3594
    if (contains(mesh_ids, id)) {
2,779!
UNCOV
3595
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
3596
                              "'{}' in the same input file",
3597
        id));
3598
    }
3599
    mesh_ids.insert(id);
2,779✔
3600

3601
    // If we've already read a mesh with the same ID in a *different* file,
3602
    // assume it is the same here
3603
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,779!
UNCOV
3604
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
UNCOV
3605
      continue;
×
3606
    }
3607

3608
    std::string mesh_type;
2,779✔
3609
    if (check_for_node(node, "type")) {
2,779✔
3610
      mesh_type = get_node_value(node, "type", true, true);
951✔
3611
    } else {
3612
      mesh_type = "regular";
1,828✔
3613
    }
3614

3615
    // determine the mesh library to use
3616
    std::string mesh_lib;
2,779✔
3617
    if (check_for_node(node, "library")) {
2,779✔
3618
      mesh_lib = get_node_value(node, "library", true, true);
46!
3619
    }
3620

3621
    // Read mesh and add to vector
3622
    if (mesh_type == RegularMesh::mesh_type) {
2,779✔
3623
      model::meshes.push_back(make_unique<RegularMesh>(node));
1,900✔
3624
    } else if (mesh_type == RectilinearMesh::mesh_type) {
879✔
3625
      model::meshes.push_back(make_unique<RectilinearMesh>(node));
115✔
3626
    } else if (mesh_type == CylindricalMesh::mesh_type) {
764✔
3627
      model::meshes.push_back(make_unique<CylindricalMesh>(node));
392✔
3628
    } else if (mesh_type == SphericalMesh::mesh_type) {
372✔
3629
      model::meshes.push_back(make_unique<SphericalMesh>(node));
326✔
3630
#ifdef OPENMC_DAGMC_ENABLED
3631
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
46!
3632
               mesh_lib == MOABMesh::mesh_lib_type) {
23✔
3633
      model::meshes.push_back(make_unique<MOABMesh>(node));
23✔
3634
#endif
3635
#ifdef OPENMC_LIBMESH_ENABLED
3636
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
46!
3637
               mesh_lib == LibMesh::mesh_lib_type) {
23✔
3638
      model::meshes.push_back(make_unique<LibMesh>(node));
23✔
3639
#endif
UNCOV
3640
    } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
UNCOV
3641
      fatal_error("Unstructured mesh support is not enabled or the mesh "
×
3642
                  "library is invalid.");
3643
    } else {
UNCOV
3644
      fatal_error("Invalid mesh type: " + mesh_type);
×
3645
    }
3646

3647
    // Map ID to position in vector
3648
    model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
2,779✔
3649
  }
2,779✔
3650
}
11,773✔
3651

3652
void meshes_to_hdf5(hid_t group)
6,775✔
3653
{
3654
  // Write number of meshes
3655
  hid_t meshes_group = create_group(group, "meshes");
6,775✔
3656
  int32_t n_meshes = model::meshes.size();
6,775✔
3657
  write_attribute(meshes_group, "n_meshes", n_meshes);
6,775✔
3658

3659
  if (n_meshes > 0) {
6,775✔
3660
    // Write IDs of meshes
3661
    vector<int> ids;
2,003✔
3662
    for (const auto& m : model::meshes) {
4,595✔
3663
      m->to_hdf5(meshes_group);
2,592✔
3664
      ids.push_back(m->id_);
2,592✔
3665
    }
3666
    write_attribute(meshes_group, "ids", ids);
2,003✔
3667
  }
2,003✔
3668

3669
  close_group(meshes_group);
6,775✔
3670
}
6,775✔
3671

3672
void free_memory_mesh()
7,877✔
3673
{
3674
  model::meshes.clear();
7,877✔
3675
  model::mesh_map.clear();
7,877✔
3676
}
7,877✔
3677

3678
extern "C" int n_meshes()
349✔
3679
{
3680
  return model::meshes.size();
349✔
3681
}
3682

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

© 2025 Coveralls, Inc