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

openmc-dev / openmc / 18011323592

25 Sep 2025 02:45PM UTC coverage: 85.11% (-0.09%) from 85.197%
18011323592

Pull #3576

github

web-flow
Merge 4a02d1657 into 66e7d8634
Pull Request #3576: Random Ray Base Source Region Refactor

167 of 177 new or added lines in 6 files covered. (94.35%)

102 existing lines in 11 files now uncovered.

53062 of 62345 relevant lines covered (85.11%)

39806669.31 hits per line

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

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

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

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

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

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

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

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

60
namespace openmc {
61

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

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

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

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

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

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

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

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

142
namespace detail {
143

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

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

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

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

168
    // Found the desired material; accumulate volume
169
    if (current_val == index_material) {
3,942,881✔
170
#pragma omp atomic
2,483,701✔
171
      this->volumes(index_elem, slot) += volume;
3,929,462✔
172
      return;
3,929,462✔
173
    }
174

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

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

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

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

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

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

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

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

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

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

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

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

346
      // Divide rays in first direction over MPI processes by computing starting
347
      // and ending indices
348
      int min_work = n1 / mpi::n_procs;
198✔
349
      int remainder = n1 % mpi::n_procs;
198✔
350
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
198✔
351
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
198✔
352
      int i1_end = i1_start + n1_local;
198✔
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) {
10,680✔
357
        for (int i2 = 0; i2 < n2; ++i2) {
625,212✔
358
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
614,730✔
359
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
614,730✔
360

361
          p.from_source(&site);
614,730✔
362

363
          // Determine particle's location
364
          if (!exhaustive_find_cell(p)) {
614,730✔
365
            out_of_model = true;
47,916✔
366
            continue;
47,916✔
367
          }
368

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

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

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

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

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

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

396
            // Add volumes to any mesh elements that were crossed
397
            int i_material = p.material();
1,184,922✔
398
            if (i_material != C_NONE) {
1,184,922✔
399
              i_material = model::materials[i_material]->id();
1,058,094✔
400
            }
401
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,632,224✔
402
              int mesh_index = bins[i_bin];
1,447,302✔
403
              double length = distance * length_fractions[i_bin];
1,447,302✔
404

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

409
            if (distance == max_distance)
1,184,922✔
410
              break;
566,814✔
411

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

550
std::string StructuredMesh::bin_label(int bin) const
6,019,627✔
551
{
552
  MeshIndex ijk = get_indices_from_bin(bin);
6,019,627✔
553

554
  if (n_dimension_ > 2) {
6,019,627✔
555
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
12,009,752✔
556
  } else if (n_dimension_ > 1) {
14,751✔
557
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
28,952✔
558
  } else {
559
    return fmt::format("Mesh Index ({})", ijk[0]);
550✔
560
  }
561
}
562

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

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

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

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

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

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

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

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

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

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

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

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

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

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

660
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
661
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
662
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
663
  if (s + t > 1) {
801,640✔
664
    s = 1.0 - s;
400,959✔
665
    t = 1.0 - t;
400,959✔
666
  }
667
  if (s + t + u > 1) {
801,640✔
668
    if (t + u > 1) {
534,383✔
669
      double old_t = t;
266,706✔
670
      t = 1.0 - u;
266,706✔
671
      u = 1.0 - s - old_t;
266,706✔
672
    } else if (t + u <= 1) {
267,677✔
673
      double old_s = s;
267,677✔
674
      s = 1.0 - t - u;
267,677✔
675
      u = old_s + t + u - 1;
267,677✔
676
    }
677
  }
678
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,603,280✔
679
         u * (coords[3] - coords[0]) + coords[0];
2,404,920✔
680
}
681

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

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

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

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

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

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

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

719
  int num_elem_skipped = 0;
34✔
720

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

728
    volumes.emplace_back(this->volume(i));
385,712✔
729

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

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

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

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

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

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

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

788
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
789
      in_mesh = false;
102,644,309✔
790
  }
791
  return ijk;
1,237,297,646✔
792
}
793

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

808
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
9,460,874✔
809
{
810
  MeshIndex ijk;
811
  if (n_dimension_ == 1) {
9,460,874✔
812
    ijk[0] = bin + 1;
275✔
813
  } else if (n_dimension_ == 2) {
9,460,599✔
814
    ijk[0] = bin % shape_[0] + 1;
14,476✔
815
    ijk[1] = bin / shape_[0] + 1;
14,476✔
816
  } else if (n_dimension_ == 3) {
9,446,123✔
817
    ijk[0] = bin % shape_[0] + 1;
9,446,123✔
818
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
9,446,123✔
819
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
9,446,123✔
820
  }
821
  return ijk;
9,460,874✔
822
}
823

