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

openmc-dev / openmc / 13712674732

07 Mar 2025 02:48AM UTC coverage: 85.126% (-0.001%) from 85.127%
13712674732

push

github

web-flow
Random Ray Source Region Mesh Subdivision (Cell-Under-Voxel Geometry) (#3333)

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

550 of 637 new or added lines in 12 files covered. (86.34%)

7 existing lines in 3 files now uncovered.

51572 of 60583 relevant lines covered (85.13%)

36891325.97 hits per line

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

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

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

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

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

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

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

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

60
namespace openmc {
61

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

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

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

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

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

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

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

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

142
namespace detail {
143

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

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

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

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

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

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

182
      // If we claimed the slot or another thread claimed it but the same
183
      // material was inserted, proceed to accumulate
184
      if (claimed_slot || (expected_val == index_material)) {
1,259✔
185
#pragma omp atomic
691✔
186
        this->volumes(index_elem, slot) += volume;
1,259✔
187
        return;
1,259✔
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,497✔
234
{
235
  // Read mesh id
236
  id_ = std::stoi(get_node_value(node, "id"));
2,497✔
237
  if (check_for_node(node, "name"))
2,497✔
238
    name_ = get_node_value(node, "name");
16✔
239
}
2,497✔
240

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

717
  int num_elem_skipped = 0;
31✔
718

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

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

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

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

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

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

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

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

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

786
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
787
      in_mesh = false;
84,293,356✔
788
  }
789
  return ijk;
1,066,266,815✔
790
}
791

792
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,585,481,224✔
793
{
794
  switch (n_dimension_) {
1,585,481,224✔
795
  case 1:
877,008✔
796
    return ijk[0] - 1;
877,008✔
797
  case 2:
46,496,186✔
798
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
46,496,186✔
799
  case 3:
1,538,108,030✔
800
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,538,108,030✔
801
  default:
×
802
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
803
  }
804
}
805

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

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

830
  // Convert indices to bin
831
  return get_bin_from_indices(ijk);
214,788,142✔
832
}
833

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

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

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

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

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

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

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

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

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

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

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

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

897
  return counts;
×
898
}
899

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

913
  // Compute the length of the entire track.
914
  double total_distance = (r1 - r0).norm();
834,938,034✔
915
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
834,938,034✔
916
    return;
9,057,726✔
917

918
  const int n = n_dimension_;
825,880,308✔
919

920
  // Flag if position is inside the mesh
921
  bool in_mesh;
922

923
  // Position is r = r0 + u * traveled_distance, start at r0
924
  double traveled_distance {0.0};
825,880,308✔
925

926
  // Calculate index of current cell. Offset the position a tiny bit in
927
  // direction of flight
928
  MeshIndex ijk = get_indices(r0 + TINY_BIT * u, in_mesh);
825,880,308✔
929

930
  // if track is very short, assume that it is completely inside one cell.
931
  // Only the current cell will score and no surfaces
932
  if (total_distance < 2 * TINY_BIT) {
825,880,308✔
933
    if (in_mesh) {
646,283✔
934
      tally.track(ijk, 1.0);
646,272✔
935
    }
936
    return;
646,283✔
937
  }
938

939
  // translate start and end positions,
940
  // this needs to come after the get_indices call because it does its own
941
  // translation
942
  local_coords(r0);
825,234,025✔
943
  local_coords(r1);
825,234,025✔
944

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

951
  // Loop until r = r1 is eventually reached
