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

openmc-dev / openmc / 13501911561

24 Feb 2025 03:41PM UTC coverage: 85.077% (+0.008%) from 85.069%
13501911561

Pull #3129

github

web-flow
Merge 279b8a0b6 into a2a5c2af1
Pull Request #3129: Compute material volumes in mesh elements based on raytracing

207 of 233 new or added lines in 3 files covered. (88.84%)

133 existing lines in 1 file now uncovered.

51001 of 59947 relevant lines covered (85.08%)

34621462.52 hits per line

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

87.51
/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
namespace model {
73

74
std::unordered_map<int32_t, int32_t> mesh_map;
75
vector<unique_ptr<Mesh>> meshes;
76

77
} // namespace model
78

79
#ifdef LIBMESH
80
namespace settings {
81
unique_ptr<libMesh::LibMeshInit> libmesh_init;
82
const libMesh::Parallel::Communicator* libmesh_comm {nullptr};
83
} // namespace settings
84
#endif
85

86
//==============================================================================
87
// Helper functions
88
//==============================================================================
89

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

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

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

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

133
#else
134
#error "No compare-and-swap implementation available for this compiler."
135
#endif
136
}
137

138
namespace detail {
139

140
//==============================================================================
141
// MaterialVolumes implementation
142
//==============================================================================
143

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

153
  // Loop for linear probing
154
  for (int attempt = 0; attempt < table_size_; ++attempt) {
2,543,388✔
155
    // Determine slot to check
156
    int slot = (index_material + attempt) % table_size_;
2,543,388✔
157
    int32_t* slot_ptr = &this->materials(index_elem, slot);
2,543,388✔
158

159
    // Non-atomic read of current material
160
    int32_t current_val = *slot_ptr;
2,543,388✔
161

162
    // Found the desired material; accumulate volume
163
    if (current_val == index_material) {
2,543,388✔
164
#pragma omp atomic
1,237,178✔
165
      this->volumes(index_elem, slot) += volume;
2,473,784✔
166
      return;
2,473,784✔
167
    }
168

169
    // Slot appears to be empty; attempt to claim
170
    if (current_val == EMPTY) {
69,604✔
171
      // Attempt compare-and-swap from EMPTY to index_material
172
      int32_t expected_val = EMPTY;
1,372✔
173
      bool claimed_slot =
174
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,372✔
175

176
      // If we claimed the slot or another thread claimed it but the same
177
      // material was inserted, proceed to accumulate
178
      if (claimed_slot || (expected_val == index_material)) {
1,372✔
179
#pragma omp atomic
690✔
180
        this->volumes(index_elem, slot) += volume;
1,372✔
181
        return;
1,372✔
182
      }
183
    }
184
  }
185

186
  // If table is full, set a flag that can be checked later
NEW
187
  table_full_ = true;
×
188
}
189

NEW
190
void MaterialVolumes::add_volume_unsafe(
×
191
  int index_elem, int index_material, double volume)
192
{
193
  // Linear probe
NEW
194
  for (int attempt = 0; attempt < table_size_; ++attempt) {
×
NEW
195
    int slot = (index_material + attempt) % table_size_;
×
196

197
    // Read current material
NEW
198
    int32_t current_val = this->materials(index_elem, slot);
×
199

200
    // Found the desired material; accumulate volume
NEW
201
    if (current_val == index_material) {
×
NEW
202
      this->volumes(index_elem, slot) += volume;
×
NEW
203
      return;
×
204
    }
205

206
    // Claim empty slot
NEW
207
    if (current_val == EMPTY) {
×
NEW
208
      this->materials(index_elem, slot) = index_material;
×
NEW
209
      this->volumes(index_elem, slot) += volume;
×
NEW
210
      return;
×
211
    }
212
  }
213

214
  // If table is full, set a flag that can be checked later
NEW
215
  table_full_ = true;
×
216
}
217

218
} // namespace detail
219

220
//==============================================================================
221
// Mesh implementation
222
//==============================================================================
223

224
Mesh::Mesh(pugi::xml_node node)
2,815✔
225
{
226
  // Read mesh id
227
  id_ = std::stoi(get_node_value(node, "id"));
2,815✔
228
  if (check_for_node(node, "name"))
2,815✔
229
    name_ = get_node_value(node, "name");
17✔
230
}
2,815✔
231

232
void Mesh::set_id(int32_t id)
1✔
233
{
234
  assert(id >= 0 || id == C_NONE);
1✔
235

236
  // Clear entry in mesh map in case one was already assigned
237
  if (id_ != C_NONE) {
1✔
238
    model::mesh_map.erase(id_);
×
239
    id_ = C_NONE;
×
240
  }
241

242
  // Ensure no other mesh has the same ID
243
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
1✔
244
    throw std::runtime_error {
×
245
      fmt::format("Two meshes have the same ID: {}", id)};
×
246
  }
247

248
  // If no ID is specified, auto-assign the next ID in the sequence
249
  if (id == C_NONE) {
1✔
250
    id = 0;
1✔
251
    for (const auto& m : model::meshes) {
3✔
252
      id = std::max(id, m->id_);
2✔
253
    }
254
    ++id;
1✔
255
  }
256

257
  // Update ID and entry in the mesh map
258
  id_ = id;
1✔
259
  model::mesh_map[id] = model::meshes.size() - 1;
1✔
260
}
1✔
261

262
vector<double> Mesh::volumes() const
508✔
263
{
264
  vector<double> volumes(n_bins());
508✔
265
  for (int i = 0; i < n_bins(); i++) {
1,057,768✔
266
    volumes[i] = this->volume(i);
1,057,260✔
267
  }
268
  return volumes;
508✔
269
}
×
270

271
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
156✔
272
  int32_t* materials, double* volumes) const
273
{
274
  if (mpi::master) {
156✔
275
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
156✔
276
  }
277
  write_message(7, "Number of rays (x) = {}", nx);
156✔
278
  write_message(7, "Number of rays (y) = {}", ny);
156✔
279
  write_message(7, "Number of rays (z) = {}", nz);
156✔
280
  int64_t n_total = nx * ny + ny * nz + nx * nz;
156✔
281
  write_message(7, "Total number of rays = {}", n_total);
156✔
282
  write_message(
156✔
283
    7, "Maximum number of materials per mesh element = {}", table_size);
284

285
  Timer timer;
156✔
286
  timer.start();
156✔
287

288
  // Create object for keeping track of materials/volumes
289
  detail::MaterialVolumes result(materials, volumes, table_size);
156✔
290

291
  // Determine bounding box
292
  auto bbox = this->bounding_box();
156✔
293

294
  std::array<int, 3> n_rays = {nx, ny, nz};
156✔
295

296
  // Determine effective width of rays
297
  Position width((bbox.xmax - bbox.xmin) / nx, (bbox.ymax - bbox.ymin) / ny,
156✔
298
    (bbox.zmax - bbox.zmin) / nz);
156✔
299

300
  // Set flag for mesh being contained within model
301
  bool out_of_model = false;
156✔
302

303
#pragma omp parallel
78✔
304
  {
305
    // Preallocate vector for mesh indices and length fractions and particle
306
    std::vector<int> bins;
78✔
307
    std::vector<double> length_fractions;
78✔
308
    Particle p;
78✔
309

310
    SourceSite site;
78✔
311
    site.E = 1.0;
78✔
312
    site.particle = ParticleType::neutron;
78✔
313

314
    for (int axis = 0; axis < 3; ++axis) {
312✔
315
      // Set starting position and direction
316
      site.r = {0.0, 0.0, 0.0};
234✔
317
      site.r[axis] = bbox.min()[axis];
234✔
318
      site.u = {0.0, 0.0, 0.0};
234✔
319
      site.u[axis] = 1.0;
234✔
320

321
      // Determine width of rays and number of rays in other directions
322
      int ax1 = (axis + 1) % 3;
234✔
323
      int ax2 = (axis + 2) % 3;
234✔
324
      double min1 = bbox.min()[ax1];
234✔
325
      double min2 = bbox.min()[ax2];
234✔
326
      double d1 = width[ax1];
234✔
327
      double d2 = width[ax2];
234✔
328
      int n1 = n_rays[ax1];
234✔
329
      int n2 = n_rays[ax2];
234✔
330

331
      // Divide rays in first direction over MPI processes by computing starting
332
      // and ending indices
333
      int min_work = n1 / mpi::n_procs;
234✔
334
      int remainder = n1 % mpi::n_procs;
234✔
335
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
234✔
336
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
234✔
337
      int i1_end = i1_start + n1_local;
234✔
338

339
      // Loop over rays on face of bounding box
340
#pragma omp for collapse(2)
341
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
9,924✔
342
        for (int i2 = 0; i2 < n2; ++i2) {
503,964✔
343
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
494,274✔
344
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
494,274✔
345

346
          p.from_source(&site);
494,274✔
347

348
          // Determine particle's location
349
          if (!exhaustive_find_cell(p)) {
494,274✔
350
            out_of_model = true;
47,916✔
351
            continue;
47,916✔
352
          }
353

354
          // Set birth cell attribute
355
          if (p.cell_born() == C_NONE)
446,358✔
356
            p.cell_born() = p.lowest_coord().cell;
446,358✔
357

358
          // Initialize last cells from current cell
359
          for (int j = 0; j < p.n_coord(); ++j) {
892,716✔
360
            p.cell_last(j) = p.coord(j).cell;
446,358✔
361
          }
362
          p.n_coord_last() = p.n_coord();
446,358✔
363

364
          while (true) {
365
            // Ray trace from r_start to r_end
366
            Position r0 = p.r();
973,974✔
367
            double max_distance = bbox.max()[axis] - r0[axis];
973,974✔
368

369
            // Find the distance to the nearest boundary
370
            BoundaryInfo boundary = distance_to_boundary(p);
973,974✔
371

372
            // Advance particle forward
373
            double distance = std::min(boundary.distance, max_distance);
973,974✔
374
            p.move_distance(distance);
973,974✔
375

376
            // Determine what mesh elements were crossed by particle
377
            bins.clear();
973,974✔
378
            length_fractions.clear();
973,974✔
379
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
973,974✔
380

381
            // Add volumes to any mesh elements that were crossed
382
            int i_material = p.material();
973,974✔
383
            if (i_material != C_NONE) {
973,974✔
384
              i_material = model::materials[i_material]->id();
939,858✔
385
            }
386
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,211,552✔
387
              int mesh_index = bins[i_bin];
1,237,578✔
388
              double length = distance * length_fractions[i_bin];
1,237,578✔
389

390
              // Add volume to result
391
              result.add_volume(mesh_index, i_material, length * d1 * d2);
1,237,578✔
392
            }
393

394
            if (distance == max_distance)
973,974✔
395
              break;
446,358✔
396

397
            // cross next geometric surface
398
            for (int j = 0; j < p.n_coord(); ++j) {
1,055,232✔
399
              p.cell_last(j) = p.coord(j).cell;
527,616✔
400
            }
401
            p.n_coord_last() = p.n_coord();
527,616✔
402

403
            // Set surface that particle is on and adjust coordinate levels
404
            p.surface() = boundary.surface;
527,616✔
405
            p.n_coord() = boundary.coord_level;
527,616✔
406

407
            if (boundary.lattice_translation[0] != 0 ||
527,616✔
408
                boundary.lattice_translation[1] != 0 ||
1,055,232✔
409
                boundary.lattice_translation[2] != 0) {
527,616✔
410
              // Particle crosses lattice boundary
411
              cross_lattice(p, boundary);
412
            } else {
413
              // Particle crosses surface
414
              const auto& surf {model::surfaces[p.surface_index()].get()};
527,616✔
415
              p.cross_surface(*surf);
527,616✔
416
            }
417
          }
527,616✔
418
        }
419
      }
420
    }
421
  }
78✔
422

423
  // Check for errors
424
  if (out_of_model) {
156✔
425
    throw std::runtime_error("Mesh not fully contained in geometry.");
12✔
426
  } else if (result.table_full()) {
144✔
NEW
427
    throw std::runtime_error("Maximum number of materials for mesh material "
×
NEW
428
                             "volume calculation insufficient.");
×
429
  }
430

431
  // Compute time for raytracing
432
  double t_raytrace = timer.elapsed();
144✔
433

434
#ifdef OPENMC_MPI
435
  // Combine results from multiple MPI processes
436
  if (mpi::n_procs > 1) {
60✔
437
    int total = this->n_bins() * table_size;
438
    if (mpi::master) {
439
      // Allocate temporary buffer for receiving data
440
      std::vector<int32_t> mats(total);
441
      std::vector<double> vols(total);
442

443
      for (int i = 1; i < mpi::n_procs; ++i) {
444
        // Receive material indices and volumes from process i
445
        MPI_Recv(
446
          mats.data(), total, MPI_INT, i, i, mpi::intracomm, MPI_STATUS_IGNORE);
447
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
448
          MPI_STATUS_IGNORE);
449

450
        // Combine with existing results; we can call thread unsafe version of
451
        // add_volume because each thread is operating on a different element
452
#pragma omp for
453
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
454
          for (int k = 0; k < table_size; ++k) {
455
            int index = index_elem * table_size + k;
456
            result.add_volume_unsafe(index_elem, mats[index], vols[index]);
457
          }
458
        }
459
      }
460
    } else {
461
      // Send material indices and volumes to process 0
462
      MPI_Send(materials, total, MPI_INT, 0, mpi::rank, mpi::intracomm);
463
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
464
    }
465
  }
466

467
  // Report time for MPI communication
468
  double t_mpi = timer.elapsed() - t_raytrace;
60✔
469
#else
470
  double t_mpi = 0.0;
84✔
471
#endif
472

473
  // Normalize based on known volumes of elements
474
  for (int i = 0; i < this->n_bins(); ++i) {
1,020✔
475
    // Estimated total volume in element i
476
    double volume = 0.0;
876✔
477
    for (int j = 0; j < table_size; ++j) {
7,884✔
478
      volume += result.volumes(i, j);
7,008✔
479
    }
480

481
    // Renormalize volumes based on known volume of element i
482
    double norm = this->volume(i) / volume;
876✔
483
    for (int j = 0; j < table_size; ++j) {
7,884✔
484
      result.volumes(i, j) *= norm;
7,008✔
485
    }
486
  }
487

488
  // Show elapsed time
489
  timer.stop();
144✔
490
  double t_total = timer.elapsed();
144✔
491
  double t_normalize = t_total - t_raytrace - t_mpi;
144✔
492
  if (mpi::master) {
144✔
493
    header("Timing Statistics", 7);
144✔
494
    show_time("Total time elapsed", t_total);
144✔
495
    show_time("Ray tracing", t_raytrace, 1);
144✔
496
    show_time("Ray tracing (per ray)", t_raytrace / n_total, 1);
144✔
497
    show_time("MPI communication", t_mpi, 1);
144✔
498
    show_time("Normalization", t_normalize, 1);
144✔
499
    std::fflush(stdout);
144✔
500
  }
501
}
144✔
502

503
void Mesh::to_hdf5(hid_t group) const
3,013✔
504
{
505
  // Create group for mesh
506
  std::string group_name = fmt::format("mesh {}", id_);
5,488✔
507
  hid_t mesh_group = create_group(group, group_name.c_str());
3,013✔
508

509
  // Write mesh type
510
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,013✔
511

512
  // Write mesh ID
513
  write_attribute(mesh_group, "id", id_);
3,013✔
514

515
  // Write mesh name
516
  write_dataset(mesh_group, "name", name_);
3,013✔
517

518
  // Write mesh data
519
  this->to_hdf5_inner(mesh_group);
3,013✔
520

521
  // Close group
522
  close_group(mesh_group);
3,013✔
523
}
3,013✔
524

525
//==============================================================================
526
// Structured Mesh implementation
527
//==============================================================================
528

529
std::string StructuredMesh::bin_label(int bin) const
5,439,708✔
530
{
531
  MeshIndex ijk = get_indices_from_bin(bin);
5,439,708✔
532

533
  if (n_dimension_ > 2) {
5,439,708✔
534
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,846,968✔
535
  } else if (n_dimension_ > 1) {
16,224✔
536
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
31,848✔
537
  } else {
538
    return fmt::format("Mesh Index ({})", ijk[0]);
600✔
539
  }
540
}
541