824
int StructuredMesh::get_bin(Position r) const
283,473,250✔
825
{
826
  // Determine indices
827
  bool in_mesh;
828
  MeshIndex ijk = get_indices(r, in_mesh);
283,473,250✔
829
  if (!in_mesh)
283,473,250✔
830
    return -1;
20,992,692✔
831

832
  // Convert indices to bin
833
  return get_bin_from_indices(ijk);
262,480,558✔
834
}
835

836
int StructuredMesh::n_bins() const
1,462,817✔
837
{
838
  return std::accumulate(
1,462,817✔
839
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,925,634✔
840
}
841

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

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

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

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

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

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

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

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

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

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

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

899
  return counts;
×
900
}
901

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

915
  // Compute the length of the entire track.
916
  double total_distance = (r1 - r0).norm();
958,658,937✔
917
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
958,658,937✔
918
    return;
11,636,511✔
919

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

925
  const int n = n_dimension_;
947,022,426✔
926

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

930
  // Position is r = r0 + u * traveled_distance, start at r0
931
  double traveled_distance {0.0};
947,022,426✔
932

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

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

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

952
  // Loop until r = r1 is eventually reached
953
  while (true) {
755,721,810✔
954

955
    if (in_mesh) {
1,702,412,709✔
956

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

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

966
      // update position and leave, if we have reached end position
967
      traveled_distance = distances[k].distance;
1,612,955,041✔
968
      if (traveled_distance >= total_distance)
1,612,955,041✔
969
        return;
864,035,201✔
970

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

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

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

984
      // If we are still inside the mesh, tally inward current for the next
985
      // cell
986
      if (in_mesh)
748,919,840✔
987
        tally.surface(ijk, k, !distances[k].max_surface, true);
732,411,781✔
988

989
    } else { // not inside mesh
990

991
      // For all directions outside the mesh, find the distance that we need
992
      // to travel to reach the next surface. Use the largest distance, as
993
      // only this will cross all outer surfaces.
994
      int k_max {-1};
89,457,668✔
995
      for (int k = 0; k < n; ++k) {
356,386,306✔
996
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
364,377,523✔
997
            (distances[k].distance > traveled_distance)) {
97,448,885✔
998
          traveled_distance = distances[k].distance;
92,470,773✔
999
          k_max = k;
92,470,773✔
1000
        }
1001
      }
1002
      // Assure some distance is traveled
1003
      if (k_max == -1) {
89,457,668✔
1004
        traveled_distance += TINY_BIT;
110✔
1005
      }
1006

1007
      // If r1 is not inside the mesh, exit here
1008
      if (traveled_distance >= total_distance)
89,457,668✔
1009
        return;
82,655,698✔
1010

1011
      // Calculate the new cell index and update all distances to next
1012
      // surfaces.
1013
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,801,970✔
1014
      for (int k = 0; k < n; ++k) {
26,999,342✔
1015
        distances[k] =
20,197,372✔
1016
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
20,197,372✔
1017
      }
1018

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

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

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

151,936,585✔
1045
    const StructuredMesh* mesh;
1046
    vector<int>& bins;
1047
    vector<double>& lengths;
1048
  };
1049

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

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

1058
  // Helper tally class.
151,936,585✔
1059
  // stores a pointer to the mesh class and a reference to the bins parameter.
×
1060
  // Performs the actual tally through the surface method.
×
1061
  struct SurfaceAggregator {
1062
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
×
1063
      : mesh(_mesh), bins(_bins)
1064
    {}
1065
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
1066
    {
303,873,170✔
1067
      int i_bin =
606,058,434✔
1068
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
454,121,849✔
1069
      if (max)
1070
        i_bin += 2;
1071
      if (inward)
1072
        i_bin += 1;
38,866,083✔
1073
      bins.push_back(i_bin);
1074
    }
190,802,668✔
1075
    void track(const MeshIndex& idx, double l) const {}
1076

1077
    const StructuredMesh* mesh;
188,620,512✔
1078
    vector<int>& bins;
188,620,512✔
1079
  };
1080

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

1085
//==============================================================================
1086
// RegularMesh implementation
188,620,512✔
1087
//==============================================================================
188,620,512✔
1088

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

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

1103
  // Check that dimensions are all greater than zero
1104
  if (xt::any(shape <= 0)) {
1105
    fatal_error("All entries on the <dimension> element for a tally "
38,643,795✔
1106
                "mesh must be positive.");
37,149,898✔
1107
  }
1108

1109
  // Check for lower-left coordinates
1110
  if (check_for_node(node, "lower_left")) {
1111
    // Read mesh lower-left corner location
1112
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1113
  } else {
2,182,156✔
1114
    fatal_error("Must specify <lower_left> on a mesh.");
8,408,975✔
1115
  }
8,548,268✔
1116

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

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

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

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

1138
    // Check for negative widths