952
  while (true) {
702,023,263✔
953

954
    if (in_mesh) {
1,527,257,288✔
955

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

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

965
      // update position and leave, if we have reached end position
966
      traveled_distance = distances[k].distance;
1,451,531,840✔
967
      if (traveled_distance >= total_distance)
1,451,531,840✔
968
        return;
754,674,406✔
969

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

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

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

983
      // If we are still inside the mesh, tally inward current for the next
984
      // cell
985
      if (in_mesh)
696,857,434✔
986
        tally.surface(ijk, k, !distances[k].max_surface, true);
682,991,296✔
987

988
    } else { // not inside mesh
989

990
      // For all directions outside the mesh, find the distance that we need
991
      // to travel to reach the next surface. Use the largest distance, as
992
      // only this will cross all outer surfaces.
993
      int k_max {0};
75,725,448✔
994
      for (int k = 0; k < n; ++k) {
300,755,536✔
995
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
301,993,868✔
996
            (distances[k].distance > traveled_distance)) {
76,963,780✔
997
          traveled_distance = distances[k].distance;
76,238,366✔
998
          k_max = k;
76,238,366✔
999
        }
1000
      }
1001

1002
      // If r1 is not inside the mesh, exit here
1003
      if (traveled_distance >= total_distance)
75,725,448✔
1004
        return;
70,559,619✔
1005

1006
      // Calculate the new cell index and update all distances to next
1007
      // surfaces.
1008
      ijk = get_indices(r0 + (traveled_distance + TINY_BIT) * u, in_mesh);
5,165,829✔
1009
      for (int k = 0; k < n; ++k) {
20,453,161✔
1010
        distances[k] =
15,287,332✔
1011
          distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
15,287,332✔
1012
      }
1013

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1163
  // Set material volumes
1164
  volume_frac_ = 1.0 / xt::prod(shape)();
714,193,106✔
1165

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

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

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

1,427,093,646✔
1179
std::string RegularMesh::get_mesh_type() const
2,147,483,647✔
1180
{
2,116,083,475✔
1181
  return mesh_type;
1182
}
1183

1184
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
672,261,740✔
1185
{
1186
  return lower_left_[i] + ijk[i] * width_[i];
1,385,808,563✔
1187
}
1188

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

1,311,973,135✔
1194
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
1,311,973,135✔
1195
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1196
  double l) const
1197
{
1198
  MeshDistance d;
1,311,973,135✔
1199
  d.next_index = ijk[i];
1,311,973,135✔
1200
  if (std::abs(u[i]) < FP_PRECISION)
644,653,935✔
1201
    return d;
1202

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

667,319,200✔
1214
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1215
  Position plot_ll, Position plot_ur) const
1216
{
1217
  // Figure out which axes lie in the plane of the plot.
667,319,200✔
1218
  array<int, 2> axes {-1, -1};
654,656,231✔
1219
  if (plot_ur.z == plot_ll.z) {
1220
    axes[0] = 0;
1221
    if (n_dimension_ > 1)
1222
      axes[1] = 1;
1223
  } else if (plot_ur.y == plot_ll.y) {
1224
    axes[0] = 0;
1225
    if (n_dimension_ > 2)
73,835,428✔
1226
      axes[1] = 2;
293,517,481✔
1227
  } else if (plot_ur.x == plot_ll.x) {
294,612,307✔
1228
    if (n_dimension_ > 1)
74,930,254✔
1229
      axes[0] = 1;
74,263,932✔
1230
    if (n_dimension_ > 2)
74,263,932✔
1231
      axes[1] = 2;
1232
  } else {
1233
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1234
  }
1235

73,835,428✔
1236
  // Get the coordinates of the mesh lines along both of the axes.
68,892,888✔
1237
  array<vector<double>, 2> axis_lines;
1238
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1239
    int axis = axes[i_ax];
1240
    if (axis == -1)
4,942,540✔
1241
      continue;
19,664,593✔
1242
    auto& lines {axis_lines[i_ax]};
14,722,053✔
1243

14,722,053✔
1244
    double coord = lower_left_[axis];
1245
    for (int i = 0; i < shape_[axis] + 1; ++i) {
1246
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1247
        lines.push_back(coord);
4,942,540✔
1248
      coord += width_[axis];
3,701,619✔
1249
    }
1250
  }
1251

1252
  return {axis_lines[0], axis_lines[1]};
1253
}
723,250,832✔
1254

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

1263
xt::xtensor<double, 1> RegularMesh::count_sites(
723,250,832✔
1264
  const SourceSite* bank, int64_t length, bool* outside) const
723,250,832✔
1265
{
1,325,677,050✔
1266
  // Determine shape of array for counts
1,312,619,407✔
1267
  std::size_t m = this->n_bins();
1268
  vector<std::size_t> shape = {m};
1,312,619,407✔
1269

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

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

1277
    // determine scoring bin for entropy mesh
1278
    int mesh_bin = get_bin(site.r);
723,250,832✔
1279

723,250,832✔
1280
    // if outside mesh, skip particle
1281
    if (mesh_bin < 0) {
111,687,202✔
1282
      outside_ = true;
1283
      continue;
1284
    }
1285

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

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

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

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

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

1315
  return counts;
1316
}
1,678✔
1317

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