542
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,898✔
543
{
544
  // because method is const, shape_ is const as well and can't be adapted
545
  auto tmp_shape = shape_;
2,898✔
546
  return xt::adapt(tmp_shape, {n_dimension_});
5,796✔
547
}
548

549
Position StructuredMesh::sample_element(
1,542,372✔
550
  const MeshIndex& ijk, uint64_t* seed) const
551
{
552
  // lookup the lower/upper bounds for the mesh element
553
  double x_min = negative_grid_boundary(ijk, 0);
1,542,372✔
554
  double x_max = positive_grid_boundary(ijk, 0);
1,542,372✔
555

556
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,542,372✔
557
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,542,372✔
558

559
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,542,372✔
560
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,542,372✔
561

562
  return {x_min + (x_max - x_min) * prn(seed),
1,542,372✔
563
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,542,372✔
564
}
565

566
//==============================================================================
567
// Unstructured Mesh implementation
568
//==============================================================================
569

570
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
46✔
571
{
572
  // check the mesh type
573
  if (check_for_node(node, "type")) {
46✔
574
    auto temp = get_node_value(node, "type", true, true);
46✔
575
    if (temp != mesh_type) {
46✔
576
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
577
    }
578
  }
46✔
579

580
  // check if a length unit multiplier was specified
581
  if (check_for_node(node, "length_multiplier")) {
46✔
582
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
583
  }
584

585
  // get the filename of the unstructured mesh to load
586
  if (check_for_node(node, "filename")) {
46✔
587
    filename_ = get_node_value(node, "filename");
46✔
588
    if (!file_exists(filename_)) {
46✔
589
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
590
    }
591
  } else {
592
    fatal_error(fmt::format(
×
593
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
594
  }
595

596
  if (check_for_node(node, "options")) {
46✔
597
    options_ = get_node_value(node, "options");
16✔
598
  }
599

600
  // check if mesh tally data should be written with
601
  // statepoint files
602
  if (check_for_node(node, "output")) {
46✔
603
    output_ = get_node_value_bool(node, "output");
×
604
  }
605
}
46✔
606

607
void UnstructuredMesh::determine_bounds()
24✔
608
{
609
  double xmin = INFTY;
24✔
610
  double ymin = INFTY;
24✔
611
  double zmin = INFTY;
24✔
612
  double xmax = -INFTY;
24✔
613
  double ymax = -INFTY;
24✔
614
  double zmax = -INFTY;
24✔
615
  int n = this->n_vertices();
24✔
616
  for (int i = 0; i < n; ++i) {
55,936✔
617
    auto v = this->vertex(i);
55,912✔
618
    xmin = std::min(v.x, xmin);
55,912✔
619
    ymin = std::min(v.y, ymin);
55,912✔
620
    zmin = std::min(v.z, zmin);
55,912✔
621
    xmax = std::max(v.x, xmax);
55,912✔
622
    ymax = std::max(v.y, ymax);
55,912✔
623
    zmax = std::max(v.z, zmax);
55,912✔
624
  }
625
  lower_left_ = {xmin, ymin, zmin};
24✔
626
  upper_right_ = {xmax, ymax, zmax};
24✔
627
}
24✔
628

629
Position UnstructuredMesh::sample_tet(
601,230✔
630
  std::array<Position, 4> coords, uint64_t* seed) const
631
{
632
  // Uniform distribution
633
  double s = prn(seed);
601,230✔
634
  double t = prn(seed);
601,230✔
635
  double u = prn(seed);
601,230✔
636

637
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
638
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
639
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
640
  if (s + t > 1) {
601,230✔
641
    s = 1.0 - s;
301,245✔
642
    t = 1.0 - t;
301,245✔
643
  }
644
  if (s + t + u > 1) {
601,230✔
645
    if (t + u > 1) {
400,908✔
646
      double old_t = t;
199,920✔
647
      t = 1.0 - u;
199,920✔
648
      u = 1.0 - s - old_t;
199,920✔
649
    } else if (t + u <= 1) {
200,988✔
650
      double old_s = s;
200,988✔
651
      s = 1.0 - t - u;
200,988✔
652
      u = old_s + t + u - 1;
200,988✔
653
    }
654
  }
655
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
656
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
657
}
658

659
const std::string UnstructuredMesh::mesh_type = "unstructured";
660

661
std::string UnstructuredMesh::get_mesh_type() const
31✔
662
{
663
  return mesh_type;
31✔
664
}
665

666
void UnstructuredMesh::surface_bins_crossed(
×
667
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
668
{
669
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
670
}
671

672
std::string UnstructuredMesh::bin_label(int bin) const
205,712✔
673
{
674
  return fmt::format("Mesh Index ({})", bin);
205,712✔
675
};
676

677
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
31✔
678
{
679
  write_dataset(mesh_group, "filename", filename_);
31✔
680
  write_dataset(mesh_group, "library", this->library());
31✔
681
  if (!options_.empty()) {
31✔
682
    write_attribute(mesh_group, "options", options_);
8✔
683
  }
684

685
  if (length_multiplier_ > 0.0)
31✔
686
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
687

688
  // write vertex coordinates
689
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
31✔
690
  for (int i = 0; i < this->n_vertices(); i++) {
70,260✔
691
    auto v = this->vertex(i);
70,229✔
692
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
70,229✔
693
  }
694
  write_dataset(mesh_group, "vertices", vertices);
31✔
695

696
  int num_elem_skipped = 0;
31✔
697

698
  // write element types and connectivity
699
  vector<double> volumes;
31✔
700
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
31✔
701
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
31✔
702
  for (int i = 0; i < this->n_bins(); i++) {
349,743✔
703
    auto conn = this->connectivity(i);
349,712✔
704

705
    volumes.emplace_back(this->volume(i));
349,712✔
706

707
    // write linear tet element
708
    if (conn.size() == 4) {
349,712✔
709
      xt::view(elem_types, i, xt::all()) =
695,424✔
710
        static_cast<int>(ElementType::LINEAR_TET);
695,424✔
711
      xt::view(connectivity, i, xt::all()) =
695,424✔
712
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,043,136✔
713
      // write linear hex element
714
    } else if (conn.size() == 8) {
2,000✔
715
      xt::view(elem_types, i, xt::all()) =
4,000✔
716
        static_cast<int>(ElementType::LINEAR_HEX);
4,000✔
717
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000✔
718
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000✔
719
    } else {
720
      num_elem_skipped++;
×
721
      xt::view(elem_types, i, xt::all()) =
×
722
        static_cast<int>(ElementType::UNSUPPORTED);
723
      xt::view(connectivity, i, xt::all()) = -1;
×
724
    }
725
  }
349,712✔
726

727
  // warn users that some elements were skipped
728
  if (num_elem_skipped > 0) {
31✔
729
    warning(fmt::format("The connectivity of {} elements "
×
730
                        "on mesh {} were not written "
731
                        "because they are not of type linear tet/hex.",
732
      num_elem_skipped, this->id_));
×
733
  }
734

735
  write_dataset(mesh_group, "volumes", volumes);
31✔
736
  write_dataset(mesh_group, "connectivity", connectivity);
31✔
737
  write_dataset(mesh_group, "element_types", elem_types);
31✔
738
}
31✔
739

740
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
741
{
742
  length_multiplier_ = length_multiplier;
23✔
743
}
23✔
744

745
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
746
{
747
  auto conn = connectivity(bin);
120,000✔
748

749
  if (conn.size() == 4)
120,000✔
750
    return ElementType::LINEAR_TET;
120,000✔
751
  else if (conn.size() == 8)
×
752
    return ElementType::LINEAR_HEX;
×
753
  else
754
    return ElementType::UNSUPPORTED;
×
755
}
120,000✔
756

757
StructuredMesh::MeshIndex StructuredMesh::get_indices(
966,677,864✔
758
  Position r, bool& in_mesh) const
759
{
760
  MeshIndex ijk;
761
  in_mesh = true;
966,677,864✔
762
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
763
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
764

765
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
766
      in_mesh = false;
91,752,208✔
767
  }
768
  return ijk;
966,677,864✔
769
}
770

771
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,033,962,955✔
772
{
773
  switch (n_dimension_) {
1,033,962,955✔
774
  case 1:
956,736✔
775
    return ijk[0] - 1;
956,736✔
776
  case 2:
21,622,536✔
777
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
21,622,536✔
778
  case 3:
1,011,383,683✔
779
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,011,383,683✔
780
  default:
×
781
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
782
  }
783
}
784

785
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,137,176✔
786
{
787
  MeshIndex ijk;
788
  if (n_dimension_ == 1) {
8,137,176✔
789
    ijk[0] = bin + 1;
300✔
790
  } else if (n_dimension_ == 2) {
8,136,876✔
791
    ijk[0] = bin % shape_[0] + 1;
15,924✔
792
    ijk[1] = bin / shape_[0] + 1;
15,924✔
793
  } else if (n_dimension_ == 3) {
8,120,952✔
794
    ijk[0] = bin % shape_[0] + 1;
8,120,952✔
795
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,120,952✔
796
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,120,952✔
797
  }
798
  return ijk;
8,137,176✔
799
}
800

801
int StructuredMesh::get_bin(Position r) const
314,738,256✔
802
{
803
  // Determine indices
804
  bool in_mesh;
805
  MeshIndex ijk = get_indices(r, in_mesh);
314,738,256✔
806
  if (!in_mesh)
314,738,256✔
807
    return -1;
22,164,978✔
808

809
  // Convert indices to bin
810
  return get_bin_from_indices(ijk);
292,573,278✔
811
}
812

813
int StructuredMesh::n_bins() const
1,076,106✔
814
{
815
  return std::accumulate(
1,076,106✔
816
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,152,212✔
817
}
818

819
int StructuredMesh::n_surface_bins() const
548✔
820
{
821
  return 4 * n_dimension_ * n_bins();
548✔
822
}
823

824
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
825
  const SourceSite* bank, int64_t length, bool* outside) const
826
{
827
  // Determine shape of array for counts
828
  std::size_t m = this->n_bins();
×
829
  vector<std::size_t> shape = {m};
×
830

831
  // Create array of zeros
832
  xt::xarray<double> cnt {shape, 0.0};
×
833
  bool outside_ = false;
×
834

835
  for (int64_t i = 0; i < length; i++) {
×
836
    const auto& site = bank[i];
×
837

838
    // determine scoring bin for entropy mesh
839
    int mesh_bin = get_bin(site.r);
×
840

841
    // if outside mesh, skip particle
842
    if (mesh_bin < 0) {
×
843
      outside_ = true;
×
844
      continue;
×
845
    }
846

847
    // Add to appropriate bin
848
    cnt(mesh_bin) += site.wgt;
×
849
  }
850

851
  // Create copy of count data. Since ownership will be acquired by xtensor,
852
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
853
  // warnings.
854
  int total = cnt.size();
×
855
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
856

857
#ifdef OPENMC_MPI
858
  // collect values from all processors
859
  MPI_Reduce(
860
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
861

862
  // Check if there were sites outside the mesh for any processor
863
  if (outside) {
864
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
865
  }
866
#else
867
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
868
  if (outside)
869
    *outside = outside_;
870
#endif
871

872
  // Adapt reduced values in array back into an xarray
873
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
874
  xt::xarray<double> counts = arr;
×
875

876
  return counts;
×
877
}
878

879
// raytrace through the mesh. The template class T will do the tallying.
880
// A modern optimizing compiler can recognize the noop method of T and
881
// eliminate that call entirely.
882
template<class T>
883
void StructuredMesh::raytrace_mesh(
656,203,037✔
884
  Position r0, Position r1, const Direction& u, T tally) const
885
{
886
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
887
  // enable/disable tally calls for now, T template type needs to provide both
888
  // surface and track methods, which might be empty. modern optimizing
889
  // compilers will (hopefully) eliminate the complete code (including
890
  // calculation of parameters) but for the future: be explicit
891

892
  // Compute the length of the entire track.
893
  double total_distance = (r1 - r0).norm();
656,203,037✔
894
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
656,203,037✔
895
    return;
9,895,473✔
896

897
  const int n = n_dimension_;
646,307,564✔
898

899
  // Flag if position is inside the mesh
900
  bool in_mesh;
901

902
  // Position is r = r0 + u * traveled_distance, start at r0
903
  double traveled_distance {0.0};
646,307,564✔
904

905
  // Calculate index of current cell. Offset the position a tiny bit in
906
  // direction of flight
907
  MeshIndex ijk = get_indices(r0 + TINY_BIT * u, in_mesh);
646,307,564✔
908

909
  // if track is very short, assume that it is completely inside one cell.
910
  // Only the current cell will score and no surfaces
911
  if (total_distance < 2 * TINY_BIT) {
646,307,564✔
912
    if (in_mesh) {
41,484✔
913
      tally.track(ijk, 1.0);
41,472✔
914
    }
915
    return;
41,484✔
916
  }
917

918
  // translate start and end positions,
919
  // this needs to come after the get_indices call because it does its own
920
  // translation
921
  local_coords(r0);
646,266,080✔
922
  local_coords(r1);
646,266,080✔
923

924
  // Calculate initial distances to next surfaces in all three dimensions
925
  std::array<MeshDistance, 3> distances;
1,292,532,160✔
926
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
927
    distances[k] = distance_to_grid_boundary(ijk, k, r0, u, 0.0);
1,920,766,200✔
928
  }
929

930
  // Loop until r = r1 is eventually reached
931
  while (true) {
351,051,615✔
932

933
    if (in_mesh) {
997,317,695✔
934

935
      // find surface with minimal distance to current position
936
      const auto k = std::min_element(distances.begin(), distances.end()) -
906,753,295✔
937
                     distances.begin();
906,753,295✔
938

939
      // Tally track length delta since last step
940
      tally.track(ijk,
906,753,295✔
941
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
906,753,295✔
942
          total_distance);
943

944
      // update position and leave, if we have reached end position
945
      traveled_distance = distances[k].distance;
906,753,295✔
946
      if (traveled_distance >= total_distance)
906,753,295✔
947
        return;
561,333,724✔
948

949
      // If we have not reached r1, we have hit a surface. Tally outward
950
      // current
951
      tally.surface(ijk, k, distances[k].max_surface, false);
345,419,571✔
952

953
      // Update cell and calculate distance to next surface in k-direction.
954
      // The two other directions are still valid!
955
      ijk[k] = distances[k].next_index;
345,419,571✔
956
      distances[k] =
345,419,571✔
957
        distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
345,419,571✔
958

959
      // Check if we have left the interior of the mesh
960
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
345,419,571✔
961

962
      // If we are still inside the mesh, tally inward current for the next
963
      // cell
964
      if (in_mesh)
345,419,571✔
965
        tally.surface(ijk, k, !distances[k].max_surface, true);
322,291,237✔
966

967
    } else { // not inside mesh
968

969
      // For all directions outside the mesh, find the distance that we need
970
      // to travel to reach the next surface. Use the largest distance, as
971
      // only this will cross all outer surfaces.
972
      int k_max {0};
90,564,400✔
973
      for (int k = 0; k < n; ++k) {
359,916,214✔
974
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
361,258,788✔
975
            (distances[k].distance > traveled_distance)) {
91,906,974✔
976
          traveled_distance = distances[k].distance;
91,121,214✔
977
          k_max = k;
91,121,214✔
978
        }
979
      }
980

981
      // If r1 is not inside the mesh, exit here
982
      if (traveled_distance >= total_distance)
90,564,400✔
983
        return;
84,932,356✔
984

985
      // Calculate the new cell index and update all distances to next
986
      // surfaces.
987
      ijk = get_indices(r0 + (traveled_distance + TINY_BIT) * u, in_mesh);
5,632,044✔
988
      for (int k = 0; k < n; ++k) {
22,298,916✔
989
        distances[k] =
16,666,872✔
990
          distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
16,666,872✔
991
      }
992

993
      // If inside the mesh, Tally inward current
994
      if (in_mesh)
5,632,044✔
995
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
4,254,984✔
996
    }
997
  }
998
}
999

220,970,564✔
1000
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1001
  vector<int>& bins, vector<double>& lengths) const
1002
{
1003

1004
  // Helper tally class.
1005
  // stores a pointer to the mesh class and references to bins and lengths
1006
  // parameters. Performs the actual tally through the track method.
1007
  struct TrackAggregator {
1008
    TrackAggregator(
1009
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
220,970,564✔
1010
      : mesh(_mesh), bins(_bins), lengths(_lengths)
220,970,564✔
1011
    {}
×
1012
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1013
    void track(const MeshIndex& ijk, double l) const
220,970,564✔
1014
    {
1015
      bins.push_back(mesh->get_bin_from_indices(ijk));
1016
      lengths.push_back(l);
1017
    }
1018

1019
    const StructuredMesh* mesh;
220,970,564✔
1020
    vector<int>& bins;
1021
    vector<double>& lengths;
1022
  };
1023

220,970,564✔
1024
  // Perform the mesh raytrace with the helper class.
1025
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1026
}
1027

220,970,564✔
1028
void StructuredMesh::surface_bins_crossed(
×
1029
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
×
1030
{
1031

×
1032
  // Helper tally class.
1033
  // stores a pointer to the mesh class and a reference to the bins parameter.
1034
  // Performs the actual tally through the surface method.
1035
  struct SurfaceAggregator {
1036
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
1037
      : mesh(_mesh), bins(_bins)
220,970,564✔
1038
    {}
220,970,564✔
1039
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
1040
    {
1041
      int i_bin =
441,941,128✔
1042
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
882,046,112✔
1043
      if (max)
661,075,548✔
1044
        i_bin += 2;
1045
      if (inward)
1046
        i_bin += 1;
1047
      bins.push_back(i_bin);
55,084,766✔
1048
    }
1049
    void track(const MeshIndex& idx, double l) const {}
276,055,330✔
1050

1051
    const StructuredMesh* mesh;
1052
    vector<int>& bins;
273,235,340✔
1053
  };
273,235,340✔
1054

1055
  // Perform the mesh raytrace with the helper class.
1056
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
273,235,340✔
1057
}
273,235,340✔
1058

1059
//==============================================================================
1060
// RegularMesh implementation
1061
//==============================================================================
273,235,340✔
1062

273,235,340✔
1063
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
218,394,162✔
1064
{
1065
  // Determine number of dimensions for mesh
1066
  if (!check_for_node(node, "dimension")) {
1067
    fatal_error("Must specify <dimension> on a regular mesh.");
54,841,178✔
1068
  }
1069

1070
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
1071
  int n = n_dimension_ = shape.size();
54,841,178✔
1072
  if (n != 1 && n != 2 && n != 3) {
54,841,178✔
1073
    fatal_error("Mesh must be one, two, or three dimensions.");
54,841,178✔
1074
  }
1075
  std::copy(shape.begin(), shape.end(), shape_.begin());
1076

54,841,178✔
1077
  // Check that dimensions are all greater than zero
1078
  if (xt::any(shape <= 0)) {
1079
    fatal_error("All entries on the <dimension> element for a tally "
1080
                "mesh must be positive.");
54,841,178✔
1081
  }
52,770,480✔
1082

1083
  // Check for lower-left coordinates
1084
  if (check_for_node(node, "lower_left")) {
1085
    // Read mesh lower-left corner location
1086
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1087
  } else {
1088
    fatal_error("Must specify <lower_left> on a mesh.");
2,819,990✔
1089
  }
10,928,660✔
1090

11,085,212✔
1091
  // Make sure lower_left and dimension match
2,976,542✔
1092
  if (shape.size() != lower_left_.size()) {
2,912,078✔
1093
    fatal_error("Number of entries on <lower_left> must be the same "
2,912,078✔
1094
                "as the number of entries on <dimension>.");
1095
  }
1096

1097
  if (check_for_node(node, "width")) {
1098
    // Make sure one of upper-right or width were specified
2,819,990✔
1099
    if (check_for_node(node, "upper_right")) {
2,576,402✔
1100
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
1101
    }
1102

1103
    width_ = get_node_xarray<double>(node, "width");
243,588✔
1104

860,256✔
1105
    // Check to ensure width has same dimensions
616,668✔
1106
    auto n = width_.size();
616,668✔
1107
    if (n != lower_left_.size()) {
1108
      fatal_error("Number of entries on <width> must be the same as "
1109
                  "the number of entries on <lower_left>.");
1110
    }
243,588✔
1111

218,592✔
1112
    // Check for negative widths
1113
    if (xt::any(width_ < 0.0)) {
1114
      fatal_error("Cannot have a negative <width> on a tally mesh.");
1115
    }
435,232,473✔
1116

1117
    // Set width and upper right coordinate
1118
    upper_right_ = xt::eval(lower_left_ + shape * width_);
1119

1120
  } else if (check_for_node(node, "upper_right")) {
1121
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1122

1123
    // Check to ensure width has same dimensions
1124
    auto n = upper_right_.size();
1125
    if (n != lower_left_.size()) {
435,232,473✔
1126
      fatal_error("Number of entries on <upper_right> must be the "
435,232,473✔
1127
                  "same as the number of entries on <lower_left>.");
9,895,473✔
1128
    }
1129

425,337,000✔
1130
    // Check that upper-right is above lower-left
1131
    if (xt::any(upper_right_ < lower_left_)) {
1132
      fatal_error("The <upper_right> coordinates must be greater than "
1133
                  "the <lower_left> coordinates on a tally mesh.");
1134
    }
1135

425,337,000✔
1136
    // Set width
1137
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1138
  } else {
1139
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
425,337,000✔
1140
  }
1141

1142
  // Set material volumes
1143
  volume_frac_ = 1.0 / xt::prod(shape)();
425,337,000✔
1144

41,484✔
1145
  element_volume_ = 1.0;
41,472✔
1146
  for (int i = 0; i < n_dimension_; i++) {
1147
    element_volume_ *= width_[i];
41,484✔
1148
  }
1149
}
1150

1151
int RegularMesh::get_index_in_direction(double r, int i) const
1152
{
1153
  return std::ceil((r - lower_left_[i]) / width_[i]);
425,295,516✔
1154
}
425,295,516✔
1155

1156
const std::string RegularMesh::mesh_type = "regular";
1157

850,591,032✔
1158
std::string RegularMesh::get_mesh_type() const
1,684,986,168✔
1159
{
1,259,690,652✔
1160
  return mesh_type;
1161
}
1162

1163
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
295,966,849✔
1164
{
1165
  return lower_left_[i] + ijk[i] * width_[i];
721,262,365✔
1166
}
1167

1168
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
633,517,955✔
1169
{
633,517,955✔
1170
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1171
}
1172

633,517,955✔
1173
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
633,517,955✔
1174
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1175
  double l) const
1176
{
1177
  MeshDistance d;
633,517,955✔
1178
  d.next_index = ijk[i];
633,517,955✔
1179
  if (std::abs(u[i]) < FP_PRECISION)
342,939,562✔
1180
    return d;
1181

1182
  d.max_surface = (u[i] > 0);
1183
  if (d.max_surface && (ijk[i] <= shape_[i])) {
290,578,393✔
1184
    d.next_index++;
1185
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1186
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1187
    d.next_index--;
290,578,393✔
1188
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
290,578,393✔
1189
  }
290,578,393✔
1190
  return d;
1191
}
1192

290,578,393✔
1193
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1194
  Position plot_ll, Position plot_ur) const
1195
{
1196
  // Figure out which axes lie in the plane of the plot.
290,578,393✔
1197
  array<int, 2> axes {-1, -1};
269,520,757✔
1198
  if (plot_ur.z == plot_ll.z) {
1199
    axes[0] = 0;
1200
    if (n_dimension_ > 1)
1201
      axes[1] = 1;
1202
  } else if (plot_ur.y == plot_ll.y) {
1203
    axes[0] = 0;
1204
    if (n_dimension_ > 2)
87,744,410✔
1205
      axes[1] = 2;
348,987,554✔
1206
  } else if (plot_ur.x == plot_ll.x) {
350,173,576✔
1207
    if (n_dimension_ > 1)
88,930,432✔
1208
      axes[0] = 1;
88,209,136✔
1209
    if (n_dimension_ > 2)
88,209,136✔
1210
      axes[1] = 2;
1211
  } else {
1212
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1213
  }
1214

87,744,410✔
1215
  // Get the coordinates of the mesh lines along both of the axes.
82,355,954✔
1216
  array<vector<double>, 2> axis_lines;
1217
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1218
    int axis = axes[i_ax];
1219
    if (axis == -1)
5,388,456✔
1220
      continue;
21,438,660✔
1221
    auto& lines {axis_lines[i_ax]};
16,050,204✔
1222

16,050,204✔
1223
    double coord = lower_left_[axis];
1224
    for (int i = 0; i < shape_[axis] + 1; ++i) {
1225
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1226
        lines.push_back(coord);
5,388,456✔
1227
      coord += width_[axis];
4,036,392✔
1228
    }
1229
  }
1230

1231
  return {axis_lines[0], axis_lines[1]};
1232
}
435,232,473✔
1233

