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

openmc-dev / openmc / 12601844593

03 Jan 2025 06:01PM UTC coverage: 84.823% (-0.003%) from 84.826%
12601844593

Pull #3129

github

web-flow
Merge 7fc29c9d4 into 775c41512
Pull Request #3129: Compute material volumes in mesh elements based on raytracing

194 of 220 new or added lines in 4 files covered. (88.18%)

1044 existing lines in 27 files now uncovered.

49959 of 58898 relevant lines covered (84.82%)

33907140.98 hits per line

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

87.26
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cmath>     // for ceil
4
#include <cstddef>   // for size_t
5
#include <gsl/gsl-lite.hpp>
6
#include <string>
7

8
#ifdef OPENMC_MPI
9
#include "mpi.h"
10
#endif
11

12
#include "xtensor/xadapt.hpp"
13
#include "xtensor/xbuilder.hpp"
14
#include "xtensor/xeval.hpp"
15
#include "xtensor/xmath.hpp"
16
#include "xtensor/xsort.hpp"
17
#include "xtensor/xtensor.hpp"
18
#include "xtensor/xview.hpp"
19
#include <fmt/core.h> // for fmt
20

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

45
#ifdef LIBMESH
46
#include "libmesh/mesh_modification.h"
47
#include "libmesh/mesh_tools.h"
48
#include "libmesh/numeric_vector.h"
49
#endif
50

51
#ifdef DAGMC
52
#include "moab/FileOptions.hpp"
53
#endif
54

55
namespace openmc {
56

57
//==============================================================================
58
// Global variables
59
//==============================================================================
60

61
#ifdef LIBMESH
62
const bool LIBMESH_ENABLED = true;
63
#else
64
const bool LIBMESH_ENABLED = false;
65
#endif
66

67
namespace model {
68

69
std::unordered_map<int32_t, int32_t> mesh_map;
70
vector<unique_ptr<Mesh>> meshes;
71

72
} // namespace model
73

74
#ifdef LIBMESH
75
namespace settings {
76
unique_ptr<libMesh::LibMeshInit> libmesh_init;
77
const libMesh::Parallel::Communicator* libmesh_comm {nullptr};
78
} // namespace settings
79
#endif
80

81
//==============================================================================
82
// Helper functions
83
//==============================================================================
84

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

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

108
//==============================================================================
109
// MaterialVolumes implementation
110
//==============================================================================
111

112
namespace detail {
113

114
void MaterialVolumes::add_volume(
2,475,156✔
115
  int index_elem, int index_material, double volume)
116
{
117
  int i;
118
#pragma omp critical(MeshMatVol)
2,475,156✔
119
  for (i = 0; i < n_mats_; ++i) {
4,142,814✔
120
    // Check whether material already is present
121
    if (this->materials(index_elem, i) == index_material)
4,142,814✔
122
      break;
2,473,788✔
123

124
    // If not already present, check for unused position (-2)
125
    if (this->materials(index_elem, i) == -2) {
1,669,026✔
126
      this->materials(index_elem, i) = index_material;
1,368✔
127
      break;
1,368✔
128
    }
129
  }
130

131
  // If maximum number of materials exceeded, set a flag that can be checked
132
  // later
133
  if (i >= n_mats_) {
2,475,156✔
NEW
134
    too_many_mats_ = true;
×
NEW
135
    return;
×
136
  }
137

138
  // Accumulate volume
139
#pragma omp atomic
1,237,612✔
140
  this->volumes(index_elem, i) += volume;
2,475,156✔
141
}
142

143
// Same as add_volume above, but without the OpenMP critical/atomic section
NEW
144
void MaterialVolumes::add_volume_unsafe(
×
145
  int index_elem, int index_material, double volume)
146
{
147
  int i;
NEW
148
  for (i = 0; i < n_mats_; ++i) {
×
149
    // Check whether material already is present
NEW
150
    if (this->materials(index_elem, i) == index_material)
×
NEW
151
      break;
×
152

153
    // If not already present, check for unused position (-2)
NEW
154
    if (this->materials(index_elem, i) == -2) {
×
NEW
155
      this->materials(index_elem, i) = index_material;
×
NEW
156
      break;
×
157
    }
158
  }
159

160
  // If maximum number of materials exceeded, set a flag that can be checked
161
  // later
NEW
162
  if (i >= n_mats_) {
×
NEW
163
    too_many_mats_ = true;
×
NEW
164
    return;
×
165
  }
166

167
  // Accumulate volume
NEW
168
  this->volumes(index_elem, i) += volume;
×
169
}
170

171
} // namespace detail
172

173
//==============================================================================
174
// Mesh implementation
175
//==============================================================================
176

177
Mesh::Mesh(pugi::xml_node node)
2,792✔
178
{
179
  // Read mesh id
180
  id_ = std::stoi(get_node_value(node, "id"));
2,792✔
181
  if (check_for_node(node, "name"))
2,792✔
182
    name_ = get_node_value(node, "name");
17✔
183
}
2,792✔
184

185
void Mesh::set_id(int32_t id)
1✔
186
{
187
  Expects(id >= 0 || id == C_NONE);
1✔
188

189
  // Clear entry in mesh map in case one was already assigned
190
  if (id_ != C_NONE) {
1✔
UNCOV
191
    model::mesh_map.erase(id_);
×
UNCOV
192
    id_ = C_NONE;
×
193
  }
194

195
  // Ensure no other mesh has the same ID
196
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
1✔
UNCOV
197
    throw std::runtime_error {
×
UNCOV
198
      fmt::format("Two meshes have the same ID: {}", id)};
×
199
  }
200

201
  // If no ID is specified, auto-assign the next ID in the sequence
202
  if (id == C_NONE) {
1✔
203
    id = 0;
1✔
204
    for (const auto& m : model::meshes) {
3✔
205
      id = std::max(id, m->id_);
2✔
206
    }
207
    ++id;
1✔
208
  }
209

210
  // Update ID and entry in the mesh map
211
  id_ = id;
1✔
212
  model::mesh_map[id] = model::meshes.size() - 1;
1✔
213
}
1✔
214

215
vector<double> Mesh::volumes() const
156✔
216
{
217
  vector<double> volumes(n_bins());
156✔
218
  for (int i = 0; i < n_bins(); i++) {
982,476✔
219
    volumes[i] = this->volume(i);
982,320✔
220
  }
221
  return volumes;
156✔
NEW
222
}
×
223

224
void Mesh::material_volumes(int nx, int ny, int nz, int max_materials,
156✔
225
  int32_t* materials, double* volumes) const
226
{
227
  if (mpi::master) {
156✔
228
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
156✔
229
  }
230
  write_message(7, "Number of rays (x) = {}", nx);
156✔
231
  write_message(7, "Number of rays (y) = {}", ny);
156✔
232
  write_message(7, "Number of rays (z) = {}", nz);
156✔
233
  int64_t n_total = nx * ny + ny * nz + nx * nz;
156✔
234
  write_message(7, "Total number of rays = {}", n_total);
156✔
235
  write_message(
156✔
236
    7, "Maximum number of materials per mesh element = {}", max_materials);
237

238
  Timer timer;
156✔
239
  timer.start();
156✔
240

241
  // Create object for keeping track of materials/volumes
242
  detail::MaterialVolumes result(materials, volumes, max_materials);
156✔
243

244
  // Determine bounding box
245
  auto bbox = this->bounding_box();
156✔
246

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

249
  // Determine effective width of rays
250
  Position width((bbox.xmax - bbox.xmin) / nx, (bbox.ymax - bbox.ymin) / ny,
156✔
251
    (bbox.zmax - bbox.zmin) / nz);
156✔
252

253
  // Set flag for mesh being contained within model
254
  bool out_of_model = false;
156✔
255

256
#pragma omp parallel
78✔
257
  {
258
    // Preallocate vector for mesh indices and lenght fractions and p
259
    std::vector<int> bins;
78✔
260
    std::vector<double> length_fractions;
78✔
261
    Particle p;
78✔
262

263
    SourceSite site;
78✔
264
    site.E = 1.0;
78✔
265
    site.particle = ParticleType::neutron;
78✔
266

267
    for (int axis = 0; axis < 3; ++axis) {
312✔
268
      // Set starting position and direction
269
      site.r = {0.0, 0.0, 0.0};
234✔
270
      site.r[axis] = bbox.min()[axis];
234✔
271
      site.u = {0.0, 0.0, 0.0};
234✔
272
      site.u[axis] = 1.0;
234✔
273

274
      // Determine width of rays and number of rays in other directions
275
      int ax1 = (axis + 1) % 3;
234✔
276
      int ax2 = (axis + 2) % 3;
234✔
277
      double min1 = bbox.min()[ax1];
234✔
278
      double min2 = bbox.min()[ax2];
234✔
279
      double d1 = width[ax1];
234✔
280
      double d2 = width[ax2];
234✔
281
      int n1 = n_rays[ax1];
234✔
282
      int n2 = n_rays[ax2];
234✔
283

284
      // Divide rays in first direction over MPI processes by computing starting
285
      // and ending indices
286
      int min_work = n1 / mpi::n_procs;
234✔
287
      int remainder = n1 % mpi::n_procs;
234✔
288
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
234✔
289
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
234✔
290
      int i1_end = i1_start + n1_local;
234✔
291

292
      // Loop over rays on face of bounding box
293
#pragma omp for collapse(2)
294
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
9,924✔
295
        for (int i2 = 0; i2 < n2; ++i2) {
503,964✔
296
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
494,274✔
297
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
494,274✔
298

299
          p.from_source(&site);
494,274✔
300

301
          // Determine particle's location
302
          if (!exhaustive_find_cell(p)) {
494,274✔
303
            out_of_model = true;
47,916✔
304
            continue;
47,916✔
305
          }
306

307
          // Set birth cell attribute
308
          if (p.cell_born() == C_NONE)
446,358✔
309
            p.cell_born() = p.lowest_coord().cell;
446,358✔
310

311
          // Initialize last cells from current cell
312
          for (int j = 0; j < p.n_coord(); ++j) {
892,716✔
313
            p.cell_last(j) = p.coord(j).cell;
446,358✔
314
          }
315
          p.n_coord_last() = p.n_coord();
446,358✔
316

317
          while (true) {
318
            // Ray trace from r_start to r_end
319
            Position r0 = p.r();
973,974✔
320
            double max_distance = bbox.max()[axis] - r0[axis];
973,974✔
321

322
            // Find the distance to the nearest boundary
323
            BoundaryInfo boundary = distance_to_boundary(p);
973,974✔
324

325
            // Advance particle forward
326
            double distance = std::min(boundary.distance, max_distance);
973,974✔
327
            p.move_distance(distance);
973,974✔
328

329
            // Determine what mesh elements were crossed by particle
330
            bins.clear();
973,974✔
331
            length_fractions.clear();
973,974✔
332
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
973,974✔
333

334
            // Add volumes to any mesh elements that were crossed
335
            int i_material = p.material();
973,974✔
336
            if (i_material != C_NONE) {
973,974✔
337
              i_material = model::materials[i_material]->id();
939,858✔
338
            }
339
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
2,211,552✔
340
              int mesh_index = bins[i_bin];
1,237,578✔
341
              double length = distance * length_fractions[i_bin];
1,237,578✔
342

343
              // Add volume to result
344
              result.add_volume(mesh_index, i_material, length * d1 * d2);
1,237,578✔
345
            }
346

347
            if (distance == max_distance)
973,974✔
348
              break;
446,358✔
349

350
            for (int j = 0; j < p.n_coord(); ++j) {
1,055,232✔
351
              p.cell_last(j) = p.coord(j).cell;
527,616✔
352
            }
353
            p.n_coord_last() = p.n_coord();
527,616✔
354

355
            // Set surface that particle is on and adjust coordinate levels
356
            p.surface() = boundary.surface_index;
527,616✔
357
            p.n_coord() = boundary.coord_level;
527,616✔
358

359
            if (boundary.lattice_translation[0] != 0 ||
527,616✔
360
                boundary.lattice_translation[1] != 0 ||
1,055,232✔
361
                boundary.lattice_translation[2] != 0) {
527,616✔
362
              // Particle crosses lattice boundary
363

364
              cross_lattice(p, boundary);
365
            } else {
366
              // Particle crosses surface
367
              // TODO: off-by-one
368
              const auto& surf {
369
                model::surfaces[std::abs(p.surface()) - 1].get()};
527,616✔
370
              p.cross_surface(*surf);
527,616✔
371
            }
372
          }
527,616✔
373
        }
374
      }
375
    }
376
  }
78✔
377

378
  // Check for errors
379
  if (out_of_model) {
156✔
380
    throw std::runtime_error("Mesh not fully contained in geometry.");
12✔
381
  } else if (result.too_many_mats()) {
144✔
UNCOV
382
    throw std::runtime_error("Maximum number of materials for mesh material "
×
UNCOV
383
                             "volume calculation insufficient.");
×
384
  }
385

386
  // Compute time for raytracing
387
  double t_raytrace = timer.elapsed();
144✔
388

389
#ifdef OPENMC_MPI
390
  // Combine results from multiple MPI processes
391
  if (mpi::n_procs > 1) {
60✔
392
    int total = this->n_bins() * max_materials;
393
    if (mpi::master) {
394
      // Allocate temporary buffer for receiving data
395
      std::vector<int32_t> mats(total);
396
      std::vector<double> vols(total);
397

398
      for (int i = 1; i < mpi::n_procs; ++i) {
399
        // Receive material indices and volumes from process i
400
        MPI_Recv(
401
          mats.data(), total, MPI_INT, i, i, mpi::intracomm, MPI_STATUS_IGNORE);
402
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
403
          MPI_STATUS_IGNORE);
404

405
        // Combine with existing results; we can call thread unsafe version of
406
        // add_volume because each thread is operating on a different element
407
#pragma omp for
408
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
409
          for (int k = 0; k < max_materials; ++k) {
410
            int index = index_elem * max_materials + k;
411
            result.add_volume_unsafe(index_elem, mats[index], vols[index]);
412
          }
413
        }
414
      }
415
    } else {
416
      // Send material indices and volumes to process 0
417
      MPI_Send(materials, total, MPI_INT, 0, mpi::rank, mpi::intracomm);
418
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
419
    }
420
  }
421

422
  // Report time for MPI communication
423
  double t_mpi = timer.elapsed() - t_raytrace;
60✔
424
#else
425
  double t_mpi = 0.0;
84✔
426
#endif
427

428
  // Normalize based on known volumes of elements
429
  for (int i = 0; i < this->n_bins(); ++i) {
1,020✔
430
    // Estimated total volume in element i
431
    double volume = 0.0;
876✔
432
    for (int j = 0; j < max_materials; ++j) {
4,380✔
433
      volume += result.volumes(i, j);
3,504✔
434
    }
435

436
    // Renormalize volumes based on known volume of element i
437
    double norm = this->volume(i) / volume;
876✔
438
    for (int j = 0; j < max_materials; ++j) {
4,380✔
439
      result.volumes(i, j) *= norm;
3,504✔
440
    }
441
  }
442

443
  // Show elapsed time
444
  timer.stop();
144✔
445
  double t_total = timer.elapsed();
144✔
446
  double t_normalize = t_total - t_raytrace - t_mpi;
144✔
447
  if (mpi::master) {
144✔
448
    header("Timing Statistics", 7);
144✔
449
    show_time("Total time elapsed", t_total);
144✔
450
    show_time("Ray tracing", t_raytrace, 1);
144✔
451
    show_time("Ray tracing (per ray)", t_raytrace / n_total, 1);
144✔
452
    show_time("MPI communication", t_mpi, 1);
144✔
453
    show_time("Normalization", t_normalize, 1);
144✔
454
  }
455
}
144✔
456

457
void Mesh::to_hdf5(hid_t group) const
2,988✔
458
{
459
  // Create group for mesh
460
  std::string group_name = fmt::format("mesh {}", id_);
5,410✔
461
  hid_t mesh_group = create_group(group, group_name.c_str());
2,988✔
462

463
  // Write mesh type
464
  write_attribute(mesh_group, "type", this->get_mesh_type());
2,988✔
465

466
  // Write mesh ID
467
  write_attribute(mesh_group, "id", id_);
2,988✔
468

469
  // Write mesh name
470
  write_dataset(mesh_group, "name", name_);
2,988✔
471

472
  // Write mesh data
473
  this->to_hdf5_inner(mesh_group);
2,988✔
474

475
  // Close group
476
  close_group(mesh_group);
2,988✔
477
}
2,988✔
478

