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

openmc-dev / openmc / 14645405719

24 Apr 2025 03:23PM UTC coverage: 84.416% (-0.4%) from 84.851%
14645405719

Pull #3279

github

web-flow
Merge 8a3e52b5d into 820648dae
Pull Request #3279: Hexagonal mesh model

94 of 475 new or added lines in 5 files covered. (19.79%)

3299 existing lines in 93 files now uncovered.

52250 of 61896 relevant lines covered (84.42%)

36990428.73 hits per line

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

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

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

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

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

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

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

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

61
namespace openmc {
62

63
//==============================================================================
64
// Global variables
65
//==============================================================================
66

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

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

77
namespace model {
78

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

82
} // namespace model
83

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

91
//==============================================================================
92
// Helper functions
93
//==============================================================================
94

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

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

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

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

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

143
namespace detail {
144

145
//==============================================================================
146
// MaterialVolumes implementation
147
//==============================================================================
148

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

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

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

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

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

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

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

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

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

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

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

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

228
} // namespace detail
229

230
//==============================================================================
231
// Mesh implementation
232
//==============================================================================
233

234
Mesh::Mesh(pugi::xml_node node)
2,607✔
235
{
236
  // Read mesh id
237
  id_ = std::stoi(get_node_value(node, "id"));
2,607✔
238
  if (check_for_node(node, "name"))
2,607✔
239
    name_ = get_node_value(node, "name");
16✔
240
}
2,607✔
241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

543
  // Close group
544
  close_group(mesh_group);
2,616✔
545
}
2,616✔
546

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

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

555
  if (n_dimension_ > 2) {
5,118,185✔
556
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,206,538✔
557
  } else if (n_dimension_ > 1) {
14,916✔
558
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
29,282✔
559
  } else {
560
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
561
  }
562
}
563

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

718
  int num_elem_skipped = 0;
31✔
719

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

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

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

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

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

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

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

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

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

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

793
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,673,987,820✔
794
{
795
  switch (n_dimension_) {
1,673,987,820✔
796
  case 1:
877,008✔
797
    return ijk[0] - 1;
877,008✔
798
  case 2:
78,932,062✔
799
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
78,932,062✔
800
  case 3:
1,594,178,750✔
801
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,594,178,750✔
UNCOV
802
  default:
×
UNCOV
803
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
804
  }
805
}
806

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

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

831
  // Convert indices to bin
832
  return get_bin_from_indices(ijk);
221,555,284✔
833
}
834

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
898
  return counts;
×
899
}
900

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

914
  // Compute the length of the entire track.
915
  double total_distance = (r1 - r0).norm();
887,386,073✔
916
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
887,386,073✔
917
    return;
9,060,385✔
918

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

924
  const int n = n_dimension_;
878,325,688✔
925

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

929
  // Position is r = r0 + u * traveled_distance, start at r0
930
  double traveled_distance {0.0};
878,325,688✔
931

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

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

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

951
  // Loop until r = r1 is eventually reached
