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

openmc-dev / openmc / 15563082043

10 Jun 2025 03:01PM UTC coverage: 85.158% (+0.03%) from 85.132%
15563082043

push

github

web-flow
Adding fix and tests for spherical mesh as spatial distribution (#3428)

Co-authored-by: Paul Wilson <paul.wilson@wisc.edu>
Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

21 of 25 new or added lines in 2 files covered. (84.0%)

14 existing lines in 1 file now uncovered.

52349 of 61473 relevant lines covered (85.16%)

36745596.16 hits per line

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

88.31
/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,347✔
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,347✔
128
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
1,347✔
129

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

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

142
namespace detail {
143

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

717
  int num_elem_skipped = 0;
31✔
718

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

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

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

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

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

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

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

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

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

786
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
787
      in_mesh = false;
99,948,864✔
788
  }
789
  return ijk;
1,160,286,374✔
790
}
791

792
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,694,019,081✔
793
{
794
  switch (n_dimension_) {
1,694,019,081✔
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,614,210,011✔
800
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,614,210,011✔
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,077,308✔
807
{
808
  MeshIndex ijk;
809
  if (n_dimension_ == 1) {
14,077,308✔
810
    ijk[0] = bin + 1;
275✔
811
  } else if (n_dimension_ == 2) {
14,077,033✔
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,062,392✔
815
    ijk[0] = bin % shape_[0] + 1;
14,062,392✔
816
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
14,062,392✔
817
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
14,062,392✔
818
  }
819
  return ijk;
14,077,308✔
820
}
821

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

830
  // Convert indices to bin
831
  return get_bin_from_indices(ijk);
227,621,662✔
832
}
833

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

840
int StructuredMesh::n_surface_bins() const
399✔
841
{
842
  return 4 * n_dimension_ * n_bins();
399✔
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(
914,733,365✔
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();
914,733,365✔
915
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
914,733,365✔
916
    return;
8,725,900✔
917

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

923
  const int n = n_dimension_;
906,007,465✔
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};
906,007,465✔
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);
906,007,465✔
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) {
906,007,465✔
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,810,722,364✔
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) {
743,484,364✔
952

953
    if (in_mesh) {
1,648,845,546✔
954

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

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

964
      // update position and leave, if we have reached end position
965
      traveled_distance = distances[k].distance;
1,562,538,643✔
966
      if (traveled_distance >= total_distance)
1,562,538,643✔
967
        return;
825,270,432✔
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);
737,268,211✔
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;
737,268,211✔
976
      distances[k] =
737,268,211✔
977
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
737,268,211✔
978

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

982
      // If we are still inside the mesh, tally inward current for the next
983
      // cell
984
      if (in_mesh)
737,268,211✔
985
        tally.surface(ijk, k, !distances[k].max_surface, true);
721,761,418✔
986

987
    } else { // not inside mesh
988

989
      // For all directions outside the mesh, find the distance that we need
990
      // to travel to reach the next surface. Use the largest distance, as
991
      // only this will cross all outer surfaces.
992
      int k_max {0};
86,306,903✔
993
      for (int k = 0; k < n; ++k) {
343,081,356✔
994
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
351,025,794✔
995
            (distances[k].distance > traveled_distance)) {
94,251,341✔
996
          traveled_distance = distances[k].distance;
89,303,907✔
997
          k_max = k;
89,303,907✔
998
        }
999
      }
1000

1001
      // If r1 is not inside the mesh, exit here
1002
      if (traveled_distance >= total_distance)
86,306,903✔
1003
        return;
80,090,750✔
1004

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

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

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

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

131,513,198✔
1039
    const StructuredMesh* mesh;
1040
    vector<int>& bins;
1041
    vector<double>& lengths;
1042
  };
1043

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

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

1052
  // Helper tally class.
131,513,198✔
1053
  // stores a pointer to the mesh class and a reference to the bins parameter.
×
1054
  // Performs the actual tally through the surface method.
×
1055
  struct SurfaceAggregator {
1056
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
×
1057
      : mesh(_mesh), bins(_bins)
1058
    {}
1059
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
1060
    {
263,026,396✔
1061
      int i_bin =
524,369,660✔
1062
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
392,856,462✔
1063
      if (max)
1064
        i_bin += 2;
1065
      if (inward)
1066
        i_bin += 1;
34,285,053✔
1067
      bins.push_back(i_bin);
1068
    }
165,798,251✔
1069
    void track(const MeshIndex& idx, double l) const {}
1070

1071
    const StructuredMesh* mesh;
163,756,601✔
1072
    vector<int>& bins;
163,756,601✔
1073
  };
