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

openmc-dev / openmc / 15332543911

29 May 2025 08:07PM UTC coverage: 85.215% (-0.003%) from 85.218%
15332543911

Pull #3423

github

web-flow
Merge be2ab1e9e into cb95c784b
Pull Request #3423: Fix raytrace infinite loop.

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

121 existing lines in 1 file now uncovered.

52339 of 61420 relevant lines covered (85.21%)

36895930.28 hits per line

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

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

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

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

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

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

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

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

60
namespace openmc {
61

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

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

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

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

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

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

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

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

142
namespace detail {
143

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

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

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

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

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

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

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

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

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

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

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

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

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

227
} // namespace detail
228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

717
  int num_elem_skipped = 0;
31✔
718

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

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

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

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

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

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

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

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

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

786
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
787
      in_mesh = false;
83,784,782✔
788
  }
789
  return ijk;
1,102,617,580✔
790
}
791

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

897
  return counts;
×
898
}
899

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

913
  // Compute the length of the entire track.
914
  double total_distance = (r1 - r0).norm();
869,585,973✔
915
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
869,585,973✔
916
    return;
8,724,478✔
917

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

923
  const int n = n_dimension_;
860,861,495✔
924

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

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

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

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

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

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

953
    if (in_mesh) {
1,595,372,548✔
954

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

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

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

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

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

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

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

987
    } else { // not inside mesh
988

989
      // For all directions outside the mesh, find the distance that we need
990
      // to travel to reach the next surface. Use the largest distance, as
991
      // only this will cross all outer surfaces.
992
      int k_max {-1};
75,038,135✔
993
      for (int k = 0; k < n; ++k) {
298,006,284✔
994
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
299,244,660✔
995
            (distances[k].distance > traveled_distance)) {
76,276,511✔
996
          traveled_distance = distances[k].distance;
75,548,523✔
997
          k_max = k;
75,548,523✔
998
        }
999
      }
1000
      // Assure some distance is traveled
1001
      if (k_max == -1)
75,038,135✔
NEW
1002
        traveled_distance += TINY_BIT;
×
1003
      // If r1 is not inside the mesh, exit here
1004
      if (traveled_distance >= total_distance)
75,038,135✔
1005
        return;
69,054,412✔
1006

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

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

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

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

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

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

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

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

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

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

1081
//==============================================================================
1082
// RegularMesh implementation
139,558,705✔
1083
//==============================================================================
139,558,705✔
1084

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

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

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

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

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

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

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

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

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

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

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

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

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

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

749,174,293✔
1164
  // Set material volumes
1165
  volume_frac_ = 1.0 / xt::prod(shape)();
1166

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

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

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

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

1185
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
705,395,813✔
1186
{
1187
  return lower_left_[i] + ijk[i] * width_[i];
1,453,923,823✔
1188
}
1189

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

1,380,775,708✔
1195
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1,380,775,708✔
1196
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1197
  double l) const
1198
{
1199
  MeshDistance d;
1,380,775,708✔
1200
  d.next_index = ijk[i];
1,380,775,708✔
1201
  if (std::abs(u[i]) < FP_PRECISION)
681,140,329✔
1202
    return d;
1203

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

699,635,379✔
1215
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1216
  Position plot_ll, Position plot_ur) const
1217
{
1218
  // Figure out which axes lie in the plane of the plot.
699,635,379✔
1219
  array<int, 2> axes {-1, -1};
687,142,503✔
1220
  if (plot_ur.z == plot_ll.z) {
1221
    axes[0] = 0;
1222
    if (n_dimension_ > 1)
1223
      axes[1] = 1;
1224
  } else if (plot_ur.y == plot_ll.y) {
1225
    axes[0] = 0;
1226
    if (n_dimension_ > 2)
73,148,115✔
1227
      axes[1] = 2;
290,768,229✔
1228
  } else if (plot_ur.x == plot_ll.x) {
291,863,099✔
1229
    if (n_dimension_ > 1)
74,242,985✔
1230
      axes[0] = 1;
73,574,089✔
1231
    if (n_dimension_ > 2)
73,574,089✔
1232
      axes[1] = 2;
1233
  } else {
1234
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1235
  }
73,148,115✔
UNCOV
1236

×
1237
  // Get the coordinates of the mesh lines along both of the axes.
1238
  array<vector<double>, 2> axis_lines;
73,148,115✔
1239
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
67,387,681✔
1240
    int axis = axes[i_ax];
1241
    if (axis == -1)
1242
      continue;
1243
    auto& lines {axis_lines[i_ax]};
5,760,434✔
1244

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

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

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

1264
xt::xtensor<double, 1> RegularMesh::count_sites(
757,898,771✔
1265
  const SourceSite* bank, int64_t length, bool* outside) const
1266
{
757,898,771✔
1267
  // Determine shape of array for counts
757,898,771✔
1268
  std::size_t m = this->n_bins();
1,392,478,520✔
1269
  vector<std::size_t> shape = {m};
1,381,421,980✔
1270

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

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

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

1281
    // if outside mesh, skip particle
757,898,771✔
1282
    if (mesh_bin < 0) {
757,898,771✔
1283
      outside_ = true;
1284
      continue;
111,687,202✔
1285
    }
1286

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

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

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

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

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

1316
  return counts;
1317
}
1318

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6,669✔
1403
  return 0;
4,911✔
1404
}
1405

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

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

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

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

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