1323
//==============================================================================
1,678✔
1324
// RectilinearMesh implementation
1,678✔
1325
//==============================================================================
1,678✔
1326

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

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

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

1,678✔
1340
const std::string RectilinearMesh::mesh_type = "rectilinear";
1341

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

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

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

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

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

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

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

1,678✔
1399
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
6,413✔
1400
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
4,735✔
1401

1402
  return 0;
1,678✔
1403
}
1404

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

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

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

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

2,147,483,647✔
1437
  return {axis_lines[0], axis_lines[1]};
1,344,159,259✔
1438
}
1,344,159,259✔
1439

1,294,033,785✔
1440
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
1,281,299,373✔
1441
{
1,281,299,373✔
1442
  write_dataset(mesh_group, "x_grid", grid_[0]);
1443
  write_dataset(mesh_group, "y_grid", grid_[1]);
2,147,483,647✔
1444
  write_dataset(mesh_group, "z_grid", grid_[2]);
1445
}
1446

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

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

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

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

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

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

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

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

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

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

1499
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
7,839✔
1500

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

1503
  return idx;
7,839✔
1504
}
7,839✔
1505

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

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

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

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

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

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

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

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

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

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

7,839✔
1545
  const double denominator = u.x * u.x + u.y * u.y;
7,839✔
1546

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

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

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

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

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

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

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

1572
  return INFTY;
1573
}
1574

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

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

1584
  const double p0 = grid_[1][shell];
1585

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

1591
  const double c0 = std::cos(p0);
53,414,482✔
1592
  const double s0 = std::sin(p0);
1593

1594
  const double denominator = (u.x * s0 - u.y * c0);
1595

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

26,442,625✔
1605
  return INFTY;
25,654,849✔
1606
}
25,654,849✔
1607

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

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

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

1629
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
1630
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1631
  double l) const
147✔
1632
{
147✔
1633
  Position r = r0 - origin_;
1634

147✔
1635
  if (i == 0) {
1636

1637
    return std::min(
73,891,983✔
1638
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r, u, l, ijk[i])),
1639
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r, u, l, ijk[i] - 1)));
73,891,983✔
1640

1641
  } else if (i == 1) {
1642

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

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

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

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

1686
    return OPENMC_E_INVALID_ARGUMENT;
132✔
1687
  }
1688

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

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

1696
  return 0;
379✔
1697
}
379✔
1698

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

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

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

1714
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
46,354,396✔
1715
{
1716
  write_dataset(mesh_group, "r_grid", grid_[0]);
1717
  write_dataset(mesh_group, "phi_grid", grid_[1]);
46,354,396✔
1718
  write_dataset(mesh_group, "z_grid", grid_[2]);
1719
  write_dataset(mesh_group, "origin", origin_);
46,354,396✔
1720
}
46,354,396✔
1721

46,354,396✔
1722
double CylindricalMesh::volume(const MeshIndex& ijk) const
1723
{
46,354,396✔
1724
  double r_i = grid_[0][ijk[0] - 1];
×
1725
  double r_o = grid_[0][ijk[0]];
1726

46,354,396✔
1727
  double phi_i = grid_[1][ijk[1] - 1];
46,354,396✔
1728
  double phi_o = grid_[1][ijk[1]];
23,191,993✔
1729

1730
  double z_i = grid_[2][ijk[2] - 1];
1731
  double z_o = grid_[2][ijk[2]];
46,354,396✔
1732

1733
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
46,354,396✔
1734
}
1735

46,354,396✔
1736
//==============================================================================
1737
// SphericalMesh implementation
1738
//==============================================================================
88,000✔
1739

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

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

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

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

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

1762
StructuredMesh::MeshIndex SphericalMesh::get_indices(
136,361,126✔
1763
  Position r, bool& in_mesh) const