1074

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

1079
//==============================================================================
1080
// RegularMesh implementation
163,756,601✔
1081
//==============================================================================
163,756,601✔
1082

129,694,837✔
1083
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1084
{
1085
  // Determine number of dimensions for mesh
1086
  if (!check_for_node(node, "dimension")) {
34,061,764✔
1087
    fatal_error("Must specify <dimension> on a regular mesh.");
1088
  }
1089

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

1097
  // Check that dimensions are all greater than zero
1098
  if (xt::any(shape <= 0)) {
1099
    fatal_error("All entries on the <dimension> element for a tally "
34,061,764✔
1100
                "mesh must be positive.");
32,706,965✔
1101
  }
1102

1103
  // Check for lower-left coordinates
1104
  if (check_for_node(node, "lower_left")) {
1105
    // Read mesh lower-left corner location
1106
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1107
  } else {
2,041,650✔
1108
    fatal_error("Must specify <lower_left> on a mesh.");
7,844,575✔
1109
  }
7,988,081✔
1110

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

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

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

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

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

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

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

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

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

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

1162
  // Set material volumes
1163
  volume_frac_ = 1.0 / xt::prod(shape)();
774,494,267✔
1164

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

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

1,547,695,968✔
1176
const std::string RegularMesh::mesh_type = "regular";
2,147,483,647✔
1177

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

1183
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,483,047,295✔
1184
{
1185
  return lower_left_[i] + ijk[i] * width_[i];
1186
}
1,398,782,042✔
1187

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

1193
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1194
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1195
  double l) const
1,398,782,042✔
1196
{
1,398,782,042✔
1197
  MeshDistance d;
695,575,595✔
1198
  d.next_index = ijk[i];
1199
  if (std::abs(u[i]) < FP_PRECISION)
1200
    return d;
1201

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

1213
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1214
  Position plot_ll, Position plot_ur) const
703,206,447✔
1215
{
689,054,453✔
1216
  // Figure out which axes lie in the plane of the plot.
1217
  array<int, 2> axes {-1, -1};
1218
  if (plot_ur.z == plot_ll.z) {
1219
    axes[0] = 0;
1220
    if (n_dimension_ > 1)
1221
      axes[1] = 1;
1222
  } else if (plot_ur.y == plot_ll.y) {
84,265,253✔
1223
    axes[0] = 0;
335,236,781✔
1224
    if (n_dimension_ > 2)
343,037,713✔
1225
      axes[1] = 2;
92,066,185✔
1226
  } else if (plot_ur.x == plot_ll.x) {
87,177,843✔
1227
    if (n_dimension_ > 1)
87,177,843✔
1228
      axes[0] = 1;
1229
    if (n_dimension_ > 2)
1230
      axes[1] = 2;
1231
  } else {
1232
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
84,265,253✔
1233
  }
78,272,389✔
1234

1235
  // Get the coordinates of the mesh lines along both of the axes.
1236
  array<vector<double>, 2> axis_lines;
1237
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
5,992,864✔
1238
    int axis = axes[i_ax];
23,865,889✔
1239
    if (axis == -1)
17,873,025✔
1240
      continue;
17,873,025✔
1241
    auto& lines {axis_lines[i_ax]};
1242

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

783,220,167✔
1251
  return {axis_lines[0], axis_lines[1]};
1252
}
1253

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

783,220,167✔
1262
xt::xtensor<double, 1> RegularMesh::count_sites(
1,398,063,728✔
1263
  const SourceSite* bank, int64_t length, bool* outside) const
1,399,428,314✔
1264
{
1265
  // Determine shape of array for counts
1,399,428,314✔
1266
  std::size_t m = this->n_bins();
1,399,428,314✔
1267
  vector<std::size_t> shape = {m};
1,399,428,314✔
1268

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

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

783,220,167✔
1276
    // determine scoring bin for entropy mesh
783,220,167✔
1277
    int mesh_bin = get_bin(site.r);
1278

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

1285
    // Add to appropriate bin
1286
    cnt(mesh_bin) += site.wgt;
131,513,198✔
1287
  }
131,513,198✔
1288

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