1234
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1235
{
1236
  write_dataset(mesh_group, "dimension", get_x_shape());
1237
  write_dataset(mesh_group, "lower_left", lower_left_);
1238
  write_dataset(mesh_group, "upper_right", upper_right_);
1239
  write_dataset(mesh_group, "width", width_);
1240
}
435,232,473✔
1241

1242
xt::xtensor<double, 1> RegularMesh::count_sites(
435,232,473✔
1243
  const SourceSite* bank, int64_t length, bool* outside) const
435,232,473✔
1244
{
564,135,542✔
1245
  // Determine shape of array for counts
633,559,427✔
1246
  std::size_t m = this->n_bins();
1247
  vector<std::size_t> shape = {m};
633,559,427✔
1248

633,559,427✔
1249
  // Create array of zeros
633,559,427✔
1250
  xt::xarray<double> cnt {shape, 0.0};
1251
  bool outside_ = false;
1252

1253
  for (int64_t i = 0; i < length; i++) {
1254
    const auto& site = bank[i];
1255

1256
    // determine scoring bin for entropy mesh
1257
    int mesh_bin = get_bin(site.r);
435,232,473✔
1258

435,232,473✔
1259
    // if outside mesh, skip particle
1260
    if (mesh_bin < 0) {
220,970,564✔
1261
      outside_ = true;
1262
      continue;
1263
    }
1264

1265
    // Add to appropriate bin
1266
    cnt(mesh_bin) += site.wgt;
1267
  }
1268

220,970,564✔
1269
  // Create copy of count data. Since ownership will be acquired by xtensor,
220,970,564✔
1270
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
220,970,564✔
1271
  // warnings.
107,830,250✔
1272
  int total = cnt.size();
1273
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
1274

107,830,250✔
1275
#ifdef OPENMC_MPI
107,830,250✔
1276
  // collect values from all processors
53,872,008✔
1277
  MPI_Reduce(
107,830,250✔
1278
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
52,989,072✔
1279

107,830,250✔
1280
  // Check if there were sites outside the mesh for any processor
107,830,250✔
1281
  if (outside) {
273,235,340✔
1282
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1283
  }
1284
#else
1285
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1286
  if (outside)
1287
    *outside = outside_;
1288
#endif
220,970,564✔
1289

220,970,564✔
1290
  // Adapt reduced values in array back into an xarray
1291
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
1292
  xt::xarray<double> counts = arr;
1293

1294
  return counts;
1295
}
1,928✔
1296

1297
double RegularMesh::volume(const MeshIndex& ijk) const
1298
{
1,928✔
1299
  return element_volume_;
×
1300
}
1301

1302
//==============================================================================
1,928✔
1303
// RectilinearMesh implementation
1,928✔
1304
//==============================================================================
1,928✔
1305

×
1306
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
1307
{
1,928✔
1308
  n_dimension_ = 3;
1309

1310
  grid_[0] = get_node_array<double>(node, "x_grid");
1,928✔
UNCOV
1311
  grid_[1] = get_node_array<double>(node, "y_grid");
×
1312
  grid_[2] = get_node_array<double>(node, "z_grid");
1313

1314
  if (int err = set_grid()) {
1315
    fatal_error(openmc_err_msg);
1316
  }
1,928✔
1317
}
1318

1,928✔
1319
const std::string RectilinearMesh::mesh_type = "rectilinear";
UNCOV
1320

×
1321
std::string RectilinearMesh::get_mesh_type() const
1322
{
1323
  return mesh_type;
1324
}
1,928✔
UNCOV
1325

×
1326
double RectilinearMesh::positive_grid_boundary(
1327
  const MeshIndex& ijk, int i) const
1328
{
1329
  return grid_[i][ijk[i]];
1,928✔
1330
}
1331

51✔
UNCOV
1332
double RectilinearMesh::negative_grid_boundary(
×
1333
  const MeshIndex& ijk, int i) const
1334
{
1335
  return grid_[i][ijk[i] - 1];
51✔
1336
}
1337

1338
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
51✔
1339
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
51✔
1340
  double l) const
×
1341
{
1342
  MeshDistance d;
1343
  d.next_index = ijk[i];
1344
  if (std::abs(u[i]) < FP_PRECISION)
1345
    return d;
51✔
UNCOV
1346

×
1347
  d.max_surface = (u[i] > 0);
1348
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1349
    d.next_index++;
1350
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
51✔
1351
  } else if (!d.max_surface && (ijk[i] > 0)) {
1352
    d.next_index--;
1,877✔
1353
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,877✔
1354
  }
1355
  return d;
1356
}
1,877✔
1357

1,877✔
1358
int RectilinearMesh::set_grid()
×
1359
{
1360
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1361
    static_cast<int>(grid_[1].size()) - 1,
1362
    static_cast<int>(grid_[2].size()) - 1};
1363

1,877✔
UNCOV
1364
  for (const auto& g : grid_) {
×
1365
    if (g.size() < 2) {
1366
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
1367
                 "must each have at least 2 points");
1368
      return OPENMC_E_INVALID_ARGUMENT;
1369
    }
1,877✔
1370
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
UNCOV
1371
        g.end()) {
×
1372
      set_errmsg("Values in for x-, y-, and z- grids for "
1373
                 "rectilinear meshes must be sorted and unique.");
1374
      return OPENMC_E_INVALID_ARGUMENT;
1375
    }
1,928✔
1376
  }
1377

1,928✔
1378
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
7,428✔
1379
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
5,500✔
1380

1381
  return 0;
1,928✔
1382
}
1383

2,147,483,647✔
1384
int RectilinearMesh::get_index_in_direction(double r, int i) const
1385
{
2,147,483,647✔
1386
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1387
}
1388

1389
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
1390
  Position plot_ll, Position plot_ur) const
3,776✔
1391
{
1392
  // Figure out which axes lie in the plane of the plot.
3,776✔
1393
  array<int, 2> axes {-1, -1};
1394
  if (plot_ur.z == plot_ll.z) {
1395
    axes = {0, 1};
863,074,029✔
1396
  } else if (plot_ur.y == plot_ll.y) {
1397
    axes = {0, 2};
863,074,029✔
1398
  } else if (plot_ur.x == plot_ll.x) {
1399
    axes = {1, 2};
1400
  } else {
794,468,020✔
1401
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1402
  }
794,468,020✔
1403

1404
  // Get the coordinates of the mesh lines along both of the axes.
1405
  array<vector<double>, 2> axis_lines;
1,671,340,743✔
1406
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1407
    int axis = axes[i_ax];
1408
    vector<double>& lines {axis_lines[i_ax]};
1409

1,671,340,743✔
1410
    for (auto coord : grid_[axis]) {
1,671,340,743✔
1411
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1,671,340,743✔
1412
        lines.push_back(coord);
1,314,072✔
1413
    }
1414
  }
1,670,026,671✔
1415

1,670,026,671✔
1416
  return {axis_lines[0], axis_lines[1]};
858,446,913✔
1417
}
858,446,913✔
1418

811,579,758✔
1419
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
789,840,904✔
1420
{
789,840,904✔
1421
  write_dataset(mesh_group, "x_grid", grid_[0]);
1422
  write_dataset(mesh_group, "y_grid", grid_[1]);
1,670,026,671✔
1423
  write_dataset(mesh_group, "z_grid", grid_[2]);
1424
}
1425

24✔
1426
double RectilinearMesh::volume(const MeshIndex& ijk) const
1427
{
1428
  double vol {1.0};
1429

24✔
1430
  for (int i = 0; i < n_dimension_; i++) {
24✔
1431
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
24✔
1432
  }
24✔
1433
  return vol;
24✔
1434
}
×
1435

×
1436
//==============================================================================
×
UNCOV
1437
// CylindricalMesh implementation
×
1438
//==============================================================================
×
UNCOV
1439