479
//==============================================================================
480
// Structured Mesh implementation
481
//==============================================================================
482

483
std::string StructuredMesh::bin_label(int bin) const
5,435,076✔
484
{
485
  MeshIndex ijk = get_indices_from_bin(bin);
5,435,076✔
486

487
  if (n_dimension_ > 2) {
5,435,076✔
488
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,837,800✔
489
  } else if (n_dimension_ > 1) {
16,176✔
490
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
31,752✔
491
  } else {
492
    return fmt::format("Mesh Index ({})", ijk[0]);
600✔
493
  }
494
}
495

496
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,922✔
497
{
498
  // because method is const, shape_ is const as well and can't be adapted
499
  auto tmp_shape = shape_;
2,922✔
500
  return xt::adapt(tmp_shape, {n_dimension_});
5,844✔
501
}
502

503
Position StructuredMesh::sample_element(
1,542,372✔
504
  const MeshIndex& ijk, uint64_t* seed) const
505
{
506
  // lookup the lower/upper bounds for the mesh element
507
  double x_min = negative_grid_boundary(ijk, 0);
1,542,372✔
508
  double x_max = positive_grid_boundary(ijk, 0);
1,542,372✔
509

510
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,542,372✔
511
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,542,372✔
512

513
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,542,372✔
514
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,542,372✔
515

516
  return {x_min + (x_max - x_min) * prn(seed),
1,542,372✔
517
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,542,372✔
518
}
519

520
//==============================================================================
521
// Unstructured Mesh implementation
522
//==============================================================================
523

524
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
45✔
525
{
526

527
  // check the mesh type
528
  if (check_for_node(node, "type")) {
45✔
529
    auto temp = get_node_value(node, "type", true, true);
45✔
530
    if (temp != mesh_type) {
45✔
UNCOV
531
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
532
    }
533
  }
45✔
534

535
  // check if a length unit multiplier was specified
536
  if (check_for_node(node, "length_multiplier")) {
45✔
UNCOV
537
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
538
  }
539

540
  // get the filename of the unstructured mesh to load
541
  if (check_for_node(node, "filename")) {
45✔
542
    filename_ = get_node_value(node, "filename");
45✔
543
    if (!file_exists(filename_)) {
45✔
UNCOV
544
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
545
    }
546
  } else {
UNCOV
547
    fatal_error(fmt::format(
×
UNCOV
548
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
549
  }
550

551
  if (check_for_node(node, "options")) {
45✔
552
    options_ = get_node_value(node, "options");
16✔
553
  }
554

555
  // check if mesh tally data should be written with
556
  // statepoint files
557
  if (check_for_node(node, "output")) {
45✔
UNCOV
558
    output_ = get_node_value_bool(node, "output");
×
559
  }
560
}
45✔
561

562
void UnstructuredMesh::determine_bounds()
23✔
563
{
564
  double xmin = INFTY;
23✔
565
  double ymin = INFTY;
23✔
566
  double zmin = INFTY;
23✔
567
  double xmax = -INFTY;
23✔
568
  double ymax = -INFTY;
23✔
569
  double zmax = -INFTY;
23✔
570
  int n = this->n_vertices();
23✔
571
  for (int i = 0; i < n; ++i) {
53,604✔
572
    auto v = this->vertex(i);
53,581✔
573
    xmin = std::min(v.x, xmin);
53,581✔
574
    ymin = std::min(v.y, ymin);
53,581✔
575
    zmin = std::min(v.z, zmin);
53,581✔
576
    xmax = std::max(v.x, xmax);
53,581✔
577
    ymax = std::max(v.y, ymax);
53,581✔
578
    zmax = std::max(v.z, zmax);
53,581✔
579
  }
580
  lower_left_ = {xmin, ymin, zmin};
23✔
581
  upper_right_ = {xmax, ymax, zmax};
23✔
582
}
23✔
583

584
Position UnstructuredMesh::sample_tet(
601,230✔
585
  std::array<Position, 4> coords, uint64_t* seed) const
586
{
587
  // Uniform distribution
588
  double s = prn(seed);
601,230✔
589
  double t = prn(seed);
601,230✔
590
  double u = prn(seed);
601,230✔
591

592
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
593
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
594
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
595
  if (s + t > 1) {
601,230✔
596
    s = 1.0 - s;
301,245✔
597
    t = 1.0 - t;
301,245✔
598
  }
599
  if (s + t + u > 1) {
601,230✔
600
    if (t + u > 1) {
400,908✔
601
      double old_t = t;
199,920✔
602
      t = 1.0 - u;
199,920✔
603
      u = 1.0 - s - old_t;
199,920✔
604
    } else if (t + u <= 1) {
200,988✔
605
      double old_s = s;
200,988✔
606
      s = 1.0 - t - u;
200,988✔
607
      u = old_s + t + u - 1;
200,988✔
608
    }
609
  }
610
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
611
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
612
}
613

614
const std::string UnstructuredMesh::mesh_type = "unstructured";
615

616
std::string UnstructuredMesh::get_mesh_type() const
30✔
617
{
618
  return mesh_type;
30✔
619
}
620

UNCOV
621
void UnstructuredMesh::surface_bins_crossed(
×
622
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
623
{
UNCOV
624
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
625
}
626

627
std::string UnstructuredMesh::bin_label(int bin) const
193,712✔
628
{
629
  return fmt::format("Mesh Index ({})", bin);
193,712✔
630
};
631

632
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
30✔
633
{
634
  write_dataset(mesh_group, "filename", filename_);
30✔
635
  write_dataset(mesh_group, "library", this->library());
30✔
636
  if (!options_.empty()) {
30✔
637
    write_attribute(mesh_group, "options", options_);
8✔
638
  }
639

640
  if (length_multiplier_ > 0.0)
30✔
UNCOV
641
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
642

643
  // write vertex coordinates
644
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
30✔
645
  for (int i = 0; i < this->n_vertices(); i++) {
67,928✔
646
    auto v = this->vertex(i);
67,898✔
647
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
67,898✔
648
  }
649
  write_dataset(mesh_group, "vertices", vertices);
30✔
650

651
  int num_elem_skipped = 0;
30✔
652

653
  // write element types and connectivity
654
  vector<double> volumes;
30✔
655
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
30✔
656
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
30✔
657
  for (int i = 0; i < this->n_bins(); i++) {
337,742✔
658
    auto conn = this->connectivity(i);
337,712✔
659

660
    volumes.emplace_back(this->volume(i));
337,712✔
661

662
    // write linear tet element
663
    if (conn.size() == 4) {
337,712✔
664
      xt::view(elem_types, i, xt::all()) =
671,424✔
665
        static_cast<int>(ElementType::LINEAR_TET);
671,424✔
666
      xt::view(connectivity, i, xt::all()) =
671,424✔
667
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,007,136✔
668
      // write linear hex element
669
    } else if (conn.size() == 8) {
2,000✔
670
      xt::view(elem_types, i, xt::all()) =
4,000✔
671
        static_cast<int>(ElementType::LINEAR_HEX);
4,000✔
672
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000✔
673
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000✔
674
    } else {
UNCOV
675
      num_elem_skipped++;
×
UNCOV
676
      xt::view(elem_types, i, xt::all()) =
×
677
        static_cast<int>(ElementType::UNSUPPORTED);
UNCOV
678
      xt::view(connectivity, i, xt::all()) = -1;
×
679
    }
680
  }
337,712✔
681

682
  // warn users that some elements were skipped
683
  if (num_elem_skipped > 0) {
30✔
UNCOV
684
    warning(fmt::format("The connectivity of {} elements "
×
685
                        "on mesh {} were not written "
686
                        "because they are not of type linear tet/hex.",
687
      num_elem_skipped, this->id_));
×
688
  }
689

690
  write_dataset(mesh_group, "volumes", volumes);
30✔
691
  write_dataset(mesh_group, "connectivity", connectivity);
30✔
692
  write_dataset(mesh_group, "element_types", elem_types);
30✔
693
}
30✔
694

695
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
696
{
697
  length_multiplier_ = length_multiplier;
23✔
698
}
23✔
699

700
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
701
{
702
  auto conn = connectivity(bin);
120,000✔
703

704
  if (conn.size() == 4)
120,000✔
705
    return ElementType::LINEAR_TET;
120,000✔
UNCOV
706
  else if (conn.size() == 8)
×
UNCOV
707
    return ElementType::LINEAR_HEX;
×
708
  else
UNCOV
709
    return ElementType::UNSUPPORTED;
×
710
}
120,000✔
711

712
StructuredMesh::MeshIndex StructuredMesh::get_indices(
944,052,110✔
713
  Position r, bool& in_mesh) const
714
{
715
  MeshIndex ijk;
716
  in_mesh = true;
944,052,110✔
717
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
718
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
719

720
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
721
      in_mesh = false;
91,752,208✔
722
  }
723
  return ijk;
944,052,110✔
724
}
725

726
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
998,360,564✔
727
{
728
  switch (n_dimension_) {
998,360,564✔
729
  case 1:
956,736✔
730
    return ijk[0] - 1;
956,736✔
731
  case 2:
21,602,040✔
732
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
21,602,040✔
733
  case 3:
975,801,788✔
734
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
975,801,788✔
UNCOV
735
  default:
×
UNCOV
736
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
737
  }
738
}
739

740
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,057,604✔
741
{
742
  MeshIndex ijk;
743
  if (n_dimension_ == 1) {
8,057,604✔
744
    ijk[0] = bin + 1;
300✔
745
  } else if (n_dimension_ == 2) {
8,057,304✔
746
    ijk[0] = bin % shape_[0] + 1;
15,876✔
747
    ijk[1] = bin / shape_[0] + 1;
15,876✔
748
  } else if (n_dimension_ == 3) {
8,041,428✔
749
    ijk[0] = bin % shape_[0] + 1;
8,041,428✔
750
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,041,428✔
751
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,041,428✔
752
  }
753
  return ijk;
8,057,604✔
754
}
755

756
int StructuredMesh::get_bin(Position r) const
318,449,702✔
757
{
758
  // Determine indices
759
  bool in_mesh;
760
  MeshIndex ijk = get_indices(r, in_mesh);
318,449,702✔
761
  if (!in_mesh)
318,449,702✔
762
    return -1;
22,164,978✔
763

764
  // Convert indices to bin
765
  return get_bin_from_indices(ijk);
296,284,724✔
766
}
767

768
int StructuredMesh::n_bins() const
1,000,946✔
769
{
770
  return std::accumulate(
1,000,946✔
771
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,001,892✔
772
}
773

774
int StructuredMesh::n_surface_bins() const
578✔
775
{
776
  return 4 * n_dimension_ * n_bins();
578✔
777
}
778

779
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
780
  const SourceSite* bank, int64_t length, bool* outside) const
781
{
782
  // Determine shape of array for counts
UNCOV
783
  std::size_t m = this->n_bins();
×
784
  vector<std::size_t> shape = {m};
×
785

786
  // Create array of zeros
UNCOV
787
  xt::xarray<double> cnt {shape, 0.0};
×
UNCOV
788
  bool outside_ = false;
×
789

790
  for (int64_t i = 0; i < length; i++) {
×
791
    const auto& site = bank[i];
×
792

793
    // determine scoring bin for entropy mesh
UNCOV
794
    int mesh_bin = get_bin(site.r);
×
795

796
    // if outside mesh, skip particle
UNCOV
797
    if (mesh_bin < 0) {
×
UNCOV
798
      outside_ = true;
×
UNCOV
799
      continue;
×
800
    }
801

802
    // Add to appropriate bin
UNCOV
803
    cnt(mesh_bin) += site.wgt;
×
804
  }
805

806
  // Create copy of count data. Since ownership will be acquired by xtensor,
807
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
808
  // warnings.
809
  int total = cnt.size();
×
810
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
811

812
#ifdef OPENMC_MPI
813
  // collect values from all processors
814
  MPI_Reduce(
815
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
816

817
  // Check if there were sites outside the mesh for any processor
818
  if (outside) {
819
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
820
  }
821
#else
822
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
823
  if (outside)
824
    *outside = outside_;
825
#endif
826

827
  // Adapt reduced values in array back into an xarray
UNCOV
828
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
UNCOV
829
  xt::xarray<double> counts = arr;
×
830

UNCOV
831
  return counts;
×
832
}
833

834
// raytrace through the mesh. The template class T will do the tallying.
835
// A modern optimizing compiler can recognize the noop method of T and
836
// eliminate that call entirely.
837
template<class T>
838
void StructuredMesh::raytrace_mesh(
625,682,220✔
839
  Position r0, Position r1, const Direction& u, T tally) const
840
{
841
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
842
  // enable/disable tally calls for now, T template type needs to provide both
843
  // surface and track methods, which might be empty. modern optimizing
844
  // compilers will (hopefully) eliminate the complete code (including
845
  // calculation of parameters) but for the future: be explicit
846

847
  // Compute the length of the entire track.
848
  double total_distance = (r1 - r0).norm();
625,682,220✔
849
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
625,682,220✔
850
    return;
5,711,856✔
851

852
  const int n = n_dimension_;
619,970,364✔
853

854
  // Flag if position is inside the mesh
855
  bool in_mesh;
856

857
  // Position is r = r0 + u * traveled_distance, start at r0
858
  double traveled_distance {0.0};
619,970,364✔
859

860
  // Calculate index of current cell. Offset the position a tiny bit in
861
  // direction of flight
862
  MeshIndex ijk = get_indices(r0 + TINY_BIT * u, in_mesh);
619,970,364✔
863

864
  // if track is very short, assume that it is completely inside one cell.
865
  // Only the current cell will score and no surfaces
866
  if (total_distance < 2 * TINY_BIT) {
619,970,364✔
867
    if (in_mesh) {
12✔
UNCOV
868
      tally.track(ijk, 1.0);
×
869
    }
870
    return;
12✔
871
  }
872

873
  // translate start and end positions,
874
  // this needs to come after the get_indices call because it does its own
875
  // translation
876
  local_coords(r0);
619,970,352✔
877
  local_coords(r1);
619,970,352✔
878

879
  // Calculate initial distances to next surfaces in all three dimensions
880
  std::array<MeshDistance, 3> distances;
1,239,940,704✔
881
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
882
    distances[k] = distance_to_grid_boundary(ijk, k, r0, u, 0.0);
1,841,879,016✔
883
  }
884

885
  // Loop until r = r1 is eventually reached
886
  while (true) {
353,982,463✔
887

888
    if (in_mesh) {
973,952,815✔
889

890
      // find surface with minimal distance to current position
891
      const auto k = std::min_element(distances.begin(), distances.end()) -
882,783,396✔
892
                     distances.begin();
882,783,396✔
893

894
      // Tally track length delta since last step
895
      tally.track(ijk,
882,783,396✔
896
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
882,783,396✔
897
          total_distance);
898

899
      // update position and leave, if we have reached end position
900
      traveled_distance = distances[k].distance;
882,783,396✔
901
      if (traveled_distance >= total_distance)
882,783,396✔
902
        return;
534,432,977✔
903

904
      // If we have not reached r1, we have hit a surface. Tally outward
905
      // current
906
      tally.surface(ijk, k, distances[k].max_surface, false);
348,350,419✔
907

908
      // Update cell and calculate distance to next surface in k-direction.
909
      // The two other directions are still valid!
910
      ijk[k] = distances[k].next_index;
348,350,419✔
911
      distances[k] =
348,350,419✔
912
        distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
348,350,419✔
913

914
      // Check if we have left the interior of the mesh
915
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
348,350,419✔
916

917
      // If we are still inside the mesh, tally inward current for the next
918
      // cell
919
      if (in_mesh)
348,350,419✔
920
        tally.surface(ijk, k, !distances[k].max_surface, true);
324,617,066✔
921

922
    } else { // not inside mesh
923

924
      // For all directions outside the mesh, find the distance that we need
925
      // to travel to reach the next surface. Use the largest distance, as
926
      // only this will cross all outer surfaces.
927
      int k_max {0};
91,169,419✔
928
      for (int k = 0; k < n; ++k) {
362,336,203✔
929
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
363,678,777✔
930
            (distances[k].distance > traveled_distance)) {
92,511,993✔
931
          traveled_distance = distances[k].distance;
91,726,233✔
932
          k_max = k;
91,726,233✔
933
        }
934
      }
935

936
      // If r1 is not inside the mesh, exit here
937
      if (traveled_distance >= total_distance)
91,169,419✔
938
        return;
85,537,375✔
939

940
      // Calculate the new cell index and update all distances to next
941
      // surfaces.
942
      ijk = get_indices(r0 + (traveled_distance + TINY_BIT) * u, in_mesh);
5,632,044✔
943
      for (int k = 0; k < n; ++k) {
22,298,916✔
944
        distances[k] =
16,666,872✔
945
          distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
16,666,872✔
946
      }
947

948
      // If inside the mesh, Tally inward current
949
      if (in_mesh)
5,632,044✔
950
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
4,254,984✔
951
    }
952
  }
953
}
954

240,796,560✔
955
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
956
  vector<int>& bins, vector<double>& lengths) const
957
{
958

959
  // Helper tally class.
960
  // stores a pointer to the mesh class and references to bins and lengths
961
  // parameters. Performs the actual tally through the track method.
962
  struct TrackAggregator {
963
    TrackAggregator(
964
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
240,796,560✔
965
      : mesh(_mesh), bins(_bins), lengths(_lengths)
240,796,560✔
UNCOV
966
    {}
×
967
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
968
    void track(const MeshIndex& ijk, double l) const
240,796,560✔
969
    {
970
      bins.push_back(mesh->get_bin_from_indices(ijk));
971
      lengths.push_back(l);
972
    }
973

974
    const StructuredMesh* mesh;
240,796,560✔
975
    vector<int>& bins;
976
    vector<double>& lengths;
977
  };
978

240,796,560✔
979
  // Perform the mesh raytrace with the helper class.
980
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
981
}
982

240,796,560✔
UNCOV
983
void StructuredMesh::surface_bins_crossed(
×
UNCOV
984
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
×
985
{
UNCOV
986

×
987
  // Helper tally class.
988
  // stores a pointer to the mesh class and a reference to the bins parameter.
989
  // Performs the actual tally through the surface method.
990
  struct SurfaceAggregator {
991
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
992
      : mesh(_mesh), bins(_bins)
240,796,560✔
993
    {}
240,796,560✔
994
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
995
    {
996
      int i_bin =
481,593,120✔
997
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
961,350,096✔
998
      if (max)
720,553,536✔
999
        i_bin += 2;
1000
      if (inward)
1001
        i_bin += 1;
1002
      bins.push_back(i_bin);
59,608,296✔
1003
    }
1004
    void track(const MeshIndex& idx, double l) const {}
300,404,856✔
1005

1006
    const StructuredMesh* mesh;
1007
    vector<int>& bins;
297,433,236✔
1008
  };
297,433,236✔
1009

1010
  // Perform the mesh raytrace with the helper class.
1011
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
297,433,236✔
1012
}
297,433,236✔
1013

1014
//==============================================================================
1015
// RegularMesh implementation
1016
//==============================================================================
297,433,236✔
1017

297,433,236✔
1018
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
238,068,528✔
1019
{
1020
  // Determine number of dimensions for mesh
1021
  if (!check_for_node(node, "dimension")) {
1022
    fatal_error("Must specify <dimension> on a regular mesh.");
59,364,708✔
1023
  }
1024

1025
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
1026
  int n = n_dimension_ = shape.size();
59,364,708✔
1027
  if (n != 1 && n != 2 && n != 3) {
59,364,708✔
1028
    fatal_error("Mesh must be one, two, or three dimensions.");
59,364,708✔
1029
  }
1030
  std::copy(shape.begin(), shape.end(), shape_.begin());
1031

59,364,708✔
1032
  // Check that dimensions are all greater than zero
1033
  if (xt::any(shape <= 0)) {
1034
    fatal_error("All entries on the <dimension> element for a tally "
1035
                "mesh must be positive.");
59,364,708✔
1036
  }
57,142,380✔
1037

1038
  // Check for lower-left coordinates
1039
  if (check_for_node(node, "lower_left")) {
1040
    // Read mesh lower-left corner location
1041
    lower_left_ = get_node_xarray<double>(node, "lower_left");
1042
  } else {
1043
    fatal_error("Must specify <lower_left> on a mesh.");
2,971,620✔
1044
  }
11,535,180✔
1045

11,691,732✔
1046
  // Make sure lower_left and dimension match
3,128,172✔
1047
  if (shape.size() != lower_left_.size()) {
3,063,708✔
1048
    fatal_error("Number of entries on <lower_left> must be the same "
3,063,708✔
1049
                "as the number of entries on <dimension>.");
1050
  }
1051

1052
  if (check_for_node(node, "width")) {
1053
    // Make sure one of upper-right or width were specified
2,971,620✔
1054
    if (check_for_node(node, "upper_right")) {
2,728,032✔
1055
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
1056
    }
1057

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

860,256✔
1060
    // Check to ensure width has same dimensions
616,668✔
1061
    auto n = width_.size();
616,668✔
1062
    if (n != lower_left_.size()) {
1063
      fatal_error("Number of entries on <width> must be the same as "
1064
                  "the number of entries on <lower_left>.");
1065
    }
243,588✔
1066

218,592✔
1067
    // Check for negative widths
1068
    if (xt::any(width_ < 0.0)) {
1069
      fatal_error("Cannot have a negative <width> on a tally mesh.");
1070
    }
384,885,660✔
1071

1072
    // Set width and upper right coordinate
1073
    upper_right_ = xt::eval(lower_left_ + shape * width_);
1074

1075
  } else if (check_for_node(node, "upper_right")) {
1076
    upper_right_ = get_node_xarray<double>(node, "upper_right");
1077

1078
    // Check to ensure width has same dimensions
1079
    auto n = upper_right_.size();
1080
    if (n != lower_left_.size()) {
384,885,660✔
1081
      fatal_error("Number of entries on <upper_right> must be the "
384,885,660✔
1082
                  "same as the number of entries on <lower_left>.");
5,711,856✔
1083
    }
1084

379,173,804✔
1085
    // Check that upper-right is above lower-left
1086
    if (xt::any(upper_right_ < lower_left_)) {
1087
      fatal_error("The <upper_right> coordinates must be greater than "
1088
                  "the <lower_left> coordinates on a tally mesh.");
1089
    }
1090

379,173,804✔
1091
    // Set width
1092
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
1093
  } else {
1094
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
379,173,804✔
1095
  }
1096

1097
  // Set material volumes
1098
  volume_frac_ = 1.0 / xt::prod(shape)();
379,173,804✔
1099

12✔
UNCOV
1100
  element_volume_ = 1.0;
×
1101
  for (int i = 0; i < n_dimension_; i++) {
1102
    element_volume_ *= width_[i];
12✔
1103
  }
1104
}
1105

1106
int RegularMesh::get_index_in_direction(double r, int i) const
1107
{
1108
  return std::ceil((r - lower_left_[i]) / width_[i]);
379,173,792✔
1109
}
379,173,792✔
1110

1111
const std::string RegularMesh::mesh_type = "regular";
1112

758,347,584✔
1113
std::string RegularMesh::get_mesh_type() const
1,500,499,272✔
1114
{
1,121,325,480✔
1115
  return mesh_type;
1116
}
1117

1118
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
294,374,167✔
1119
{
1120
  return lower_left_[i] + ijk[i] * width_[i];
673,547,959✔
1121
}
1122

1123
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
585,350,160✔
1124
{
585,350,160✔
1125
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1126
}
1127

585,350,160✔
1128
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
585,350,160✔
1129
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1130
  double l) const
1131
{
1132
  MeshDistance d;
585,350,160✔
1133
  d.next_index = ijk[i];
585,350,160✔
1134
  if (std::abs(u[i]) < FP_PRECISION)
296,364,449✔
1135
    return d;
1136

1137
  d.max_surface = (u[i] > 0);
1138
  if (d.max_surface && (ijk[i] <= shape_[i])) {
288,985,711✔
1139
    d.next_index++;
1140
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1141
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1142
    d.next_index--;
288,985,711✔
1143
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
288,985,711✔
1144
  }
288,985,711✔
1145
  return d;
1146
}
1147

288,985,711✔
1148
std::pair<vector<double>, vector<double>> RegularMesh::plot(
1149
  Position plot_ll, Position plot_ur) const
1150
{
1151
  // Figure out which axes lie in the plane of the plot.
288,985,711✔
1152
  array<int, 2> axes {-1, -1};
267,474,686✔
1153
  if (plot_ur.z == plot_ll.z) {
1154
    axes[0] = 0;
1155
    if (n_dimension_ > 1)
1156
      axes[1] = 1;
1157
  } else if (plot_ur.y == plot_ll.y) {
1158
    axes[0] = 0;
1159
    if (n_dimension_ > 2)
88,197,799✔
1160
      axes[1] = 2;
350,801,023✔
1161
  } else if (plot_ur.x == plot_ll.x) {
351,987,045✔
1162
    if (n_dimension_ > 1)
89,383,821✔
1163
      axes[0] = 1;
88,662,525✔
1164
    if (n_dimension_ > 2)
88,662,525✔
1165
      axes[1] = 2;
1166
  } else {
1167
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1168
  }
1169

88,197,799✔
1170
  // Get the coordinates of the mesh lines along both of the axes.
82,809,343✔
1171
  array<vector<double>, 2> axis_lines;
1172
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1173
    int axis = axes[i_ax];
1174
    if (axis == -1)
5,388,456✔
1175
      continue;
21,438,660✔
1176
    auto& lines {axis_lines[i_ax]};
16,050,204✔
1177

16,050,204✔
1178
    double coord = lower_left_[axis];
1179
    for (int i = 0; i < shape_[axis] + 1; ++i) {
1180
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1181
        lines.push_back(coord);
5,388,456✔
1182
      coord += width_[axis];
4,036,392✔
1183
    }
1184
  }
1185

1186
  return {axis_lines[0], axis_lines[1]};
1187
}
384,885,660✔
1188

1189
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1190
{
1191
  write_dataset(mesh_group, "type", "regular");
1192
  write_dataset(mesh_group, "dimension", get_x_shape());
1193
  write_dataset(mesh_group, "lower_left", lower_left_);
1194
  write_dataset(mesh_group, "upper_right", upper_right_);
1195
  write_dataset(mesh_group, "width", width_);
384,885,660✔
1196
}
1197

384,885,660✔
1198
xt::xtensor<double, 1> RegularMesh::count_sites(
384,885,660✔
1199
  const SourceSite* bank, int64_t length, bool* outside) const
560,496,789✔
1200
{
585,350,160✔
1201
  // Determine shape of array for counts
1202
  std::size_t m = this->n_bins();
585,350,160✔
1203
  vector<std::size_t> shape = {m};
585,350,160✔
1204

585,350,160✔
1205
  // Create array of zeros
1206
  xt::xarray<double> cnt {shape, 0.0};
1207
  bool outside_ = false;
1208

1209
  for (int64_t i = 0; i < length; i++) {
1210
    const auto& site = bank[i];
1211

1212
    // determine scoring bin for entropy mesh
384,885,660✔
1213
    int mesh_bin = get_bin(site.r);
384,885,660✔
1214

1215
    // if outside mesh, skip particle
240,796,560✔
1216
    if (mesh_bin < 0) {
1217
      outside_ = true;
1218
      continue;
1219
    }
1220

1221
    // Add to appropriate bin
1222
    cnt(mesh_bin) += site.wgt;
1223
  }
240,796,560✔
1224

240,796,560✔
1225
  // Create copy of count data. Since ownership will be acquired by xtensor,
240,796,560✔
1226
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
116,725,680✔
1227
  // warnings.
1228
  int total = cnt.size();
1229
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
116,725,680✔
1230

116,725,680✔
1231
#ifdef OPENMC_MPI
58,318,668✔
1232
  // collect values from all processors
116,725,680✔
1233
  MPI_Reduce(
57,360,972✔
1234
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
116,725,680✔
1235

116,725,680✔
1236
  // Check if there were sites outside the mesh for any processor
297,433,236✔
1237
  if (outside) {
1238
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1239
  }
1240
#else
1241
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1242
  if (outside)
1243
    *outside = outside_;
240,796,560✔
1244
#endif
240,796,560✔
1245

1246
  // Adapt reduced values in array back into an xarray
1247
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
1248
  xt::xarray<double> counts = arr;
1249

1250
  return counts;
1,906✔
1251
}
1252

1253
double RegularMesh::volume(const MeshIndex& ijk) const
1,906✔
UNCOV
1254
{
×
1255
  return element_volume_;
1256
}
1257

1,906✔
1258
//==============================================================================
1,906✔
1259
// RectilinearMesh implementation
1,906✔
UNCOV
1260
//==============================================================================
×
1261

1262
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
1,906✔
1263
{
1264
  n_dimension_ = 3;
1265

1,906✔
UNCOV
1266
  grid_[0] = get_node_array<double>(node, "x_grid");
×
1267
  grid_[1] = get_node_array<double>(node, "y_grid");
1268
  grid_[2] = get_node_array<double>(node, "z_grid");
1269

1270
  if (int err = set_grid()) {
1271
    fatal_error(openmc_err_msg);
1,906✔
1272
  }
1273
}
1,906✔
1274

UNCOV
1275
const std::string RectilinearMesh::mesh_type = "rectilinear";
×
1276

1277
std::string RectilinearMesh::get_mesh_type() const
1278
{
1279
  return mesh_type;
1,906✔
UNCOV
1280
}
×
1281

1282
double RectilinearMesh::positive_grid_boundary(
1283
  const MeshIndex& ijk, int i) const
1284
{
1,906✔
1285
  return grid_[i][ijk[i]];
1286
}
51✔
UNCOV
1287

×
1288
double RectilinearMesh::negative_grid_boundary(
1289
  const MeshIndex& ijk, int i) const
1290
{
51✔
1291
  return grid_[i][ijk[i] - 1];
1292
}
1293

51✔
1294
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
51✔
UNCOV
1295
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
×
1296
  double l) const
1297
{
1298
  MeshDistance d;
1299
  d.next_index = ijk[i];
1300
  if (std::abs(u[i]) < FP_PRECISION)
51✔
1301
    return d;
×
1302

1303
  d.max_surface = (u[i] > 0);
1304
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1305
    d.next_index++;
51✔
1306
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1307
  } else if (!d.max_surface && (ijk[i] > 0)) {
1,855✔
1308
    d.next_index--;
1,855✔
1309
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1310
  }
1311
  return d;
1,855✔
1312
}
1,855✔
UNCOV
1313