1,398,969,355✔
1441
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
1,398,969,355✔
1442
{
1,348,829,143✔
1443
  write_dataset(mesh_group, "x_grid", grid_[0]);
1,336,094,742✔
1444
  write_dataset(mesh_group, "y_grid", grid_[1]);
1,336,094,742✔
1445
  write_dataset(mesh_group, "z_grid", grid_[2]);
1446
}
2,147,483,647✔
1447

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

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

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

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

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

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

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

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

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

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

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

1502
  idx[1] = sanitize_phi(idx[1]);
7,839✔
1503

7,839✔
1504
  return idx;
1505
}
1506

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1573
  return INFTY;
103✔
1574
}
1575

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

26,400,033✔
1583
  shell = sanitize_phi(shell);
1584

1585
  const double p0 = grid_[1][shell];
26,400,033✔
1586

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

25,654,849✔
1592
  const double c0 = std::cos(p0);
1593
  const double s0 = std::sin(p0);
1594

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

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

26,400,033✔
1606
  return INFTY;
26,400,033✔
1607
}
26,442,625✔
1608

25,654,849✔
1609
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
25,654,849✔
1610
  const Position& r, const Direction& u, double l, int shell) const
1611
{
52,842,658✔
1612
  MeshDistance d;
1613
  d.next_index = shell;
1614

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

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

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

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

1640
  } else if (i == 1) {
73,891,983✔
1641

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

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

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

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

132✔
1685
    return OPENMC_E_INVALID_ARGUMENT;
1686
  }
528✔
1687

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

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

1695
  return 0;
1696
}
379✔
1697

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

73,733,814✔
1811
  return origin_ + Position(x, y, z);
1812
}
1813

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

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

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

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

23,754,555✔
1841
  return INFTY;
1842
}
1843

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

36,340,216✔
1851
  shell = sanitize_theta(shell);
1,118,216✔
1852

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

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

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

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

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

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

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

401✔
1889
  if (D < 0.0)
401✔
1890
    return INFTY;
401✔
1891

1892
  D = std::sqrt(D);
1,604✔
1893

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

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

1905
  return INFTY;
401✔
UNCOV
1906
}
×
1907

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

1915
  shell = sanitize_phi(shell);
401✔
UNCOV
1916

×
1917
  const double p0 = grid_[2][shell];
1918

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

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

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

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

×
1938
  return INFTY;
1939
}
UNCOV
1940

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

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

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

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

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

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

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

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

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

67,739,463✔
2008
  return 0;
67,739,463✔
2009
}
67,739,463✔
2010

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

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

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

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

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

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

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

UNCOV
2045
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
×
2046
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
2047
}
2048

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

972✔
UNCOV
2218
  BoundingBox bbox = model::meshes[index]->bounding_box();
×
2219

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

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

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

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

UNCOV
2250
  return 0;
×
2251
}
2252

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

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

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

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

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

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

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

2307
  return 0;
1,100✔
2308
}
2309

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

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

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

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

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

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

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

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

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

253✔
2387
  // Set material volumes
2388

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

22✔
2397
  return 0;
2398
}
×
2399

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

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

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

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

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

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

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

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

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

429✔
2452
  return 0;
429✔
2453
}
2454

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

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

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

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

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

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

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

2508
#ifdef DAGMC
132✔
2509

132✔
2510
const std::string MOABMesh::mesh_lib_type = "moab";
132✔
2511

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

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

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

11✔
2531
void MOABMesh::initialize()
2532
{
132✔
2533

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2650
  // combine into one range
2651
  moab::Range all_tets_and_tris;
220✔
2652
  all_tets_and_tris.merge(all_tets);
220✔
2653
  all_tets_and_tris.merge(all_tris);
198✔
2654

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

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

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

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

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

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

88✔
2698
  // sorts by first component of std::pair by default
2699
  std::sort(hits.begin(), hits.end());
572✔
2700
}
484✔
2701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2818
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
385✔
2819

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

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

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

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

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

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

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

2874
  baryc_data_.clear();
143✔
2875
  baryc_data_.resize(tets.size());
143✔
2876

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

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

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

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

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

2904
  moab::ErrorCode rval;
2905

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3048
  moab::ErrorCode rval;
3049

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

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

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

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

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

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

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

3080
  return verts;
20✔
3081
}
20✔
3082

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3208
#endif
7,307,001✔
3209

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3444
    return;
3445
  }
3446

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

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

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

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

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

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

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

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

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

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

203,856✔
3495
    return;
3496
  }
3497

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

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

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

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

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

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

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

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

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

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

3555
#endif // LIBMESH
3556

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

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

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

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

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

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

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

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

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

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

3643
  close_group(meshes_group);
23✔
3644
}
3645

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

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

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

© 2025 Coveralls, Inc