×
UNCOV
1440
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
×
UNCOV
1441
  : PeriodicStructuredMesh {node}
×
UNCOV
1442
{
×
1443
  n_dimension_ = 3;
UNCOV
1444
  grid_[0] = get_node_array<double>(node, "r_grid");
×
1445
  grid_[1] = get_node_array<double>(node, "phi_grid");
1446
  grid_[2] = get_node_array<double>(node, "z_grid");
1447
  origin_ = get_node_position(node, "origin");
1448

24✔
1449
  if (int err = set_grid()) {
72✔
1450
    fatal_error(openmc_err_msg);
48✔
1451
  }
48✔
UNCOV
1452
}
×
1453

48✔
1454
const std::string CylindricalMesh::mesh_type = "cylindrical";
1455

48✔
1456
std::string CylindricalMesh::get_mesh_type() const
312✔
1457
{
264✔
1458
  return mesh_type;
264✔
1459
}
264✔
1460

1461
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
1462
  Position r, bool& in_mesh) const
1463
{
48✔
1464
  local_coords(r);
24✔
1465

1466
  Position mapped_r;
2,158✔
1467
  mapped_r[0] = std::hypot(r.x, r.y);
1468
  mapped_r[2] = r[2];
2,158✔
1469

2,158✔
1470
  if (mapped_r[0] < FP_PRECISION) {
2,158✔
1471
    mapped_r[1] = 0.0;
2,158✔
1472
  } else {
2,158✔
1473
    mapped_r[1] = std::atan2(r.y, r.x);
1474
    if (mapped_r[1] < 0)
11,393✔
1475
      mapped_r[1] += 2 * M_PI;
1476
  }
1477

1478
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
11,393✔
1479

11,393✔
1480
  idx[1] = sanitize_phi(idx[1]);
1481

1482
  return idx;
11,393✔
1483
}
11,393✔
1484

1485
Position CylindricalMesh::sample_element(
11,181,219✔
1486
  const MeshIndex& ijk, uint64_t* seed) const
11,169,826✔
1487
{
1488
  double r_min = this->r(ijk[0] - 1);
1489
  double r_max = this->r(ijk[0]);
11,169,826✔
1490

1491
  double phi_min = this->phi(ijk[1] - 1);
1492
  double phi_max = this->phi(ijk[1]);
11,169,826✔
UNCOV
1493

×
UNCOV
1494
  double z_min = this->z(ijk[2] - 1);
×
1495
  double z_max = this->z(ijk[2]);
1496

1497
  double r_min_sq = r_min * r_min;
1498
  double r_max_sq = r_max * r_max;
11,169,826✔
1499
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
1500
  double phi = uniform_distribution(phi_min, phi_max, seed);
1501
  double z = uniform_distribution(z_min, z_max, seed);
1502

1503
  double x = r * std::cos(phi);
1504
  double y = r * std::sin(phi);
11,393✔
1505

11,393✔
1506
  return origin_ + Position(x, y, z);
1507
}
1508

1509
double CylindricalMesh::find_r_crossing(
6,465✔
1510
  const Position& r, const Direction& u, double l, int shell) const
6,465✔
1511
{
1512

1513
  if ((shell < 0) || (shell > shape_[0]))
6,465✔
1514
    return INFTY;
6,465✔
1515

1516
  // solve r.x^2 + r.y^2 == r0^2
1517
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
4,928✔
1518
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
4,928✔
1519

4,928✔
1520
  const double r0 = grid_[0][shell];
1521
  if (r0 == 0.0)
1522
    return INFTY;
1523

11,393✔
1524
  const double denominator = u.x * u.x + u.y * u.y;
11,393✔
1525

1526
  // Direction of flight is in z-direction. Will never intersect r.
22,786✔
1527
  if (std::abs(denominator) < FP_PRECISION)
11,393✔
1528
    return INFTY;
1529

1,058,040✔
1530
  // inverse of dominator to help the compiler to speed things up
1531
  const double inv_denominator = 1.0 / denominator;
1,058,040✔
1532

1533
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
1534
  double c = r.x * r.x + r.y * r.y - r0 * r0;
1535
  double D = p * p - c * inv_denominator;
1536

1537
  if (D < 0.0)
1538
    return INFTY;
111✔
1539

1540
  D = std::sqrt(D);
111✔
1541

1542
  // the solution -p - D is always smaller as -p + D : Check this one first
111✔
1543
  if (std::abs(c) <= RADIAL_MESH_TOL)
111✔
1544
    return INFTY;
111✔
1545

1546
  if (-p - D > l)
111✔
UNCOV
1547
    return -p - D;
×
1548
  if (-p + D > l)
1549
    return -p + D;
111✔
1550

1551
  return INFTY;
1552
}
1553

316✔
1554
double CylindricalMesh::find_phi_crossing(
1555
  const Position& r, const Direction& u, double l, int shell) const
316✔
1556
{
1557
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1558
  if (full_phi_ && (shape_[1] == 1))
49,665,496✔
1559
    return INFTY;
1560

1561
  shell = sanitize_phi(shell);
49,665,496✔
1562

1563
  const double p0 = grid_[1][shell];
1564

48,826,538✔
1565
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1566
  // => x(s) * cos(p0) = y(s) * sin(p0)
1567
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
48,826,538✔
1568
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1569

1570
  const double c0 = std::cos(p0);
100,099,584✔
1571
  const double s0 = std::sin(p0);
1572

1573
  const double denominator = (u.x * s0 - u.y * c0);
1574

100,099,584✔
1575
  // Check if direction of flight is not parallel to phi surface
100,099,584✔
1576
  if (std::abs(denominator) > FP_PRECISION) {
100,099,584✔
1577
    const double s = -(r.x * s0 - r.y * c0) / denominator;
623,808✔
1578
    // Check if solution is in positive direction of flight and crosses the
1579
    // correct phi surface (not -phi)
99,475,776✔
1580
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
99,475,776✔
1581
      return s;
49,665,496✔
1582
  }
49,665,496✔
1583

49,810,280✔
1584
  return INFTY;
48,826,538✔
1585
}
48,826,538✔
1586

1587
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
99,475,776✔
1588
  const Position& r, const Direction& u, double l, int shell) const
1589
{
1590
  MeshDistance d;
179✔
1591
  d.next_index = shell;
1592

179✔
1593
  // Direction of flight is within xy-plane. Will never intersect z.
179✔
1594
  if (std::abs(u.z) < FP_PRECISION)
179✔
1595
    return d;
1596

716✔
1597
  d.max_surface = (u.z > 0.0);
537✔
1598
  if (d.max_surface && (shell <= shape_[2])) {
×
1599
    d.next_index += 1;
1600
    d.distance = (grid_[2][shell] - r.z) / u.z;
×
1601
  } else if (!d.max_surface && (shell > 0)) {
1602
    d.next_index -= 1;
537✔
1603
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
1,074✔
UNCOV
1604
  }
×
1605
  return d;
UNCOV
1606
}
×
1607

1608
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
1609
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1610
  double l) const
179✔
1611
{
179✔
1612
  Position r = r0 - origin_;
1613

179✔
1614
  if (i == 0) {
1615

1616
    return std::min(
142,697,256✔
1617
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r, u, l, ijk[i])),
1618
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r, u, l, ijk[i] - 1)));
142,697,256✔
1619

1620
  } else if (i == 1) {
1621

12✔
1622
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
1623
                      find_phi_crossing(r, u, l, ijk[i])),
1624
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
1625
        find_phi_crossing(r, u, l, ijk[i] - 1)));
12✔
1626

12✔
1627
  } else {
×
1628
    return find_z_crossing(r, u, l, ijk[i]);
12✔
1629
  }
12✔
UNCOV
1630
}
×
UNCOV
1631

×
1632
int CylindricalMesh::set_grid()
UNCOV
1633
{
×
1634
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1635
    static_cast<int>(grid_[1].size()) - 1,
1636
    static_cast<int>(grid_[2].size()) - 1};
1637

12✔
1638
  for (const auto& g : grid_) {
36✔
1639
    if (g.size() < 2) {
24✔
1640
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
24✔
1641
                 "must each have at least 2 points");
1642
      return OPENMC_E_INVALID_ARGUMENT;
120✔
1643
    }
96✔
1644
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
96✔
1645
        g.end()) {
1646
      set_errmsg("Values in for r-, phi-, and z- grids for "
1647
                 "cylindrical meshes must be sorted and unique.");
1648
      return OPENMC_E_INVALID_ARGUMENT;
24✔
1649
    }
12✔
1650
  }
1651
  if (grid_[0].front() < 0.0) {
116✔
1652
    set_errmsg("r-grid for "
1653
               "cylindrical meshes must start at r >= 0.");
116✔
1654
    return OPENMC_E_INVALID_ARGUMENT;
116✔
1655
  }
116✔
1656
  if (grid_[1].front() < 0.0) {
116✔
1657
    set_errmsg("phi-grid for "
1658
               "cylindrical meshes must start at phi >= 0.");
144✔
1659
    return OPENMC_E_INVALID_ARGUMENT;
1660
  }
144✔
1661
  if (grid_[1].back() > 2.0 * PI) {
1662
    set_errmsg("phi-grids for "
576✔
1663
               "cylindrical meshes must end with theta <= 2*pi.");
432✔
1664

1665
    return OPENMC_E_INVALID_ARGUMENT;
144✔
1666
  }
1667

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

1670
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
1671
    origin_[2] + grid_[2].front()};
1672
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
413✔
1673
    origin_[2] + grid_[2].back()};
413✔
1674

1675
  return 0;
413✔
1676
}
413✔
1677

413✔
1678
int CylindricalMesh::get_index_in_direction(double r, int i) const
413✔
1679
{
413✔
1680
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1681
}
413✔
UNCOV
1682

×
1683
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
1684
  Position plot_ll, Position plot_ur) const
413✔
1685
{
1686
  fatal_error("Plot of cylindrical Mesh not implemented");
1687

1688
  // Figure out which axes lie in the plane of the plot.
516✔
1689
  array<vector<double>, 2> axis_lines;
1690
  return {axis_lines[0], axis_lines[1]};
516✔
1691
}
1692

1693
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
50,568,432✔
1694
{
1695
  write_dataset(mesh_group, "r_grid", grid_[0]);
1696
  write_dataset(mesh_group, "phi_grid", grid_[1]);
50,568,432✔
1697
  write_dataset(mesh_group, "z_grid", grid_[2]);
1698
  write_dataset(mesh_group, "origin", origin_);
50,568,432✔
1699
}
50,568,432✔
1700

50,568,432✔
1701
double CylindricalMesh::volume(const MeshIndex& ijk) const
1702
{
50,568,432✔
UNCOV
1703
  double r_i = grid_[0][ijk[0] - 1];
×
1704
  double r_o = grid_[0][ijk[0]];
1705

50,568,432✔
1706
  double phi_i = grid_[1][ijk[1] - 1];
50,568,432✔
1707
  double phi_o = grid_[1][ijk[1]];
25,300,356✔
1708

1709
  double z_i = grid_[2][ijk[2] - 1];
1710
  double z_o = grid_[2][ijk[2]];
50,568,432✔
1711

1712
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
50,568,432✔
1713
}
1714

50,568,432✔
1715
//==============================================================================
1716
// SphericalMesh implementation
1717
//==============================================================================
96,000✔
1718

1719
SphericalMesh::SphericalMesh(pugi::xml_node node)
1720
  : PeriodicStructuredMesh {node}
96,000✔
1721
{
96,000✔
1722
  n_dimension_ = 3;
1723

96,000✔
1724
  grid_[0] = get_node_array<double>(node, "r_grid");
96,000✔
1725
  grid_[1] = get_node_array<double>(node, "theta_grid");
1726
  grid_[2] = get_node_array<double>(node, "phi_grid");
96,000✔
1727
  origin_ = get_node_position(node, "origin");
96,000✔
1728

1729
  if (int err = set_grid()) {
96,000✔
1730
    fatal_error(openmc_err_msg);
96,000✔
1731
  }
96,000✔
1732
}
96,000✔
1733

96,000✔
1734
const std::string SphericalMesh::mesh_type = "spherical";
1735

96,000✔
1736
std::string SphericalMesh::get_mesh_type() const
96,000✔
1737
{
1738
  return mesh_type;
96,000✔
1739
}
1740

1741
StructuredMesh::MeshIndex SphericalMesh::get_indices(
148,757,592✔
1742
  Position r, bool& in_mesh) const
1743
{
1744
  local_coords(r);
1745

148,757,592✔
1746
  Position mapped_r;
18,260,184✔
1747
  mapped_r[0] = r.norm();
1748

1749
  if (mapped_r[0] < FP_PRECISION) {
1750
    mapped_r[1] = 0.0;
1751
    mapped_r[2] = 0.0;
1752
  } else {
130,497,408✔
1753
    mapped_r[1] = std::acos(r.z / mapped_r.x);
130,497,408✔
1754
    mapped_r[2] = std::atan2(r.y, r.x);
7,273,620✔
1755
    if (mapped_r[2] < 0)
1756
      mapped_r[2] += 2 * M_PI;
123,223,788✔
1757
  }
1758

1759
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
123,223,788✔
1760

64,320✔
1761
  idx[1] = sanitize_theta(idx[1]);
1762
  idx[2] = sanitize_phi(idx[2]);
1763

123,159,468✔
1764
  return idx;
1765
}
123,159,468✔
1766

123,159,468✔
1767
Position SphericalMesh::sample_element(
123,159,468✔
1768
  const MeshIndex& ijk, uint64_t* seed) const
1769
{
123,159,468✔
1770
  double r_min = this->r(ijk[0] - 1);
17,009,892✔
1771
  double r_max = this->r(ijk[0]);
1772

106,149,576✔
1773
  double theta_min = this->theta(ijk[1] - 1);
1774
  double theta_max = this->theta(ijk[1]);
1775

106,149,576✔
1776
  double phi_min = this->phi(ijk[2] - 1);
7,057,536✔
1777
  double phi_max = this->phi(ijk[2]);
1778

99,092,040✔
1779
  double cos_theta = uniform_distribution(theta_min, theta_max, seed);
20,246,952✔
1780
  double sin_theta = std::sin(std::acos(cos_theta));
78,845,088✔
1781
  double phi = uniform_distribution(phi_min, phi_max, seed);
47,862,120✔
1782
  double r_min_cub = std::pow(r_min, 3);
1783
  double r_max_cub = std::pow(r_max, 3);
30,982,968✔
1784
  // might be faster to do rejection here?
1785
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
1786

74,283,288✔
1787
  double x = r * std::cos(phi) * sin_theta;
1788
  double y = r * std::sin(phi) * sin_theta;
1789
  double z = r * cos_theta;
1790

74,283,288✔
1791
  return origin_ + Position(x, y, z);
32,466,432✔
1792
}
1793

41,816,856✔
1794
double SphericalMesh::find_r_crossing(
1795
  const Position& r, const Direction& u, double l, int shell) const
41,816,856✔
1796
{
1797
  if ((shell < 0) || (shell > shape_[0]))
1798
    return INFTY;
1799

1800
  // solve |r+s*u| = r0
1801
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
1802
  const double r0 = grid_[0][shell];
41,816,856✔
1803
  if (r0 == 0.0)
41,816,856✔
1804
    return INFTY;
1805
  const double p = r.dot(u);
41,816,856✔
1806
  double c = r.dot(r) - r0 * r0;
1807
  double D = p * p - c;
1808

41,816,856✔
1809
  if (std::abs(c) <= RADIAL_MESH_TOL)
41,532,408✔
1810
    return INFTY;
1811

1812
  if (D >= 0.0) {
41,532,408✔
1813
    D = std::sqrt(D);
19,437,552✔
1814
    // the solution -p - D is always smaller as -p + D : Check this one first
1815
    if (-p - D > l)
1816
      return -p - D;
22,379,304✔
1817
    if (-p + D > l)
1818
      return -p + D;
1819
  }
39,992,448✔
1820

1821
  return INFTY;
1822
}
39,992,448✔
1823

39,992,448✔
1824
double SphericalMesh::find_theta_crossing(
1825
  const Position& r, const Direction& u, double l, int shell) const