1764
{
1765
  local_coords(r);
1766

136,361,126✔
1767
  Position mapped_r;
16,738,502✔
1768
  mapped_r[0] = r.norm();
1769

1770
  if (mapped_r[0] < FP_PRECISION) {
1771
    mapped_r[1] = 0.0;
1772
    mapped_r[2] = 0.0;
1773
  } else {
119,622,624✔
1774
    mapped_r[1] = std::acos(r.z / mapped_r.x);
119,622,624✔
1775
    mapped_r[2] = std::atan2(r.y, r.x);
6,667,485✔
1776
    if (mapped_r[2] < 0)
1777
      mapped_r[2] += 2 * M_PI;
112,955,139✔
1778
  }
1779

1780
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
112,955,139✔
1781

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

112,896,179✔
1785
  return idx;
1786
}
112,896,179✔
1787

112,896,179✔
1788
Position SphericalMesh::sample_element(
112,896,179✔
1789
  const MeshIndex& ijk, uint64_t* seed) const
1790
{
112,896,179✔
1791
  double r_min = this->r(ijk[0] - 1);
15,592,401✔
1792
  double r_max = this->r(ijk[0]);
1793

97,303,778✔
1794
  double theta_min = this->theta(ijk[1] - 1);
1795
  double theta_max = this->theta(ijk[1]);
1796

97,303,778✔
1797
  double phi_min = this->phi(ijk[2] - 1);
6,469,408✔
1798
  double phi_max = this->phi(ijk[2]);
1799

90,834,370✔
1800
  double cos_theta = uniform_distribution(theta_min, theta_max, seed);
18,559,706✔
1801
  double sin_theta = std::sin(std::acos(cos_theta));
72,274,664✔
1802
  double phi = uniform_distribution(phi_min, phi_max, seed);
43,873,610✔
1803
  double r_min_cub = std::pow(r_min, 3);
1804
  double r_max_cub = std::pow(r_max, 3);
28,401,054✔
1805
  // might be faster to do rejection here?
1806
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
1807

68,093,014✔
1808
  double x = r * std::cos(phi) * sin_theta;
1809
  double y = r * std::sin(phi) * sin_theta;
1810
  double z = r * cos_theta;
1811

68,093,014✔
1812
  return origin_ + Position(x, y, z);
29,760,896✔
1813
}
1814

38,332,118✔
1815
double SphericalMesh::find_r_crossing(
1816
  const Position& r, const Direction& u, double l, int shell) const
38,332,118✔
1817
{
1818
  if ((shell < 0) || (shell > shape_[0]))
1819
    return INFTY;
1820

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

38,332,118✔
1830
  if (std::abs(c) <= RADIAL_MESH_TOL)
38,071,374✔
1831
    return INFTY;
1832

1833
  if (D >= 0.0) {
38,071,374✔
1834
    D = std::sqrt(D);
17,817,756✔
1835
    // the solution -p - D is always smaller as -p + D : Check this one first
1836
    if (-p - D > l)
1837
      return -p - D;
20,514,362✔
1838
    if (-p + D > l)
1839
      return -p + D;
1840
  }
36,659,744✔
1841

1842
  return INFTY;
1843
}
36,659,744✔
1844

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

35,541,528✔
1852
  shell = sanitize_theta(shell);
16,288,668✔
1853

16,288,668✔
1854
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
19,252,860✔
1855
  // yields
16,534,419✔
1856
  // a*s^2 + 2*b*s + c == 0 with
16,534,419✔
1857
  // a = cos(theta)^2 - u.z * u.z
1858
  // b = r*u * cos(theta)^2 - u.z * r.z
35,541,528✔
1859
  // c = r*r * cos(theta)^2 - r.z^2
1860

1861
  const double cos_t = std::cos(grid_[1][shell]);
138,886,814✔
1862
  const bool sgn = std::signbit(cos_t);
1863
  const double cos_t_2 = cos_t * cos_t;
1864

1865
  const double a = cos_t_2 - u.z * u.z;
138,886,814✔
1866
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1867
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
138,886,814✔
1868

1869
  // if factor of s^2 is zero, direction of flight is parallel to theta
68,180,563✔
1870
  // surface