1139
    if (xt::any(width_ < 0.0)) {
222,288✔
1140
      fatal_error("Cannot have a negative <width> on a tally mesh.");
199,320✔
1141
    }
1142

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

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

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

806,722,352✔
1156
    // Check that upper-right is above lower-left
11,636,511✔
1157
    if (xt::any(upper_right_ < lower_left_)) {
1158
      fatal_error("The <upper_right> coordinates must be greater than "
1159
                  "the <lower_left> coordinates on a tally mesh.");
1160
    }
795,085,841✔
1161

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

1168
  // Set material volumes
1169
  volume_frac_ = 1.0 / xt::prod(shape)();
795,085,841✔
1170

1171
  element_volume_ = 1.0;
1172
  for (int i = 0; i < n_dimension_; i++) {
1173
    element_volume_ *= width_[i];
795,085,841✔
1174
  }
1175
}
1176

1177
int RegularMesh::get_index_in_direction(double r, int i) const
795,085,841✔
1178
{
331,527✔
1179
  return std::ceil((r - lower_left_[i]) / width_[i]);
331,043✔
1180
}
1181

331,527✔
1182
const std::string RegularMesh::mesh_type = "regular";
1183

1184
std::string RegularMesh::get_mesh_type() const
1185
{
1,589,508,628✔
1186
  return mesh_type;
2,147,483,647✔
1187
}
2,147,483,647✔
1188

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

1,511,610,041✔
1194
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1195
{
1196
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,424,334,529✔
1197
}
1,424,334,529✔
1198

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

714,058,484✔
1208
  d.max_surface = (u[i] > 0);
1209
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1210
    d.next_index++;
1211
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
710,276,045✔
1212
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1213
    d.next_index--;
1214
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1215
  }
710,276,045✔
1216

710,276,045✔
1217
  return d;
710,276,045✔
1218
}
1219

1220
std::pair<vector<double>, vector<double>> RegularMesh::plot(
710,276,045✔
1221
  Position plot_ll, Position plot_ur) const
1222
{
1223
  // Figure out which axes lie in the plane of the plot.
1224
  array<int, 2> axes {-1, -1};
710,276,045✔
1225
  if (plot_ur.z == plot_ll.z) {
695,261,883✔
1226
    axes[0] = 0;
1227
    if (n_dimension_ > 1)
1228
      axes[1] = 1;
1229
  } else if (plot_ur.y == plot_ll.y) {
1230
    axes[0] = 0;
1231
    if (n_dimension_ > 2)
1232
      axes[1] = 2;
87,275,512✔
1233
  } else if (plot_ur.x == plot_ll.x) {
347,977,331✔
1234
    if (n_dimension_ > 1)
355,829,255✔
1235
      axes[0] = 1;
95,127,436✔
1236
    if (n_dimension_ > 2)
90,205,127✔
1237
      axes[1] = 2;
90,205,127✔
1238
  } else {
1239
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1240
  }
1241

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

1250
    double coord = lower_left_[axis];
1251
    for (int i = 0; i < shape_[axis] + 1; ++i) {
6,579,682✔
1252
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
26,214,041✔
1253
        lines.push_back(coord);
19,634,359✔
1254
      coord += width_[axis];
19,634,359✔
1255
    }
1256
  }
1257

1258
  return {axis_lines[0], axis_lines[1]};
6,579,682✔
1259
}
6,183,335✔
1260

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

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

806,722,352✔
1276
  // Create array of zeros
1,411,721,263✔
1277
  xt::xarray<double> cnt {shape, 0.0};
1,424,665,572✔
1278
  bool outside_ = false;
1279

1,424,665,572✔
1280
  for (int64_t i = 0; i < length; i++) {
1,424,665,572✔
1281
    const auto& site = bank[i];
1,424,665,572✔
1282

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

1286
    // if outside mesh, skip particle
1287
    if (mesh_bin < 0) {
1288
      outside_ = true;
1289
      continue;
806,722,352✔
1290
    }
806,722,352✔
1291

1292
    // Add to appropriate bin
151,936,585✔
1293
    cnt(mesh_bin) += site.wgt;
1294
  }
1295

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

151,936,585✔
1302
#ifdef OPENMC_MPI
151,936,585✔
1303
  // collect values from all processors
75,993,013✔
1304
  MPI_Reduce(
1305
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
1306

75,993,013✔
1307
  // Check if there were sites outside the mesh for any processor
75,993,013✔
1308
  if (outside) {
37,967,936✔
1309
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
75,993,013✔
1310
  }
37,349,218✔
1311
#else
75,993,013✔
1312
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
75,993,013✔
1313
  if (outside)
188,620,512✔
1314
    *outside = outside_;
1315
#endif
1316

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

151,936,585✔
1321
  return counts;
151,936,585✔
1322
}
1323

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

1329
//==============================================================================
1330
// RectilinearMesh implementation
2,076✔
1331
//==============================================================================
×
1332

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

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