×
1314
int RectilinearMesh::set_grid()
1315
{
1316
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1317
    static_cast<int>(grid_[1].size()) - 1,
1318
    static_cast<int>(grid_[2].size()) - 1};
1,855✔
UNCOV
1319

×
1320
  for (const auto& g : grid_) {
1321
    if (g.size() < 2) {
1322
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
1323
                 "must each have at least 2 points");
1324
      return OPENMC_E_INVALID_ARGUMENT;
1,855✔
1325
    }
UNCOV
1326
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
×
1327
        g.end()) {
1328
      set_errmsg("Values in for x-, y-, and z- grids for "
1329
                 "rectilinear meshes must be sorted and unique.");
1330
      return OPENMC_E_INVALID_ARGUMENT;
1,906✔
1331
    }
1332
  }
1,906✔
1333

7,357✔
1334
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
5,451✔
1335
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
1336

1,906✔
1337
  return 0;
1338
}
2,147,483,647✔
1339

1340
int RectilinearMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1341
{
1342
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1343
}
1344

1345
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
3,834✔
1346
  Position plot_ll, Position plot_ur) const
1347
{
3,834✔
1348
  // Figure out which axes lie in the plane of the plot.
1349
  array<int, 2> axes {-1, -1};
1350
  if (plot_ur.z == plot_ll.z) {
786,947,219✔
1351
    axes = {0, 1};
1352
  } else if (plot_ur.y == plot_ll.y) {
786,947,219✔
1353
    axes = {0, 2};
1354
  } else if (plot_ur.x == plot_ll.x) {
1355
    axes = {1, 2};
785,692,497✔
1356
  } else {
1357
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
785,692,497✔
1358
  }
1359

1360
  // Get the coordinates of the mesh lines along both of the axes.
1,587,018,559✔
1361
  array<vector<double>, 2> axis_lines;
1362
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
1363
    int axis = axes[i_ax];
1364
    vector<double>& lines {axis_lines[i_ax]};
1,587,018,559✔
1365

1,587,018,559✔
1366
    for (auto coord : grid_[axis]) {
1,587,018,559✔
1367
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
1,314,072✔
1368
        lines.push_back(coord);
1369
    }
1,585,704,487✔
1370
  }
1,585,704,487✔
1371

782,320,103✔
1372
  return {axis_lines[0], axis_lines[1]};
782,320,103✔
1373
}
803,384,384✔
1374