68,180,563✔
1871
  if (std::abs(a) < FP_PRECISION) {
136,361,126✔
1872
    // if b vanishes, direction of flight is within theta surface and crossing
1873
    // is not possible
70,706,251✔
1874
    if (std::abs(b) < FP_PRECISION)
1875
      return INFTY;
34,046,507✔
1876

34,046,507✔
1877
    const double s = -0.5 * c / b;
34,046,507✔
1878
    // Check if solution is in positive direction of flight and has correct
68,093,014✔
1879
    // sign
1880
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1881
      return s;
36,659,744✔
1882

1883
    // no crossing is possible
1884
    return INFTY;
1885
  }
401✔
1886

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

401✔
1890
  if (D < 0.0)
1891
    return INFTY;
1,604✔
1892

1,203✔
1893
  D = std::sqrt(D);
×
1894

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

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

×
1906
  return INFTY;
1907
}
×
1908

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

×
1916
  shell = sanitize_phi(shell);
1917

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

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

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

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

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

1939
  return INFTY;
×
1940
}
1941

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

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

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

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

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

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

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

2002
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
67,606,671✔
2003
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
×
2004

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

67,606,671✔
2009
  return 0;
33,808,808✔
2010
}
2011

2012
int SphericalMesh::get_index_in_direction(double r, int i) const
67,606,671✔
2013
{
2014
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
67,606,671✔
2015
}
67,606,671✔
2016

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

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

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

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

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

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

2046
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
2047
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
441,480,512✔
2048
}
2049

2050
//==============================================================================
441,480,512✔
2051
// Helper functions for the C API
40,361,585✔
2052
//==============================================================================
2053

2054
int check_mesh(int32_t index)
2055
{
401,118,927✔
2056
  if (index < 0 || index >= model::meshes.size()) {
401,118,927✔
2057
    set_errmsg("Index in meshes array is out of bounds.");
6,967,752✔
2058
    return OPENMC_E_OUT_OF_BOUNDS;
394,151,175✔
2059
  }
394,151,175✔
2060
  return 0;
394,151,175✔
2061
}
2062

394,151,175✔
2063
template<class T>
10,586,180✔
2064
int check_mesh_type(int32_t index)
2065
{
383,564,995✔
2066
  if (int err = check_mesh(index))
356,433,220✔
2067
    return err;
2068

356,433,220✔
2069
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
63,719,645✔
2070
  if (!mesh) {
292,713,575✔
2071
    set_errmsg("This function is not valid for input mesh.");
176,340,659✔
2072
    return OPENMC_E_INVALID_TYPE;
2073
  }
2074
  return 0;
143,504,691✔
2075
}
2076

2077
template<class T>
108,366,060✔
2078
bool is_mesh_type(int32_t index)
2079
{
2080
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2081
  return mesh;
108,366,060✔
2082
}
70,123,416✔
2083

2084
//==============================================================================
38,242,644✔
2085
// C API functions
2086
//==============================================================================
2087

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

38,242,644✔
2094
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
38,242,644✔
2095

38,242,644✔
2096
  return 0;
2097
}
38,242,644✔
2098

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

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

37,760,096✔
2123
  return 0;
10,959,168✔
2124
}
2125

26,800,928✔
2126
//! Adds a new unstructured mesh to OpenMC
2127
extern "C" int openmc_add_unstructured_mesh(
2128
  const char filename[], const char library[], int* id)
26,800,928✔
2129
{
2130
  std::string lib_name(library);
26,800,928✔
2131
  std::string mesh_file(filename);
5,133,018✔
2132
  bool valid_lib = false;
2133

21,667,910✔
2134
#ifdef DAGMC
2135
  if (lib_name == MOABMesh::mesh_lib_type) {
21,667,910✔
2136
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
10,142,462✔
2137
    valid_lib = true;
2138
  }
11,525,448✔
2139
#endif
2140

2141
#ifdef LIBMESH
109,969,046✔
2142
  if (lib_name == LibMesh::mesh_lib_type) {
2143
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
2144
    valid_lib = true;
2145
  }
109,969,046✔
2146
#endif
70,123,416✔
2147

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

2155
  // auto-assign new ID
2156
  model::meshes.back()->set_id(-1);
2157
  *id = model::meshes.back()->id_;
39,845,630✔
2158

39,845,630✔
2159
  return 0;
2160
}
39,845,630✔
2161