1341
  if (int err = set_grid()) {
1342
    fatal_error(openmc_err_msg);
2,076✔
1343
  }
×
1344
}
1345

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

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

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

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

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

1374
  d.max_surface = (u[i] > 0);
1375
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1376
    d.next_index++;
1377
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
49✔
1378
  } else if (!d.max_surface && (ijk[i] > 0)) {
×
1379
    d.next_index--;
1380
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1381
  }
1382
  return d;
49✔
1383
}
1384

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

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

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

2,076✔
1408
  return 0;
1409
}
2,076✔
1410

7,930✔
1411
int RectilinearMesh::get_index_in_direction(double r, int i) const
5,854✔
1412
{
1413
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
2,076✔
1414
}
1415

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

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

1437
    for (auto coord : grid_[axis]) {
2,147,483,647✔
1438
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1439
        lines.push_back(coord);
1440
    }
1441
  }
2,147,483,647✔
1442

2,147,483,647✔
1443
  return {axis_lines[0], axis_lines[1]};
2,147,483,647✔
1444
}
2,146,610✔
1445

1446
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
2,147,483,647✔
1447
{
2,147,483,647✔
1448
  write_dataset(mesh_group, "x_grid", grid_[0]);
1,524,870,158✔
1449
  write_dataset(mesh_group, "y_grid", grid_[1]);
1,524,870,158✔
1450
  write_dataset(mesh_group, "z_grid", grid_[2]);
1,486,949,979✔
1451
}
1,462,645,430✔
1452

1,462,645,430✔
1453
double RectilinearMesh::volume(const MeshIndex& ijk) const
1454
{
1455
  double vol {1.0};
2,147,483,647✔
1456

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

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

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

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

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

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

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

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

44✔
1497
  if (mapped_r[0] < FP_PRECISION) {
22✔
1498
    mapped_r[1] = 0.0;
1499
  } else {
2,153✔
1500
    mapped_r[1] = std::atan2(r.y, r.x);
1501
    if (mapped_r[1] < 0)
2,153✔
1502
      mapped_r[1] += 2 * M_PI;
2,153✔
1503
  }
2,153✔
1504

2,153✔
1505
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
2,153✔
1506

1507
  idx[1] = sanitize_phi(idx[1]);
10,179✔
1508

1509
  return idx;
1510
}
1511

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

1518
  double phi_min = this->phi(ijk[1] - 1);
9,992,910✔
1519
  double phi_max = this->phi(ijk[1]);
9,982,731✔
1520

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

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

1530
  double x = r * std::cos(phi);
1531
  double y = r * std::sin(phi);
9,982,731✔
1532

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

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

1540
  if ((shell < 0) || (shell > shape_[0]))
1541
    return INFTY;
1542

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

5,955✔
1547
  const double r0 = grid_[0][shell];
5,955✔
1548
  if (r0 == 0.0)
1549
    return INFTY;
1550

4,224✔
1551
  const double denominator = u.x * u.x + u.y * u.y;
4,224✔
1552

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

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

20,358✔
1560
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
10,179✔
1561
  double c = r.x * r.x + r.y * r.y - r0 * r0;
1562
  double D = p * p - c * inv_denominator;
1,446,031✔
1563

1564
  if (D < 0.0)
1,446,031✔
1565
    return INFTY;
1566

1567
  D = std::sqrt(D);
1568

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

1573
  if (-p - D > l)
118✔
1574
    return -p - D;
1575
  if (-p + D > l)
118✔
1576
    return -p + D;
118✔
1577

118✔
1578
  return INFTY;
1579
}
118✔
1580

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

1588
  shell = sanitize_phi(shell);
362✔
1589

1590
  const double p0 = grid_[1][shell];
1591

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

1597
  const double c0 = std::cos(p0);
34,105,254✔
1598
  const double s0 = std::sin(p0);
1599

1600
  const double denominator = (u.x * s0 - u.y * c0);
34,105,254✔
1601

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

883,728✔
1611
  return INFTY;
1612
}
70,010,791✔
1613

70,010,791✔
1614
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
35,071,611✔
1615
  const Position& r, const Direction& u, double l, int shell) const
35,071,611✔
1616
{
34,939,180✔
1617
  MeshDistance d;
34,105,254✔
1618
  d.next_index = shell;
34,105,254✔
1619

1620
  // Direction of flight is within xy-plane. Will never intersect z.
70,010,791✔
1621
  if (std::abs(u.z) < FP_PRECISION)
1622
    return d;
1623

182✔
1624
  d.max_surface = (u.z > 0.0);
1625
  if (d.max_surface && (shell <= shape_[2])) {
182✔
1626
    d.next_index += 1;
182✔
1627
    d.distance = (grid_[2][shell] - r.z) / u.z;
182✔
1628
  } else if (!d.max_surface && (shell > 0)) {
1629
    d.next_index -= 1;
728✔
1630
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
546✔
1631
  }
×
1632
  return d;
1633
}
×
1634

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

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