781,065,381✔
1375
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
781,065,381✔
1376
{
1377
  write_dataset(mesh_group, "type", "rectilinear");
1,585,704,487✔
1378
  write_dataset(mesh_group, "x_grid", grid_[0]);
1379
  write_dataset(mesh_group, "y_grid", grid_[1]);
1380
  write_dataset(mesh_group, "z_grid", grid_[2]);
24✔
1381
}
1382

1383
double RectilinearMesh::volume(const MeshIndex& ijk) const
1384
{
24✔
1385
  double vol {1.0};
24✔
1386

24✔
1387
  for (int i = 0; i < n_dimension_; i++) {
24✔
1388
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
24✔
UNCOV
1389
  }
×
UNCOV
1390
  return vol;
×
UNCOV
1391
}
×
UNCOV
1392

×
UNCOV
1393
//==============================================================================
×
UNCOV
1394
// CylindricalMesh implementation
×
UNCOV
1395
//==============================================================================
×
UNCOV
1396

×
UNCOV
1397
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
×
1398
  : PeriodicStructuredMesh {node}
UNCOV
1399
{
×
1400
  n_dimension_ = 3;
1401
  grid_[0] = get_node_array<double>(node, "r_grid");
1402
  grid_[1] = get_node_array<double>(node, "phi_grid");
1403
  grid_[2] = get_node_array<double>(node, "z_grid");
24✔
1404
  origin_ = get_node_position(node, "origin");
72✔
1405

48✔
1406
  if (int err = set_grid()) {
48✔
UNCOV
1407
    fatal_error(openmc_err_msg);
×
1408
  }
48✔
1409
}
1410

48✔
1411
const std::string CylindricalMesh::mesh_type = "cylindrical";
312✔
1412

264✔
1413
std::string CylindricalMesh::get_mesh_type() const
264✔
1414
{
264✔
1415
  return mesh_type;
1416
}
1417

1418
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
48✔
1419
  Position r, bool& in_mesh) const
24✔
1420
{
1421
  local_coords(r);
2,130✔
1422

1423
  Position mapped_r;
2,130✔
1424
  mapped_r[0] = std::hypot(r.x, r.y);
2,130✔
1425
  mapped_r[2] = r[2];
2,130✔
1426

2,130✔
1427
  if (mapped_r[0] < FP_PRECISION) {
2,130✔
1428
    mapped_r[1] = 0.0;
2,130✔
1429
  } else {
1430
    mapped_r[1] = std::atan2(r.y, r.x);
11,963✔
1431
    if (mapped_r[1] < 0)
1432
      mapped_r[1] += 2 * M_PI;
1433
  }
1434

11,963✔
1435
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
11,963✔
1436

1437
  idx[1] = sanitize_phi(idx[1]);
1438

11,963✔
1439
  return idx;
11,963✔
1440
}
1441

11,739,911✔
1442
Position CylindricalMesh::sample_element(
11,727,948✔
1443
  const MeshIndex& ijk, uint64_t* seed) const
1444
{
1445
  double r_min = this->r(ijk[0] - 1);
11,727,948✔
1446
  double r_max = this->r(ijk[0]);
1447

1448
  double phi_min = this->phi(ijk[1] - 1);
11,727,948✔
UNCOV
1449
  double phi_max = this->phi(ijk[1]);
×
UNCOV
1450

×
1451
  double z_min = this->z(ijk[2] - 1);
1452
  double z_max = this->z(ijk[2]);
1453

1454
  double r_min_sq = r_min * r_min;
11,727,948✔
1455
  double r_max_sq = r_max * r_max;
1456
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
1457
  double phi = uniform_distribution(phi_min, phi_max, seed);
1458
  double z = uniform_distribution(z_min, z_max, seed);
1459

1460
  double x = r * std::cos(phi);
11,963✔
1461
  double y = r * std::sin(phi);
11,963✔
1462

1463
  return origin_ + Position(x, y, z);
1464
}
1465

7,035✔
1466
double CylindricalMesh::find_r_crossing(
7,035✔
1467
  const Position& r, const Direction& u, double l, int shell) const
1468
{
1469

7,035✔
1470
  if ((shell < 0) || (shell > shape_[0]))
7,035✔
1471
    return INFTY;
1472

1473
  // solve r.x^2 + r.y^2 == r0^2
4,928✔
1474
  // 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✔
1475
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
4,928✔
1476

1477
  const double r0 = grid_[0][shell];
1478
  if (r0 == 0.0)
1479
    return INFTY;
11,963✔
1480

11,963✔
1481
  const double denominator = u.x * u.x + u.y * u.y;
1482

23,926✔
1483
  // Direction of flight is in z-direction. Will never intersect r.
11,963✔
1484
  if (std::abs(denominator) < FP_PRECISION)
1485
    return INFTY;
983,100✔
1486

1487
  // inverse of dominator to help the compiler to speed things up
983,100✔
1488
  const double inv_denominator = 1.0 / denominator;
1489

1490
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
1491
  double c = r.x * r.x + r.y * r.y - r0 * r0;
1492
  double D = p * p - c * inv_denominator;
1493

1494
  if (D < 0.0)
111✔
1495
    return INFTY;
1496

111✔
1497
  D = std::sqrt(D);
1498

111✔
1499
  // the solution -p - D is always smaller as -p + D : Check this one first
111✔
1500
  if (std::abs(c) <= RADIAL_MESH_TOL)
111✔
1501
    return INFTY;
1502

111✔
UNCOV
1503
  if (-p - D > l)
×
1504
    return -p - D;
1505
  if (-p + D > l)
111✔
1506
    return -p + D;
1507

1508
  return INFTY;
1509
}
324✔
1510

1511
double CylindricalMesh::find_phi_crossing(
324✔
1512
  const Position& r, const Direction& u, double l, int shell) const
1513
{
1514
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
53,838,588✔
1515
  if (full_phi_ && (shape_[1] == 1))
1516
    return INFTY;
1517

53,838,588✔
1518
  shell = sanitize_phi(shell);
1519

1520
  const double p0 = grid_[1][shell];
52,994,424✔
1521

1522
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1523
  // => x(s) * cos(p0) = y(s) * sin(p0)
52,994,424✔
1524
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1525
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1526

108,465,432✔
1527
  const double c0 = std::cos(p0);
1528
  const double s0 = std::sin(p0);
1529

1530
  const double denominator = (u.x * s0 - u.y * c0);
108,465,432✔
1531

108,465,432✔
1532
  // Check if direction of flight is not parallel to phi surface
108,465,432✔
1533
  if (std::abs(denominator) > FP_PRECISION) {
623,808✔
1534
    const double s = -(r.x * s0 - r.y * c0) / denominator;
1535
    // Check if solution is in positive direction of flight and crosses the
107,841,624✔
1536
    // correct phi surface (not -phi)
107,841,624✔
1537
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
53,838,588✔
1538
      return s;
53,838,588✔
1539
  }
54,003,036✔
1540

52,994,424✔
1541
  return INFTY;
52,994,424✔
1542
}
1543

107,841,624✔
1544
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
1545
  const Position& r, const Direction& u, double l, int shell) const
1546
{
183✔
1547
  MeshDistance d;
1548
  d.next_index = shell;
183✔
1549

183✔
1550
  // Direction of flight is within xy-plane. Will never intersect z.
183✔
1551
  if (std::abs(u.z) < FP_PRECISION)
1552
    return d;
732✔
1553

549✔
UNCOV
1554
  d.max_surface = (u.z > 0.0);
×
1555
  if (d.max_surface && (shell <= shape_[2])) {
UNCOV
1556
    d.next_index += 1;
×
1557
    d.distance = (grid_[2][shell] - r.z) / u.z;
1558
  } else if (!d.max_surface && (shell > 0)) {
549✔
1559
    d.next_index -= 1;
1,098✔
UNCOV
1560
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
×
1561
  }
1562
  return d;
×
1563
}
1564

1565
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
1566
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
183✔
1567
  double l) const
183✔
1568
{
1569
  Position r = r0 - origin_;
183✔
1570

1571
  if (i == 0) {
1572

155,114,820✔
1573
    return std::min(
1574
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r, u, l, ijk[i])),
155,114,820✔
1575
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r, u, l, ijk[i] - 1)));
1576

1577
  } else if (i == 1) {
12✔
1578

1579
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
1580
                      find_phi_crossing(r, u, l, ijk[i])),
1581
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
12✔
1582
        find_phi_crossing(r, u, l, ijk[i] - 1)));
12✔
UNCOV
1583

×
1584
  } else {
12✔
1585
    return find_z_crossing(r, u, l, ijk[i]);
12✔
UNCOV
1586
  }
×
UNCOV
1587
}
×
1588

UNCOV
1589
int CylindricalMesh::set_grid()
×
1590
{
1591
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1592
    static_cast<int>(grid_[1].size()) - 1,
1593
    static_cast<int>(grid_[2].size()) - 1};
12✔
1594

36✔
1595
  for (const auto& g : grid_) {
24✔
1596
    if (g.size() < 2) {
24✔
1597
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
1598
                 "must each have at least 2 points");
120✔
1599
      return OPENMC_E_INVALID_ARGUMENT;
96✔
1600
    }
96✔
1601
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1602
        g.end()) {
1603
      set_errmsg("Values in for r-, phi-, and z- grids for "
1604
                 "cylindrical meshes must be sorted and unique.");
24✔
1605
      return OPENMC_E_INVALID_ARGUMENT;
12✔
1606
    }
1607
  }
120✔
1608
  if (grid_[0].front() < 0.0) {
1609
    set_errmsg("r-grid for "
120✔
1610
               "cylindrical meshes must start at r >= 0.");
120✔
1611
    return OPENMC_E_INVALID_ARGUMENT;
120✔
1612
  }
120✔
1613
  if (grid_[1].front() < 0.0) {
120✔
1614
    set_errmsg("phi-grid for "
1615
               "cylindrical meshes must start at phi >= 0.");
144✔
1616
    return OPENMC_E_INVALID_ARGUMENT;
1617
  }
144✔
1618
  if (grid_[1].back() > 2.0 * PI) {
1619
    set_errmsg("phi-grids for "
576✔
1620
               "cylindrical meshes must end with theta <= 2*pi.");
432✔
1621

1622
    return OPENMC_E_INVALID_ARGUMENT;
144✔
1623
  }
1624

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

1627
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
1628
    origin_[2] + grid_[2].front()};
1629
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
413✔
1630
    origin_[2] + grid_[2].back()};
413✔
1631

1632
  return 0;
413✔
1633
}
413✔
1634

413✔
1635
int CylindricalMesh::get_index_in_direction(double r, int i) const
413✔
1636
{
413✔
1637
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1638
}
413✔
UNCOV
1639

×
1640
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
1641
  Position plot_ll, Position plot_ur) const
413✔
1642
{
1643
  fatal_error("Plot of cylindrical Mesh not implemented");
1644

1645
  // Figure out which axes lie in the plane of the plot.
516✔
1646
  array<vector<double>, 2> axis_lines;
1647
  return {axis_lines[0], axis_lines[1]};
516✔
1648
}
1649

1650
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
50,568,432✔
1651
{
1652
  write_dataset(mesh_group, "type", "cylindrical");
1653
  write_dataset(mesh_group, "r_grid", grid_[0]);
50,568,432✔
1654
  write_dataset(mesh_group, "phi_grid", grid_[1]);
1655
  write_dataset(mesh_group, "z_grid", grid_[2]);
50,568,432✔
1656
  write_dataset(mesh_group, "origin", origin_);
50,568,432✔
1657
}
50,568,432✔
1658

1659
double CylindricalMesh::volume(const MeshIndex& ijk) const
50,568,432✔
UNCOV
1660
{
×
1661
  double r_i = grid_[0][ijk[0] - 1];
1662
  double r_o = grid_[0][ijk[0]];
50,568,432✔
1663

50,568,432✔
1664
  double phi_i = grid_[1][ijk[1] - 1];
25,300,356✔
1665
  double phi_o = grid_[1][ijk[1]];
1666

1667
  double z_i = grid_[2][ijk[2] - 1];
50,568,432✔
1668
  double z_o = grid_[2][ijk[2]];
1669

50,568,432✔
1670
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
1671
}
50,568,432✔
1672

1673
//==============================================================================
1674
// SphericalMesh implementation
96,000✔
1675
//==============================================================================
1676

1677
SphericalMesh::SphericalMesh(pugi::xml_node node)
96,000✔
1678
  : PeriodicStructuredMesh {node}
96,000✔
1679
{
1680
  n_dimension_ = 3;
96,000✔
1681

96,000✔
1682
  grid_[0] = get_node_array<double>(node, "r_grid");
1683
  grid_[1] = get_node_array<double>(node, "theta_grid");
96,000✔
1684
  grid_[2] = get_node_array<double>(node, "phi_grid");
96,000✔
1685
  origin_ = get_node_position(node, "origin");
1686

96,000✔
1687
  if (int err = set_grid()) {
96,000✔
1688
    fatal_error(openmc_err_msg);
96,000✔
1689
  }
96,000✔
1690
}
96,000✔
1691

1692
const std::string SphericalMesh::mesh_type = "spherical";
96,000✔
1693

96,000✔
1694
std::string SphericalMesh::get_mesh_type() const
1695
{
96,000✔
1696
  return mesh_type;
1697
}
1698

148,757,592✔
1699
StructuredMesh::MeshIndex SphericalMesh::get_indices(
1700
  Position r, bool& in_mesh) const
1701
{
1702
  local_coords(r);
148,757,592✔
1703

18,260,184✔
1704
  Position mapped_r;
1705
  mapped_r[0] = r.norm();
1706

1707
  if (mapped_r[0] < FP_PRECISION) {
1708
    mapped_r[1] = 0.0;
1709
    mapped_r[2] = 0.0;
130,497,408✔
1710
  } else {
130,497,408✔
1711
    mapped_r[1] = std::acos(r.z / mapped_r.x);
7,273,620✔
1712
    mapped_r[2] = std::atan2(r.y, r.x);
1713
    if (mapped_r[2] < 0)
123,223,788✔
1714
      mapped_r[2] += 2 * M_PI;
1715
  }
1716

123,223,788✔
1717
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
64,320✔
1718

1719
  idx[1] = sanitize_theta(idx[1]);
1720
  idx[2] = sanitize_phi(idx[2]);
123,159,468✔
1721

1722
  return idx;
123,159,468✔
1723
}
123,159,468✔
1724

123,159,468✔
1725
Position SphericalMesh::sample_element(
1726
  const MeshIndex& ijk, uint64_t* seed) const
123,159,468✔
1727
{
17,009,892✔
1728
  double r_min = this->r(ijk[0] - 1);
1729
  double r_max = this->r(ijk[0]);
106,149,576✔
1730

1731
  double theta_min = this->theta(ijk[1] - 1);
1732
  double theta_max = this->theta(ijk[1]);
106,149,576✔
1733

7,057,536✔
1734
  double phi_min = this->phi(ijk[2] - 1);
1735
  double phi_max = this->phi(ijk[2]);
99,092,040✔
1736

20,246,952✔
1737
  double cos_theta = uniform_distribution(theta_min, theta_max, seed);
78,845,088✔
1738
  double sin_theta = std::sin(std::acos(cos_theta));
47,862,120✔
1739
  double phi = uniform_distribution(phi_min, phi_max, seed);
1740
  double r_min_cub = std::pow(r_min, 3);
30,982,968✔
1741
  double r_max_cub = std::pow(r_max, 3);
1742
  // might be faster to do rejection here?
1743
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
74,283,288✔
1744

1745
  double x = r * std::cos(phi) * sin_theta;
1746
  double y = r * std::sin(phi) * sin_theta;
1747
  double z = r * cos_theta;
74,283,288✔
1748

32,466,432✔
1749
  return origin_ + Position(x, y, z);
1750
}
41,816,856✔
1751

1752
double SphericalMesh::find_r_crossing(
41,816,856✔
1753
  const Position& r, const Direction& u, double l, int shell) const
1754
{
1755
  if ((shell < 0) || (shell > shape_[0]))
1756
    return INFTY;
1757

1758
  // solve |r+s*u| = r0
1759
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
41,816,856✔
1760
  const double r0 = grid_[0][shell];
41,816,856✔
1761
  if (r0 == 0.0)
1762
    return INFTY;
41,816,856✔
1763
  const double p = r.dot(u);
1764
  double c = r.dot(r) - r0 * r0;
1765
  double D = p * p - c;
41,816,856✔
1766

41,532,408✔
1767
  if (std::abs(c) <= RADIAL_MESH_TOL)
1768
    return INFTY;
1769

41,532,408✔
1770
  if (D >= 0.0) {
19,437,552✔
1771
    D = std::sqrt(D);
1772
    // the solution -p - D is always smaller as -p + D : Check this one first
1773
    if (-p - D > l)
22,379,304✔
1774
      return -p - D;
1775
    if (-p + D > l)
1776
      return -p + D;
39,992,448✔
1777
  }
1778

1779
  return INFTY;
39,992,448✔
1780
}
39,992,448✔
1781