1826
{
39,992,448✔
1827
  // Theta grid is [0, π], thus there is no real surface to cross
1,219,872✔
1828
  if (full_theta_ && (shape_[1] == 1))
1829
    return INFTY;
38,772,576✔
1830

38,772,576✔
1831
  shell = sanitize_theta(shell);
17,769,456✔
1832

17,769,456✔
1833
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
21,003,120✔
1834
  // yields
18,037,548✔
1835
  // a*s^2 + 2*b*s + c == 0 with
18,037,548✔
1836
  // a = cos(theta)^2 - u.z * u.z
1837
  // b = r*u * cos(theta)^2 - u.z * r.z
38,772,576✔
1838
  // c = r*r * cos(theta)^2 - r.z^2
1839

1840
  const double cos_t = std::cos(grid_[1][shell]);
151,512,888✔
1841
  const bool sgn = std::signbit(cos_t);
1842
  const double cos_t_2 = cos_t * cos_t;
1843

1844
  const double a = cos_t_2 - u.z * u.z;
151,512,888✔
1845
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1846
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
151,512,888✔
1847

1848
  // if factor of s^2 is zero, direction of flight is parallel to theta
74,378,796✔
1849
  // surface
74,378,796✔
1850
  if (std::abs(a) < FP_PRECISION) {
148,757,592✔
1851
    // if b vanishes, direction of flight is within theta surface and crossing
1852
    // is not possible
77,134,092✔
1853
    if (std::abs(b) < FP_PRECISION)
1854
      return INFTY;
37,141,644✔
1855

37,141,644✔
1856
    const double s = -0.5 * c / b;
37,141,644✔
1857
    // Check if solution is in positive direction of flight and has correct
74,283,288✔
1858
    // sign
1859
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1860
      return s;
39,992,448✔
1861

1862
    // no crossing is possible
1863
    return INFTY;
1864
  }
437✔
1865

1866
  const double p = b / a;
437✔
1867
  double D = p * p - c / a;
437✔
1868

437✔
1869
  if (D < 0.0)
1870
    return INFTY;
1,748✔
1871

1,311✔
UNCOV
1872
  D = std::sqrt(D);
×
1873

1874
  // the solution -p-D is always smaller as -p+D : Check this one first
×
1875
  double s = -p - D;
1876
  // Check if solution is in positive direction of flight and has correct sign
1,311✔
1877
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
2,622✔
UNCOV
1878
    return s;
×
1879

1880
  s = -p + D;
×
1881
  // Check if solution is in positive direction of flight and has correct sign
1882
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1883
    return s;
437✔
UNCOV
1884

×
1885
  return INFTY;
UNCOV
1886
}
×
1887

1888
double SphericalMesh::find_phi_crossing(
437✔
UNCOV
1889
  const Position& r, const Direction& u, double l, int shell) const
×
1890
{
UNCOV
1891
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
×
1892
  if (full_phi_ && (shape_[2] == 1))
1893
    return INFTY;
437✔
UNCOV
1894

×
1895
  shell = sanitize_phi(shell);
1896

UNCOV
1897
  const double p0 = grid_[2][shell];
×
1898

1899
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1900
  // => x(s) * cos(p0) = y(s) * sin(p0)
437✔
1901
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1902
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
874✔
1903

874✔
1904
  const double c0 = std::cos(p0);
874✔
1905
  const double s0 = std::sin(p0);
874✔
1906

1907
  const double denominator = (u.x * s0 - u.y * c0);
437✔
1908

1909
  // Check if direction of flight is not parallel to phi surface
1910
  if (std::abs(denominator) > FP_PRECISION) {
151,705,296✔
1911
    const double s = -(r.x * s0 - r.y * c0) / denominator;
1912
    // Check if solution is in positive direction of flight and crosses the
151,705,296✔
1913
    // correct phi surface (not -phi)
1914
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
UNCOV
1915
      return s;
×
1916
  }
1917

UNCOV
1918
  return INFTY;
×
1919
}
1920

1921
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
1922
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1923
  double l) const
1924
{
1925

396✔
1926
  if (i == 0) {
1927
    return std::min(
396✔
1928
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
396✔
1929
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
396✔
1930

396✔
1931
  } else if (i == 1) {
396✔
1932
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
1933
                      find_theta_crossing(r0, u, l, ijk[i])),
384✔
1934
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
1935
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
384✔
1936

384✔
1937
  } else {
1938
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
384✔
1939
                      find_phi_crossing(r0, u, l, ijk[i])),
384✔
1940
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
1941
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
384✔
1942
  }
384✔
1943
}
1944

384✔
1945
int SphericalMesh::set_grid()
1946
{
1947
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1948
    static_cast<int>(grid_[1].size()) - 1,
1949
    static_cast<int>(grid_[2].size()) - 1};
1950

1951
  for (const auto& g : grid_) {
317✔
1952
    if (g.size() < 2) {
317✔
1953
      set_errmsg("x-, y-, and z- grids for spherical meshes "
1954
                 "must each have at least 2 points");
317✔
1955
      return OPENMC_E_INVALID_ARGUMENT;
1956
    }
317✔
1957
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
317✔
1958
        g.end()) {
317✔
1959
      set_errmsg("Values in for r-, theta-, and phi- grids for "
317✔
1960
                 "spherical meshes must be sorted and unique.");
1961
      return OPENMC_E_INVALID_ARGUMENT;
317✔
UNCOV
1962
    }
×
1963
    if (g.front() < 0.0) {
1964
      set_errmsg("r-, theta-, and phi- grids for "
317✔
1965
                 "spherical meshes must start at v >= 0.");
1966
      return OPENMC_E_INVALID_ARGUMENT;
1967
    }
1968
  }
372✔
1969
  if (grid_[1].back() > PI) {
1970
    set_errmsg("theta-grids for "
372✔
1971
               "spherical meshes must end with theta <= pi.");
1972

1973
    return OPENMC_E_INVALID_ARGUMENT;
73,752,732✔
1974
  }
1975
  if (grid_[2].back() > 2 * PI) {
1976
    set_errmsg("phi-grids for "
73,752,732✔
1977
               "spherical meshes must end with phi <= 2*pi.");
1978
    return OPENMC_E_INVALID_ARGUMENT;
73,752,732✔
1979
  }
73,752,732✔
1980

1981
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
73,752,732✔
UNCOV
1982
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
×
UNCOV
1983

×
1984
  double r = grid_[0].back();
1985
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
73,752,732✔
1986
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
73,752,732✔
1987

73,752,732✔
1988
  return 0;
36,882,336✔
1989
}
1990

1991
int SphericalMesh::get_index_in_direction(double r, int i) const
73,752,732✔
1992
{
1993
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
73,752,732✔
1994
}
73,752,732✔
1995

1996
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
73,752,732✔
1997
  Position plot_ll, Position plot_ur) const
1998
{
UNCOV
1999
  fatal_error("Plot of spherical Mesh not implemented");
×
2000

2001
  // Figure out which axes lie in the plane of the plot.
UNCOV
2002
  array<vector<double>, 2> axis_lines;
×
UNCOV
2003
  return {axis_lines[0], axis_lines[1]};
×
2004
}
UNCOV
2005

×
UNCOV
2006
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
×
2007
{
UNCOV
2008
  write_dataset(mesh_group, "r_grid", grid_[0]);
×
UNCOV
2009
  write_dataset(mesh_group, "theta_grid", grid_[1]);
×
2010
  write_dataset(mesh_group, "phi_grid", grid_[2]);
UNCOV
2011
  write_dataset(mesh_group, "origin", origin_);
×
UNCOV
2012
}
×
UNCOV
2013

×
UNCOV
2014
double SphericalMesh::volume(const MeshIndex& ijk) const
×
UNCOV
2015
{
×
2016
  double r_i = grid_[0][ijk[0] - 1];
UNCOV
2017
  double r_o = grid_[0][ijk[0]];
×
2018

UNCOV
2019
  double theta_i = grid_[1][ijk[1] - 1];
×
UNCOV
2020
  double theta_o = grid_[1][ijk[1]];
×
UNCOV
2021

×
2022
  double phi_i = grid_[2][ijk[2] - 1];
UNCOV
2023
  double phi_o = grid_[2][ijk[2]];
×
2024

2025
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
2026
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
481,615,104✔
2027
}
2028

2029
//==============================================================================
481,615,104✔
2030
// Helper functions for the C API
44,030,820✔
2031
//==============================================================================
2032

2033
int check_mesh(int32_t index)
2034
{
437,584,284✔
2035
  if (index < 0 || index >= model::meshes.size()) {
437,584,284✔
2036
    set_errmsg("Index in meshes array is out of bounds.");
7,601,184✔
2037
    return OPENMC_E_OUT_OF_BOUNDS;
429,983,100✔
2038
  }
429,983,100✔
2039
  return 0;
429,983,100✔
2040
}
2041

429,983,100✔
2042
template<class T>
11,548,560✔
2043
int check_mesh_type(int32_t index)
2044
{
418,434,540✔
2045
  if (int err = check_mesh(index))
388,836,240✔
2046
    return err;
2047

388,836,240✔
2048
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
69,512,340✔
2049
  if (!mesh) {
319,323,900✔
2050
    set_errmsg("This function is not valid for input mesh.");
192,371,628✔
2051
    return OPENMC_E_INVALID_TYPE;
2052
  }
2053
  return 0;
156,550,572✔
2054
}
2055

2056
template<class T>
118,217,520✔
2057
bool is_mesh_type(int32_t index)
2058
{
2059
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2060
  return mesh;
118,217,520✔
2061
}
76,498,272✔
2062

2063
//==============================================================================
41,719,248✔
2064
// C API functions
2065
//==============================================================================
2066

2067
// Return the type of mesh as a C string
2068
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
2069
{
2070
  if (int err = check_mesh(index))
2071
    return err;
2072

41,719,248✔
2073
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
41,719,248✔
2074

41,719,248✔
2075
  return 0;
2076
}
41,719,248✔
2077

41,719,248✔
2078
//! Extend the meshes array by n elements
41,719,248✔
2079
extern "C" int openmc_extend_meshes(
2080
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2081
{
2082
  if (index_start)
41,719,248✔
2083
    *index_start = model::meshes.size();
2084
  std::string mesh_type;
2085

526,416✔
2086
  for (int i = 0; i < n; ++i) {
526,416✔
2087
    if (RegularMesh::mesh_type == type) {
UNCOV
2088
      model::meshes.push_back(make_unique<RegularMesh>());
×
2089
    } else if (RectilinearMesh::mesh_type == type) {
2090
      model::meshes.push_back(make_unique<RectilinearMesh>());
UNCOV
2091
    } else if (CylindricalMesh::mesh_type == type) {
×
UNCOV
2092
      model::meshes.push_back(make_unique<CylindricalMesh>());
×
2093
    } else if (SphericalMesh::mesh_type == type) {
2094
      model::meshes.push_back(make_unique<SphericalMesh>());
UNCOV
2095
    } else {
×
2096
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
2097
    }
2098
  }
41,192,832✔
2099
  if (index_end)
41,192,832✔
2100
    *index_end = model::meshes.size() - 1;
2101

41,192,832✔
2102
  return 0;
11,955,456✔
2103
}
2104

29,237,376✔
2105
//! Adds a new unstructured mesh to OpenMC
2106
extern "C" int openmc_add_unstructured_mesh(
2107
  const char filename[], const char library[], int* id)
29,237,376✔
2108
{
2109
  std::string lib_name(library);
29,237,376✔
2110
  std::string mesh_file(filename);
5,599,656✔
2111
  bool valid_lib = false;
2112

23,637,720✔
2113
#ifdef DAGMC
2114
  if (lib_name == MOABMesh::mesh_lib_type) {
23,637,720✔
2115
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
11,064,504✔
2116
    valid_lib = true;
2117
  }
12,573,216✔
2118
#endif
2119

2120
#ifdef LIBMESH
119,966,232✔
2121
  if (lib_name == LibMesh::mesh_lib_type) {
2122
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
2123
    valid_lib = true;
2124
  }
119,966,232✔
2125
#endif
76,498,272✔
2126

2127
  if (!valid_lib) {
43,467,960✔
2128
    set_errmsg(fmt::format("Mesh library {} is not supported "
2129
                           "by this build of OpenMC",
43,467,960✔
2130
      lib_name));
2131
    return OPENMC_E_INVALID_ARGUMENT;
2132
  }
2133

2134
  // auto-assign new ID
2135
  model::meshes.back()->set_id(-1);
2136
  *id = model::meshes.back()->id_;
43,467,960✔
2137

43,467,960✔
2138
  return 0;
2139
}
43,467,960✔
2140

2141
//! Return the index in the meshes array of a mesh with a given ID
2142
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
43,467,960✔
2143
{
43,212,696✔
2144
  auto pair = model::mesh_map.find(id);
2145
  if (pair == model::mesh_map.end()) {
2146
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
43,212,696✔
2147
    return OPENMC_E_INVALID_ID;
19,003,152✔
2148
  }
2149
  *index = pair->second;
2150
  return 0;
24,464,808✔
2151
}
2152

2153
//! Return the ID of a mesh
359,899,428✔
2154
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2155
{
2156
  if (int err = check_mesh(index))
2157
    return err;
2158
  *id = model::meshes[index]->id_;
359,899,428✔
2159
  return 0;
240,807,552✔
2160
}
240,807,552✔
2161

481,615,104✔
2162
//! Set the ID of a mesh
2163
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
119,091,876✔
2164
{
59,108,760✔
2165
  if (int err = check_mesh(index))
59,108,760✔
2166
    return err;
59,108,760✔
2167
  model::meshes[index]->id_ = id;
118,217,520✔
2168
  model::mesh_map[id] = index;
2169
  return 0;
2170
}
59,983,116✔
2171

59,983,116✔
2172
//! Get the number of elements in a mesh
59,983,116✔
2173
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
119,966,232✔
2174
{
2175
  if (int err = check_mesh(index))
2176
    return err;
2177
  *n = model::meshes[index]->n_bins();
341✔
2178
  return 0;
2179
}
341✔
2180

341✔
2181
//! Get the volume of each element in the mesh
341✔
2182
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
2183
{
1,364✔
2184
  if (int err = check_mesh(index))
1,023✔
2185
    return err;
×
2186
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
2187
    volumes[i] = model::meshes[index]->volume(i);
×
2188
  }
2189
  return 0;
1,023✔
2190
}
2,046✔
UNCOV
2191

×
2192
//! Get the bounding box of a mesh
UNCOV
2193
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
×
2194
{
2195
  if (int err = check_mesh(index))
1,023✔
2196
    return err;
×
2197

UNCOV
2198
  BoundingBox bbox = model::meshes[index]->bounding_box();
×
2199

2200
  // set lower left corner values
2201
  ll[0] = bbox.xmin;
341✔
2202
  ll[1] = bbox.ymin;
×
2203
  ll[2] = bbox.zmin;
2204

UNCOV
2205
  // set upper right corner values
×
2206
  ur[0] = bbox.xmax;
2207
  ur[1] = bbox.ymax;
341✔
UNCOV
2208
  ur[2] = bbox.zmax;
×
2209
  return 0;
UNCOV
2210
}
×
2211

2212
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
2213
  int nz, int table_size, int32_t* materials, double* volumes)
341✔
2214
{
341✔
2215
  if (int err = check_mesh(index))
2216
    return err;
341✔
2217

341✔
2218
  try {
341✔
2219
    model::meshes[index]->material_volumes(
2220
      nx, ny, nz, table_size, materials, volumes);
341✔
2221
  } catch (const std::exception& e) {
2222
    set_errmsg(e.what());
2223
    if (starts_with(e.what(), "Mesh")) {
221,258,196✔
2224
      return OPENMC_E_GEOMETRY;
2225
    } else {
221,258,196✔
2226
      return OPENMC_E_ALLOCATE;
2227
    }
NEW
2228
  }
×
2229

2230
  return 0;
UNCOV
2231
}
×
2232

2233
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
2234
  Position width, int basis, int* pixels, int32_t* data)