2162
//! Return the index in the meshes array of a mesh with a given ID
2163
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
39,845,630✔
2164
{
39,611,638✔
2165
  auto pair = model::mesh_map.find(id);
2166
  if (pair == model::mesh_map.end()) {
2167
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
39,611,638✔
2168
    return OPENMC_E_INVALID_ID;
17,419,556✔
2169
  }
2170
  *index = pair->second;
2171
  return 0;
22,426,074✔
2172
}
2173

2174
//! Return the ID of a mesh
329,907,809✔
2175
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2176
{
2177
  if (int err = check_mesh(index))
2178
    return err;
2179
  *id = model::meshes[index]->id_;
329,907,809✔
2180
  return 0;
220,740,256✔
2181
}
220,740,256✔
2182

441,480,512✔
2183
//! Set the ID of a mesh
2184
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
109,167,553✔
2185
{
54,183,030✔
2186
  if (int err = check_mesh(index))
54,183,030✔
2187
    return err;
54,183,030✔
2188
  model::meshes[index]->id_ = id;
108,366,060✔
2189
  model::mesh_map[id] = index;
2190
  return 0;
2191
}
54,984,523✔
2192

54,984,523✔
2193
//! Get the number of elements in a mesh
54,984,523✔
2194
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
109,969,046✔
2195
{
2196
  if (int err = check_mesh(index))
2197
    return err;
2198
  *n = model::meshes[index]->n_bins();
313✔
2199
  return 0;
2200
}
313✔
2201

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

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

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

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

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

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

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

2251
  return 0;
2252
}
×
2253

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

2261
  int pixel_width = pixels[0];
286✔
2262
  int pixel_height = pixels[1];
286✔
2263

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

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

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

2294
#pragma omp parallel
2295
  {
2296
    Position r = xyz;
1,100✔
2297

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

2308
  return 0;
143✔
2309
}
2310

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

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

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

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

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

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

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

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

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

506✔
2388
  // Set material volumes
253✔
2389

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

×
2398
  return 0;
2399
}
2400

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

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

×
2412
  m->n_dimension_ = 3;
×
2413

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

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

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

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

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

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

2453
  return 0;
2454
}
2455

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

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

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

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

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

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

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

132✔
2509
#ifdef DAGMC
132✔
2510

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

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

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

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

132✔
2532
void MOABMesh::initialize()
2533
{
2534

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2715
  start -= TINY_BIT * dir;
22✔
2716
  end += TINY_BIT * dir;
×
2717

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

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

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

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

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

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

2757
    bins.push_back(bin);
99✔
2758
    lengths.push_back(segment_length / track_len);
77✔
2759
  }
2760

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

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

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

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

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

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

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

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

2819
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
121✔
2820

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

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

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

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

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

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

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

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

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

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

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

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

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

121✔
2905
  moab::ErrorCode rval;
121✔
2906

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

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

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

2930
  moab::CartVect bary_coords = a_inv * (r - p_zero);
2931

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

24✔
3049
  moab::ErrorCode rval;
1✔
3050

3051
  moab::EntityHandle vert = verts_[id];
3052

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

3059
  return {coords[0], coords[1], coords[2]};
3060
}
3061

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

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

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

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

20✔
3081
  return verts;
20✔
3082
}
3083

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7,307,001✔
3209
#endif
7,307,001✔
3210

1,010,077✔
3211
#ifdef LIBMESH
3212

3213
const std::string LibMesh::mesh_lib_type = "libmesh";
3214

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

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

167,856✔
3233
  m_ = &input_mesh;
3234
  set_length_multiplier(length_multiplier);
167,856✔
3235
  initialize();
3236
}
3237

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3445
    return;
3446
  }
3447

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

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

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

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

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

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

3473
    auto bin = get_bin_from_element(*it);
86,199✔
3474

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

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

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

3496
    return;
203,856✔
3497
  }
203,856✔
3498

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

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

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

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

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

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

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

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

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

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

3556
#endif // LIBMESH
3557

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

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

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

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

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

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

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

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

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

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

3644
  close_group(meshes_group);
3645
}
3646

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

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

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

© 2025 Coveralls, Inc