952
  while (true) {
739,082,010✔
953

954
    if (in_mesh) {
1,616,761,415✔
955

956
      // find surface with minimal distance to current position
957
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,540,922,527✔
958
                     distances.begin();
1,540,922,527✔
959

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

965
      // update position and leave, if we have reached end position
966
      traveled_distance = distances[k].distance;
1,540,922,527✔
967
      if (traveled_distance >= total_distance)
1,540,922,527✔
968
        return;
807,824,240✔
969

970
      // If we have not reached r1, we have hit a surface. Tally outward
971
      // current
972
      tally.surface(ijk, k, distances[k].max_surface, false);
733,098,287✔
973

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

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

983
      // If we are still inside the mesh, tally inward current for the next
984
      // cell
985
      if (in_mesh)
733,098,287✔
986
        tally.surface(ijk, k, !distances[k].max_surface, true);
718,601,489✔
987

988
    } else { // not inside mesh
989

990
      // For all directions outside the mesh, find the distance that we need
991
      // to travel to reach the next surface. Use the largest distance, as
992
      // only this will cross all outer surfaces.
993
      int k_max {0};
75,838,888✔
994
      for (int k = 0; k < n; ++k) {
301,209,296✔
995
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
302,447,672✔
996
            (distances[k].distance > traveled_distance)) {
77,077,264✔
997
          traveled_distance = distances[k].distance;
76,349,276✔
998
          k_max = k;
76,349,276✔
999
        }
1000
      }
1001

1002
      // If r1 is not inside the mesh, exit here
1003
      if (traveled_distance >= total_distance)
75,838,888✔
1004
        return;
69,855,165✔
1005

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1144
    // Check to ensure width has same dimensions
1145
    auto n = upper_right_.size();
765,785,873✔
1146
    if (n != lower_left_.size()) {
765,785,873✔
1147
      fatal_error("Number of entries on <upper_right> must be the "
9,060,385✔
1148
                  "same as the number of entries on <lower_left>.");
1149
    }
1150

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

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

1163
  // Set material volumes
1164
  volume_frac_ = 1.0 / xt::prod(shape)();
756,725,488✔
1165

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

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

1,512,158,410✔
1177
const std::string RegularMesh::mesh_type = "regular";
2,147,483,647✔
1178

2,147,483,647✔
1179
std::string RegularMesh::get_mesh_type() const
1180
{
1181
  return mesh_type;
1182
}
707,058,722✔
1183

1184
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,463,137,927✔
1185
{
1186
  return lower_left_[i] + ijk[i] * width_[i];
1187
}
1,389,264,874✔
1188

1,389,264,874✔
1189
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1190
{
1191
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,389,264,874✔
1192
}
1,389,264,874✔
1193

1194
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1195
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1196
  double l) const
1,389,264,874✔
1197
{
1,389,264,874✔
1198
  MeshDistance d;
687,966,586✔
1199
  d.next_index = ijk[i];
1200
  if (std::abs(u[i]) < FP_PRECISION)
1201
    return d;
1202

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

1214
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1215
  Position plot_ll, Position plot_ur) const
701,298,288✔
1216
{
688,080,474✔
1217
  // Figure out which axes lie in the plane of the plot.
1218
  array<int, 2> axes {-1, -1};
1219
  if (plot_ur.z == plot_ll.z) {
1220
    axes[0] = 0;
1221
    if (n_dimension_ > 1)
1222
      axes[1] = 1;
1223
  } else if (plot_ur.y == plot_ll.y) {
73,873,053✔
1224
    axes[0] = 0;
293,667,981✔
1225
    if (n_dimension_ > 2)
294,762,851✔
1226
      axes[1] = 2;
74,967,923✔
1227
  } else if (plot_ur.x == plot_ll.x) {
74,299,027✔
1228
    if (n_dimension_ > 1)
74,299,027✔
1229
      axes[0] = 1;
1230
    if (n_dimension_ > 2)
1231
      axes[1] = 2;
1232
  } else {
1233
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
73,873,053✔
1234
  }
68,112,619✔
1235

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

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

765,785,873✔
1252
  return {axis_lines[0], axis_lines[1]};
1253
}
1254

1255
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1256
{
1257
  write_dataset(mesh_group, "dimension", get_x_shape());
1258
  write_dataset(mesh_group, "lower_left", lower_left_);
1259
  write_dataset(mesh_group, "upper_right", upper_right_);
765,785,873✔
1260
  write_dataset(mesh_group, "width", width_);
1261
}
765,785,873✔
1262

765,785,873✔
1263
xt::xtensor<double, 1> RegularMesh::count_sites(
1,395,079,400✔
1264
  const SourceSite* bank, int64_t length, bool* outside) const
1,389,911,146✔
1265
{
1266
  // Determine shape of array for counts
1,389,911,146✔
1267
  std::size_t m = this->n_bins();
1,389,911,146✔
1268
  vector<std::size_t> shape = {m};
1,389,911,146✔
1269

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

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

765,785,873✔
1277
    // determine scoring bin for entropy mesh
765,785,873✔
1278
    int mesh_bin = get_bin(site.r);
1279

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

1286
    // Add to appropriate bin
1287
    cnt(mesh_bin) += site.wgt;
121,600,200✔
1288
  }