1782
double SphericalMesh::find_theta_crossing(
1783
  const Position& r, const Direction& u, double l, int shell) const
39,992,448✔
1784
{
1,219,872✔
1785
  // Theta grid is [0, π], thus there is no real surface to cross
1786
  if (full_theta_ && (shape_[1] == 1))
38,772,576✔
1787
    return INFTY;
38,772,576✔
1788

17,769,456✔
1789
  shell = sanitize_theta(shell);
17,769,456✔
1790

21,003,120✔
1791
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
18,037,548✔
1792
  // yields
18,037,548✔
1793
  // a*s^2 + 2*b*s + c == 0 with
1794
  // a = cos(theta)^2 - u.z * u.z
38,772,576✔
1795
  // b = r*u * cos(theta)^2 - u.z * r.z
1796
  // c = r*r * cos(theta)^2 - r.z^2
1797

151,512,888✔
1798
  const double cos_t = std::cos(grid_[1][shell]);
1799
  const bool sgn = std::signbit(cos_t);
1800
  const double cos_t_2 = cos_t * cos_t;
1801

151,512,888✔
1802
  const double a = cos_t_2 - u.z * u.z;
1803
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
151,512,888✔
1804
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
1805

74,378,796✔
1806
  // if factor of s^2 is zero, direction of flight is parallel to theta
74,378,796✔
1807
  // surface
148,757,592✔
1808
  if (std::abs(a) < FP_PRECISION) {
1809
    // if b vanishes, direction of flight is within theta surface and crossing
77,134,092✔
1810
    // is not possible
1811
    if (std::abs(b) < FP_PRECISION)
37,141,644✔
1812
      return INFTY;
37,141,644✔
1813

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

1820
    // no crossing is possible
1821
    return INFTY;
437✔
1822
  }
1823

437✔
1824
  const double p = b / a;
437✔
1825
  double D = p * p - c / a;
437✔
1826

1827
  if (D < 0.0)
1,748✔
1828
    return INFTY;
1,311✔
UNCOV
1829

×
1830
  D = std::sqrt(D);
1831

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

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

UNCOV
1843
  return INFTY;
×
1844
}
1845

437✔
UNCOV
1846
double SphericalMesh::find_phi_crossing(
×
1847
  const Position& r, const Direction& u, double l, int shell) const
UNCOV
1848
{
×
1849
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1850
  if (full_phi_ && (shape_[2] == 1))
437✔
UNCOV
1851
    return INFTY;
×
1852

1853
  shell = sanitize_phi(shell);
UNCOV
1854

×
1855
  const double p0 = grid_[2][shell];
1856

1857
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
437✔
1858
  // => x(s) * cos(p0) = y(s) * sin(p0)
1859
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
874✔
1860
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
874✔
1861

874✔
1862
  const double c0 = std::cos(p0);
874✔
1863
  const double s0 = std::sin(p0);
1864

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

1867
  // Check if direction of flight is not parallel to phi surface
151,705,296✔
1868
  if (std::abs(denominator) > FP_PRECISION) {
1869
    const double s = -(r.x * s0 - r.y * c0) / denominator;
151,705,296✔
1870
    // Check if solution is in positive direction of flight and crosses the
1871
    // correct phi surface (not -phi)
UNCOV
1872
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
×
1873
      return s;
1874
  }
UNCOV
1875

×
1876
  return INFTY;
1877
}
1878

1879
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
1880
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1881
  double l) const
1882
{
396✔
1883

1884
  if (i == 0) {
396✔
1885
    return std::min(
396✔
1886
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
396✔
1887
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
396✔
1888

396✔
1889
  } else if (i == 1) {
396✔
1890
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
1891
                      find_theta_crossing(r0, u, l, ijk[i])),
384✔
1892
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
1893
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
384✔
1894

384✔
1895
  } else {
1896
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
384✔
1897
                      find_phi_crossing(r0, u, l, ijk[i])),
384✔
1898
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
1899
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
384✔
1900
  }
384✔
1901
}
1902

384✔
1903
int SphericalMesh::set_grid()
1904
{
1905
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1906
    static_cast<int>(grid_[1].size()) - 1,
1907
    static_cast<int>(grid_[2].size()) - 1};
1908

1909
  for (const auto& g : grid_) {
317✔
1910
    if (g.size() < 2) {
317✔
1911
      set_errmsg("x-, y-, and z- grids for spherical meshes "
1912
                 "must each have at least 2 points");
317✔
1913
      return OPENMC_E_INVALID_ARGUMENT;
1914
    }
317✔
1915
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
317✔
1916
        g.end()) {
317✔
1917
      set_errmsg("Values in for r-, theta-, and phi- grids for "
317✔
1918
                 "spherical meshes must be sorted and unique.");
1919
      return OPENMC_E_INVALID_ARGUMENT;
317✔
UNCOV
1920
    }
×
1921
    if (g.front() < 0.0) {
1922
      set_errmsg("r-, theta-, and phi- grids for "
317✔
1923
                 "spherical meshes must start at v >= 0.");
1924
      return OPENMC_E_INVALID_ARGUMENT;
1925
    }
1926
  }
372✔
1927
  if (grid_[1].back() > PI) {
1928
    set_errmsg("theta-grids for "
372✔
1929
               "spherical meshes must end with theta <= pi.");
1930

1931
    return OPENMC_E_INVALID_ARGUMENT;
73,752,732✔
1932
  }
1933
  if (grid_[2].back() > 2 * PI) {
1934
    set_errmsg("phi-grids for "
73,752,732✔
1935
               "spherical meshes must end with phi <= 2*pi.");
1936
    return OPENMC_E_INVALID_ARGUMENT;
73,752,732✔
1937
  }
73,752,732✔
1938

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

×
1942
  double r = grid_[0].back();
1943
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
73,752,732✔
1944
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
73,752,732✔
1945

73,752,732✔
1946
  return 0;
36,882,336✔
1947
}
1948

1949
int SphericalMesh::get_index_in_direction(double r, int i) const
73,752,732✔
1950
{
1951
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
73,752,732✔
1952
}
73,752,732✔
1953

1954
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
73,752,732✔
1955
  Position plot_ll, Position plot_ur) const
1956
{
UNCOV
1957
  fatal_error("Plot of spherical Mesh not implemented");
×
1958

1959
  // Figure out which axes lie in the plane of the plot.
UNCOV
1960
  array<vector<double>, 2> axis_lines;
×
UNCOV
1961
  return {axis_lines[0], axis_lines[1]};
×
1962
}
UNCOV
1963

×
UNCOV
1964
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
×
1965
{
UNCOV
1966
  write_dataset(mesh_group, "type", SphericalMesh::mesh_type);
×
UNCOV
1967
  write_dataset(mesh_group, "r_grid", grid_[0]);
×
1968
  write_dataset(mesh_group, "theta_grid", grid_[1]);
UNCOV
1969
  write_dataset(mesh_group, "phi_grid", grid_[2]);
×
UNCOV
1970
  write_dataset(mesh_group, "origin", origin_);
×
UNCOV
1971
}
×
UNCOV
1972

×
UNCOV
1973
double SphericalMesh::volume(const MeshIndex& ijk) const
×
1974
{
UNCOV
1975
  double r_i = grid_[0][ijk[0] - 1];
×
1976
  double r_o = grid_[0][ijk[0]];
UNCOV
1977

×
UNCOV
1978
  double theta_i = grid_[1][ijk[1] - 1];
×
UNCOV
1979
  double theta_o = grid_[1][ijk[1]];
×
1980

UNCOV
1981
  double phi_i = grid_[2][ijk[2] - 1];
×
1982
  double phi_o = grid_[2][ijk[2]];
1983

1984
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
481,615,104✔
1985
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
1986
}
1987

481,615,104✔
1988
//==============================================================================
44,030,820✔
1989
// Helper functions for the C API
1990
//==============================================================================
1991

1992
int check_mesh(int32_t index)
437,584,284✔
1993
{
437,584,284✔
1994
  if (index < 0 || index >= model::meshes.size()) {
7,601,184✔
1995
    set_errmsg("Index in meshes array is out of bounds.");
429,983,100✔
1996
    return OPENMC_E_OUT_OF_BOUNDS;
429,983,100✔
1997
  }
429,983,100✔
1998
  return 0;
1999
}
429,983,100✔
2000

11,548,560✔
2001
template<class T>
2002
int check_mesh_type(int32_t index)
418,434,540✔
2003
{
388,836,240✔
2004
  if (int err = check_mesh(index))
2005
    return err;
388,836,240✔
2006

69,512,340✔
2007
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
319,323,900✔
2008
  if (!mesh) {
192,371,628✔
2009
    set_errmsg("This function is not valid for input mesh.");
2010
    return OPENMC_E_INVALID_TYPE;
2011
  }
156,550,572✔
2012
  return 0;
2013
}
2014

118,217,520✔
2015
template<class T>
2016
bool is_mesh_type(int32_t index)
2017
{
2018
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
118,217,520✔
2019
  return mesh;
76,498,272✔
2020
}
2021

41,719,248✔
2022
//==============================================================================
2023
// C API functions
2024
//==============================================================================
2025

2026
// Return the type of mesh as a C string
2027
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
2028
{
2029
  if (int err = check_mesh(index))
2030
    return err;
41,719,248✔
2031

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

2034
  return 0;
41,719,248✔
2035
}
41,719,248✔
2036

41,719,248✔
2037
//! Extend the meshes array by n elements
2038
extern "C" int openmc_extend_meshes(
2039
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2040
{
41,719,248✔
2041
  if (index_start)
2042
    *index_start = model::meshes.size();
2043
  std::string mesh_type;
526,416✔
2044

526,416✔
2045
  for (int i = 0; i < n; ++i) {
UNCOV
2046
    if (RegularMesh::mesh_type == type) {
×
2047
      model::meshes.push_back(make_unique<RegularMesh>());
2048
    } else if (RectilinearMesh::mesh_type == type) {
UNCOV
2049
      model::meshes.push_back(make_unique<RectilinearMesh>());
×
UNCOV
2050
    } else if (CylindricalMesh::mesh_type == type) {
×
2051
      model::meshes.push_back(make_unique<CylindricalMesh>());
2052
    } else if (SphericalMesh::mesh_type == type) {
UNCOV
2053
      model::meshes.push_back(make_unique<SphericalMesh>());
×
2054
    } else {
2055
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
2056
    }
41,192,832✔
2057
  }
41,192,832✔
2058
  if (index_end)
2059
    *index_end = model::meshes.size() - 1;
41,192,832✔
2060

11,955,456✔
2061
  return 0;
2062
}
29,237,376✔
2063

2064
//! Adds a new unstructured mesh to OpenMC
2065
extern "C" int openmc_add_unstructured_mesh(
29,237,376✔
2066
  const char filename[], const char library[], int* id)
2067
{
29,237,376✔
2068
  std::string lib_name(library);
5,599,656✔
2069
  std::string mesh_file(filename);
2070
  bool valid_lib = false;
23,637,720✔
2071

2072
#ifdef DAGMC
23,637,720✔
2073
  if (lib_name == MOABMesh::mesh_lib_type) {
11,064,504✔
2074
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
2075
    valid_lib = true;
12,573,216✔
2076
  }
2077
#endif
2078

119,966,232✔
2079
#ifdef LIBMESH
2080
  if (lib_name == LibMesh::mesh_lib_type) {
2081
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
2082
    valid_lib = true;
119,966,232✔
2083
  }
76,498,272✔
2084
#endif
2085

43,467,960✔
2086
  if (!valid_lib) {
2087
    set_errmsg(fmt::format("Mesh library {} is not supported "
43,467,960✔
2088
                           "by this build of OpenMC",
2089
      lib_name));
2090
    return OPENMC_E_INVALID_ARGUMENT;
2091
  }
2092

2093
  // auto-assign new ID
2094
  model::meshes.back()->set_id(-1);
43,467,960✔
2095
  *id = model::meshes.back()->id_;
43,467,960✔
2096

2097
  return 0;
43,467,960✔
2098
}
2099

2100
//! Return the index in the meshes array of a mesh with a given ID
43,467,960✔
2101
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
43,212,696✔
2102
{
2103
  auto pair = model::mesh_map.find(id);
2104
  if (pair == model::mesh_map.end()) {
43,212,696✔
2105
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
19,003,152✔
2106
    return OPENMC_E_INVALID_ID;
2107
  }
2108
  *index = pair->second;
24,464,808✔
2109
  return 0;
2110
}
2111

359,899,428✔
2112
//! Return the ID of a mesh
2113
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2114
{
2115
  if (int err = check_mesh(index))
2116
    return err;
359,899,428✔
2117
  *id = model::meshes[index]->id_;
240,807,552✔
2118
  return 0;
240,807,552✔
2119
}
481,615,104✔
2120

2121
//! Set the ID of a mesh
119,091,876✔
2122
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
59,108,760✔
2123
{
59,108,760✔
2124
  if (int err = check_mesh(index))
59,108,760✔
2125
    return err;
118,217,520✔
2126
  model::meshes[index]->id_ = id;
2127
  model::mesh_map[id] = index;
2128
  return 0;
59,983,116✔
2129
}
59,983,116✔
2130

59,983,116✔
2131
//! Get the number of elements in a mesh
119,966,232✔
2132
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
2133
{
2134
  if (int err = check_mesh(index))
2135
    return err;
341✔
2136
  *n = model::meshes[index]->n_bins();
2137
  return 0;
341✔
2138
}
341✔
2139

341✔
2140
//! Get the volume of each element in the mesh
2141
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
1,364✔
2142
{
1,023✔
2143
  if (int err = check_mesh(index))
×
2144
    return err;
UNCOV
2145
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
×
2146
    volumes[i] = model::meshes[index]->volume(i);
2147
  }
1,023✔
2148
  return 0;
2,046✔
UNCOV
2149
}
×
2150

UNCOV
2151
//! Get the bounding box of a mesh
×
2152
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
2153
{
1,023✔
UNCOV
2154
  if (int err = check_mesh(index))
×
2155
    return err;
UNCOV
2156

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

2159
  // set lower left corner values
341✔
UNCOV
2160
  ll[0] = bbox.xmin;
×
2161
  ll[1] = bbox.ymin;
2162
  ll[2] = bbox.zmin;
UNCOV
2163

×
2164
  // set upper right corner values
2165
  ur[0] = bbox.xmax;
341✔
UNCOV
2166
  ur[1] = bbox.ymax;
×
2167
  ur[2] = bbox.zmax;
NEW
2168
  return 0;
×
2169
}
2170

2171
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
341✔
2172
  int nz, int max_mats, int32_t* materials, double* volumes)
341✔
2173
{
2174
  if (int err = check_mesh(index))
341✔
2175
    return err;
341✔
2176

341✔
2177
  try {
2178
    model::meshes[index]->material_volumes(
341✔
2179
      nx, ny, nz, max_mats, materials, volumes);
2180
  } catch (const std::exception& e) {
2181
    set_errmsg(e.what());
221,258,196✔
2182
    if (starts_with(e.what(), "Mesh")) {
2183
      return OPENMC_E_GEOMETRY;
221,258,196✔
2184
    } else {
2185
      return OPENMC_E_ALLOCATE;
NEW
2186
    }
×
2187
  }
2188

UNCOV
2189
  return 0;
×
2190
}
2191

2192
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
2193
  Position width, int basis, int* pixels, int32_t* data)