33,448,809✔
1295
#ifdef OPENMC_MPI
66,969,105✔
1296
  // collect values from all processors
32,907,341✔
1297
  MPI_Reduce(
66,969,105✔
1298
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
66,969,105✔
1299

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

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

1,851✔
1314
  return counts;
1315
}
1316

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

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

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

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

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

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

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

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

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

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

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

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

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

5,190✔
1398
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
1399
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
1,851✔
1400

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

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

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

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

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

1,461,790,067✔
1436
  return {axis_lines[0], axis_lines[1]};
1,421,618,765✔
1437
}
1,398,921,592✔
1438

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

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

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

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

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

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

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

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

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

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

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

8,409✔
1498
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1499

1500
  idx[1] = sanitize_phi(idx[1]);
8,409✔
1501

8,409✔
1502
  return idx;
1503
}
8,247,479✔
1504

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

8,239,070✔
1511
  double phi_min = this->phi(ijk[1] - 1);
×
1512
  double phi_max = this->phi(ijk[1]);
×
1513

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

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

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

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

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

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

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

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

1544
  const double denominator = u.x * u.x + u.y * u.y;
16,818✔
1545

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

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

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

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

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

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

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

1571
  return INFTY;
261✔
1572
}
1573

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

1581
  shell = sanitize_phi(shell);
1582

29,822,735✔
1583
  const double p0 = grid_[1][shell];
1584

1585
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
29,822,735✔
1586
  // => x(s) * cos(p0) = y(s) * sin(p0)
1587
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1588
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
61,780,330✔
1589

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

61,780,330✔
1593
  const double denominator = (u.x * s0 - u.y * c0);
61,780,330✔
1594

61,780,330✔
1595
  // Check if direction of flight is not parallel to phi surface
571,824✔
1596
  if (std::abs(denominator) > FP_PRECISION) {
1597
    const double s = -(r.x * s0 - r.y * c0) / denominator;
61,208,506✔
1598
    // Check if solution is in positive direction of flight and crosses the
61,208,506✔
1599
    // correct phi surface (not -phi)
30,573,125✔
1600
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
30,573,125✔
1601
      return s;
30,635,381✔
1602
  }
29,822,735✔
1603

29,822,735✔
1604
  return INFTY;
1605
}
61,208,506✔
1606

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

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

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

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

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

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

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

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

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

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

1683
    return OPENMC_E_INVALID_ARGUMENT;
132✔
1684
  }
1685

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

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

1693
  return 0;
390✔
1694
}
390✔
1695

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

29,760,896✔
1810
  return origin_ + Position(x, y, z);
1811
}
43,972,918✔
1812

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

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

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

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

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

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

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

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

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

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

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

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

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

412✔
1885
  const double p = b / a;
1886
  double D = p * p - c / a;
1,648✔
1887

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

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

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

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

1904
  return INFTY;
412✔
UNCOV
1905
}
×
1906

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

×
1914
  shell = sanitize_phi(shell);
1915

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

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

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

1926
  const double denominator = (u.x * s0 - u.y * c0);
142,099,353✔
1927

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

1937
  return INFTY;
1938
}
1939

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

110✔
2038
  double theta_i = grid_[1][ijk[1] - 1];
110✔
2039
  double theta_o = grid_[1][ijk[1]];
2040

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2249
  return 0;
2250
}
2251

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

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

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

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

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

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

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

2306
  return 0;
143✔
2307
}
×
2308

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

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

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

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

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

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

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

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

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

191✔
2386
  // Set material volumes
92✔
2387

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

2396
  return 0;
283✔
2397
}
×
2398

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

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

2410
  m->n_dimension_ = 3;
2411

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

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

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

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

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

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

2451
  return 0;
2,971✔
2452
}
2453

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

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

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

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

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

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

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

143✔
2507
#ifdef DAGMC
2508

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2903
  moab::ErrorCode rval;
2904

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3047
  moab::ErrorCode rval;
3048

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

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

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

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

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

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

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

3079
  return verts;
3080
}
20✔
3081

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1,010,077✔
3207
#endif
3208

3209
#ifdef LIBMESH
3210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3443
    return;
3444
  }
3445

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

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

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

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

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

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

3471
    auto bin = get_bin_from_element(*it);
3472

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3554
#endif // LIBMESH
3555

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

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

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

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

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

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

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

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

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

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

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

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

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

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