182✔
1645
  } else if (i == 1) {
1646

182✔
1647
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
1648
                      find_phi_crossing(r0, u, l, ijk[i])),
1649
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
99,488,052✔
1650
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
1651

99,488,052✔
1652
  } else {
1653
    return find_z_crossing(r0, u, l, ijk[i]);
1654
  }
11✔
1655
}
1656

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

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

111✔
1690
    return OPENMC_E_INVALID_ARGUMENT;
1691
  }
204✔
1692

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

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

1700
  return 0;
1701
}
1702

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

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

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

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

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

1731
  double phi_i = grid_[1][ijk[1] - 1];
48,066,788✔
1732
  double phi_o = grid_[1][ijk[1]];
48,066,788✔
1733

48,066,788✔
1734
  double z_i = grid_[2][ijk[2] - 1];
1735
  double z_o = grid_[2][ijk[2]];
48,066,788✔
1736

×
1737
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
1738
}
48,066,788✔
1739

48,066,788✔
1740
//==============================================================================
24,062,675✔
1741
// SphericalMesh implementation
1742
//==============================================================================
1743

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

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

88,150✔
1754
  if (int err = set_grid()) {
88,150✔
1755
    fatal_error(openmc_err_msg);
1756
  }
88,150✔
1757
}
88,150✔
1758

1759
const std::string SphericalMesh::mesh_type = "spherical";
88,150✔
1760

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

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

1771
  Position mapped_r;
88,150✔
1772
  mapped_r[0] = r.norm();
1773

1774
  if (mapped_r[0] < FP_PRECISION) {
143,491,360✔
1775
    mapped_r[1] = 0.0;
1776
    mapped_r[2] = 0.0;
1777
  } else {
1778
    mapped_r[1] = std::acos(r.z / mapped_r.x);
143,491,360✔
1779
    mapped_r[2] = std::atan2(r.y, r.x);
18,078,908✔
1780
    if (mapped_r[2] < 0)
1781
      mapped_r[2] += 2 * M_PI;
1782
  }
1783

1784
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1785

125,412,452✔
1786
  idx[1] = sanitize_theta(idx[1]);
125,412,452✔
1787
  idx[2] = sanitize_phi(idx[2]);
7,215,419✔
1788

1789
  return idx;
118,197,033✔
1790
}
1791

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

1798
  double theta_min = this->theta(ijk[1] - 1);
118,105,913✔
1799
  double theta_max = this->theta(ijk[1]);
118,105,913✔
1800

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

9,808,738✔
1804
  double cos_theta =
1805
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
108,297,175✔
1806
  double sin_theta = std::sin(std::acos(cos_theta));
1807
  double phi = uniform_distribution(phi_min, phi_max, seed);
1808
  double r_min_cub = std::pow(r_min, 3);
108,297,175✔
1809
  double r_max_cub = std::pow(r_max, 3);
6,611,374✔
1810
  // might be faster to do rejection here?
1811
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
101,685,801✔
1812

20,348,578✔
1813
  double x = r * std::cos(phi) * sin_theta;
81,337,223✔
1814
  double y = r * std::sin(phi) * sin_theta;
50,371,137✔
1815
  double z = r * cos_theta;
1816

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

75,312,966✔
1820
double SphericalMesh::find_r_crossing(
1821
  const Position& r, const Direction& u, double l, int shell) const
1822
{
1823
  if ((shell < 0) || (shell > shape_[0]))
75,312,966✔
1824
    return INFTY;
30,474,840✔
1825

1826
  // solve |r+s*u| = r0
44,838,126✔
1827
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
1828
  const double r0 = grid_[0][shell];
44,838,126✔
1829
  if (r0 == 0.0)
1830
    return INFTY;
1831
  const double p = r.dot(u);
1832
  double c = r.dot(r) - r0 * r0;
1833
  double D = p * p - c;
1834

1835
  if (std::abs(c) <= RADIAL_MESH_TOL)
44,838,126✔
1836
    return INFTY;
44,838,126✔
1837

1838
  if (D >= 0.0) {
44,838,126✔
1839
    D = std::sqrt(D);
1840
    // the solution -p - D is always smaller as -p + D : Check this one first
1841
    if (-p - D > l)
44,838,126✔
1842
      return -p - D;
44,449,158✔
1843
    if (-p + D > l)
1844
      return -p + D;
1845
  }
44,449,158✔
1846

20,504,807✔
1847
  return INFTY;
1848
}
1849

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

37,030,444✔
1857
  shell = sanitize_theta(shell);
1858

1859
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
37,030,444✔
1860
  // yields