2194
{
2195
  if (int err = check_mesh(index))
2196
    return err;
312✔
2197
  const auto& mesh = model::meshes[index].get();
2198

312✔
2199
  int pixel_width = pixels[0];
312✔
2200
  int pixel_height = pixels[1];
312✔
2201

312✔
2202
  // get pixel size
312✔
2203
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
312✔
2204
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
2205

528✔
2206
  // setup basis indices and initial position centered on pixel
2207
  int in_i, out_i;
528✔
2208
  Position xyz = origin;
528✔
2209
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
2210
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
528✔
2211
  switch (basis_enum) {
528✔
2212
  case PlotBasis::xy:
2213
    in_i = 0;
528✔
2214
    out_i = 1;
528✔
2215
    break;
2216
  case PlotBasis::xz:
528✔
2217
    in_i = 0;
528✔
2218
    out_i = 2;
2219
    break;
2220
  case PlotBasis::yz:
2221
    in_i = 1;
2222
    out_i = 2;
2223
    break;
2224
  default:
9,216✔
2225
    UNREACHABLE();
2226
  }
9,216✔
UNCOV
2227

×
UNCOV
2228
  // set initial position
×
2229
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
2230
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
9,216✔
2231

2232
#pragma omp parallel
2233
  {
2234
    Position r = xyz;
1,716✔
2235

2236
#pragma omp for
1,716✔
UNCOV
2237
    for (int y = 0; y < pixel_height; y++) {
×
2238
      r[out_i] = xyz[out_i] - out_pixel * y;
2239
      for (int x = 0; x < pixel_width; x++) {
1,716✔
2240
        r[in_i] = xyz[in_i] + in_pixel * x;
1,716✔
UNCOV
2241
        data[pixel_width * y + x] = mesh->get_bin(r);
×
UNCOV
2242
      }
×
2243
    }
2244
  }
1,716✔
2245

2246
  return 0;
156✔
2247
}
2248

156✔
UNCOV
2249
//! Get the dimension of a regular mesh
×
2250
extern "C" int openmc_regular_mesh_get_dimension(
2251
  int32_t index, int** dims, int* n)
156✔
2252
{
156✔
UNCOV
2253
  if (int err = check_mesh_type<RegularMesh>(index))
×
UNCOV
2254
    return err;
×
2255
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2256
  *dims = mesh->shape_.data();
156✔
2257
  *n = mesh->n_dimension_;
2258
  return 0;
156✔
2259
}
2260

156✔
UNCOV
2261
//! Set the dimension of a regular mesh
×
2262
extern "C" int openmc_regular_mesh_set_dimension(
2263
  int32_t index, int n, const int* dims)
156✔
2264
{
156✔
UNCOV
2265
  if (int err = check_mesh_type<RegularMesh>(index))
×
UNCOV
2266
    return err;
×
2267
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2268

156✔
2269
  // Copy dimension
2270
  mesh->n_dimension_ = n;
252✔
2271
  std::copy(dims, dims + n, mesh->shape_.begin());
2272
  return 0;
252✔
UNCOV
2273
}
×
2274

2275
//! Get the regular mesh parameters
252✔
2276
extern "C" int openmc_regular_mesh_get_params(
252✔
UNCOV
2277
  int32_t index, double** ll, double** ur, double** width, int* n)
×
UNCOV
2278
{
×
2279
  if (int err = check_mesh_type<RegularMesh>(index))
2280
    return err;
252✔
2281
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2282

1,152✔
2283
  if (m->lower_left_.dimension() == 0) {
2284
    set_errmsg("Mesh parameters have not been set.");
1,152✔
UNCOV
2285
    return OPENMC_E_ALLOCATE;
×
2286
  }
2287

1,152✔
2288
  *ll = m->lower_left_.data();
1,152✔
UNCOV
2289
  *ur = m->upper_right_.data();
×
UNCOV
2290
  *width = m->width_.data();
×
2291
  *n = m->n_dimension_;
2292
  return 0;
1,152✔
2293
}
2294

2295
//! Set the regular mesh parameters
2296
extern "C" int openmc_regular_mesh_set_params(
2297
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2298
{
2299
  if (int err = check_mesh_type<RegularMesh>(index))
2300
    return err;
2301
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2302

2303
  if (m->n_dimension_ == -1) {
2304
    set_errmsg("Need to set mesh dimension before setting parameters.");
2305
    return OPENMC_E_UNASSIGNED;
2306
  }
2307

2,088✔
2308
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
2309
  if (ll && ur) {
2,088✔
UNCOV
2310
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
×
2311
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
2312
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
2,088✔
2313
  } else if (ll && width) {
2314
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
2,088✔
2315
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
2316
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
2317
  } else if (ur && width) {
2318
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
456✔
2319
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
2320
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
2321
  } else {
456✔
2322
    set_errmsg("At least two parameters must be specified.");
456✔
2323
    return OPENMC_E_INVALID_ARGUMENT;
456✔
2324
  }
2325

912✔
2326
  // Set material volumes
456✔
2327

336✔
2328
  // TODO: incorporate this into method in RegularMesh that can be called from
120✔
2329
  // here and from constructor
72✔
2330
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
48✔
2331
  m->element_volume_ = 1.0;
24✔
2332
  for (int i = 0; i < m->n_dimension_; i++) {
24✔
2333
    m->element_volume_ *= m->width_[i];
24✔
2334
  }
UNCOV
2335

×
2336
  return 0;
2337
}
2338

456✔
2339
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
×
2340
template<class C>
2341
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
456✔
2342
  const int nx, const double* grid_y, const int ny, const double* grid_z,
456✔
2343
  const int nz)
2344
{
UNCOV
2345
  if (int err = check_mesh_type<C>(index))
×
2346
    return err;
2347

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

×
UNCOV
2350
  m->n_dimension_ = 3;
×
2351

2352
  m->grid_[0].reserve(nx);
2353
  m->grid_[1].reserve(ny);
2354
  m->grid_[2].reserve(nz);
2355

2356
  for (int i = 0; i < nx; i++) {
2357
    m->grid_[0].push_back(grid_x[i]);
2358
  }
2359
  for (int i = 0; i < ny; i++) {
2360
    m->grid_[1].push_back(grid_y[i]);
2361
  }
2362
  for (int i = 0; i < nz; i++) {
2363
    m->grid_[2].push_back(grid_z[i]);
2364
  }
2365

UNCOV
2366
  int err = m->set_grid();
×
UNCOV
2367
  return err;
×
2368
}
2369

UNCOV
2370
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
×
2371
template<class C>
2372
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
2373
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
UNCOV
2374
{
×
UNCOV
2375
  if (int err = check_mesh_type<C>(index))
×
2376
    return err;
UNCOV
2377
  C* m = dynamic_cast<C*>(model::meshes[index].get());
×
2378

2379
  if (m->lower_left_.dimension() == 0) {
2380
    set_errmsg("Mesh parameters have not been set.");
2381
    return OPENMC_E_ALLOCATE;
648✔
2382
  }
2383

648✔
2384
  *grid_x = m->grid_[0].data();
648✔
UNCOV
2385
  *nx = m->grid_[0].size();
×
UNCOV
2386
  *grid_y = m->grid_[1].data();
×
2387
  *ny = m->grid_[1].size();
2388
  *grid_z = m->grid_[2].data();
648✔
2389
  *nz = m->grid_[2].size();
648✔
2390

2391
  return 0;
2392
}
2393

4,260✔
2394
//! Get the rectilinear mesh grid
2395
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
4,260✔
UNCOV
2396
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
×
2397
{
4,260✔
2398
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
4,260✔
2399
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2400
}
2401

2402
//! Set the rectilienar mesh parameters
456✔
2403
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
2404
  const double* grid_x, const int nx, const double* grid_y, const int ny,
456✔
UNCOV
2405
  const double* grid_z, const int nz)
×
2406
{
456✔
2407
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
456✔
2408
    index, grid_x, nx, grid_y, ny, grid_z, nz);
456✔
2409
}
2410

2411
//! Get the cylindrical mesh grid
2412
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
252✔
2413
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2414
{
252✔
UNCOV
2415
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
×
2416
    index, grid_x, nx, grid_y, ny, grid_z, nz);
252✔
2417
}
252✔
2418

2419
//! Set the cylindrical mesh parameters
2420
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
2421
  const double* grid_x, const int nx, const double* grid_y, const int ny,
96✔
2422
  const double* grid_z, const int nz)
2423
{
96✔
UNCOV
2424
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
×
2425
    index, grid_x, nx, grid_y, ny, grid_z, nz);
1,056✔
2426
}
960✔
2427

2428
//! Get the spherical mesh grid
96✔
2429
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
2430
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2431
{
2432

144✔
2433
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
2434
    index, grid_x, nx, grid_y, ny, grid_z, nz);
144✔
UNCOV
2435
  ;
×
2436
}
2437

144✔
2438
//! Set the spherical mesh parameters
2439
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
2440
  const double* grid_x, const int nx, const double* grid_y, const int ny,
144✔
2441
  const double* grid_z, const int nz)
144✔
2442
{
144✔
2443
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
2444
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2445
}
144✔
2446

144✔
2447
#ifdef DAGMC
144✔
2448

144✔
2449
const std::string MOABMesh::mesh_lib_type = "moab";
2450

2451
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
156✔
2452
{
2453
  initialize();
2454
}
156✔
2455

×
2456
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2457
{
2458
  filename_ = filename;
156✔
2459
  set_length_multiplier(length_multiplier);
2460
  initialize();
12✔
2461
}
12✔
2462

12✔
2463
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
12✔
2464
{
UNCOV
2465
  mbi_ = external_mbi;
×
2466
  filename_ = "unknown (external file)";
2467
  this->initialize();
12✔
2468
}
2469

144✔
2470
void MOABMesh::initialize()
2471
{
2472

48✔
2473
  // Create the MOAB interface and load data from file
2474
  this->create_interface();
2475

48✔
UNCOV
2476
  // Initialise MOAB error code
×
2477
  moab::ErrorCode rval = moab::MB_SUCCESS;
48✔
2478

2479
  // Set the dimension
48✔
2480
  n_dimension_ = 3;
48✔
2481

2482
  // set member range of tetrahedral entities
2483
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
48✔
2484
  if (rval != moab::MB_SUCCESS) {
48✔
2485
    fatal_error("Failed to get all tetrahedral elements");
2486
  }
2487

2488
  if (!ehs_.all_of_type(moab::MBTET)) {
48✔
2489
    warning("Non-tetrahedral elements found in unstructured "
2490
            "mesh file: " +
48✔
2491
            filename_);
48✔
2492
  }
48✔
2493

48✔
2494
  // set member range of vertices
48✔
2495
  int vertex_dim = 0;
48✔
2496
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
×
UNCOV
2497
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2498
    fatal_error("Failed to get all vertex handles");
×
UNCOV
2499
  }
×
UNCOV
2500

×
UNCOV
2501
  // make an entity set for all tetrahedra
×
UNCOV
2502
  // this is used for convenience later in output
×
UNCOV
2503
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
×
UNCOV
2504
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2505
    fatal_error("Failed to create an entity set for the tetrahedral elements");
×
2506
  }
2507

2508
  rval = mbi_->add_entities(tetset_, ehs_);
2509
  if (rval != moab::MB_SUCCESS) {
48✔
2510
    fatal_error("Failed to add tetrahedra to an entity set.");
48✔
2511
  }
2512

24✔
2513
  if (length_multiplier_ > 0.0) {
2514
    // get the connectivity of all tets
24✔
2515
    moab::Range adj;
2516
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2517
    if (rval != moab::MB_SUCCESS) {
504✔
2518
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
480✔
2519
    }
10,080✔
2520
    // scale all vertex coords by multiplier (done individually so not all
9,600✔
2521
    // coordinates are in memory twice at once)
9,600✔
2522
    for (auto vert : adj) {
2523
      // retrieve coords
2524
      std::array<double, 3> coord;
2525
      rval = mbi_->get_coords(&vert, 1, coord.data());
2526
      if (rval != moab::MB_SUCCESS) {
48✔
2527
        fatal_error("Could not get coordinates of vertex.");
2528
      }
2529
      // scale coords
2530
      for (auto& c : coord) {
12✔
2531
        c *= length_multiplier_;
2532
      }
2533
      // set new coords
12✔
UNCOV
2534
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2535
      if (rval != moab::MB_SUCCESS) {
12✔
2536
        fatal_error("Failed to set new vertex coordinates");
12✔
2537
      }
12✔
2538
    }
12✔
2539
  }
2540

2541
  // Determine bounds of mesh
2542
  this->determine_bounds();
360✔
2543
}
2544

2545
void MOABMesh::prepare_for_point_location()
360✔
UNCOV
2546
{
×
2547
  // if the KDTree has already been constructed, do nothing
360✔
2548
  if (kdtree_)
2549
    return;
2550

360✔
2551
  // build acceleration data structures
360✔
2552
  compute_barycentric_data(ehs_);
360✔
2553
  build_kdtree(ehs_);
2554
}
2555

2556
void MOABMesh::create_interface()
384✔
2557
{
2558
  // Do not create a MOAB instance if one is already in memory
2559
  if (mbi_)
384✔
UNCOV
2560
    return;
×
2561

384✔
2562
  // create MOAB instance
2563
  mbi_ = std::make_shared<moab::Core>();
384✔
UNCOV
2564

×
UNCOV
2565
  // load unstructured mesh file
×
2566
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
2567
  if (rval != moab::MB_SUCCESS) {
2568
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
384✔
2569
  }
384✔
2570
}
384✔
2571

384✔
2572
void MOABMesh::build_kdtree(const moab::Range& all_tets)
384✔
2573
{
2574
  moab::Range all_tris;
2575
  int adj_dim = 2;
2576
  write_message("Getting tet adjacencies...", 7);
396✔
2577
  moab::ErrorCode rval = mbi_->get_adjacencies(
2578
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2579
  if (rval != moab::MB_SUCCESS) {
396✔
UNCOV
2580
    fatal_error("Failed to get adjacent triangles for tets");
×
2581
  }
396✔
2582

2583
  if (!all_tris.all_of_type(moab::MBTRI)) {
396✔
UNCOV
2584
    warning("Non-triangle elements found in tet adjacencies in "
×
UNCOV
2585
            "unstructured mesh file: " +
×
2586
            filename_);
2587
  }
2588

396✔
2589
  // combine into one range
396✔
2590
  moab::Range all_tets_and_tris;
372✔
2591
  all_tets_and_tris.merge(all_tets);
372✔
2592
  all_tets_and_tris.merge(all_tris);
372✔
2593

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

12✔
2599
  // Determine what options to use
12✔
2600
  std::ostringstream options_stream;
12✔
2601
  if (options_.empty()) {
UNCOV
2602
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
×
UNCOV
2603
  } else {
×
2604
    options_stream << options_;
2605
  }
2606
  moab::FileOptions file_opts(options_stream.str().c_str());
2607

2608
  // Build the k-d tree
2609
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
2610
  if (rval != moab::MB_SUCCESS) {
396✔
2611
    fatal_error("Failed to construct KDTree for the "
396✔
2612
                "unstructured mesh file: " +
1,584✔
2613
                filename_);
1,188✔
2614
  }
2615
}
2616

396✔
2617
void MOABMesh::intersect_track(const moab::CartVect& start,
396✔
2618
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2619
{
2620
  hits.clear();
2621

120✔
2622
  moab::ErrorCode rval;
2623
  vector<moab::EntityHandle> tris;
2624
  // get all intersections with triangles in the tet mesh
2625
  // (distances are relative to the start point, not the previous
120✔
UNCOV
2626
  // intersection)
×
2627
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
2628
    dir.array(), start.array(), tris, hits, 0, track_len);
120✔
2629
  if (rval != moab::MB_SUCCESS) {
2630
    fatal_error(
120✔
2631
      "Failed to compute intersections on unstructured mesh: " + filename_);
2632
  }
120✔
2633

120✔
2634
  // remove duplicate intersection distances
120✔
2635
  std::unique(hits.begin(), hits.end());
2636

960✔
2637
  // sorts by first component of std::pair by default
840✔
2638
  std::sort(hits.begin(), hits.end());
2639
}
444✔
2640

324✔
2641
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
2642
  vector<int>& bins, vector<double>& lengths) const