2235
{
2236
  if (int err = check_mesh(index))
2237
    return err;
2238
  const auto& mesh = model::meshes[index].get();
312✔
2239

2240
  int pixel_width = pixels[0];
312✔
2241
  int pixel_height = pixels[1];
312✔
2242

312✔
2243
  // get pixel size
312✔
2244
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
312✔
2245
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
2246

528✔
2247
  // setup basis indices and initial position centered on pixel
2248
  int in_i, out_i;
528✔
2249
  Position xyz = origin;
528✔
2250
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
2251
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
528✔
2252
  switch (basis_enum) {
528✔
2253
  case PlotBasis::xy:
2254
    in_i = 0;
528✔
2255
    out_i = 1;
528✔
2256
    break;
2257
  case PlotBasis::xz:
528✔
2258
    in_i = 0;
528✔
2259
    out_i = 2;
2260
    break;
2261
  case PlotBasis::yz:
2262
    in_i = 1;
2263
    out_i = 2;
2264
    break;
2265
  default:
8,800✔
2266
    UNREACHABLE();
2267
  }
8,800✔
UNCOV
2268

×
UNCOV
2269
  // set initial position
×
2270
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
2271
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
8,800✔
2272

2273
#pragma omp parallel
2274
  {
2275
    Position r = xyz;
1,630✔
2276

2277
#pragma omp for
1,630✔
UNCOV
2278
    for (int y = 0; y < pixel_height; y++) {
×
2279
      r[out_i] = xyz[out_i] - out_pixel * y;
2280
      for (int x = 0; x < pixel_width; x++) {
1,630✔
2281
        r[in_i] = xyz[in_i] + in_pixel * x;
1,630✔
UNCOV
2282
        data[pixel_width * y + x] = mesh->get_bin(r);
×
UNCOV
2283
      }
×
2284
    }
2285
  }
1,630✔
2286

2287
  return 0;
156✔
2288
}
2289

156✔
UNCOV
2290
//! Get the dimension of a regular mesh
×
2291
extern "C" int openmc_regular_mesh_get_dimension(
2292
  int32_t index, int** dims, int* n)
156✔
2293
{
156✔
UNCOV
2294
  if (int err = check_mesh_type<RegularMesh>(index))
×
UNCOV
2295
    return err;
×
2296
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2297
  *dims = mesh->shape_.data();
156✔
2298
  *n = mesh->n_dimension_;
2299
  return 0;
156✔
2300
}
2301

156✔
UNCOV
2302
//! Set the dimension of a regular mesh
×
2303
extern "C" int openmc_regular_mesh_set_dimension(
2304
  int32_t index, int n, const int* dims)
156✔
2305
{
156✔
UNCOV
2306
  if (int err = check_mesh_type<RegularMesh>(index))
×
UNCOV
2307
    return err;
×
2308
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2309

156✔
2310
  // Copy dimension
2311
  mesh->n_dimension_ = n;
244✔
2312
  std::copy(dims, dims + n, mesh->shape_.begin());
2313
  return 0;
244✔
UNCOV
2314
}
×
2315

2316
//! Get the regular mesh parameters
244✔
2317
extern "C" int openmc_regular_mesh_get_params(
244✔
UNCOV
2318
  int32_t index, double** ll, double** ur, double** width, int* n)
×
UNCOV
2319
{
×
2320
  if (int err = check_mesh_type<RegularMesh>(index))
2321
    return err;
244✔
2322
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2323

1,074✔
2324
  if (m->lower_left_.dimension() == 0) {
2325
    set_errmsg("Mesh parameters have not been set.");
1,074✔
UNCOV
2326
    return OPENMC_E_ALLOCATE;
×
2327
  }
2328

1,074✔
2329
  *ll = m->lower_left_.data();
1,074✔
UNCOV
2330
  *ur = m->upper_right_.data();
×
UNCOV
2331
  *width = m->width_.data();
×
2332
  *n = m->n_dimension_;
2333
  return 0;
1,074✔
2334
}
2335

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

2344
  if (m->n_dimension_ == -1) {
2345
    set_errmsg("Need to set mesh dimension before setting parameters.");
2346
    return OPENMC_E_UNASSIGNED;
2347
  }
2348

1,998✔
2349
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
2350
  if (ll && ur) {
1,998✔
UNCOV
2351
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
×
2352
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
2353
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
1,998✔
2354
  } else if (ll && width) {
2355
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
1,998✔
2356
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
2357
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
2358
  } else if (ur && width) {
2359
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
426✔
2360
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
2361
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
2362
  } else {
426✔
2363
    set_errmsg("At least two parameters must be specified.");
426✔
2364
    return OPENMC_E_INVALID_ARGUMENT;
426✔
2365
  }
2366

852✔
2367
  // Set material volumes
426✔
2368

310✔
2369
  // TODO: incorporate this into method in RegularMesh that can be called from
116✔
2370
  // here and from constructor
68✔
2371
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
48✔
2372
  m->element_volume_ = 1.0;
24✔
2373
  for (int i = 0; i < m->n_dimension_; i++) {
24✔
2374
    m->element_volume_ *= m->width_[i];
24✔
2375
  }
UNCOV
2376

×
2377
  return 0;
2378
}
2379

426✔
UNCOV
2380
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
×
2381
template<class C>
2382
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
426✔
2383
  const int nx, const double* grid_y, const int ny, const double* grid_z,
426✔
2384
  const int nz)
2385
{
2386
  if (int err = check_mesh_type<C>(index))
×
2387
    return err;
2388

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

×
UNCOV
2391
  m->n_dimension_ = 3;
×
2392

2393
  m->grid_[0].reserve(nx);
2394
  m->grid_[1].reserve(ny);
2395
  m->grid_[2].reserve(nz);
2396

2397
  for (int i = 0; i < nx; i++) {
2398
    m->grid_[0].push_back(grid_x[i]);
2399
  }
2400
  for (int i = 0; i < ny; i++) {
2401
    m->grid_[1].push_back(grid_y[i]);
2402
  }
2403
  for (int i = 0; i < nz; i++) {
2404
    m->grid_[2].push_back(grid_z[i]);
2405
  }
2406

UNCOV
2407
  int err = m->set_grid();
×
2408
  return err;
×
2409
}
2410

UNCOV
2411
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
×
2412
template<class C>
2413
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
2414
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2415
{
×
UNCOV
2416
  if (int err = check_mesh_type<C>(index))
×
2417
    return err;
UNCOV
2418
  C* m = dynamic_cast<C*>(model::meshes[index].get());
×
2419

2420
  if (m->lower_left_.dimension() == 0) {
2421
    set_errmsg("Mesh parameters have not been set.");
2422
    return OPENMC_E_ALLOCATE;
618✔
2423
  }
2424

618✔
2425
  *grid_x = m->grid_[0].data();
618✔
UNCOV
2426
  *nx = m->grid_[0].size();
×
UNCOV
2427
  *grid_y = m->grid_[1].data();
×
2428
  *ny = m->grid_[1].size();
2429
  *grid_z = m->grid_[2].data();
618✔
2430
  *nz = m->grid_[2].size();
618✔
2431

2432
  return 0;
2433
}
2434

4,050✔
2435
//! Get the rectilinear mesh grid
2436
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
4,050✔
UNCOV
2437
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
×
2438
{
4,050✔
2439
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
4,050✔
2440
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2441
}
2442

2443
//! Set the rectilienar mesh parameters
426✔
2444
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
2445
  const double* grid_x, const int nx, const double* grid_y, const int ny,
426✔
UNCOV
2446
  const double* grid_z, const int nz)
×
2447
{
426✔
2448
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
426✔
2449
    index, grid_x, nx, grid_y, ny, grid_z, nz);
426✔
2450
}
2451

2452
//! Get the cylindrical mesh grid
2453
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
252✔
2454
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2455
{
252✔
UNCOV
2456
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
×
2457
    index, grid_x, nx, grid_y, ny, grid_z, nz);
252✔
2458
}
252✔
2459

2460
//! Set the cylindrical mesh parameters
2461
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
2462
  const double* grid_x, const int nx, const double* grid_y, const int ny,
96✔
2463
  const double* grid_z, const int nz)
2464
{
96✔
UNCOV
2465
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
×
2466
    index, grid_x, nx, grid_y, ny, grid_z, nz);
1,056✔
2467
}
960✔
2468

2469
//! Get the spherical mesh grid
96✔
2470
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
2471
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2472
{
2473

144✔
2474
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
2475
    index, grid_x, nx, grid_y, ny, grid_z, nz);
144✔
UNCOV
2476
  ;
×
2477
}
2478

144✔
2479
//! Set the spherical mesh parameters
2480
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
2481
  const double* grid_x, const int nx, const double* grid_y, const int ny,
144✔
2482
  const double* grid_z, const int nz)
144✔
2483
{
144✔
2484
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
2485
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2486
}
144✔
2487

144✔
2488
#ifdef DAGMC
144✔
2489

144✔
2490
const std::string MOABMesh::mesh_lib_type = "moab";
2491

2492
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
156✔
2493
{
2494
  initialize();
2495
}
156✔
UNCOV
2496

×
2497
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2498
{
2499
  filename_ = filename;
156✔
2500
  set_length_multiplier(length_multiplier);
2501
  initialize();
12✔
2502
}
12✔
2503

12✔
2504
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
12✔
2505
{
UNCOV
2506
  mbi_ = external_mbi;
×
2507
  filename_ = "unknown (external file)";
2508
  this->initialize();
12✔
2509
}
2510

144✔
2511
void MOABMesh::initialize()
2512
{
2513

48✔
2514
  // Create the MOAB interface and load data from file
2515
  this->create_interface();
2516

48✔
UNCOV
2517
  // Initialise MOAB error code
×
2518
  moab::ErrorCode rval = moab::MB_SUCCESS;
48✔
2519

2520
  // Set the dimension
48✔
2521
  n_dimension_ = 3;
48✔
2522

2523
  // set member range of tetrahedral entities
2524
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
48✔
2525
  if (rval != moab::MB_SUCCESS) {
48✔
2526
    fatal_error("Failed to get all tetrahedral elements");
2527
  }
2528

2529
  if (!ehs_.all_of_type(moab::MBTET)) {
48✔
2530
    warning("Non-tetrahedral elements found in unstructured "
2531
            "mesh file: " +
48✔
2532
            filename_);
48✔
2533
  }
48✔
2534

48✔
2535
  // set member range of vertices
48✔
2536
  int vertex_dim = 0;
48✔
2537
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
×
2538
  if (rval != moab::MB_SUCCESS) {
×
2539
    fatal_error("Failed to get all vertex handles");
×
2540
  }
×
UNCOV
2541

×
UNCOV
2542
  // make an entity set for all tetrahedra
×
UNCOV
2543
  // this is used for convenience later in output
×
UNCOV
2544
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
×
UNCOV
2545
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2546
    fatal_error("Failed to create an entity set for the tetrahedral elements");
×
2547
  }
2548

2549
  rval = mbi_->add_entities(tetset_, ehs_);
2550
  if (rval != moab::MB_SUCCESS) {
48✔
2551
    fatal_error("Failed to add tetrahedra to an entity set.");
48✔
2552
  }
2553

24✔
2554
  if (length_multiplier_ > 0.0) {
2555
    // get the connectivity of all tets
24✔
2556
    moab::Range adj;
2557
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2558
    if (rval != moab::MB_SUCCESS) {
504✔
2559
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
480✔
2560
    }
10,080✔
2561
    // scale all vertex coords by multiplier (done individually so not all
9,600✔
2562
    // coordinates are in memory twice at once)
9,600✔
2563
    for (auto vert : adj) {
2564
      // retrieve coords
2565
      std::array<double, 3> coord;
2566
      rval = mbi_->get_coords(&vert, 1, coord.data());
2567
      if (rval != moab::MB_SUCCESS) {
48✔
2568
        fatal_error("Could not get coordinates of vertex.");
2569
      }
2570
      // scale coords
2571
      for (auto& c : coord) {
12✔
2572
        c *= length_multiplier_;
2573
      }
2574
      // set new coords
12✔
UNCOV
2575
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2576
      if (rval != moab::MB_SUCCESS) {
12✔
2577
        fatal_error("Failed to set new vertex coordinates");
12✔
2578
      }
12✔
2579
    }
12✔
2580
  }
2581

2582
  // Determine bounds of mesh
2583
  this->determine_bounds();
334✔
2584
}
2585

2586
void MOABMesh::prepare_for_point_location()
334✔
UNCOV
2587
{
×
2588
  // if the KDTree has already been constructed, do nothing
334✔
2589
  if (kdtree_)
2590
    return;
2591

334✔
2592
  // build acceleration data structures
334✔
2593
  compute_barycentric_data(ehs_);
334✔
2594
  build_kdtree(ehs_);
2595
}
2596

2597
void MOABMesh::create_interface()
358✔
2598
{
2599
  // Do not create a MOAB instance if one is already in memory
2600
  if (mbi_)
358✔
UNCOV
2601
    return;
×
2602

358✔
2603
  // create MOAB instance
2604
  mbi_ = std::make_shared<moab::Core>();
358✔
UNCOV
2605

×
UNCOV
2606
  // load unstructured mesh file
×
2607
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
2608
  if (rval != moab::MB_SUCCESS) {
2609
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
358✔
2610
  }
358✔
2611
}
358✔
2612