1,438,152✔
1861
  // a*s^2 + 2*b*s + c == 0 with
1862
  // a = cos(theta)^2 - u.z * u.z
35,592,292✔
1863
  // b = r*u * cos(theta)^2 - u.z * r.z
35,592,292✔
1864
  // c = r*r * cos(theta)^2 - r.z^2
16,893,425✔
1865

16,893,425✔
1866
  const double cos_t = std::cos(grid_[1][shell]);
18,698,867✔
1867
  const bool sgn = std::signbit(cos_t);
16,843,453✔
1868
  const double cos_t_2 = cos_t * cos_t;
16,843,453✔
1869

1870
  const double a = cos_t_2 - u.z * u.z;
35,592,292✔
1871
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1872
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
1873

146,432,607✔
1874
  // if factor of s^2 is zero, direction of flight is parallel to theta
1875
  // surface
1876
  if (std::abs(a) < FP_PRECISION) {
1877
    // if b vanishes, direction of flight is within theta surface and crossing
146,432,607✔
1878
    // is not possible
1879
    if (std::abs(b) < FP_PRECISION)
71,745,680✔
1880
      return INFTY;
71,745,680✔
1881

143,491,360✔
1882
    const double s = -0.5 * c / b;
1883
    // Check if solution is in positive direction of flight and has correct
74,686,927✔
1884
    // sign
1885
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
37,656,483✔
1886
      return s;
37,656,483✔
1887

37,656,483✔
1888
    // no crossing is possible
75,312,966✔
1889
    return INFTY;
1890
  }
1891

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

1895
  if (D < 0.0)
432✔
1896
    return INFTY;
1897

432✔
1898
  D = std::sqrt(D);
432✔
1899

432✔
1900
  // the solution -p-D is always smaller as -p+D : Check this one first
1901
  double s = -p - D;
1,728✔
1902
  // Check if solution is in positive direction of flight and has correct sign
1,296✔
1903
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
1904
    return s;
1905

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

1911
  return INFTY;
×
1912
}
1913

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

×
1921
  shell = sanitize_phi(shell);
1922

×
1923
  const double p0 = grid_[2][shell];
1924

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

1930
  const double c0 = std::cos(p0);
1931
  const double s0 = std::sin(p0);
432✔
1932

1933
  const double denominator = (u.x * s0 - u.y * c0);
864✔
1934

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

144,200,364✔
1944
  return INFTY;
1945
}
1946

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

1952
  if (i == 0) {
1953
    return std::min(
1954
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
1955
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
1956

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

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

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

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

1999
    return OPENMC_E_INVALID_ARGUMENT;
397✔
2000
  }
2001
  if (grid_[2].back() > 2 * PI) {
397✔
2002
    set_errmsg("phi-grids for "
2003
               "spherical meshes must end with phi <= 2*pi.");
2004
    return OPENMC_E_INVALID_ARGUMENT;
68,548,554✔
2005
  }
2006

2007
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
68,548,554✔
2008
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
2009

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

×
2014
  return 0;
×
2015
}
2016

68,548,554✔
2017
int SphericalMesh::get_index_in_direction(double r, int i) const
68,548,554✔
2018
{
68,548,554✔
2019
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
34,266,957✔
2020
}
2021

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

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

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

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

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

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

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

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

444,038,016✔
2059
int check_mesh(int32_t index)
2060
{
2061
  if (index < 0 || index >= model::meshes.size()) {
444,038,016✔
2062
    set_errmsg("Index in meshes array is out of bounds.");
39,868,253✔
2063
    return OPENMC_E_OUT_OF_BOUNDS;
2064
  }
2065
  return 0;
2066
}
404,169,763✔
2067

404,169,763✔
2068
template<class T>
7,359,263✔
2069
int check_mesh_type(int32_t index)
396,810,500✔
2070
{
396,810,500✔
2071
  if (int err = check_mesh(index))
396,810,500✔
2072
    return err;
2073

396,810,500✔
2074
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
10,598,654✔
2075
  if (!mesh) {
2076
    set_errmsg("This function is not valid for input mesh.");
386,211,846✔
2077
    return OPENMC_E_INVALID_TYPE;
358,215,914✔
2078
  }
2079
  return 0;
358,215,914✔
2080
}
64,410,404✔
2081

293,805,510✔
2082
template<class T>
177,133,028✔
2083
bool is_mesh_type(int32_t index)
2084
{
2085
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
144,668,414✔
2086
  return mesh;
2087
}
2088

110,105,928✔
2089
//==============================================================================
2090
// C API functions
2091
//==============================================================================
2092

110,105,928✔
2093
// Return the type of mesh as a C string
71,220,972✔
2094
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
2095
{
38,884,956✔
2096
  if (int err = check_mesh(index))
2097
    return err;
2098

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

2101
  return 0;
2102
}
2103

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