121,600,200✔
1289

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

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

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

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

1,788✔
1315
  return counts;
1316
}
1317

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

1,788✔
1323
//==============================================================================
1,788✔
UNCOV
1324
// RectilinearMesh implementation
×
1325
//==============================================================================
1326

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

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

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

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

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

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

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

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

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

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

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

5,001✔
1399
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
1400
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
1,788✔
1401

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

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

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

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

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

1,424,640,337✔
1437
  return {axis_lines[0], axis_lines[1]};
1,375,292,490✔
1438
}
1,361,769,771✔
1439

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

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

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

×
UNCOV
1457
//==============================================================================
×
UNCOV
1458
// CylindricalMesh implementation
×
UNCOV
1459
//==============================================================================
×
UNCOV
1460

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

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

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

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

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

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

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

8,124✔
1499
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1500

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

8,124✔
1503
  return idx;
1504
}
7,968,133✔
1505

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

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

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

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

8,124✔
1524
  double x = r * std::cos(phi);
8,124✔
1525
  double y = r * std::sin(phi);
1526

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

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

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

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

1541
  const double r0 = grid_[0][shell];
1542
  if (r0 == 0.0)
8,124✔
1543
    return INFTY;
8,124✔
1544

1545
  const double denominator = u.x * u.x + u.y * u.y;
16,248✔
1546

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

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

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

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

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

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

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

1572
  return INFTY;
257✔
1573
}
1574

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

1582
  shell = sanitize_phi(shell);
1583

27,738,792✔
1584
  const double p0 = grid_[1][shell];
1585

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

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

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

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

27,738,792✔
1605
  return INFTY;
1606
}
57,025,582✔
1607

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

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

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

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

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

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

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

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

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

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

1684
    return OPENMC_E_INVALID_ARGUMENT;
132✔
1685
  }
1686

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

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

1694
  return 0;
379✔
1695
}
379✔
1696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1904
  return INFTY;
1905
}
401✔
UNCOV
1906

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

1914
  shell = sanitize_phi(shell);
×
1915

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

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

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

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

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

1937
  return INFTY;
1938
}
1939

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2249
  return 0;
2250
}
2251

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

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

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

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

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

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

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

2306
  return 0;
143✔
UNCOV
2307
}
×
2308

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

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

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

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

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

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

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

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

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

178✔
2386
  // Set material volumes
90✔
2387

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

2396
  return 0;
268✔
UNCOV
2397
}
×
2398

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

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

2410
  m->n_dimension_ = 3;
2411

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

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

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

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

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

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

2451
  return 0;
2,855✔
2452
}
2453

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

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

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

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

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

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

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

132✔
2507
#ifdef DAGMC
2508

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

200✔
2611
  // build acceleration data structures
2612
  compute_barycentric_data(ehs_);
2613
  build_kdtree(ehs_);
2614
}
222✔
2615

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

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

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

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

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

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

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

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

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

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

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

2694
  // remove duplicate intersection distances
600✔
2695
  std::unique(hits.begin(), hits.end());
510✔
2696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

145✔
2873
  baryc_data_.clear();
145✔
2874
  baryc_data_.resize(tets.size());
145✔
2875

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

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

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

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

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

2903
  moab::ErrorCode rval;
2904

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3047
  moab::ErrorCode rval;
3048

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

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

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

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

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

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

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

3079
  return verts;
3080
}
20✔
3081

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1,010,077✔
3207
#endif
3208

3209
#ifdef LIBMESH
3210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3443
    return;
3444
  }
3445

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

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

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

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

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

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

3471
    auto bin = get_bin_from_element(*it);
3472

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3554
#endif // LIBMESH
3555

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

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

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

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

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

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

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

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

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

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

23✔
3644
  close_group(meshes_group);
23✔
3645
}
23✔
3646

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

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

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

© 2026 Coveralls, Inc