358✔
2613
void MOABMesh::build_kdtree(const moab::Range& all_tets)
358✔
2614
{
2615
  moab::Range all_tris;
2616
  int adj_dim = 2;
2617
  write_message("Getting tet adjacencies...", 7);
370✔
2618
  moab::ErrorCode rval = mbi_->get_adjacencies(
2619
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2620
  if (rval != moab::MB_SUCCESS) {
370✔
UNCOV
2621
    fatal_error("Failed to get adjacent triangles for tets");
×
2622
  }
370✔
2623

2624
  if (!all_tris.all_of_type(moab::MBTRI)) {
370✔
UNCOV
2625
    warning("Non-triangle elements found in tet adjacencies in "
×
UNCOV
2626
            "unstructured mesh file: " +
×
2627
            filename_);
2628
  }
2629

370✔
2630
  // combine into one range
370✔
2631
  moab::Range all_tets_and_tris;
346✔
2632
  all_tets_and_tris.merge(all_tets);
346✔
2633
  all_tets_and_tris.merge(all_tris);
346✔
2634

24✔
2635
  // create a kd-tree instance
12✔
2636
  write_message(
12✔
2637
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
12✔
2638
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
12✔
2639

12✔
2640
  // Determine what options to use
12✔
2641
  std::ostringstream options_stream;
12✔
2642
  if (options_.empty()) {
UNCOV
2643
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
×
UNCOV
2644
  } else {
×
2645
    options_stream << options_;
2646
  }
2647
  moab::FileOptions file_opts(options_stream.str().c_str());
2648

2649
  // Build the k-d tree
2650
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
2651
  if (rval != moab::MB_SUCCESS) {
370✔
2652
    fatal_error("Failed to construct KDTree for the "
370✔
2653
                "unstructured mesh file: " +
1,480✔
2654
                filename_);
1,110✔
2655
  }
2656
}
2657

370✔
2658
void MOABMesh::intersect_track(const moab::CartVect& start,
370✔
2659
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2660
{
2661
  hits.clear();
2662

116✔
2663
  moab::ErrorCode rval;
2664
  vector<moab::EntityHandle> tris;
2665
  // get all intersections with triangles in the tet mesh
2666
  // (distances are relative to the start point, not the previous
116✔
NEW
2667
  // intersection)
×
2668
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
2669
    dir.array(), start.array(), tris, hits, 0, track_len);
116✔
2670
  if (rval != moab::MB_SUCCESS) {
2671
    fatal_error(
116✔
2672
      "Failed to compute intersections on unstructured mesh: " + filename_);
2673
  }
116✔
2674

116✔
2675
  // remove duplicate intersection distances
116✔
2676
  std::unique(hits.begin(), hits.end());
2677

904✔
2678
  // sorts by first component of std::pair by default
788✔
2679
  std::sort(hits.begin(), hits.end());
2680
}
432✔
2681

316✔
2682
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
2683
  vector<int>& bins, vector<double>& lengths) const
408✔
2684
{
292✔
2685
  moab::CartVect start(r0.x, r0.y, r0.z);
2686
  moab::CartVect end(r1.x, r1.y, r1.z);
2687
  moab::CartVect dir(u.x, u.y, u.z);
116✔
2688
  dir.normalize();
116✔
2689

2690
  double track_len = (end - start).length();
24✔
2691
  if (track_len == 0.0)
2692
    return;
2693

2694
  start -= TINY_BIT * dir;
24✔
UNCOV
2695
  end += TINY_BIT * dir;
×
2696

2697
  vector<double> hits;
24✔
2698
  intersect_track(start, dir, track_len, hits);
2699

24✔
2700
  bins.clear();
2701
  lengths.clear();
24✔
2702

24✔
2703
  // if there are no intersections the track may lie entirely
24✔
2704
  // within a single tet. If this is the case, apply entire
2705
  // score to that tet and return.
96✔
2706
  if (hits.size() == 0) {
72✔
2707
    Position midpoint = r0 + u * (track_len * 0.5);
2708
    int bin = this->get_bin(midpoint);
96✔
2709
    if (bin != -1) {
72✔
2710
      bins.push_back(bin);
2711
      lengths.push_back(1.0);
108✔
2712
    }
84✔
2713
    return;
2714
  }
2715

24✔
2716
  // for each segment in the set of tracks, try to look up a tet
24✔
2717
  // at the midpoint of the segment
2718
  Position current = r0;
24✔
2719
  double last_dist = 0.0;
2720
  for (const auto& hit : hits) {
2721
    // get the segment length
2722
    double segment_length = hit - last_dist;
24✔
UNCOV
2723
    last_dist = hit;
×
2724
    // find the midpoint of this segment
2725
    Position midpoint = current + u * (segment_length * 0.5);
24✔
2726
    // try to find a tet for this position
2727
    int bin = this->get_bin(midpoint);
24✔
2728

2729
    // determine the start point for this segment
24✔
2730
    current = r0 + u * hit;
24✔
2731

24✔
2732
    if (bin == -1) {
2733
      continue;
96✔
2734
    }
72✔
2735

2736
    bins.push_back(bin);
108✔
2737
    lengths.push_back(segment_length / track_len);
84✔
2738
  }
2739

84✔
2740
  // tally remaining portion of track after last hit if
60✔
2741
  // the last segment of the track is in the mesh but doesn't
2742
  // reach the other side of the tet
2743
  if (hits.back() < track_len) {
24✔
2744
    Position segment_start = r0 + u * hits.back();
24✔
2745
    double segment_length = track_len - hits.back();
2746
    Position midpoint = segment_start + u * (segment_length * 0.5);
68✔
2747
    int bin = this->get_bin(midpoint);
2748
    if (bin != -1) {
2749
      bins.push_back(bin);
2750
      lengths.push_back(segment_length / track_len);
68✔
UNCOV
2751
    }
×
2752
  }
2753
};
68✔
2754

2755
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
68✔
2756
{
2757
  moab::CartVect pos(r.x, r.y, r.z);
68✔
2758
  // find the leaf of the kd-tree for this position
68✔
2759
  moab::AdaptiveKDTreeIter kdtree_iter;
68✔
2760
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
2761
  if (rval != moab::MB_SUCCESS) {
712✔
2762
    return 0;
644✔
2763
  }
2764

228✔
2765
  // retrieve the tet elements of this leaf
160✔
2766
  moab::EntityHandle leaf = kdtree_iter.handle();
2767
  moab::Range tets;
216✔
2768
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
148✔
2769
  if (rval != moab::MB_SUCCESS) {
2770
    warning("MOAB error finding tets.");
2771
  }
68✔
2772

68✔
2773
  // loop over the tets in this leaf, returning the containing tet if found
2774
  for (const auto& tet : tets) {
2775
    if (point_in_tet(pos, tet)) {
2776
      return tet;
2777
    }
440✔
2778
  }
2779

2780
  // if no tet is found, return an invalid handle
440✔
2781
  return 0;
×
2782
}
440✔
2783

2784
double MOABMesh::volume(int bin) const
440✔
UNCOV
2785
{
×
UNCOV
2786
  return tet_volume(get_ent_handle_from_bin(bin));
×
2787
}
2788

2789
std::string MOABMesh::library() const
440✔
2790
{
440✔
2791
  return mesh_lib_type;
440✔
2792
}
440✔
2793

440✔
2794
// Sample position within a tet for MOAB type tets
440✔
2795
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
2796
{
440✔
2797

2798
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
132✔
2799

2800
  // Get vertex coordinates for MOAB tet
2801
  const moab::EntityHandle* conn1;
132✔
2802
  int conn1_size;
×
2803
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
132✔
2804
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
2805
    fatal_error(fmt::format(
132✔
UNCOV
2806
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
×
UNCOV
2807
      conn1_size));
×
2808
  }
2809
  moab::CartVect p[4];
2810
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
132✔
2811
  if (rval != moab::MB_SUCCESS) {
132✔
2812
    fatal_error("Failed to get tet coords");
132✔
2813
  }
132✔
2814

132✔
2815
  std::array<Position, 4> tet_verts;
132✔
2816
  for (int i = 0; i < 4; i++) {
2817
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
132✔
2818
  }
2819
  // Samples position within tet using Barycentric stuff
132✔
2820
  return this->sample_tet(tet_verts, seed);
2821
}
2822

132✔
2823
double MOABMesh::tet_volume(moab::EntityHandle tet) const
×
2824
{
132✔
2825
  vector<moab::EntityHandle> conn;
2826
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
132✔
UNCOV
2827
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2828
    fatal_error("Failed to get tet connectivity");
×
2829
  }
2830

2831
  moab::CartVect p[4];
132✔
2832
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
132✔
2833
  if (rval != moab::MB_SUCCESS) {
132✔
2834
    fatal_error("Failed to get tet coords");
132✔
2835
  }
132✔
2836

132✔
2837
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
2838
}
132✔
2839

2840
int MOABMesh::get_bin(Position r) const
176✔
2841
{
2842
  moab::EntityHandle tet = get_tet(r);
2843
  if (tet == 0) {
176✔
2844
    return -1;
×
2845
  } else {
176✔
2846
    return get_bin_from_ent_handle(tet);
2847
  }
176✔
UNCOV
2848
}
×
UNCOV
2849

×
2850
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
2851
{
2852
  moab::ErrorCode rval;
176✔
2853

176✔
2854
  baryc_data_.clear();
176✔
2855
  baryc_data_.resize(tets.size());
176✔
2856

176✔
2857
  // compute the barycentric data for each tet element
176✔
2858
  // and store it as a 3x3 matrix
2859
  for (auto& tet : tets) {
176✔
2860
    vector<moab::EntityHandle> verts;
2861
    rval = mbi_->get_connectivity(&tet, 1, verts);
2862
    if (rval != moab::MB_SUCCESS) {
2863
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
176✔
2864
    }
2865

2866
    moab::CartVect p[4];
176✔
2867
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
176✔
2868
    if (rval != moab::MB_SUCCESS) {
2869
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
2870
    }
2871

68✔
2872
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
2873

2874
    // invert now to avoid this cost later
2875
    a = a.transpose().inverse();
68✔
2876
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
68✔
2877
  }
2878
}
2879

2880
bool MOABMesh::point_in_tet(
132✔
2881
  const moab::CartVect& r, moab::EntityHandle tet) const
2882
{
2883

132✔
2884
  moab::ErrorCode rval;
132✔
2885

2886
  // get tet vertices
2887
  vector<moab::EntityHandle> verts;
2888
  rval = mbi_->get_connectivity(&tet, 1, verts);
24✔
2889
  if (rval != moab::MB_SUCCESS) {
2890
    warning("Failed to get vertices of tet in umesh: " + filename_);
2891
    return false;
2892
  }
24✔
2893

24✔
2894
  // first vertex is used as a reference point for the barycentric data -
2895
  // retrieve its coordinates
2896
  moab::CartVect p_zero;
2897
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
132✔
2898
  if (rval != moab::MB_SUCCESS) {
2899
    warning("Failed to get coordinates of a vertex in "
2900
            "unstructured mesh: " +
2901
            filename_);
132✔
2902
    return false;
132✔
2903
  }
2904

2905
  // look up barycentric data
2906
  int idx = get_bin_from_ent_handle(tet);
2907
  const moab::Matrix3& a_inv = baryc_data_[idx];
24✔
2908

2909
  moab::CartVect bary_coords = a_inv * (r - p_zero);
2910

2911
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
24✔
2912
          bary_coords[2] >= 0.0 &&
24✔
2913
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
2914
}
2915

2916
int MOABMesh::get_bin_from_index(int idx) const
2917
{
2918
  if (idx >= n_bins()) {
2919
    fatal_error(fmt::format("Invalid bin index: {}", idx));
23✔
2920
  }
2921
  return ehs_[idx] - ehs_[0];
23✔
2922
}
23✔
2923

2924
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
2925
{
2926
  int bin = get_bin(r);
2927
  *in_mesh = bin != -1;
2928
  return bin;
2929
}
2930

2931
int MOABMesh::get_index_from_bin(int bin) const
1✔
2932
{
2933
  return bin;
1✔
2934
}
1✔
2935

1✔
2936
std::pair<vector<double>, vector<double>> MOABMesh::plot(
1✔
2937
  Position plot_ll, Position plot_ur) const
2938
{
24✔
2939
  // TODO: Implement mesh lines
2940
  return {};
2941
}
2942

24✔
2943
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
2944
{
2945
  int idx = vert - verts_[0];
24✔
2946
  if (idx >= n_vertices()) {
2947
    fatal_error(
2948
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
24✔
2949
  }
2950
  return idx;
2951
}
24✔
2952

24✔
2953
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
2954
{
2955
  int bin = eh - ehs_[0];
2956
  if (bin >= n_bins()) {
24✔
2957
    fatal_error(fmt::format("Invalid bin: {}", bin));
2958
  }
2959
  return bin;
2960
}
2961

2962
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
2963
{
24✔
2964
  if (bin >= n_bins()) {
24✔
2965
    fatal_error(fmt::format("Invalid bin index: ", bin));
24✔
2966
  }
2967
  return ehs_[0] + bin;
2968
}
2969

2970
int MOABMesh::n_bins() const
2971
{
24✔
2972
  return ehs_.size();
24✔
2973
}
2974

2975
int MOABMesh::n_surface_bins() const
2976
{
24✔
2977
  // collect all triangles in the set of tets for this mesh
24✔
2978
  moab::Range tris;
2979
  moab::ErrorCode rval;
2980
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
2981
  if (rval != moab::MB_SUCCESS) {
24✔
2982
    warning("Failed to get all triangles in the mesh instance");
2983
    return -1;
2984
  }
2985
  return 2 * tris.size();
2986
}
2987

2988
Position MOABMesh::centroid(int bin) const
2989
{
2990
  moab::ErrorCode rval;
2991

2992
  auto tet = this->get_ent_handle_from_bin(bin);
2993

2994
  // look up the tet connectivity
2995
  vector<moab::EntityHandle> conn;
2996
  rval = mbi_->get_connectivity(&tet, 1, conn);
2997
  if (rval != moab::MB_SUCCESS) {
2998
    warning("Failed to get connectivity of a mesh element.");
2999
    return {};
3000
  }
3001

3002
  // get the coordinates
3003
  vector<moab::CartVect> coords(conn.size());
3004
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3005
  if (rval != moab::MB_SUCCESS) {
3006
    warning("Failed to get the coordinates of a mesh element.");
3007
    return {};
3008
  }
3009

3010
  // compute the centroid of the element vertices
24✔
3011
  moab::CartVect centroid(0.0, 0.0, 0.0);
24✔
3012
  for (const auto& coord : coords) {
3013
    centroid += coord;
20✔
3014
  }
3015
  centroid /= double(coords.size());
3016

20✔
3017
  return {centroid[0], centroid[1], centroid[2]};
3018
}
3019

3020
int MOABMesh::n_vertices() const
20✔
3021
{
20✔
3022
  return verts_.size();
3023
}
3024

24✔
3025
Position MOABMesh::vertex(int id) const
3026
{
3027

24✔
3028
  moab::ErrorCode rval;
1✔
3029

3030
  moab::EntityHandle vert = verts_[id];
3031

23✔
3032
  moab::CartVect coords;
3033
  rval = mbi_->get_coords(&vert, 1, coords.array());
3034
  if (rval != moab::MB_SUCCESS) {
23✔
3035
    fatal_error("Failed to get the coordinates of a vertex.");
23✔
3036
  }
3037

3038
  return {coords[0], coords[1], coords[2]};
3039
}
3040

20✔
3041
std::vector<int> MOABMesh::connectivity(int bin) const
3042
{
20✔
3043
  moab::ErrorCode rval;
20✔
3044

20✔
3045
  auto tet = get_ent_handle_from_bin(bin);
20✔
3046

3047
  // look up the tet connectivity
20✔
3048
  vector<moab::EntityHandle> conn;
3049
  rval = mbi_->get_connectivity(&tet, 1, conn);
3050
  if (rval != moab::MB_SUCCESS) {
3051
    fatal_error("Failed to get connectivity of a mesh element.");
20✔
3052
    return {};
3053
  }
3054

3055
  std::vector<int> verts(4);
3056
  for (int i = 0; i < verts.size(); i++) {
3057
    verts[i] = get_vert_idx_from_handle(conn[i]);
3058
  }
20✔
3059

20✔
3060
  return verts;
20✔
3061
}
3062

3063
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
20✔
3064
  std::string score) const
20✔
3065
{
20✔
3066
  moab::ErrorCode rval;
3067
  // add a tag to the mesh
3068
  // all scores are treated as a single value
20✔
3069
  // with an uncertainty
20✔
3070
  moab::Tag value_tag;
4✔
3071

3072
  // create the value tag if not present and get handle
16✔
3073
  double default_val = 0.0;
3074
  auto val_string = score + "_mean";
20✔
3075
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3076
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3077
  if (rval != moab::MB_SUCCESS) {
20✔
3078
    auto msg =
20✔
3079
      fmt::format("Could not create or retrieve the value tag for the score {}"
3080
                  " on unstructured mesh {}",
3081
        score, id_);
3082
    fatal_error(msg);
3083
  }
20✔
3084

3085
  // create the std dev tag if not present and get handle
1,542,122✔
3086
  moab::Tag error_tag;
3087
  std::string err_string = score + "_std_dev";
3088
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
1,542,122✔
3089
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3090
  if (rval != moab::MB_SUCCESS) {
3091
    auto msg =
1,542,122✔
3092
      fmt::format("Could not create or retrieve the error tag for the score {}"
3093
                  " on unstructured mesh {}",
3094
        score, id_);
3095
    fatal_error(msg);
1,542,122✔
3096
  }
3097

1,542,122✔
3098
  // return the populated tag handles
3099
  return {value_tag, error_tag};
3100
}
3101

3102
void MOABMesh::add_score(const std::string& score)
3103
{
1,542,122✔
3104
  auto score_tags = get_score_tags(score);
3105
  tag_names_.push_back(score);
3106
}
1,542,122✔
3107

1,542,122✔
3108
void MOABMesh::remove_scores()
3109
{
1,542,122✔
3110
  for (const auto& name : tag_names_) {
3111
    auto value_name = name + "_mean";
3112
    moab::Tag tag;
1,542,122✔
3113
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
1,542,122✔
3114
    if (rval != moab::MB_SUCCESS)
1,542,122✔
3115
      return;
1,542,122✔
3116

3117
    rval = mbi_->tag_delete(tag);
1,542,122✔
3118
    if (rval != moab::MB_SUCCESS) {
1,542,122✔
3119
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
720,627✔
3120
                             " on unstructured mesh {}",
3121
        name, id_);
1,542,122✔
3122
      fatal_error(msg);
1,542,122✔
3123
    }
3124

1,542,122✔
3125
    auto std_dev_name = name + "_std_dev";
1,542,122✔
3126
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3127
    if (rval != moab::MB_SUCCESS) {
1,542,122✔
3128
      auto msg =
1,542,122✔
3129
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3130
                    " on unstructured mesh {}",
3131
          name, id_);
3132
    }
3133

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

3145
void MOABMesh::set_score_data(const std::string& score,
821,495✔
3146
  const vector<double>& values, const vector<double>& std_dev)
821,495✔
3147
{
5,514,377✔
3148
  auto score_tags = this->get_score_tags(score);
3149

4,692,882✔
3150
  moab::ErrorCode rval;
4,692,882✔
3151
  // set the score value
3152
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
4,692,882✔
3153
  if (rval != moab::MB_SUCCESS) {
3154
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
4,692,882✔
3155
                           "on unstructured mesh {}",
3156
      score, id_);
3157
    warning(msg);
4,692,882✔
3158
  }
3159