2112
  for (int i = 0; i < n; ++i) {
2113
    if (RegularMesh::mesh_type == type) {
2114
      model::meshes.push_back(make_unique<RegularMesh>());
38,884,956✔
2115
    } else if (RectilinearMesh::mesh_type == type) {
2116
      model::meshes.push_back(make_unique<RectilinearMesh>());
2117
    } else if (CylindricalMesh::mesh_type == type) {
745,756✔
2118
      model::meshes.push_back(make_unique<CylindricalMesh>());
745,756✔
2119
    } else if (SphericalMesh::mesh_type == type) {
2120
      model::meshes.push_back(make_unique<SphericalMesh>());
×
2121
    } else {
2122
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
2123
    }
×
2124
  }
×
2125
  if (index_end)
2126
    *index_end = model::meshes.size() - 1;
2127

×
2128
  return 0;
2129
}
2130

38,139,200✔
2131
//! Adds a new unstructured mesh to OpenMC
38,139,200✔
2132
extern "C" int openmc_add_unstructured_mesh(
2133
  const char filename[], const char library[], int* id)
38,139,200✔
2134
{
11,166,284✔
2135
  std::string lib_name(library);
2136
  std::string mesh_file(filename);
26,972,916✔
2137
  bool valid_lib = false;
2138

2139
#ifdef OPENMC_DAGMC_ENABLED
26,972,916✔
2140
  if (lib_name == MOABMesh::mesh_lib_type) {
2141
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
26,972,916✔
2142
    valid_lib = true;
5,318,655✔
2143
  }
2144
#endif
21,654,261✔
2145

2146
#ifdef OPENMC_LIBMESH_ENABLED
21,654,261✔
2147
  if (lib_name == LibMesh::mesh_lib_type) {
10,163,296✔
2148
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
2149
    valid_lib = true;
11,490,965✔
2150
  }
2151
#endif
2152

111,722,886✔
2153
  if (!valid_lib) {
2154
    set_errmsg(fmt::format("Mesh library {} is not supported "
2155
                           "by this build of OpenMC",
2156
      lib_name));
111,722,886✔
2157
    return OPENMC_E_INVALID_ARGUMENT;
71,220,972✔
2158
  }
2159

40,501,914✔
2160
  // auto-assign new ID
2161
  model::meshes.back()->set_id(-1);
40,501,914✔
2162
  *id = model::meshes.back()->id_;
2163

2164
  return 0;
2165
}
2166

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

40,140,290✔
2179
//! Return the ID of a mesh
17,727,172✔
2180
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2181
{
2182
  if (int err = check_mesh(index))
22,774,742✔
2183
    return err;
2184
  *id = model::meshes[index]->id_;
2185
  return 0;
332,933,415✔
2186
}
2187

2188
//! Set the ID of a mesh
2189
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
2190
{
332,933,415✔
2191
  if (int err = check_mesh(index))
222,019,008✔
2192
    return err;
222,019,008✔
2193
  model::meshes[index]->id_ = id;
444,038,016✔
2194
  model::mesh_map[id] = index;
2195
  return 0;
110,914,407✔
2196
}
55,052,964✔
2197

55,052,964✔
2198
//! Get the number of elements in a mesh
55,052,964✔
2199
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
110,105,928✔
2200
{
2201
  if (int err = check_mesh(index))
2202
    return err;
55,861,443✔
2203
  *n = model::meshes[index]->n_bins();
55,861,443✔
2204
  return 0;
55,861,443✔
2205
}
111,722,886✔
2206

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

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

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

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

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

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

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

205,645,662✔
2256
  return 0;
2257
}
205,645,662✔
2258

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

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

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

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

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

2299
#pragma omp parallel
9,027✔
2300
  {
×
2301
    Position r = xyz;
×
2302

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

1,614✔
2313
  return 0;
1,614✔
2314
}
×
2315

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

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

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

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

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

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

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

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

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

2393
  // Set material volumes
2394

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

64✔
2403
  return 0;
68✔
2404
}
34✔
2405

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

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

2417
  m->n_dimension_ = 3;
2418

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

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

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

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

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

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

599✔
2458
  return 0;
×
2459
}
×
2460

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

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

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

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

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

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

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

215✔
2514
#ifdef OPENMC_DAGMC_ENABLED
215✔
2515

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

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

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

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

×
2539
void MOABMesh::initialize()
2540
{
17✔
2541

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2718
  double track_len = (end - start).length();
2719
  if (track_len == 0.0)
132✔
2720
    return;
132✔
2721

2722
  start -= TINY_BIT * dir;
34✔
2723
  end += TINY_BIT * dir;
2724

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

×
2728
  bins.clear();
2729
  lengths.clear();
34✔
2730

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

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

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

34✔
2760
    if (bin == -1) {
2761
      continue;
34✔
2762
    }
34✔
2763

34✔
2764
    bins.push_back(bin);
2765
    lengths.push_back(segment_length / track_len);
136✔
2766
  }