420✔
2643
{
300✔
2644
  moab::CartVect start(r0.x, r0.y, r0.z);
2645
  moab::CartVect end(r1.x, r1.y, r1.z);
2646
  moab::CartVect dir(u.x, u.y, u.z);
120✔
2647
  dir.normalize();
120✔
2648

2649
  double track_len = (end - start).length();
24✔
2650
  if (track_len == 0.0)
2651
    return;
2652

2653
  start -= TINY_BIT * dir;
24✔
UNCOV
2654
  end += TINY_BIT * dir;
×
2655

2656
  vector<double> hits;
24✔
2657
  intersect_track(start, dir, track_len, hits);
2658

24✔
2659
  bins.clear();
2660
  lengths.clear();
24✔
2661

24✔
2662
  // if there are no intersections the track may lie entirely
24✔
2663
  // within a single tet. If this is the case, apply entire
2664
  // score to that tet and return.
96✔
2665
  if (hits.size() == 0) {
72✔
2666
    Position midpoint = r0 + u * (track_len * 0.5);
2667
    int bin = this->get_bin(midpoint);
96✔
2668
    if (bin != -1) {
72✔
2669
      bins.push_back(bin);
2670
      lengths.push_back(1.0);
108✔
2671
    }
84✔
2672
    return;
2673
  }
2674

24✔
2675
  // for each segment in the set of tracks, try to look up a tet
24✔
2676
  // at the midpoint of the segment
2677
  Position current = r0;
24✔
2678
  double last_dist = 0.0;
2679
  for (const auto& hit : hits) {
2680
    // get the segment length
2681
    double segment_length = hit - last_dist;
24✔
UNCOV
2682
    last_dist = hit;
×
2683
    // find the midpoint of this segment
2684
    Position midpoint = current + u * (segment_length * 0.5);
24✔
2685
    // try to find a tet for this position
2686
    int bin = this->get_bin(midpoint);
24✔
2687

2688
    // determine the start point for this segment
24✔
2689
    current = r0 + u * hit;
24✔
2690

24✔
2691
    if (bin == -1) {
2692
      continue;
96✔
2693
    }
72✔
2694

2695
    bins.push_back(bin);
108✔
2696
    lengths.push_back(segment_length / track_len);
84✔
2697
  }
2698

84✔
2699
  // tally remaining portion of track after last hit if
60✔
2700
  // the last segment of the track is in the mesh but doesn't
2701
  // reach the other side of the tet
2702
  if (hits.back() < track_len) {
24✔
2703
    Position segment_start = r0 + u * hits.back();
24✔
2704
    double segment_length = track_len - hits.back();
2705
    Position midpoint = segment_start + u * (segment_length * 0.5);
72✔
2706
    int bin = this->get_bin(midpoint);
2707
    if (bin != -1) {
2708
      bins.push_back(bin);
2709
      lengths.push_back(segment_length / track_len);
72✔
UNCOV
2710
    }
×
2711
  }
2712
};
72✔
2713

2714
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
72✔
2715
{
2716
  moab::CartVect pos(r.x, r.y, r.z);
72✔
2717
  // find the leaf of the kd-tree for this position
72✔
2718
  moab::AdaptiveKDTreeIter kdtree_iter;
72✔
2719
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
2720
  if (rval != moab::MB_SUCCESS) {
768✔
2721
    return 0;
696✔
2722
  }
2723

240✔
2724
  // retrieve the tet elements of this leaf
168✔
2725
  moab::EntityHandle leaf = kdtree_iter.handle();
2726
  moab::Range tets;
228✔
2727
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
156✔
2728
  if (rval != moab::MB_SUCCESS) {
2729
    warning("MOAB error finding tets.");
2730
  }
72✔
2731

72✔
2732
  // loop over the tets in this leaf, returning the containing tet if found
2733
  for (const auto& tet : tets) {
2734
    if (point_in_tet(pos, tet)) {
2735
      return tet;
2736
    }
444✔
2737
  }
2738

2739
  // if no tet is found, return an invalid handle
444✔
UNCOV
2740
  return 0;
×
2741
}
444✔
2742

2743
double MOABMesh::volume(int bin) const
444✔
UNCOV
2744
{
×
UNCOV
2745
  return tet_volume(get_ent_handle_from_bin(bin));
×
2746
}
2747

2748
std::string MOABMesh::library() const
444✔
2749
{
444✔
2750
  return mesh_lib_type;
444✔
2751
}
444✔
2752

444✔
2753
// Sample position within a tet for MOAB type tets
444✔
2754
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
2755
{
444✔
2756

2757
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
132✔
2758

2759
  // Get vertex coordinates for MOAB tet
2760
  const moab::EntityHandle* conn1;
132✔
UNCOV
2761
  int conn1_size;
×
2762
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
132✔
2763
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
2764
    fatal_error(fmt::format(
132✔
UNCOV
2765
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
×
UNCOV
2766
      conn1_size));
×
2767
  }
2768
  moab::CartVect p[4];
2769
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
132✔
2770
  if (rval != moab::MB_SUCCESS) {
132✔
2771
    fatal_error("Failed to get tet coords");
132✔
2772
  }
132✔
2773

132✔
2774
  std::array<Position, 4> tet_verts;
132✔
2775
  for (int i = 0; i < 4; i++) {
2776
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
132✔
2777
  }
2778
  // Samples position within tet using Barycentric stuff
132✔
2779
  return this->sample_tet(tet_verts, seed);
2780
}
2781

132✔
UNCOV
2782
double MOABMesh::tet_volume(moab::EntityHandle tet) const
×
2783
{
132✔
2784
  vector<moab::EntityHandle> conn;
2785
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
132✔
UNCOV
2786
  if (rval != moab::MB_SUCCESS) {
×
UNCOV
2787
    fatal_error("Failed to get tet connectivity");
×
2788
  }
2789

2790
  moab::CartVect p[4];
132✔
2791
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
132✔
2792
  if (rval != moab::MB_SUCCESS) {
132✔
2793
    fatal_error("Failed to get tet coords");
132✔
2794
  }
132✔
2795

132✔
2796
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
2797
}
132✔
2798

2799
int MOABMesh::get_bin(Position r) const
180✔
2800
{
2801
  moab::EntityHandle tet = get_tet(r);
2802
  if (tet == 0) {
180✔
UNCOV
2803
    return -1;
×
2804
  } else {
180✔
2805
    return get_bin_from_ent_handle(tet);
2806
  }
180✔
UNCOV
2807
}
×
UNCOV
2808

×
2809
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
2810
{
2811
  moab::ErrorCode rval;
180✔
2812

180✔
2813
  baryc_data_.clear();
180✔
2814
  baryc_data_.resize(tets.size());
180✔
2815

180✔
2816
  // compute the barycentric data for each tet element
180✔
2817
  // and store it as a 3x3 matrix
2818
  for (auto& tet : tets) {
180✔
2819
    vector<moab::EntityHandle> verts;
2820
    rval = mbi_->get_connectivity(&tet, 1, verts);
2821
    if (rval != moab::MB_SUCCESS) {
2822
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
180✔
2823
    }
2824

2825
    moab::CartVect p[4];
180✔
2826
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
180✔
2827
    if (rval != moab::MB_SUCCESS) {
2828
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
2829
    }
2830

72✔
2831
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
2832

2833
    // invert now to avoid this cost later
2834
    a = a.transpose().inverse();
72✔
2835
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
72✔
2836
  }
2837
}
2838

2839
bool MOABMesh::point_in_tet(
132✔
2840
  const moab::CartVect& r, moab::EntityHandle tet) const
2841
{
2842

132✔
2843
  moab::ErrorCode rval;
132✔
2844

2845
  // get tet vertices
2846
  vector<moab::EntityHandle> verts;
2847
  rval = mbi_->get_connectivity(&tet, 1, verts);
24✔
2848
  if (rval != moab::MB_SUCCESS) {
2849
    warning("Failed to get vertices of tet in umesh: " + filename_);
2850
    return false;
2851
  }
24✔
2852

24✔
2853
  // first vertex is used as a reference point for the barycentric data -
2854
  // retrieve its coordinates
2855
  moab::CartVect p_zero;
2856
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
132✔
2857
  if (rval != moab::MB_SUCCESS) {
2858
    warning("Failed to get coordinates of a vertex in "
2859
            "unstructured mesh: " +
2860
            filename_);
132✔
2861
    return false;
132✔
2862
  }
2863

2864
  // look up barycentric data
2865
  int idx = get_bin_from_ent_handle(tet);
2866
  const moab::Matrix3& a_inv = baryc_data_[idx];
24✔
2867

2868
  moab::CartVect bary_coords = a_inv * (r - p_zero);
2869

2870
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
24✔
2871
          bary_coords[2] >= 0.0 &&
24✔
2872
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
2873
}
2874

2875
int MOABMesh::get_bin_from_index(int idx) const
2876
{
2877
  if (idx >= n_bins()) {
2878
    fatal_error(fmt::format("Invalid bin index: {}", idx));
22✔
2879
  }
2880
  return ehs_[idx] - ehs_[0];
22✔
2881
}
22✔
2882

2883
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
2884
{
2885
  int bin = get_bin(r);
2886
  *in_mesh = bin != -1;
2887
  return bin;
2888
}
2889

2890
int MOABMesh::get_index_from_bin(int bin) const
1✔
2891
{
2892
  return bin;
1✔
2893
}
1✔
2894

1✔
2895
std::pair<vector<double>, vector<double>> MOABMesh::plot(
1✔
2896
  Position plot_ll, Position plot_ur) const
2897
{
23✔
2898
  // TODO: Implement mesh lines
2899
  return {};
2900
}
2901

23✔
2902
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
2903
{
2904
  int idx = vert - verts_[0];
23✔
2905
  if (idx >= n_vertices()) {
2906
    fatal_error(
2907
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
23✔
2908
  }
2909
  return idx;
2910
}
23✔
2911

23✔
2912
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
2913
{
2914
  int bin = eh - ehs_[0];
2915
  if (bin >= n_bins()) {
23✔
2916
    fatal_error(fmt::format("Invalid bin: {}", bin));
2917
  }
2918
  return bin;
2919
}
2920

2921
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
2922
{
23✔
2923
  if (bin >= n_bins()) {
23✔
2924
    fatal_error(fmt::format("Invalid bin index: ", bin));
23✔
2925
  }
2926
  return ehs_[0] + bin;
2927
}
2928

2929
int MOABMesh::n_bins() const
2930
{
23✔
2931
  return ehs_.size();
23✔
2932
}
2933

2934
int MOABMesh::n_surface_bins() const
2935
{
23✔
2936
  // collect all triangles in the set of tets for this mesh
23✔
2937
  moab::Range tris;
2938
  moab::ErrorCode rval;
2939
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
2940
  if (rval != moab::MB_SUCCESS) {
23✔
2941
    warning("Failed to get all triangles in the mesh instance");
2942
    return -1;
2943
  }
2944
  return 2 * tris.size();
2945
}
2946

2947
Position MOABMesh::centroid(int bin) const
2948
{
2949
  moab::ErrorCode rval;
2950

2951
  auto tet = this->get_ent_handle_from_bin(bin);
2952

2953
  // look up the tet connectivity
2954
  vector<moab::EntityHandle> conn;
2955
  rval = mbi_->get_connectivity(&tet, 1, conn);
2956
  if (rval != moab::MB_SUCCESS) {
2957
    warning("Failed to get connectivity of a mesh element.");
2958
    return {};
2959
  }
2960

2961
  // get the coordinates
2962
  vector<moab::CartVect> coords(conn.size());
2963
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
2964
  if (rval != moab::MB_SUCCESS) {
2965
    warning("Failed to get the coordinates of a mesh element.");
2966
    return {};
2967
  }
2968

2969
  // compute the centroid of the element vertices
23✔
2970
  moab::CartVect centroid(0.0, 0.0, 0.0);
23✔
2971
  for (const auto& coord : coords) {
2972
    centroid += coord;
19✔
2973
  }
2974
  centroid /= double(coords.size());
2975

19✔
2976
  return {centroid[0], centroid[1], centroid[2]};
2977
}
2978

2979
int MOABMesh::n_vertices() const
19✔
2980
{
19✔
2981
  return verts_.size();
2982
}
2983

23✔
2984
Position MOABMesh::vertex(int id) const
2985
{
2986

23✔
2987
  moab::ErrorCode rval;
1✔
2988

2989
  moab::EntityHandle vert = verts_[id];
2990

22✔
2991
  moab::CartVect coords;
2992
  rval = mbi_->get_coords(&vert, 1, coords.array());
2993
  if (rval != moab::MB_SUCCESS) {
22✔
2994
    fatal_error("Failed to get the coordinates of a vertex.");
22✔
2995
  }
2996

2997
  return {coords[0], coords[1], coords[2]};
2998
}
2999

19✔
3000
std::vector<int> MOABMesh::connectivity(int bin) const
3001
{
19✔
3002
  moab::ErrorCode rval;
19✔
3003

19✔
3004
  auto tet = get_ent_handle_from_bin(bin);
19✔
3005

3006
  // look up the tet connectivity
19✔
3007
  vector<moab::EntityHandle> conn;
3008
  rval = mbi_->get_connectivity(&tet, 1, conn);
3009
  if (rval != moab::MB_SUCCESS) {
3010
    fatal_error("Failed to get connectivity of a mesh element.");
19✔
3011
    return {};
3012
  }
3013

3014
  std::vector<int> verts(4);
3015
  for (int i = 0; i < verts.size(); i++) {
3016
    verts[i] = get_vert_idx_from_handle(conn[i]);
3017
  }
19✔
3018

19✔
3019
  return verts;
19✔
3020
}
3021

3022
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
19✔
3023
  std::string score) const
19✔
3024
{
19✔
3025
  moab::ErrorCode rval;
3026
  // add a tag to the mesh
3027
  // all scores are treated as a single value
19✔
3028
  // with an uncertainty
19✔
3029
  moab::Tag value_tag;
3✔
3030

3031
  // create the value tag if not present and get handle
16✔
3032
  double default_val = 0.0;
3033
  auto val_string = score + "_mean";
19✔
3034
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3035
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3036
  if (rval != moab::MB_SUCCESS) {
19✔
3037
    auto msg =
19✔
3038
      fmt::format("Could not create or retrieve the value tag for the score {}"
3039
                  " on unstructured mesh {}",
3040
        score, id_);
3041
    fatal_error(msg);
3042
  }
19✔
3043

3044
  // create the std dev tag if not present and get handle
1,519,602✔
3045
  moab::Tag error_tag;
3046
  std::string err_string = score + "_std_dev";
3047
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
1,519,602✔
3048
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3049
  if (rval != moab::MB_SUCCESS) {
3050
    auto msg =
1,519,602✔
3051
      fmt::format("Could not create or retrieve the error tag for the score {}"
3052
                  " on unstructured mesh {}",
3053
        score, id_);
3054
    fatal_error(msg);
1,519,602✔
3055
  }
3056

1,519,602✔
3057
  // return the populated tag handles
3058
  return {value_tag, error_tag};
3059
}
3060

3061
void MOABMesh::add_score(const std::string& score)
3062
{
1,519,602✔
3063
  auto score_tags = get_score_tags(score);
3064
  tag_names_.push_back(score);
3065
}
1,519,602✔
3066

1,519,602✔
3067
void MOABMesh::remove_scores()
3068
{
1,519,602✔
3069
  for (const auto& name : tag_names_) {
3070
    auto value_name = name + "_mean";
3071
    moab::Tag tag;
1,519,602✔
3072
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
1,519,602✔
3073
    if (rval != moab::MB_SUCCESS)
1,519,602✔
3074
      return;
1,519,602✔
3075

3076
    rval = mbi_->tag_delete(tag);
1,519,602✔
3077
    if (rval != moab::MB_SUCCESS) {
1,519,602✔
3078
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
701,483✔
3079
                             " on unstructured mesh {}",
3080
        name, id_);
1,519,602✔
3081
      fatal_error(msg);
1,519,602✔
3082
    }
3083

1,519,602✔
3084
    auto std_dev_name = name + "_std_dev";
1,519,602✔
3085
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3086
    if (rval != moab::MB_SUCCESS) {
1,519,602✔
3087
      auto msg =
1,519,602✔
3088
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3089
                    " on unstructured mesh {}",
3090
          name, id_);
3091
    }
3092

1,519,602✔
3093
    rval = mbi_->tag_delete(tag);
701,483✔
3094
    if (rval != moab::MB_SUCCESS) {
701,483✔
3095
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
701,483✔
3096
                             " on unstructured mesh {}",
223,515✔
3097
        name, id_);
223,515✔
3098
      fatal_error(msg);
3099
    }
701,483✔
3100
  }
3101
  tag_names_.clear();
3102
}
3103

3104
void MOABMesh::set_score_data(const std::string& score,
818,119✔
3105
  const vector<double>& values, const vector<double>& std_dev)
818,119✔
3106
{
5,506,248✔
3107
  auto score_tags = this->get_score_tags(score);
3108

4,688,129✔
3109
  moab::ErrorCode rval;
4,688,129✔
3110
  // set the score value
3111
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
4,688,129✔
3112
  if (rval != moab::MB_SUCCESS) {
3113
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
4,688,129✔
3114
                           "on unstructured mesh {}",
3115
      score, id_);
3116
    warning(msg);
4,688,129✔
3117
  }
3118

4,688,129✔
3119
  // set the error value