4,692,882✔
3160
  // set the error value
20,480✔
3161
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3162
  if (rval != moab::MB_SUCCESS) {
3163
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
4,672,402✔
3164
                           "on unstructured mesh {}",
4,672,402✔
3165
      score, id_);
3166
    warning(msg);
3167
  }
3168
}
3169

3170
void MOABMesh::write(const std::string& base_filename) const
821,495✔
3171
{
821,495✔
3172
  // add extension to the base name
821,495✔
3173
  auto filename = base_filename + ".vtk";
821,495✔
3174
  write_message(5, "Writing unstructured mesh {}...", filename);
821,495✔
3175
  filename = settings::path_output + filename;
821,495✔
3176

766,195✔
3177
  // write the tetrahedral elements of the mesh only
766,195✔
3178
  // to avoid clutter from zero-value data on other
3179
  // elements during visualization
3180
  moab::ErrorCode rval;
1,542,122✔
3181
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3182
  if (rval != moab::MB_SUCCESS) {
7,307,001✔
3183
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3184
    warning(msg);
7,307,001✔
3185
  }
3186
}
7,307,001✔
3187

7,307,001✔
3188
#endif
7,307,001✔
3189

1,010,077✔
3190
#ifdef LIBMESH
3191

3192
const std::string LibMesh::mesh_lib_type = "libmesh";
3193

6,296,924✔
3194
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node), adaptive_(false)
6,296,924✔
3195
{
6,296,924✔
3196
  // filename_ and length_multiplier_ will already be set by the
6,296,924✔
3197
  // UnstructuredMesh constructor
3198
  set_mesh_pointer_from_filename(filename_);
3199
  set_length_multiplier(length_multiplier_);
3200
  initialize();
3201
}
260,010,824✔
3202

260,007,978✔
3203
// create the mesh from a pointer to a libMesh Mesh
6,294,078✔
3204
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3205
  : adaptive_(input_mesh.n_active_elem() != input_mesh.n_elem())
3206
{
3207
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
3208
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
2,846✔
3209
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
7,307,001✔
3210
  }
3211

167,856✔
3212
  m_ = &input_mesh;
3213
  set_length_multiplier(length_multiplier);
167,856✔
3214
  initialize();
3215
}
3216

32✔
3217
// create the mesh from an input file
3218
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
32✔
3219
  : adaptive_(false)
3220
{
3221
  set_mesh_pointer_from_filename(filename);
3222
  set_length_multiplier(length_multiplier);
200,410✔
3223
  initialize();
3224
}
3225

200,410✔
3226
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3227
{
3228
  filename_ = filename;
3229
  unique_m_ =
3230
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
200,410✔
3231
  m_ = unique_m_.get();
200,410✔
3232
  m_->read(filename_);
3233
}
3234

3235
// build a libMesh equation system for storing values
3236
void LibMesh::build_eqn_sys()
1,002,050✔
3237
{
200,410✔
3238
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
200,410✔
3239
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3240
  libMesh::ExplicitSystem& eq_sys =
3241
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3242
}
200,410✔
3243

1,002,050✔
3244
// intialize from mesh file
801,640✔
3245
void LibMesh::initialize()
3246
{
3247
  if (!settings::libmesh_comm) {
400,820✔
3248
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3249
                "communicator.");
3250
  }
167,856✔
3251

3252
  // assuming that unstructured meshes used in OpenMC are 3D
167,856✔
3253
  n_dimension_ = 3;
167,856✔
3254

167,856✔
3255
  if (length_multiplier_ > 0.0) {
3256
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
3257
  }
3258
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
839,280✔
3259
  // Otherwise assume that it is prepared by its owning application
167,856✔
3260
  if (unique_m_) {
167,856✔
3261
    m_->prepare_for_use();
3262
  }
3263

3264
  // ensure that the loaded mesh is 3 dimensional
335,712✔
3265
  if (m_->mesh_dimension() != n_dimension_) {
167,856✔
3266
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3267
                            "mesh is not a 3D mesh.",
7,307,001✔
3268
      filename_));
3269
  }
7,307,001✔
3270

7,307,001✔
3271
  for (int i = 0; i < num_threads(); i++) {
1,012,923✔
3272
    pl_.emplace_back(m_->sub_point_locator());
3273
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
6,294,078✔
3274
    pl_.back()->enable_out_of_mesh_mode();
3275
  }
3276

3277
  // store first element in the mesh to use as an offset for bin indices
20✔
3278
  auto first_elem = *m_->elements_begin();
3279
  first_element_id_ = first_elem->id();
3280

3281
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
20✔
3282
  // contiguous in ID space, so we need to map from bin indices (defined over
20✔
3283
  // active elements) to global dof ids
3284
  if (adaptive_) {
3285
    bin_to_elem_map_.reserve(m_->n_active_elem());
3286
    elem_to_bin_map_.resize(m_->n_elem(), -1);
239,732✔
3287
    for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
239,712✔
3288
         it++) {
239,712✔
3289
      auto elem = *it;
239,712✔
3290

3291
      bin_to_elem_map_.push_back(elem->id());
3292
      elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3293
    }
1,198,560✔
3294
  }
239,712✔
3295

239,712✔
3296
  // bounding box for the mesh for quick rejection checks
3297
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3298
  libMesh::Point ll = bbox_.min();
3299
  libMesh::Point ur = bbox_.max();
239,712✔
3300
  lower_left_ = {ll(0), ll(1), ll(2)};
3301
  upper_right_ = {ur(0), ur(1), ur(2)};
3302
}
239,712✔
3303

239,712✔
3304
// Sample position within a tet for LibMesh type tets
239,712✔
3305
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
20✔
3306
{
3307
  const auto& elem = get_element_from_bin(bin);
260,007,978✔
3308
  // Get tet vertex coordinates from LibMesh
3309
  std::array<Position, 4> tet_verts;
3310
  for (int i = 0; i < elem.n_nodes(); i++) {
3311
    auto node_ref = elem.node_ref(i);
3312
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3313
  }
3314
  // Samples position within tet using Barycentric coordinates
260,007,978✔
3315
  return this->sample_tet(tet_verts, seed);
260,007,978✔
3316
}
260,007,978✔
3317

3318
Position LibMesh::centroid(int bin) const
3319
{
3320
  const auto& elem = this->get_element_from_bin(bin);
3321
  auto centroid = elem.vertex_average();
3322
  return {centroid(0), centroid(1), centroid(2)};
3323
}
260,007,978✔
3324

260,007,978✔
3325
int LibMesh::n_vertices() const
260,007,978✔
3326
{
3327
  return m_->n_nodes();
3328
}
3329

3330
Position LibMesh::vertex(int vertex_id) const
3331
{
3332
  const auto node_ref = m_->node_ref(vertex_id);
3333
  return {node_ref(0), node_ref(1), node_ref(2)};
260,007,978✔
3334
}
260,007,978✔
3335

3336
std::vector<int> LibMesh::connectivity(int elem_id) const
260,007,978✔
3337
{
3338
  std::vector<int> conn;
421,084,473✔
3339
  const auto* elem_ptr = m_->elem_ptr(elem_id);
442,748,125✔
3340
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
281,671,630✔
3341
    conn.push_back(elem_ptr->node_id(i));
260,007,978✔
3342
  }
3343
  return conn;
3344
}
3345

3346
std::string LibMesh::library() const
3347
{
3348
  return mesh_lib_type;
3349
}
3350

3351
int LibMesh::n_bins() const
3352
{
3353
  return m_->n_active_elem();
3354
}
3355

3356
int LibMesh::n_surface_bins() const
3357
{
3358
  int n_bins = 0;
3359
  for (int i = 0; i < this->n_bins(); i++) {
3360
    const libMesh::Elem& e = get_element_from_bin(i);
3361
    n_bins += e.n_faces();
3362
    // if this is a boundary element, it will only be visited once,
3363
    // the number of surface bins is incremented to
3364
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3365
      // null neighbor pointer indicates a boundary face
3366
      if (!neighbor_ptr) {
3367
        n_bins++;
3368
      }
3369
    }
3370
  }
815,424✔
3371
  return n_bins;
3372
}
815,424✔
3373

815,424✔
3374
void LibMesh::add_score(const std::string& var_name)
3375
{
3376
  if (adaptive_) {
3377
    warning(fmt::format(
815,424✔
3378
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3379
      this->id_));
3380

266,541,768✔
3381
    return;
3382
  }
266,541,768✔
3383

266,541,768✔
3384
  if (!equation_systems_) {
3385
    build_eqn_sys();
3386
  }
266,541,768✔
3387

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

3397
  std::string std_dev_name = var_name + "_std_dev";
267,317,815✔
3398
  // check if this is a new variable
3399
  if (!variable_map_.count(std_dev_name)) {
267,317,815✔
3400
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3401
    auto var_num =
3402
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3403
    variable_map_[std_dev_name] = var_num;
3404
  }
3405
}
3406

3407
void LibMesh::remove_scores()
3408
{
3409
  if (equation_systems_) {
3410
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3411
    eqn_sys.clear();
3412
    variable_map_.clear();
3413
  }
3414
}
3415

3416
void LibMesh::set_score_data(const std::string& var_name,
3417
  const vector<double>& values, const vector<double>& std_dev)
3418
{
3419
  if (adaptive_) {
3420
    warning(fmt::format(
3421
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3422
      this->id_));
3423

3424
    return;
3425
  }
3426

3427
  if (!equation_systems_) {
3428
    build_eqn_sys();
3429
  }
3430

3431
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3432

3433
  if (!eqn_sys.is_initialized()) {
3434
    equation_systems_->init();
3435
  }
3436

3437
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3438

3439
  // look up the value variable
3440
  std::string value_name = var_name + "_mean";
3441
  unsigned int value_num = variable_map_.at(value_name);
3442
  // look up the std dev variable
3443
  std::string std_dev_name = var_name + "_std_dev";
3444
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3445

3446
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3447
       it++) {
845,761✔
3448
    if (!(*it)->active()) {
3449
      continue;
845,761✔
3450
    }
3451

3452
    auto bin = get_bin_from_element(*it);
86,199✔
3453

3454
    // set value
3455
    vector<libMesh::dof_id_type> value_dof_indices;
3456
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3457
    assert(value_dof_indices.size() == 1);
86,199✔
3458
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3459

86,199✔
3460
    // set std dev
86,199✔
3461
    vector<libMesh::dof_id_type> std_dev_dof_indices;
86,199✔
3462
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3463
    assert(std_dev_dof_indices.size() == 1);
3464
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3465
  }
172,398✔
3466
}
3467

3468
void LibMesh::write(const std::string& filename) const
203,856✔
3469
{
3470
  if (adaptive_) {
3471
    warning(fmt::format(
3472
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
203,856✔
3473
      this->id_));
3474

3475
    return;
203,856✔
3476
  }
203,856✔
3477

203,856✔
3478
  write_message(fmt::format(
3479
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3480
  libMesh::ExodusII_IO exo(*m_);
3481
  std::set<std::string> systems_out = {eq_system_name_};
3482
  exo.write_discontinuous_exodusII(
203,856✔
3483
    filename + ".e", *equation_systems_, &systems_out);
1,019,280✔
3484
}
815,424✔
3485

3486
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3487
  vector<int>& bins, vector<double>& lengths) const
203,856✔
3488
{
203,856✔
3489
  // TODO: Implement triangle crossings here
3490
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3491
}
3492

3493
int LibMesh::get_bin(Position r) const
3494
{
3495
  // look-up a tet using the point locator
3496
  libMesh::Point p(r.x, r.y, r.z);
3497

3498
  // quick rejection check
3499
  if (!bbox_.contains_point(p)) {
3500
    return -1;
3501
  }
3502

3503
  const auto& point_locator = pl_.at(thread_num());
3504

3505
  const auto elem_ptr = (*point_locator)(p);
3506
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3507
}
3508

3509
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3510
{
3511
  int bin =
3512
    adaptive_ ? elem_to_bin_map_[elem->id()] : elem->id() - first_element_id_;
3513
  if (bin >= n_bins() || bin < 0) {
3514
    fatal_error(fmt::format("Invalid bin: {}", bin));
3515
  }
3516
  return bin;
3517
}
3518

3519
std::pair<vector<double>, vector<double>> LibMesh::plot(
3520
  Position plot_ll, Position plot_ur) const
3521
{
3522
  return {};
3523
}
3524

3525
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3526
{
3527
  return adaptive_ ? m_->elem_ref(bin_to_elem_map_.at(bin)) : m_->elem_ref(bin);
3528
}
3529

3530
double LibMesh::volume(int bin) const
3531
{
3532
  return this->get_element_from_bin(bin).volume();
3533
}
3534

3535
#endif // LIBMESH
3536

3537
//==============================================================================
3538
// Non-member functions
3539
//==============================================================================
3540

3541
void read_meshes(pugi::xml_node root)
3542
{
3543
  std::unordered_set<int> mesh_ids;
3544

3545
  for (auto node : root.children("mesh")) {
3546
    // Check to make sure multiple meshes in the same file don't share IDs
3547
    int id = std::stoi(get_node_value(node, "id"));
3548
    if (contains(mesh_ids, id)) {
3549
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
3550
                              "'{}' in the same input file",
3551
        id));
3552
    }
3553
    mesh_ids.insert(id);
3554

3555
    // If we've already read a mesh with the same ID in a *different* file,
3556
    // assume it is the same here
3557
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3558
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
3559
      continue;
3560
    }
3561

3562
    std::string mesh_type;
3563
    if (check_for_node(node, "type")) {
3564
      mesh_type = get_node_value(node, "type", true, true);
3565
    } else {
3566
      mesh_type = "regular";
3567
    }
3568

3569
    // determine the mesh library to use
3570
    std::string mesh_lib;
3571
    if (check_for_node(node, "library")) {
3572
      mesh_lib = get_node_value(node, "library", true, true);
3573
    }
3574

3575
    // Read mesh and add to vector
3576
    if (mesh_type == RegularMesh::mesh_type) {
3577
      model::meshes.push_back(make_unique<RegularMesh>(node));
3578
    } else if (mesh_type == RectilinearMesh::mesh_type) {
3579
      model::meshes.push_back(make_unique<RectilinearMesh>(node));
3580
    } else if (mesh_type == CylindricalMesh::mesh_type) {
3581
      model::meshes.push_back(make_unique<CylindricalMesh>(node));
3582
    } else if (mesh_type == SphericalMesh::mesh_type) {
3583
      model::meshes.push_back(make_unique<SphericalMesh>(node));
3584
#ifdef DAGMC
3585
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3586
               mesh_lib == MOABMesh::mesh_lib_type) {
3587
      model::meshes.push_back(make_unique<MOABMesh>(node));
3588
#endif
3589
#ifdef LIBMESH
3590
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3591
               mesh_lib == LibMesh::mesh_lib_type) {
3592
      model::meshes.push_back(make_unique<LibMesh>(node));
3593
#endif
3594
    } else if (mesh_type == UnstructuredMesh::mesh_type) {
3595
      fatal_error("Unstructured mesh support is not enabled or the mesh "
3596
                  "library is invalid.");
3597
    } else {
3598
      fatal_error("Invalid mesh type: " + mesh_type);
3599
    }
3600

3601
    // Map ID to position in vector
3602
    model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3603
  }
3604
}
3605

3606
void meshes_to_hdf5(hid_t group)
3607
{
3608
  // Write number of meshes
3609
  hid_t meshes_group = create_group(group, "meshes");
3610
  int32_t n_meshes = model::meshes.size();
3611
  write_attribute(meshes_group, "n_meshes", n_meshes);
3612

3613
  if (n_meshes > 0) {
3614
    // Write IDs of meshes
3615
    vector<int> ids;
3616
    for (const auto& m : model::meshes) {
3617
      m->to_hdf5(meshes_group);
3618
      ids.push_back(m->id_);
3619
    }
3620
    write_attribute(meshes_group, "ids", ids);
3621
  }
23✔
3622

3623
  close_group(meshes_group);
3624
}
3625

23✔
3626
void free_memory_mesh()
23✔
3627
{
23✔
3628
  model::meshes.clear();
23✔
3629
  model::mesh_map.clear();
3630
}
3631

3632
extern "C" int n_meshes()
3633
{
3634
  return model::meshes.size();
3635
}
3636

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

© 2026 Coveralls, Inc