102✔
2767

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

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

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

145✔
2801
  // loop over the tets in this leaf, returning the containing tet if found
2802
  for (const auto& tet : tets) {
2803
    if (point_in_tet(pos, tet)) {
64✔
2804
      return tet;
64✔
2805
    }
2806
  }
2807

2808
  // if no tet is found, return an invalid handle
2809
  return 0;
591✔
2810
}
2811

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

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

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

591✔
2826
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
591✔
2827

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

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

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

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

187✔
2865
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
187✔
2866
}
187✔
2867

187✔
2868
int MOABMesh::get_bin(Position r) const
187✔
2869
{
2870
  moab::EntityHandle tet = get_tet(r);
187✔
2871
  if (tet == 0) {
2872
    return -1;
217✔
2873
  } else {
2874
    return get_bin_from_ent_handle(tet);
2875
  }
217✔
2876
}
×
2877

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

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

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

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

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

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

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

2912
  moab::ErrorCode rval;
187✔
2913

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

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

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

2937
  moab::CartVect bary_coords = a_inv * (r - p_zero);
2938

2939
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
34✔
2940
          bary_coords[2] >= 0.0 &&
2941
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
2942
}
2943

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3053
Position MOABMesh::vertex(int id) const
3054
{
20✔
3055

20✔
3056
  moab::ErrorCode rval;
3057

3058
  moab::EntityHandle vert = verts_[id];
27✔
3059

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

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

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

3073
  auto tet = get_ent_handle_from_bin(bin);
3074

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

3083
  std::vector<int> verts(4);
3084
  for (int i = 0; i < verts.size(); i++) {
3085
    verts[i] = get_vert_idx_from_handle(conn[i]);
20✔
3086
  }
3087

3088
  return verts;
3089
}
3090

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3216
#endif
7,317,030✔
3217

3218
#ifdef OPENMC_LIBMESH_ENABLED
7,317,030✔
3219

3220
const std::string LibMesh::mesh_lib_type = "libmesh";
7,317,030✔
3221

7,317,030✔
3222
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
7,317,030✔
3223
{
1,011,877✔
3224
  // filename_ and length_multiplier_ will already be set by the
3225
  // UnstructuredMesh constructor
3226
  set_mesh_pointer_from_filename(filename_);
3227
  set_length_multiplier(length_multiplier_);
6,305,153✔
3228
  initialize();
6,305,153✔
3229
}
6,305,153✔
3230

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

3239
  m_ = &input_mesh;
3240
  set_length_multiplier(length_multiplier);
3241
  initialize();
3242
}
2,847✔
3243

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

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

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

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

1,603,280✔
3279
  // assuming that unstructured meshes used in OpenMC are 3D
3280
  n_dimension_ = 3;
3281

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

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

3298
  for (int i = 0; i < num_threads(); i++) {
431,712✔
3299
    pl_.emplace_back(m_->sub_point_locator());
215,856✔
3300
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3301
    pl_.back()->enable_out_of_mesh_mode();
7,317,030✔
3302
  }
3303

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

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

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

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

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

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

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

260,206,154✔
3358
std::string LibMesh::library() const
260,206,154✔
3359
{
260,206,154✔
3360
  return mesh_lib_type;
3361
}
3362

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

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

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

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

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

3411
void LibMesh::remove_scores()
1,103,424✔
3412
{
3413
  if (equation_systems_) {
3414
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
266,748,172✔
3415
    eqn_sys.clear();
3416
    variable_map_.clear();
266,748,172✔
3417
  }
266,748,172✔
3418
}
3419

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

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

892,532✔
3429
  if (!eqn_sys.is_initialized()) {
3430
    equation_systems_->init();
3431
  }
267,916,644✔
3432

3433
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
267,916,644✔
3434

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

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

3448
    auto bin = get_bin_from_element(*it);
3449

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

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

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

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

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

3486
  // quick rejection check
100,185✔
3487
  if (!bbox_.contains_point(p)) {
3488
    return -1;
3489
  }
3490

3491
  const auto& point_locator = pl_.at(thread_num());
100,185✔
3492

3493
  const auto elem_ptr = (*point_locator)(p);
100,185✔
3494
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
100,185✔
3495
}
100,185✔
3496

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

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

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

275,856✔
3517
double LibMesh::volume(int bin) const
1,379,280✔
3518
{
1,103,424✔
3519
  return this->get_element_from_bin(bin).volume();
3520
}
3521

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

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

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

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

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

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

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

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

3581
#endif // OPENMC_LIBMESH_ENABLED
3582

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

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

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

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

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

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

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

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

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

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

3669
  close_group(meshes_group);
3670
}
3671

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

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

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

© 2026 Coveralls, Inc