20,480✔
3120
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3121
  if (rval != moab::MB_SUCCESS) {
3122
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
4,667,649✔
3123
                           "on unstructured mesh {}",
4,667,649✔
3124
      score, id_);
3125
    warning(msg);
3126
  }
3127
}
3128

3129
void MOABMesh::write(const std::string& base_filename) const
818,119✔
3130
{
818,119✔
3131
  // add extension to the base name
818,119✔
3132
  auto filename = base_filename + ".vtk";
818,119✔
3133
  write_message(5, "Writing unstructured mesh {}...", filename);
818,119✔
3134
  filename = settings::path_output + filename;
818,119✔
3135

762,819✔
3136
  // write the tetrahedral elements of the mesh only
762,819✔
3137
  // to avoid clutter from zero-value data on other
3138
  // elements during visualization
3139
  moab::ErrorCode rval;
1,519,602✔
3140
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3141
  if (rval != moab::MB_SUCCESS) {
7,279,728✔
3142
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3143
    warning(msg);
7,279,728✔
3144
  }
3145
}
7,279,728✔
3146

7,279,728✔
3147
#endif
7,279,728✔
3148

1,010,077✔
3149
#ifdef LIBMESH
3150

3151
const std::string LibMesh::mesh_lib_type = "libmesh";
3152

6,269,651✔
3153
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node), adaptive_(false)
6,269,651✔
3154
{
6,269,651✔
3155
  // filename_ and length_multiplier_ will already be set by the
6,269,651✔
3156
  // UnstructuredMesh constructor
3157
  set_mesh_pointer_from_filename(filename_);
3158
  set_length_multiplier(length_multiplier_);
3159
  initialize();
3160
}
259,367,091✔
3161

259,364,245✔
3162
// create the mesh from a pointer to a libMesh Mesh
6,266,805✔
3163
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3164
  : adaptive_(input_mesh.n_active_elem() != input_mesh.n_elem())
3165
{
3166
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
3167
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
2,846✔
3168
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
7,279,728✔
3169
  }
3170

155,856✔
3171
  m_ = &input_mesh;
3172
  set_length_multiplier(length_multiplier);
155,856✔
3173
  initialize();
3174
}
3175

30✔
3176
// create the mesh from an input file
3177
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
30✔
3178
  : adaptive_(false)
3179
{
3180
  set_mesh_pointer_from_filename(filename);
3181
  set_length_multiplier(length_multiplier);
200,410✔
3182
  initialize();
3183
}
3184

200,410✔
3185
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3186
{
3187
  filename_ = filename;
3188
  unique_m_ =
3189
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
200,410✔
3190
  m_ = unique_m_.get();
200,410✔
3191
  m_->read(filename_);
3192
}
3193

3194
// build a libMesh equation system for storing values
3195
void LibMesh::build_eqn_sys()
1,002,050✔
3196
{
200,410✔
3197
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
200,410✔
3198
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3199
  libMesh::ExplicitSystem& eq_sys =
3200
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3201
}
200,410✔
3202

1,002,050✔
3203
// intialize from mesh file
801,640✔
3204
void LibMesh::initialize()
3205
{
3206
  if (!settings::libmesh_comm) {
400,820✔
3207
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3208
                "communicator.");
3209
  }
155,856✔
3210

3211
  // assuming that unstructured meshes used in OpenMC are 3D
155,856✔
3212
  n_dimension_ = 3;
155,856✔
3213

155,856✔
3214
  if (length_multiplier_ > 0.0) {
3215
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
3216
  }
3217
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
779,280✔
3218
  // Otherwise assume that it is prepared by its owning application
155,856✔
3219
  if (unique_m_) {
155,856✔
3220
    m_->prepare_for_use();
3221
  }
3222

3223
  // ensure that the loaded mesh is 3 dimensional
311,712✔
3224
  if (m_->mesh_dimension() != n_dimension_) {
155,856✔
3225
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3226
                            "mesh is not a 3D mesh.",
7,279,728✔
3227
      filename_));
3228
  }
7,279,728✔
3229

7,279,728✔
3230
  for (int i = 0; i < num_threads(); i++) {
1,012,923✔
3231
    pl_.emplace_back(m_->sub_point_locator());
3232
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
6,266,805✔
3233
    pl_.back()->enable_out_of_mesh_mode();
3234
  }
3235

3236
  // store first element in the mesh to use as an offset for bin indices
19✔
3237
  auto first_elem = *m_->elements_begin();
3238
  first_element_id_ = first_elem->id();
3239

3240
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
19✔
3241
  // contiguous in ID space, so we need to map from bin indices (defined over
19✔
3242
  // active elements) to global dof ids
3243
  if (adaptive_) {
3244
    bin_to_elem_map_.reserve(m_->n_active_elem());
3245
    elem_to_bin_map_.resize(m_->n_elem(), -1);
227,731✔
3246
    for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
227,712✔
3247
         it++) {
227,712✔
3248
      auto elem = *it;
227,712✔
3249

3250
      bin_to_elem_map_.push_back(elem->id());
3251
      elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3252
    }
1,138,560✔
3253
  }
227,712✔
3254

227,712✔
3255
  // bounding box for the mesh for quick rejection checks
3256
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3257
  libMesh::Point ll = bbox_.min();
3258
  libMesh::Point ur = bbox_.max();
227,712✔
3259
  lower_left_ = {ll(0), ll(1), ll(2)};
3260
  upper_right_ = {ur(0), ur(1), ur(2)};
3261
}
227,712✔
3262

227,712✔
3263
// Sample position within a tet for LibMesh type tets
227,712✔
3264
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
19✔
3265
{
3266
  const auto& elem = get_element_from_bin(bin);
259,364,245✔
3267
  // Get tet vertex coordinates from LibMesh
3268
  std::array<Position, 4> tet_verts;
3269
  for (int i = 0; i < elem.n_nodes(); i++) {
3270
    auto node_ref = elem.node_ref(i);
3271
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3272
  }
3273
  // Samples position within tet using Barycentric coordinates
259,364,245✔
3274
  return this->sample_tet(tet_verts, seed);
259,364,245✔
3275
}
259,364,245✔
3276

3277
Position LibMesh::centroid(int bin) const
3278
{
3279
  const auto& elem = this->get_element_from_bin(bin);
3280
  auto centroid = elem.vertex_average();
3281
  return {centroid(0), centroid(1), centroid(2)};
3282
}
259,364,245✔
3283

259,364,245✔
3284
int LibMesh::n_vertices() const
259,364,245✔
3285
{
3286
  return m_->n_nodes();
3287
}
3288

3289
Position LibMesh::vertex(int vertex_id) const
3290
{
3291
  const auto node_ref = m_->node_ref(vertex_id);
3292
  return {node_ref(0), node_ref(1), node_ref(2)};
259,364,245✔
3293
}
259,364,245✔
3294

3295
std::vector<int> LibMesh::connectivity(int elem_id) const
259,364,245✔
3296
{
3297
  std::vector<int> conn;
420,046,390✔
3298
  const auto* elem_ptr = m_->elem_ptr(elem_id);
441,624,143✔
3299
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
280,941,998✔
3300
    conn.push_back(elem_ptr->node_id(i));
259,364,245✔
3301
  }
3302
  return conn;
3303
}
3304

3305
std::string LibMesh::library() const
3306
{
3307
  return mesh_lib_type;
3308
}
3309

3310
int LibMesh::n_bins() const
3311
{
3312
  return m_->n_active_elem();
3313
}
3314

3315
int LibMesh::n_surface_bins() const
3316
{
3317
  int n_bins = 0;
3318
  for (int i = 0; i < this->n_bins(); i++) {
3319
    const libMesh::Elem& e = get_element_from_bin(i);
3320
    n_bins += e.n_faces();
3321
    // if this is a boundary element, it will only be visited once,
3322
    // the number of surface bins is incremented to
3323
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3324
      // null neighbor pointer indicates a boundary face
3325
      if (!neighbor_ptr) {
3326
        n_bins++;
3327
      }
3328
    }
3329
  }
767,424✔
3330
  return n_bins;
3331
}
767,424✔
3332

767,424✔
3333
void LibMesh::add_score(const std::string& var_name)
3334
{
3335
  if (adaptive_) {
3336
    warning(fmt::format(
767,424✔
3337
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3338
      this->id_));
3339

265,858,762✔
3340
    return;
3341
  }
265,858,762✔
3342

265,858,762✔
3343
  if (!equation_systems_) {
3344
    build_eqn_sys();
3345
  }
265,858,762✔
3346

3347
  // check if this is a new variable
3348
  std::string value_name = var_name + "_mean";
548,122✔
3349
  if (!variable_map_.count(value_name)) {
3350
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
548,122✔
3351
    auto var_num =
3352
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3353
    variable_map_[value_name] = var_num;
548,122✔
3354
  }
3355

3356
  std::string std_dev_name = var_name + "_std_dev";
266,598,805✔
3357
  // check if this is a new variable
3358
  if (!variable_map_.count(std_dev_name)) {
266,598,805✔
3359
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3360
    auto var_num =
3361
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3362
    variable_map_[std_dev_name] = var_num;
3363
  }
3364
}
3365

3366
void LibMesh::remove_scores()
3367
{
3368
  if (equation_systems_) {
3369
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3370
    eqn_sys.clear();
3371
    variable_map_.clear();
3372
  }
3373
}
3374

3375
void LibMesh::set_score_data(const std::string& var_name,
3376
  const vector<double>& values, const vector<double>& std_dev)
3377
{
3378
  if (adaptive_) {
3379
    warning(fmt::format(
3380
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3381
      this->id_));
3382

3383
    return;
3384
  }
3385

3386
  if (!equation_systems_) {
3387
    build_eqn_sys();
3388
  }
3389

3390
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3391

3392
  if (!eqn_sys.is_initialized()) {
3393
    equation_systems_->init();
3394
  }
3395

3396
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3397

3398
  // look up the value variable
3399
  std::string value_name = var_name + "_mean";
3400
  unsigned int value_num = variable_map_.at(value_name);
3401
  // look up the std dev variable
3402
  std::string std_dev_name = var_name + "_std_dev";
3403
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3404

3405
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3406
       it++) {
795,427✔
3407
    if (!(*it)->active()) {
3408
      continue;
795,427✔
3409
    }
3410

3411
    auto bin = get_bin_from_element(*it);
81,537✔
3412

3413
    // set value
3414
    vector<libMesh::dof_id_type> value_dof_indices;
3415
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3416
    Ensures(value_dof_indices.size() == 1);
81,537✔
3417
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3418

81,537✔
3419
    // set std dev
81,537✔
3420
    vector<libMesh::dof_id_type> std_dev_dof_indices;
81,537✔
3421
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3422
    Ensures(std_dev_dof_indices.size() == 1);
3423
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3424
  }
163,074✔
3425
}
3426

3427
void LibMesh::write(const std::string& filename) const
191,856✔
3428
{
3429
  if (adaptive_) {
3430
    warning(fmt::format(
3431
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
191,856✔
3432
      this->id_));
3433

3434
    return;
191,856✔
3435
  }
191,856✔
3436

191,856✔
3437
  write_message(fmt::format(
3438
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3439
  libMesh::ExodusII_IO exo(*m_);
3440
  std::set<std::string> systems_out = {eq_system_name_};
3441
  exo.write_discontinuous_exodusII(
191,856✔
3442
    filename + ".e", *equation_systems_, &systems_out);
959,280✔
3443
}
767,424✔
3444

3445
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3446
  vector<int>& bins, vector<double>& lengths) const
191,856✔
3447
{
191,856✔
3448
  // TODO: Implement triangle crossings here
3449
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3450
}
3451

3452
int LibMesh::get_bin(Position r) const
3453
{
3454
  // look-up a tet using the point locator
3455
  libMesh::Point p(r.x, r.y, r.z);
3456

3457
  // quick rejection check
3458
  if (!bbox_.contains_point(p)) {
3459
    return -1;
3460
  }
3461

3462
  const auto& point_locator = pl_.at(thread_num());
3463

3464
  const auto elem_ptr = (*point_locator)(p);
3465
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3466
}
3467

3468
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3469
{
3470
  int bin =
3471
    adaptive_ ? elem_to_bin_map_[elem->id()] : elem->id() - first_element_id_;
3472
  if (bin >= n_bins() || bin < 0) {
3473
    fatal_error(fmt::format("Invalid bin: {}", bin));
3474
  }
3475
  return bin;
3476
}
3477

3478
std::pair<vector<double>, vector<double>> LibMesh::plot(
3479
  Position plot_ll, Position plot_ur) const
3480
{
3481
  return {};
3482
}
3483

3484
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3485
{
3486
  return adaptive_ ? m_->elem_ref(bin_to_elem_map_.at(bin)) : m_->elem_ref(bin);
3487
}
3488

3489
double LibMesh::volume(int bin) const
3490
{
3491
  return this->get_element_from_bin(bin).volume();
3492
}
3493

3494
#endif // LIBMESH
3495

3496
//==============================================================================
3497
// Non-member functions
3498
//==============================================================================
3499

3500
void read_meshes(pugi::xml_node root)
3501
{
3502
  std::unordered_set<int> mesh_ids;
3503

3504
  for (auto node : root.children("mesh")) {
3505
    // Check to make sure multiple meshes in the same file don't share IDs
3506
    int id = std::stoi(get_node_value(node, "id"));
3507
    if (contains(mesh_ids, id)) {
3508
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
3509
                              "'{}' in the same input file",
3510
        id));
3511
    }
3512
    mesh_ids.insert(id);
3513

3514
    // If we've already read a mesh with the same ID in a *different* file,
3515
    // assume it is the same here
3516
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3517
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
3518
      continue;
3519
    }
3520

3521
    std::string mesh_type;
3522
    if (check_for_node(node, "type")) {
3523
      mesh_type = get_node_value(node, "type", true, true);
3524
    } else {
3525
      mesh_type = "regular";
3526
    }
3527

3528
    // determine the mesh library to use
3529
    std::string mesh_lib;
3530
    if (check_for_node(node, "library")) {
3531
      mesh_lib = get_node_value(node, "library", true, true);
3532
    }
3533

3534
    // Read mesh and add to vector
3535
    if (mesh_type == RegularMesh::mesh_type) {
3536
      model::meshes.push_back(make_unique<RegularMesh>(node));
3537
    } else if (mesh_type == RectilinearMesh::mesh_type) {
3538
      model::meshes.push_back(make_unique<RectilinearMesh>(node));
3539
    } else if (mesh_type == CylindricalMesh::mesh_type) {
3540
      model::meshes.push_back(make_unique<CylindricalMesh>(node));
3541
    } else if (mesh_type == SphericalMesh::mesh_type) {
3542
      model::meshes.push_back(make_unique<SphericalMesh>(node));
3543
#ifdef DAGMC
3544
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3545
               mesh_lib == MOABMesh::mesh_lib_type) {
3546
      model::meshes.push_back(make_unique<MOABMesh>(node));
3547
#endif
3548
#ifdef LIBMESH
3549
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3550
               mesh_lib == LibMesh::mesh_lib_type) {
3551
      model::meshes.push_back(make_unique<LibMesh>(node));
3552
#endif
3553
    } else if (mesh_type == UnstructuredMesh::mesh_type) {
3554
      fatal_error("Unstructured mesh support is not enabled or the mesh "
3555
                  "library is invalid.");
3556
    } else {
3557
      fatal_error("Invalid mesh type: " + mesh_type);
3558
    }
3559

3560
    // Map ID to position in vector
3561
    model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3562
  }
3563
}
3564

3565
void meshes_to_hdf5(hid_t group)
3566
{
3567
  // Write number of meshes
3568
  hid_t meshes_group = create_group(group, "meshes");
3569
  int32_t n_meshes = model::meshes.size();
3570
  write_attribute(meshes_group, "n_meshes", n_meshes);
3571

3572
  if (n_meshes > 0) {
3573
    // Write IDs of meshes
3574
    vector<int> ids;
3575
    for (const auto& m : model::meshes) {
3576
      m->to_hdf5(meshes_group);
3577
      ids.push_back(m->id_);
3578
    }
3579
    write_attribute(meshes_group, "ids", ids);
3580
  }
23✔
3581

3582
  close_group(meshes_group);
3583
}
3584

23✔
3585
void free_memory_mesh()
23✔
3586
{
23✔
3587
  model::meshes.clear();
23✔
3588
  model::mesh_map.clear();
3589
}
3590

3591
extern "C" int n_meshes()
3592
{
3593
  return model::meshes.size();
3594
}
3595

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