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

openmc-dev / openmc / 12776996362

14 Jan 2025 09:49PM UTC coverage: 84.938% (+0.2%) from 84.729%
12776996362

Pull #3133

github

web-flow
Merge 0495246d9 into 549cc0973
Pull Request #3133: Kinetics parameters using Iterated Fission Probability

318 of 330 new or added lines in 10 files covered. (96.36%)

1658 existing lines in 66 files now uncovered.

50402 of 59340 relevant lines covered (84.94%)

33987813.96 hits per line

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

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

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

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/particle_data.h"
33
#include "openmc/plot.h"
34
#include "openmc/random_dist.h"
35
#include "openmc/search.h"
36
#include "openmc/settings.h"
37
#include "openmc/tallies/filter.h"
38
#include "openmc/tallies/tally.h"
39
#include "openmc/volume_calc.h"
40
#include "openmc/xml_interface.h"
41

42
#ifdef LIBMESH
43
#include "libmesh/mesh_modification.h"
44
#include "libmesh/mesh_tools.h"
45
#include "libmesh/numeric_vector.h"
46
#endif
47

48
#ifdef DAGMC
49
#include "moab/FileOptions.hpp"
50
#endif
51

52
namespace openmc {
53

54
//==============================================================================
55
// Global variables
56
//==============================================================================
57

58
#ifdef LIBMESH
59
const bool LIBMESH_ENABLED = true;
60
#else
61
const bool LIBMESH_ENABLED = false;
62
#endif
63

64
namespace model {
65

66
std::unordered_map<int32_t, int32_t> mesh_map;
67
vector<unique_ptr<Mesh>> meshes;
68

69
} // namespace model
70

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

78
//==============================================================================
79
// Helper functions
80
//==============================================================================
81

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

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

105
//==============================================================================
106
// Mesh implementation
107
//==============================================================================
108

109
Mesh::Mesh(pugi::xml_node node)
2,762✔
110
{
111
  // Read mesh id
112
  id_ = std::stoi(get_node_value(node, "id"));
2,762✔
113
  if (check_for_node(node, "name"))
2,762✔
114
    name_ = get_node_value(node, "name");
17✔
115
}
2,762✔
116

117
void Mesh::set_id(int32_t id)
1✔
118
{
119
  Expects(id >= 0 || id == C_NONE);
1✔
120

121
  // Clear entry in mesh map in case one was already assigned
122
  if (id_ != C_NONE) {
1✔
UNCOV
123
    model::mesh_map.erase(id_);
×
UNCOV
124
    id_ = C_NONE;
×
125
  }
126

127
  // Ensure no other mesh has the same ID
128
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
1✔
UNCOV
129
    throw std::runtime_error {
×
UNCOV
130
      fmt::format("Two meshes have the same ID: {}", id)};
×
131
  }
132

133
  // If no ID is specified, auto-assign the next ID in the sequence
134
  if (id == C_NONE) {
1✔
135
    id = 0;
1✔
136
    for (const auto& m : model::meshes) {
3✔
137
      id = std::max(id, m->id_);
2✔
138
    }
139
    ++id;
1✔
140
  }
141

142
  // Update ID and entry in the mesh map
143
  id_ = id;
1✔
144
  model::mesh_map[id] = model::meshes.size() - 1;
1✔
145
}
1✔
146

147
vector<double> Mesh::volumes() const
156✔
148
{
149
  vector<double> volumes(n_bins());
156✔
150
  for (int i = 0; i < n_bins(); i++) {
982,476✔
151
    volumes[i] = this->volume(i);
982,320✔
152
  }
153
  return volumes;
156✔
UNCOV
154
}
×
155

156
int Mesh::material_volumes(
384✔
157
  int n_sample, int bin, gsl::span<MaterialVolume> result, uint64_t* seed) const
158
{
159
  vector<int32_t> materials;
384✔
160
  vector<int64_t> hits;
384✔
161

162
#pragma omp parallel
192✔
163
  {
164
    vector<int32_t> local_materials;
192✔
165
    vector<int64_t> local_hits;
192✔
166
    GeometryState geom;
192✔
167

168
#pragma omp for
169
    for (int i = 0; i < n_sample; ++i) {
26,166,192✔
170
      // Get seed for i-th sample
171
      uint64_t seed_i = future_seed(3 * i, *seed);
26,166,000✔
172

173
      // Sample position and set geometry state
174
      geom.r() = this->sample_element(bin, &seed_i);
26,166,000✔
175
      geom.u() = {1., 0., 0.};
26,166,000✔
176
      geom.n_coord() = 1;
26,166,000✔
177

178
      // If this location is not in the geometry at all, move on to next block
179
      if (!exhaustive_find_cell(geom))
26,166,000✔
180
        continue;
363,036✔
181

182
      int i_material = geom.material();
25,802,964✔
183

184
      // Check if this material was previously hit and if so, increment count
185
      auto it =
186
        std::find(local_materials.begin(), local_materials.end(), i_material);
25,802,964✔
187
      if (it == local_materials.end()) {
25,802,964✔
188
        local_materials.push_back(i_material);
384✔
189
        local_hits.push_back(1);
384✔
190
      } else {
191
        local_hits[it - local_materials.begin()]++;
25,802,580✔
192
      }
193
    } // omp for
194

195
    // Reduce index/hits lists from each thread into a single copy
196
    reduce_indices_hits(local_materials, local_hits, materials, hits);
192✔
197
  } // omp parallel
192✔
198

199
  // Advance RNG seed
200
  advance_prn_seed(3 * n_sample, seed);
384✔
201

202
  // Make sure span passed in is large enough
203
  if (hits.size() > result.size()) {
384✔
UNCOV
204
    return -1;
×
205
  }
206

207
  // Convert hits to fractions
208
  for (int i_mat = 0; i_mat < hits.size(); ++i_mat) {
1,152✔
209
    double fraction = double(hits[i_mat]) / n_sample;
768✔
210
    result[i_mat].material = materials[i_mat];
768✔
211
    result[i_mat].volume = fraction * this->volume(bin);
768✔
212
  }
213
  return hits.size();
384✔
214
}
384✔
215

UNCOV
216
vector<Mesh::MaterialVolume> Mesh::material_volumes(
×
217
  int n_sample, int bin, uint64_t* seed) const
218
{
219
  // Create result vector with space for 8 pairs
220
  vector<Mesh::MaterialVolume> result;
×
UNCOV
221
  result.reserve(8);
×
222

223
  int size = -1;
×
224
  while (true) {
225
    // Get material volumes
UNCOV
226
    size = this->material_volumes(
×
227
      n_sample, bin, {result.data(), result.data() + result.capacity()}, seed);
×
228

229
    // If capacity was sufficient, resize the vector and return
UNCOV
230
    if (size >= 0) {
×
UNCOV
231
      result.resize(size);
×
UNCOV
232
      break;
×
233
    }
234

235
    // Otherwise, increase capacity of the vector
236
    result.reserve(2 * result.capacity());
×
237
  }
238

UNCOV
239
  return result;
×
UNCOV
240
}
×
241

242
void Mesh::to_hdf5(hid_t group) const
3,036✔
243
{
244
  // Create group for mesh
245
  std::string group_name = fmt::format("mesh {}", id_);
5,506✔
246
  hid_t mesh_group = create_group(group, group_name.c_str());
3,036✔
247

248
  // Write mesh type
249
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,036✔
250

251
  // Write mesh ID
252
  write_attribute(mesh_group, "id", id_);
3,036✔
253

254
  // Write mesh name
255
  write_dataset(mesh_group, "name", name_);
3,036✔
256

257
  // Write mesh data
258
  this->to_hdf5_inner(mesh_group);
3,036✔
259

260
  // Close group
261
  close_group(mesh_group);
3,036✔
262
}
3,036✔
263

264
//==============================================================================
265
// Structured Mesh implementation
266
//==============================================================================
267

268
std::string StructuredMesh::bin_label(int bin) const
5,437,344✔
269
{
270
  MeshIndex ijk = get_indices_from_bin(bin);
5,437,344✔
271

272
  if (n_dimension_ > 2) {
5,437,344✔
273
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
10,842,336✔
274
  } else if (n_dimension_ > 1) {
16,176✔
275
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
31,752✔
276
  } else {
277
    return fmt::format("Mesh Index ({})", ijk[0]);
600✔
278
  }
279
}
280

281
xt::xtensor<int, 1> StructuredMesh::get_x_shape() const
2,994✔
282
{
283
  // because method is const, shape_ is const as well and can't be adapted
284
  auto tmp_shape = shape_;
2,994✔
285
  return xt::adapt(tmp_shape, {n_dimension_});
5,988✔
286
}
287

288
Position StructuredMesh::sample_element(
51,712,212✔
289
  const MeshIndex& ijk, uint64_t* seed) const
290
{
291
  // lookup the lower/upper bounds for the mesh element
292
  double x_min = negative_grid_boundary(ijk, 0);
51,712,212✔
293
  double x_max = positive_grid_boundary(ijk, 0);
51,712,212✔
294

295
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
51,712,212✔
296
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
51,712,212✔
297

298
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
51,712,212✔
299
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
51,712,212✔
300

301
  return {x_min + (x_max - x_min) * prn(seed),
51,712,212✔
302
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
51,712,212✔
303
}
304

305
//==============================================================================
306
// Unstructured Mesh implementation
307
//==============================================================================
308

309
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
45✔
310
{
311
  // check the mesh type
312
  if (check_for_node(node, "type")) {
45✔
313
    auto temp = get_node_value(node, "type", true, true);
45✔
314
    if (temp != mesh_type) {
45✔
UNCOV
315
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
316
    }
317
  }
45✔
318

319
  // check if a length unit multiplier was specified
320
  if (check_for_node(node, "length_multiplier")) {
45✔
UNCOV
321
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
322
  }
323

324
  // get the filename of the unstructured mesh to load
325
  if (check_for_node(node, "filename")) {
45✔
326
    filename_ = get_node_value(node, "filename");
45✔
327
    if (!file_exists(filename_)) {
45✔
UNCOV
328
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
329
    }
330
  } else {
UNCOV
331
    fatal_error(fmt::format(
×
UNCOV
332
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
333
  }
334

335
  if (check_for_node(node, "options")) {
45✔
336
    options_ = get_node_value(node, "options");
16✔
337
  }
338

339
  // check if mesh tally data should be written with
340
  // statepoint files
341
  if (check_for_node(node, "output")) {
45✔
UNCOV
342
    output_ = get_node_value_bool(node, "output");
×
343
  }
344
}
45✔
345

346
void UnstructuredMesh::determine_bounds()
23✔
347
{
348
  double xmin = INFTY;
23✔
349
  double ymin = INFTY;
23✔
350
  double zmin = INFTY;
23✔
351
  double xmax = -INFTY;
23✔
352
  double ymax = -INFTY;
23✔
353
  double zmax = -INFTY;
23✔
354
  int n = this->n_vertices();
23✔
355
  for (int i = 0; i < n; ++i) {
53,604✔
356
    auto v = this->vertex(i);
53,581✔
357
    xmin = std::min(v.x, xmin);
53,581✔
358
    ymin = std::min(v.y, ymin);
53,581✔
359
    zmin = std::min(v.z, zmin);
53,581✔
360
    xmax = std::max(v.x, xmax);
53,581✔
361
    ymax = std::max(v.y, ymax);
53,581✔
362
    zmax = std::max(v.z, zmax);
53,581✔
363
  }
364
  lower_left_ = {xmin, ymin, zmin};
23✔
365
  upper_right_ = {xmax, ymax, zmax};
23✔
366
}
23✔
367

368
Position UnstructuredMesh::sample_tet(
601,230✔
369
  std::array<Position, 4> coords, uint64_t* seed) const
370
{
371
  // Uniform distribution
372
  double s = prn(seed);
601,230✔
373
  double t = prn(seed);
601,230✔
374
  double u = prn(seed);
601,230✔
375

376
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
377
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
378
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
379
  if (s + t > 1) {
601,230✔
380
    s = 1.0 - s;
301,419✔
381
    t = 1.0 - t;
301,419✔
382
  }
383
  if (s + t + u > 1) {
601,230✔
384
    if (t + u > 1) {
400,902✔
385
      double old_t = t;
200,169✔
386
      t = 1.0 - u;
200,169✔
387
      u = 1.0 - s - old_t;
200,169✔
388
    } else if (t + u <= 1) {
200,733✔
389
      double old_s = s;
200,733✔
390
      s = 1.0 - t - u;
200,733✔
391
      u = old_s + t + u - 1;
200,733✔
392
    }
393
  }
394
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,202,460✔
395
         u * (coords[3] - coords[0]) + coords[0];
1,803,690✔
396
}
397

398
const std::string UnstructuredMesh::mesh_type = "unstructured";
399

400
std::string UnstructuredMesh::get_mesh_type() const
30✔
401
{
402
  return mesh_type;
30✔
403
}
404

UNCOV
405
void UnstructuredMesh::surface_bins_crossed(
×
406
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
407
{
UNCOV
408
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
409
}
410

411
std::string UnstructuredMesh::bin_label(int bin) const
193,712✔
412
{
413
  return fmt::format("Mesh Index ({})", bin);
193,712✔
414
};
415

416
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
30✔
417
{
418
  write_dataset(mesh_group, "filename", filename_);
30✔
419
  write_dataset(mesh_group, "library", this->library());
30✔
420
  if (!options_.empty()) {
30✔
421
    write_attribute(mesh_group, "options", options_);
8✔
422
  }
423

424
  if (length_multiplier_ > 0.0)
30✔
UNCOV
425
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
426

427
  // write vertex coordinates
428
  xt::xtensor<double, 2> vertices({static_cast<size_t>(this->n_vertices()), 3});
30✔
429
  for (int i = 0; i < this->n_vertices(); i++) {
67,928✔
430
    auto v = this->vertex(i);
67,898✔
431
    xt::view(vertices, i, xt::all()) = xt::xarray<double>({v.x, v.y, v.z});
67,898✔
432
  }
433
  write_dataset(mesh_group, "vertices", vertices);
30✔
434

435
  int num_elem_skipped = 0;
30✔
436

437
  // write element types and connectivity
438
  vector<double> volumes;
30✔
439
  xt::xtensor<int, 2> connectivity({static_cast<size_t>(this->n_bins()), 8});
30✔
440
  xt::xtensor<int, 2> elem_types({static_cast<size_t>(this->n_bins()), 1});
30✔
441
  for (int i = 0; i < this->n_bins(); i++) {
337,742✔
442
    auto conn = this->connectivity(i);
337,712✔
443

444
    volumes.emplace_back(this->volume(i));
337,712✔
445

446
    // write linear tet element
447
    if (conn.size() == 4) {
337,712✔
448
      xt::view(elem_types, i, xt::all()) =
671,424✔
449
        static_cast<int>(ElementType::LINEAR_TET);
671,424✔
450
      xt::view(connectivity, i, xt::all()) =
671,424✔
451
        xt::xarray<int>({conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1});
1,007,136✔
452
      // write linear hex element
453
    } else if (conn.size() == 8) {
2,000✔
454
      xt::view(elem_types, i, xt::all()) =
4,000✔
455
        static_cast<int>(ElementType::LINEAR_HEX);
4,000✔
456
      xt::view(connectivity, i, xt::all()) = xt::xarray<int>({conn[0], conn[1],
8,000✔
457
        conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]});
6,000✔
458
    } else {
UNCOV
459
      num_elem_skipped++;
×
UNCOV
460
      xt::view(elem_types, i, xt::all()) =
×
461
        static_cast<int>(ElementType::UNSUPPORTED);
UNCOV
462
      xt::view(connectivity, i, xt::all()) = -1;
×
463
    }
464
  }
337,712✔
465

466
  // warn users that some elements were skipped
467
  if (num_elem_skipped > 0) {
30✔
UNCOV
468
    warning(fmt::format("The connectivity of {} elements "
×
469
                        "on mesh {} were not written "
470
                        "because they are not of type linear tet/hex.",
471
      num_elem_skipped, this->id_));
×
472
  }
473

474
  write_dataset(mesh_group, "volumes", volumes);
30✔
475
  write_dataset(mesh_group, "connectivity", connectivity);
30✔
476
  write_dataset(mesh_group, "element_types", elem_types);
30✔
477
}
30✔
478

479
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
23✔
480
{
481
  length_multiplier_ = length_multiplier;
23✔
482
}
23✔
483

484
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
485
{
486
  auto conn = connectivity(bin);
120,000✔
487

488
  if (conn.size() == 4)
120,000✔
489
    return ElementType::LINEAR_TET;
120,000✔
UNCOV
490
  else if (conn.size() == 8)
×
UNCOV
491
    return ElementType::LINEAR_HEX;
×
492
  else
UNCOV
493
    return ElementType::UNSUPPORTED;
×
494
}
120,000✔
495

496
StructuredMesh::MeshIndex StructuredMesh::get_indices(
965,112,484✔
497
  Position r, bool& in_mesh) const
498
{
499
  MeshIndex ijk;
500
  in_mesh = true;
965,112,484✔
501
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
502
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
503

504
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
505
      in_mesh = false;
91,285,024✔
506
  }
507
  return ijk;
965,112,484✔
508
}
509

510
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,014,653,005✔
511
{
512
  switch (n_dimension_) {
1,014,653,005✔
513
  case 1:
956,736✔
514
    return ijk[0] - 1;
956,736✔
515
  case 2:
21,602,040✔
516
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
21,602,040✔
517
  case 3:
992,094,229✔
518
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
992,094,229✔
UNCOV
519
  default:
×
UNCOV
520
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
521
  }
522
}
523

524
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
60,389,604✔
525
{
526
  MeshIndex ijk;
527
  if (n_dimension_ == 1) {
60,389,604✔
528
    ijk[0] = bin + 1;
300✔
529
  } else if (n_dimension_ == 2) {
60,389,304✔
530
    ijk[0] = bin % shape_[0] + 1;
15,876✔
531
    ijk[1] = bin / shape_[0] + 1;
15,876✔
532
  } else if (n_dimension_ == 3) {
60,373,428✔
533
    ijk[0] = bin % shape_[0] + 1;
60,373,428✔
534
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
60,373,428✔
535
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
60,373,428✔
536
  }
537
  return ijk;
60,389,604✔
538
}
539

540
int StructuredMesh::get_bin(Position r) const
324,599,216✔
541
{
542
  // Determine indices
543
  bool in_mesh;
544
  MeshIndex ijk = get_indices(r, in_mesh);
324,599,216✔
545
  if (!in_mesh)
324,599,216✔
546
    return -1;
22,164,978✔
547

548
  // Convert indices to bin
549
  return get_bin_from_indices(ijk);
302,434,238✔
550
}
551

552
int StructuredMesh::n_bins() const
1,000,136✔
553
{
554
  return std::accumulate(
1,000,136✔
555
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
2,000,272✔
556
}
557

558
int StructuredMesh::n_surface_bins() const
593✔
559
{
560
  return 4 * n_dimension_ * n_bins();
593✔
561
}
562

563
xt::xtensor<double, 1> StructuredMesh::count_sites(
×
564
  const SourceSite* bank, int64_t length, bool* outside) const
565
{
566
  // Determine shape of array for counts
UNCOV
567
  std::size_t m = this->n_bins();
×
568
  vector<std::size_t> shape = {m};
×
569

570
  // Create array of zeros
UNCOV
571
  xt::xarray<double> cnt {shape, 0.0};
×
UNCOV
572
  bool outside_ = false;
×
573

574
  for (int64_t i = 0; i < length; i++) {
×
575
    const auto& site = bank[i];
×
576

577
    // determine scoring bin for entropy mesh
UNCOV
578
    int mesh_bin = get_bin(site.r);
×
579

580
    // if outside mesh, skip particle
UNCOV
581
    if (mesh_bin < 0) {
×
UNCOV
582
      outside_ = true;
×
UNCOV
583
      continue;
×
584
    }
585

586
    // Add to appropriate bin
UNCOV
587
    cnt(mesh_bin) += site.wgt;
×
588
  }
589

590
  // Create copy of count data. Since ownership will be acquired by xtensor,
591
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
592
  // warnings.
593
  int total = cnt.size();
×
594
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
×
595

596
#ifdef OPENMC_MPI
597
  // collect values from all processors
598
  MPI_Reduce(
599
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
600

601
  // Check if there were sites outside the mesh for any processor
602
  if (outside) {
603
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
604
  }
605
#else
606
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
607
  if (outside)
608
    *outside = outside_;
609
#endif
610

611
  // Adapt reduced values in array back into an xarray
UNCOV
612
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
×
UNCOV
613
  xt::xarray<double> counts = arr;
×
614

UNCOV
615
  return counts;
×
616
}
617

618
// raytrace through the mesh. The template class T will do the tallying.
619
// A modern optimizing compiler can recognize the noop method of T and eleminate
620
// that call entirely.
621
template<class T>
622
void StructuredMesh::raytrace_mesh(
640,889,000✔
623
  Position r0, Position r1, const Direction& u, T tally) const
624
{
625
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
626
  // enable/disable tally calls for now, T template type needs to provide both
627
  // surface and track methods, which might be empty. modern optimizing
628
  // compilers will (hopefully) eliminate the complete code (including
629
  // calculation of parameters) but for the future: be explicit
630

631
  // Compute the length of the entire track.
632
  double total_distance = (r1 - r0).norm();
640,889,000✔
633
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
640,889,000✔
634
    return;
5,711,856✔
635

636
  const int n = n_dimension_;
635,177,144✔
637

638
  // Flag if position is inside the mesh
639
  bool in_mesh;
640

641
  // Position is r = r0 + u * traveled_distance, start at r0
642
  double traveled_distance {0.0};
635,177,144✔
643

644
  // Calculate index of current cell. Offset the position a tiny bit in
645
  // direction of flight
646
  MeshIndex ijk = get_indices(r0 + TINY_BIT * u, in_mesh);
635,177,144✔
647

648
  // if track is very short, assume that it is completely inside one cell.
649
  // Only the current cell will score and no surfaces
650
  if (total_distance < 2 * TINY_BIT) {
635,177,144✔
651
    if (in_mesh) {
12✔
UNCOV
652
      tally.track(ijk, 1.0);
×
653
    }
654
    return;
12✔
655
  }
656

657
  // translate start and end positions,
658
  // this needs to come after the get_indices call because it does its own
659
  // translation
660
  local_coords(r0);
635,177,132✔
661
  local_coords(r1);
635,177,132✔
662

663
  // Calculate initial distances to next surfaces in all three dimensions
664
  std::array<MeshDistance, 3> distances;
1,270,354,264✔
665
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
666
    distances[k] = distance_to_grid_boundary(ijk, k, r0, u, 0.0);
1,887,499,356✔
667
  }
668

669
  // Loop until r = r1 is eventually reached
670
  while (true) {
356,607,394✔
671

672
    if (in_mesh) {
991,784,526✔
673

674
      // find surface with minimal distance to current position
675
      const auto k = std::min_element(distances.begin(), distances.end()) -
900,577,556✔
676
                     distances.begin();
900,577,556✔
677

678
      // Tally track length delta since last step
679
      tally.track(ijk,
900,577,556✔
680
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
900,577,556✔
681
          total_distance);
682

683
      // update position and leave, if we have reached end position
684
      traveled_distance = distances[k].distance;
900,577,556✔
685
      if (traveled_distance >= total_distance)
900,577,556✔
686
        return;
549,306,286✔
687

688
      // If we have not reached r1, we have hit a surface. Tally outward current
689
      tally.surface(ijk, k, distances[k].max_surface, false);
351,271,270✔
690

691
      // Update cell and calculate distance to next surface in k-direction.
692
      // The two other directions are still valid!
693
      ijk[k] = distances[k].next_index;
351,271,270✔
694
      distances[k] =
351,271,270✔
695
        distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
351,271,270✔
696

697
      // Check if we have left the interior of the mesh
698
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
351,271,270✔
699

700
      // If we are still inside the mesh, tally inward current for the next cell
701
      if (in_mesh)
351,271,270✔
702
        tally.surface(ijk, k, !distances[k].max_surface, true);
327,033,182✔
703

704
    } else { // not inside mesh
705

706
      // For all directions outside the mesh, find the distance that we need to
707
      // travel to reach the next surface. Use the largest distance, as only
708
      // this will cross all outer surfaces.
709
      int k_max {0};
91,206,970✔
710
      for (int k = 0; k < n; ++k) {
362,486,494✔
711
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
363,829,068✔
712
            (distances[k].distance > traveled_distance)) {
92,549,544✔
713
          traveled_distance = distances[k].distance;
91,763,784✔
714
          k_max = k;
91,763,784✔
715
        }
716
      }
717

718
      // If r1 is not inside the mesh, exit here
719
      if (traveled_distance >= total_distance)
91,206,970✔
720
        return;
85,870,846✔
721

722
      // Calculate the new cell index and update all distances to next surfaces.
723
      ijk = get_indices(r0 + (traveled_distance + TINY_BIT) * u, in_mesh);
5,336,124✔
724
      for (int k = 0; k < n; ++k) {
21,115,236✔
725
        distances[k] =
15,779,112✔
726
          distance_to_grid_boundary(ijk, k, r0, u, traveled_distance);
15,779,112✔
727
      }
728

729
      // If inside the mesh, Tally inward current
730
      if (in_mesh)
5,336,124✔
731
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
3,959,064✔
732
    }
733
  }
734
}
735

250,709,558✔
736
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
737
  vector<int>& bins, vector<double>& lengths) const
738
{
739

740
  // Helper tally class.
741
  // stores a pointer to the mesh class and references to bins and lengths
742
  // parameters. Performs the actual tally through the track method.
743
  struct TrackAggregator {
744
    TrackAggregator(
745
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
250,709,558✔
746
      : mesh(_mesh), bins(_bins), lengths(_lengths)
250,709,558✔
UNCOV
747
    {}
×
748
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
749
    void track(const MeshIndex& ijk, double l) const
250,709,558✔
750
    {
751
      bins.push_back(mesh->get_bin_from_indices(ijk));
752
      lengths.push_back(l);
753
    }
754

755
    const StructuredMesh* mesh;
250,709,558✔
756
    vector<int>& bins;
757
    vector<double>& lengths;
758
  };
759

250,709,558✔
760
  // Perform the mesh raytrace with the helper class.
761
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
762
}
763

250,709,558✔
UNCOV
764
void StructuredMesh::surface_bins_crossed(
×
UNCOV
765
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
×
766
{
UNCOV
767

×
768
  // Helper tally class.
769
  // stores a pointer to the mesh class and a reference to the bins parameter.
770
  // Performs the actual tally through the surface method.
771
  struct SurfaceAggregator {
772
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
773
      : mesh(_mesh), bins(_bins)
250,709,558✔
774
    {}
250,709,558✔
775
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
776
    {
777
      int i_bin =
501,419,116✔
778
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
1,001,002,088✔
779
      if (max)
750,292,530✔
780
        i_bin += 2;
781
      if (inward)
782
        i_bin += 1;
783
      bins.push_back(i_bin);
61,870,061✔
784
    }
785
    void track(const MeshIndex& idx, double l) const {}
312,579,619✔
786

787
    const StructuredMesh* mesh;
788
    vector<int>& bins;
309,532,184✔
789
  };
309,532,184✔
790

791
  // Perform the mesh raytrace with the helper class.
792
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
309,532,184✔
793
}
309,532,184✔
794

795
//==============================================================================
796
// RegularMesh implementation
797
//==============================================================================
309,532,184✔
798

309,532,184✔
799
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
247,905,711✔
800
{
801
  // Determine number of dimensions for mesh
802
  if (!check_for_node(node, "dimension")) {
61,626,473✔
803
    fatal_error("Must specify <dimension> on a regular mesh.");
804
  }
805

806
  xt::xtensor<int, 1> shape = get_node_xarray<int>(node, "dimension");
61,626,473✔
807
  int n = n_dimension_ = shape.size();
61,626,473✔
808
  if (n != 1 && n != 2 && n != 3) {
61,626,473✔
809
    fatal_error("Mesh must be one, two, or three dimensions.");
810
  }
811
  std::copy(shape.begin(), shape.end(), shape_.begin());
61,626,473✔
812

813
  // Check that dimensions are all greater than zero
814
  if (xt::any(shape <= 0)) {
61,626,473✔
815
    fatal_error("All entries on the <dimension> element for a tally "
59,328,330✔
816
                "mesh must be positive.");
817
  }
818

819
  // Check for lower-left coordinates
820
  if (check_for_node(node, "lower_left")) {
821
    // Read mesh lower-left corner location
822
    lower_left_ = get_node_xarray<double>(node, "lower_left");
3,047,435✔
823
  } else {
11,838,440✔
824
    fatal_error("Must specify <lower_left> on a mesh.");
11,994,992✔
825
  }
3,203,987✔
826

3,139,523✔
827
  // Make sure lower_left and dimension match
3,139,523✔
828
  if (shape.size() != lower_left_.size()) {
829
    fatal_error("Number of entries on <lower_left> must be the same "
830
                "as the number of entries on <dimension>.");
831
  }
832

3,047,435✔
833
  if (check_for_node(node, "width")) {
2,803,847✔
834
    // Make sure one of upper-right or width were specified
835
    if (check_for_node(node, "upper_right")) {
836
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
243,588✔
837
    }
860,256✔
838

616,668✔
839
    width_ = get_node_xarray<double>(node, "width");
616,668✔
840

841
    // Check to ensure width has same dimensions
842
    auto n = width_.size();
843
    if (n != lower_left_.size()) {
243,588✔
844
      fatal_error("Number of entries on <width> must be the same as "
218,592✔
845
                  "the number of entries on <lower_left>.");
846
    }
847

848
    // Check for negative widths
390,179,442✔
849
    if (xt::any(width_ < 0.0)) {
850
      fatal_error("Cannot have a negative <width> on a tally mesh.");
851
    }
852

853
    // Set width and upper right coordinate
854
    upper_right_ = xt::eval(lower_left_ + shape * width_);
855

856
  } else if (check_for_node(node, "upper_right")) {
857
    upper_right_ = get_node_xarray<double>(node, "upper_right");
858

390,179,442✔
859
    // Check to ensure width has same dimensions
390,179,442✔
860
    auto n = upper_right_.size();
5,711,856✔
861
    if (n != lower_left_.size()) {
862
      fatal_error("Number of entries on <upper_right> must be the "
384,467,586✔
863
                  "same as the number of entries on <lower_left>.");
864
    }
865

866
    // Check that upper-right is above lower-left
867
    if (xt::any(upper_right_ < lower_left_)) {
868
      fatal_error("The <upper_right> coordinates must be greater than "
384,467,586✔
869
                  "the <lower_left> coordinates on a tally mesh.");
870
    }
871

872
    // Set width
384,467,586✔
873
    width_ = xt::eval((upper_right_ - lower_left_) / shape);
874
  } else {
875
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
876
  }
384,467,586✔
877

12✔
UNCOV
878
  // Set material volumes
×
879
  volume_frac_ = 1.0 / xt::prod(shape)();
880

12✔
881
  element_volume_ = 1.0;
882
  for (int i = 0; i < n_dimension_; i++) {
883
    element_volume_ *= width_[i];
884
  }
885
}
886

384,467,574✔
887
int RegularMesh::get_index_in_direction(double r, int i) const
384,467,574✔
888
{
889
  return std::ceil((r - lower_left_[i]) / width_[i]);
890
}
768,935,148✔
891

1,521,674,400✔
892
const std::string RegularMesh::mesh_type = "regular";
1,137,206,826✔
893

894
std::string RegularMesh::get_mesh_type() const
895
{
896
  return mesh_type;
294,737,333✔
897
}
898

679,204,907✔
899
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
900
{
901
  return lower_left_[i] + ijk[i] * width_[i];
591,045,372✔
902
}
591,045,372✔
903

904
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
905
{
591,045,372✔
906
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
591,045,372✔
907
}
908

909
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
910
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
591,045,372✔
911
  double l) const
591,045,372✔
912
{
301,400,575✔
913
  MeshDistance d;
914
  d.next_index = ijk[i];
915
  if (std::abs(u[i]) < FP_PRECISION)
289,644,797✔
916
    return d;
917

918
  d.max_surface = (u[i] > 0);
919
  if (d.max_surface && (ijk[i] <= shape_[i])) {
289,644,797✔
920
    d.next_index++;
289,644,797✔
921
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
289,644,797✔
922
  } else if (!d.max_surface && (ijk[i] >= 1)) {
923
    d.next_index--;
924
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
289,644,797✔
925
  }
926
  return d;
927
}
289,644,797✔
928

267,704,852✔
929
std::pair<vector<double>, vector<double>> RegularMesh::plot(
930
  Position plot_ll, Position plot_ur) const
931
{
932
  // Figure out which axes lie in the plane of the plot.
933
  array<int, 2> axes {-1, -1};
934
  if (plot_ur.z == plot_ll.z) {
935
    axes[0] = 0;
88,159,535✔
936
    if (n_dimension_ > 1)
350,648,054✔
937
      axes[1] = 1;
351,834,076✔
938
  } else if (plot_ur.y == plot_ll.y) {
89,345,557✔
939
    axes[0] = 0;
88,624,261✔
940
    if (n_dimension_ > 2)
88,624,261✔
941
      axes[1] = 2;
942
  } else if (plot_ur.x == plot_ll.x) {
943
    if (n_dimension_ > 1)
944
      axes[0] = 1;
945
    if (n_dimension_ > 2)
88,159,535✔
946
      axes[1] = 2;
83,066,999✔
947
  } else {
948
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
949
  }
5,092,536✔
950

20,254,980✔
951
  // Get the coordinates of the mesh lines along both of the axes.
15,162,444✔
952
  array<vector<double>, 2> axis_lines;
15,162,444✔
953
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
954
    int axis = axes[i_ax];
955
    if (axis == -1)
956
      continue;
5,092,536✔
957
    auto& lines {axis_lines[i_ax]};
3,740,472✔
958

959
    double coord = lower_left_[axis];
960
    for (int i = 0; i < shape_[axis] + 1; ++i) {
961
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
962
        lines.push_back(coord);
390,179,442✔
963
      coord += width_[axis];
964
    }
965
  }
966

967
  return {axis_lines[0], axis_lines[1]};
968
}
969

970
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
390,179,442✔
971
{
972
  write_dataset(mesh_group, "dimension", get_x_shape());
390,179,442✔
973
  write_dataset(mesh_group, "lower_left", lower_left_);
390,179,442✔
974
  write_dataset(mesh_group, "upper_right", upper_right_);
561,090,121✔
975
  write_dataset(mesh_group, "width", width_);
591,045,372✔
976
}
977

591,045,372✔
978
xt::xtensor<double, 1> RegularMesh::count_sites(
591,045,372✔
979
  const SourceSite* bank, int64_t length, bool* outside) const
591,045,372✔
980
{
981
  // Determine shape of array for counts
982
  std::size_t m = this->n_bins();
983
  vector<std::size_t> shape = {m};
984

985
  // Create array of zeros
986
  xt::xarray<double> cnt {shape, 0.0};
987
  bool outside_ = false;
390,179,442✔
988

390,179,442✔
989
  for (int64_t i = 0; i < length; i++) {
990
    const auto& site = bank[i];
250,709,558✔
991

992
    // determine scoring bin for entropy mesh
993
    int mesh_bin = get_bin(site.r);
994

995
    // if outside mesh, skip particle
996
    if (mesh_bin < 0) {
997
      outside_ = true;
998
      continue;
250,709,558✔
999
    }
250,709,558✔
1000

250,709,558✔
1001
    // Add to appropriate bin
121,173,395✔
1002
    cnt(mesh_bin) += site.wgt;
1003
  }
1004

121,173,395✔
1005
  // Create copy of count data. Since ownership will be acquired by xtensor,
121,173,395✔
1006
  // std::allocator must be used to avoid Valgrind mismatched free() / delete
60,541,998✔
1007
  // warnings.
121,173,395✔
1008
  int total = cnt.size();
59,546,922✔
1009
  double* cnt_reduced = std::allocator<double> {}.allocate(total);
121,173,395✔
1010

121,173,395✔
1011
#ifdef OPENMC_MPI
309,532,184✔
1012
  // collect values from all processors
1013
  MPI_Reduce(
1014
    cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
1015

1016
  // Check if there were sites outside the mesh for any processor
1017
  if (outside) {
1018
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
250,709,558✔
1019
  }
250,709,558✔
1020
#else
1021
  std::copy(cnt.data(), cnt.data() + total, cnt_reduced);
1022
  if (outside)
1023
    *outside = outside_;
1024
#endif
1025

1,888✔
1026
  // Adapt reduced values in array back into an xarray
1027
  auto arr = xt::adapt(cnt_reduced, total, xt::acquire_ownership(), shape);
1028
  xt::xarray<double> counts = arr;
1,888✔
UNCOV
1029

×
1030
  return counts;
1031
}
1032

1,888✔
1033
double RegularMesh::volume(const MeshIndex& ijk) const
1,888✔
1034
{
1,888✔
UNCOV
1035
  return element_volume_;
×
1036
}
1037

1,888✔
1038
//==============================================================================
1039
// RectilinearMesh implementation
1040
//==============================================================================
1,888✔
UNCOV
1041

×
1042
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
1043
{
1044
  n_dimension_ = 3;
1045

1046
  grid_[0] = get_node_array<double>(node, "x_grid");
1,888✔
1047
  grid_[1] = get_node_array<double>(node, "y_grid");
1048
  grid_[2] = get_node_array<double>(node, "z_grid");
1,888✔
1049

UNCOV
1050
  if (int err = set_grid()) {
×
1051
    fatal_error(openmc_err_msg);
1052
  }
1053
}
1054

1,888✔
UNCOV
1055
const std::string RectilinearMesh::mesh_type = "rectilinear";
×
1056

1057
std::string RectilinearMesh::get_mesh_type() const
1058
{
1059
  return mesh_type;
1,888✔
1060
}
1061

51✔
UNCOV
1062
double RectilinearMesh::positive_grid_boundary(
×
1063
  const MeshIndex& ijk, int i) const
1064
{
1065
  return grid_[i][ijk[i]];
51✔
1066
}
1067

1068
double RectilinearMesh::negative_grid_boundary(
51✔
1069
  const MeshIndex& ijk, int i) const
51✔
UNCOV
1070
{
×
1071
  return grid_[i][ijk[i] - 1];
1072
}
1073

1074
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
1075
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
51✔
UNCOV
1076
  double l) const
×
1077
{
1078
  MeshDistance d;
1079
  d.next_index = ijk[i];
1080
  if (std::abs(u[i]) < FP_PRECISION)
51✔
1081
    return d;
1082

1,837✔
1083
  d.max_surface = (u[i] > 0);
1,837✔
1084
  if (d.max_surface && (ijk[i] <= shape_[i])) {
1085
    d.next_index++;
1086
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,837✔
1087
  } else if (!d.max_surface && (ijk[i] > 0)) {
1,837✔
UNCOV
1088
    d.next_index--;
×
1089
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1090
  }
1091
  return d;
1092
}
1093

1,837✔
UNCOV
1094
int RectilinearMesh::set_grid()
×
1095
{
1096
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
1097
    static_cast<int>(grid_[1].size()) - 1,
1098
    static_cast<int>(grid_[2].size()) - 1};
1099

1,837✔
1100
  for (const auto& g : grid_) {
UNCOV
1101
    if (g.size() < 2) {
×
1102
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
1103
                 "must each have at least 2 points");
1104
      return OPENMC_E_INVALID_ARGUMENT;
1105
    }
1,888✔
1106
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1107
        g.end()) {
1,888✔
1108
      set_errmsg("Values in for x-, y-, and z- grids for "
7,285✔
1109
                 "rectilinear meshes must be sorted and unique.");
5,397✔
1110
      return OPENMC_E_INVALID_ARGUMENT;
1111
    }
1,888✔
1112
  }
1113

2,147,483,647✔
1114
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
1115
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
2,147,483,647✔
1116

1117
  return 0;
1118
}
1119

1120
int RectilinearMesh::get_index_in_direction(double r, int i) const
3,875✔
1121
{
1122
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
3,875✔
1123
}
1124

1125
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
960,394,317✔
1126
  Position plot_ll, Position plot_ur) const
1127
{
960,394,317✔
1128
  // Figure out which axes lie in the plane of the plot.
1129
  array<int, 2> axes {-1, -1};
1130
  if (plot_ur.z == plot_ll.z) {
959,974,406✔
1131
    axes = {0, 1};
1132
  } else if (plot_ur.y == plot_ll.y) {
959,974,406✔
1133
    axes = {0, 2};
1134
  } else if (plot_ur.x == plot_ll.x) {
1135
    axes = {1, 2};
1,636,082,674✔
1136
  } else {
1137
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
1138
  }
1139

1,636,082,674✔
1140
  // Get the coordinates of the mesh lines along both of the axes.
1,636,082,674✔
1141
  array<vector<double>, 2> axis_lines;
1,636,082,674✔
UNCOV
1142
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
×
1143
    int axis = axes[i_ax];
1144
    vector<double>& lines {axis_lines[i_ax]};
1,636,082,674✔
1145

1,636,082,674✔
1146
    for (auto coord : grid_[axis]) {
806,697,681✔
1147
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
806,697,681✔
1148
        lines.push_back(coord);
829,384,993✔
1149
    }
806,277,770✔
1150
  }
806,277,770✔
1151

1152
  return {axis_lines[0], axis_lines[1]};
1,636,082,674✔
1153
}
1154

1155
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
24✔
1156
{
1157
  write_dataset(mesh_group, "x_grid", grid_[0]);
1158
  write_dataset(mesh_group, "y_grid", grid_[1]);
1159
  write_dataset(mesh_group, "z_grid", grid_[2]);
24✔
1160
}
24✔
1161

24✔
1162
double RectilinearMesh::volume(const MeshIndex& ijk) const
24✔
1163
{
24✔
UNCOV
1164
  double vol {1.0};
×
UNCOV
1165

×
UNCOV
1166
  for (int i = 0; i < n_dimension_; i++) {
×
UNCOV
1167
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
×
UNCOV
1168
  }
×
UNCOV
1169
  return vol;
×
UNCOV
1170
}
×
UNCOV
1171

×
UNCOV
1172
//==============================================================================
×
1173
// CylindricalMesh implementation
UNCOV
1174
//==============================================================================
×
1175

1176
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
1177
  : PeriodicStructuredMesh {node}
1178
{
24✔
1179
  n_dimension_ = 3;
72✔
1180
  grid_[0] = get_node_array<double>(node, "r_grid");
48✔
1181
  grid_[1] = get_node_array<double>(node, "phi_grid");
48✔
UNCOV
1182
  grid_[2] = get_node_array<double>(node, "z_grid");
×
1183
  origin_ = get_node_position(node, "origin");
48✔
1184

1185
  if (int err = set_grid()) {
48✔
1186
    fatal_error(openmc_err_msg);
312✔
1187
  }
264✔
1188
}
264✔
1189

264✔
1190
const std::string CylindricalMesh::mesh_type = "cylindrical";
1191

1192
std::string CylindricalMesh::get_mesh_type() const
1193
{
48✔
1194
  return mesh_type;
24✔
1195
}
1196

2,176✔
1197
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
1198
  Position r, bool& in_mesh) const
2,176✔
1199
{
2,176✔
1200
  local_coords(r);
2,176✔
1201

2,176✔
1202
  Position mapped_r;
2,176✔
1203
  mapped_r[0] = std::hypot(r.x, r.y);
1204
  mapped_r[2] = r[2];
12,248✔
1205

1206
  if (mapped_r[0] < FP_PRECISION) {
1207
    mapped_r[1] = 0.0;
1208
  } else {
12,248✔
1209
    mapped_r[1] = std::atan2(r.y, r.x);
12,248✔
1210
    if (mapped_r[1] < 0)
1211
      mapped_r[1] += 2 * M_PI;
1212
  }
12,248✔
1213

12,248✔
1214
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
1215

12,019,257✔
1216
  idx[1] = sanitize_phi(idx[1]);
12,007,009✔
1217

1218
  return idx;
1219
}
12,007,009✔
1220

1221
Position CylindricalMesh::sample_element(
1222
  const MeshIndex& ijk, uint64_t* seed) const
12,007,009✔
UNCOV
1223
{
×
UNCOV
1224
  double r_min = this->r(ijk[0] - 1);
×
1225
  double r_max = this->r(ijk[0]);
1226

1227
  double phi_min = this->phi(ijk[1] - 1);
1228
  double phi_max = this->phi(ijk[1]);
12,007,009✔
1229

1230
  double z_min = this->z(ijk[2] - 1);
1231
  double z_max = this->z(ijk[2]);
1232

1233
  double r_min_sq = r_min * r_min;
1234
  double r_max_sq = r_max * r_max;
12,248✔
1235
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
12,248✔
1236
  double phi = uniform_distribution(phi_min, phi_max, seed);
1237
  double z = uniform_distribution(z_min, z_max, seed);
1238

1239
  double x = r * std::cos(phi);
7,320✔
1240
  double y = r * std::sin(phi);
7,320✔
1241

1242
  return origin_ + Position(x, y, z);
1243
}
7,320✔
1244

7,320✔
1245
double CylindricalMesh::find_r_crossing(
1246
  const Position& r, const Direction& u, double l, int shell) const
1247
{
4,928✔
1248

4,928✔
1249
  if ((shell < 0) || (shell > shape_[0]))
4,928✔
1250
    return INFTY;
1251

1252
  // solve r.x^2 + r.y^2 == r0^2
1253
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
12,248✔
1254
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
12,248✔
1255

1256
  const double r0 = grid_[0][shell];
24,496✔
1257
  if (r0 == 0.0)
12,248✔
1258
    return INFTY;
1259

982,884✔
1260
  const double denominator = u.x * u.x + u.y * u.y;
1261

982,884✔
1262
  // Direction of flight is in z-direction. Will never intersect r.
1263
  if (std::abs(denominator) < FP_PRECISION)
1264
    return INFTY;
1265

1266
  // inverse of dominator to help the compiler to speed things up
1267
  const double inv_denominator = 1.0 / denominator;
1268

111✔
1269
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
1270
  double c = r.x * r.x + r.y * r.y - r0 * r0;
111✔
1271
  double D = p * p - c * inv_denominator;
1272

111✔
1273
  if (D < 0.0)
111✔
1274
    return INFTY;
111✔
1275

1276
  D = std::sqrt(D);
111✔
UNCOV
1277

×
1278
  // the solution -p - D is always smaller as -p + D : Check this one first
1279
  if (std::abs(c) <= RADIAL_MESH_TOL)
111✔
1280
    return INFTY;
1281

1282
  if (-p - D > l)
1283
    return -p - D;
328✔
1284
  if (-p + D > l)
1285
    return -p + D;
328✔
1286

1287
  return INFTY;
1288
}
56,980,318✔
1289

1290
double CylindricalMesh::find_phi_crossing(
1291
  const Position& r, const Direction& u, double l, int shell) const
56,980,318✔
1292
{
1293
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1294
  if (full_phi_ && (shape_[1] == 1))
56,518,367✔
1295
    return INFTY;
1296

1297
  shell = sanitize_phi(shell);
56,518,367✔
1298

1299
  const double p0 = grid_[1][shell];
1300

111,639,732✔
1301
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1302
  // => x(s) * cos(p0) = y(s) * sin(p0)
1303
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1304
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
111,639,732✔
1305

111,639,732✔
1306
  const double c0 = std::cos(p0);
111,639,732✔
UNCOV
1307
  const double s0 = std::sin(p0);
×
1308

1309
  const double denominator = (u.x * s0 - u.y * c0);
111,639,732✔
1310

111,639,732✔
1311
  // Check if direction of flight is not parallel to phi surface
55,540,318✔
1312
  if (std::abs(denominator) > FP_PRECISION) {
55,540,318✔
1313
    const double s = -(r.x * s0 - r.y * c0) / denominator;
56,099,414✔
1314
    // Check if solution is in positive direction of flight and crosses the
55,078,367✔
1315
    // correct phi surface (not -phi)
55,078,367✔
1316
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
1317
      return s;
111,639,732✔
1318
  }
1319

1320
  return INFTY;
185✔
1321
}
1322

185✔
1323
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
185✔
1324
  const Position& r, const Direction& u, double l, int shell) const
185✔
1325
{
1326
  MeshDistance d;
740✔
1327
  d.next_index = shell;
555✔
UNCOV
1328

×
1329
  // Direction of flight is within xy-plane. Will never intersect z.
UNCOV
1330
  if (std::abs(u.z) < FP_PRECISION)
×
1331
    return d;
1332

555✔
1333
  d.max_surface = (u.z > 0.0);
1,110✔
UNCOV
1334
  if (d.max_surface && (shell <= shape_[2])) {
×
1335
    d.next_index += 1;
UNCOV
1336
    d.distance = (grid_[2][shell] - r.z) / u.z;
×
1337
  } else if (!d.max_surface && (shell > 0)) {
1338
    d.next_index -= 1;
1339
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
1340
  }
185✔
1341
  return d;
185✔
1342
}
1343

185✔
1344
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
1345
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1346
  double l) const
160,387,890✔
1347
{
1348
  Position r = r0 - origin_;
160,387,890✔
1349

1350
  if (i == 0) {
1351

12✔
1352
    return std::min(
1353
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r, u, l, ijk[i])),
1354
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r, u, l, ijk[i] - 1)));
1355

12✔
1356
  } else if (i == 1) {
12✔
UNCOV
1357

×
1358
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
12✔
1359
                      find_phi_crossing(r, u, l, ijk[i])),
12✔
UNCOV
1360
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
×
UNCOV
1361
        find_phi_crossing(r, u, l, ijk[i] - 1)));
×
1362

UNCOV
1363
  } else {
×
1364
    return find_z_crossing(r, u, l, ijk[i]);
1365
  }
1366
}
1367

12✔
1368
int CylindricalMesh::set_grid()
36✔
1369
{
24✔
1370
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
24✔
1371
    static_cast<int>(grid_[1].size()) - 1,
1372
    static_cast<int>(grid_[2].size()) - 1};
120✔
1373

96✔
1374
  for (const auto& g : grid_) {
96✔
1375
    if (g.size() < 2) {
1376
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
1377
                 "must each have at least 2 points");
1378
      return OPENMC_E_INVALID_ARGUMENT;
24✔
1379
    }
12✔
1380
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1381
        g.end()) {
122✔
1382
      set_errmsg("Values in for r-, phi-, and z- grids for "
1383
                 "cylindrical meshes must be sorted and unique.");
122✔
1384
      return OPENMC_E_INVALID_ARGUMENT;
122✔
1385
    }
122✔
1386
  }
122✔
1387
  if (grid_[0].front() < 0.0) {
1388
    set_errmsg("r-grid for "
228✔
1389
               "cylindrical meshes must start at r >= 0.");
1390
    return OPENMC_E_INVALID_ARGUMENT;
228✔
1391
  }
1392
  if (grid_[1].front() < 0.0) {
912✔
1393
    set_errmsg("phi-grid for "
684✔
1394
               "cylindrical meshes must start at phi >= 0.");
1395
    return OPENMC_E_INVALID_ARGUMENT;
228✔
1396
  }
1397
  if (grid_[1].back() > 2.0 * PI) {
1398
    set_errmsg("phi-grids for "
1399
               "cylindrical meshes must end with theta <= 2*pi.");
1400

1401
    return OPENMC_E_INVALID_ARGUMENT;
1402
  }
401✔
1403

401✔
1404
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
1405

401✔
1406
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
401✔
1407
    origin_[2] + grid_[2].front()};
401✔
1408
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
401✔
1409
    origin_[2] + grid_[2].back()};
401✔
1410

1411
  return 0;
401✔
UNCOV
1412
}
×
1413

1414
int CylindricalMesh::get_index_in_direction(double r, int i) const
401✔
1415
{
1416
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1417
}
1418

504✔
1419
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
1420
  Position plot_ll, Position plot_ur) const
504✔
1421
{
1422
  fatal_error("Plot of cylindrical Mesh not implemented");
1423

49,788,192✔
1424
  // Figure out which axes lie in the plane of the plot.
1425
  array<vector<double>, 2> axis_lines;
1426
  return {axis_lines[0], axis_lines[1]};
49,788,192✔
1427
}
1428

49,788,192✔
1429
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
49,788,192✔
1430
{
49,788,192✔
1431
  write_dataset(mesh_group, "r_grid", grid_[0]);
1432
  write_dataset(mesh_group, "phi_grid", grid_[1]);
49,788,192✔
UNCOV
1433
  write_dataset(mesh_group, "z_grid", grid_[2]);
×
1434
  write_dataset(mesh_group, "origin", origin_);
1435
}
49,788,192✔
1436

49,788,192✔
1437
double CylindricalMesh::volume(const MeshIndex& ijk) const
24,869,868✔
1438
{
1439
  double r_i = grid_[0][ijk[0] - 1];
1440
  double r_o = grid_[0][ijk[0]];
49,788,192✔
1441

1442
  double phi_i = grid_[1][ijk[1] - 1];
49,788,192✔
1443
  double phi_o = grid_[1][ijk[1]];
1444

49,788,192✔
1445
  double z_i = grid_[2][ijk[2] - 1];
1446
  double z_o = grid_[2][ijk[2]];
1447

816,000✔
1448
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
1449
}
1450

816,000✔
1451
//==============================================================================
816,000✔
1452
// SphericalMesh implementation
1453
//==============================================================================
816,000✔
1454

816,000✔
1455
SphericalMesh::SphericalMesh(pugi::xml_node node)
1456
  : PeriodicStructuredMesh {node}
816,000✔
1457
{
816,000✔
1458
  n_dimension_ = 3;
1459

816,000✔
1460
  grid_[0] = get_node_array<double>(node, "r_grid");
816,000✔
1461
  grid_[1] = get_node_array<double>(node, "theta_grid");
816,000✔
1462
  grid_[2] = get_node_array<double>(node, "phi_grid");
816,000✔
1463
  origin_ = get_node_position(node, "origin");
816,000✔
1464

1465
  if (int err = set_grid()) {
816,000✔
1466
    fatal_error(openmc_err_msg);
816,000✔
1467
  }
1468
}
816,000✔
1469

1470
const std::string SphericalMesh::mesh_type = "spherical";
1471

146,628,600✔
1472
std::string SphericalMesh::get_mesh_type() const
1473
{
1474
  return mesh_type;
1475
}
146,628,600✔
1476

17,850,072✔
1477
StructuredMesh::MeshIndex SphericalMesh::get_indices(
1478
  Position r, bool& in_mesh) const
1479
{
1480
  local_coords(r);
1481

1482
  Position mapped_r;
128,778,528✔
1483
  mapped_r[0] = r.norm();
128,778,528✔
1484

7,044,084✔
1485
  if (mapped_r[0] < FP_PRECISION) {
1486
    mapped_r[1] = 0.0;
121,734,444✔
1487
    mapped_r[2] = 0.0;
1488
  } else {
1489
    mapped_r[1] = std::acos(r.z / mapped_r.x);
121,734,444✔
UNCOV
1490
    mapped_r[2] = std::atan2(r.y, r.x);
×
1491
    if (mapped_r[2] < 0)
1492
      mapped_r[2] += 2 * M_PI;
1493
  }
121,734,444✔
1494

1495
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
121,734,444✔
1496

121,734,444✔
1497
  idx[1] = sanitize_theta(idx[1]);
121,734,444✔
1498
  idx[2] = sanitize_phi(idx[2]);
1499

121,734,444✔
1500
  return idx;
16,859,556✔
1501
}
1502

104,874,888✔
1503
Position SphericalMesh::sample_element(
1504
  const MeshIndex& ijk, uint64_t* seed) const
1505
{
104,874,888✔
1506
  double r_min = this->r(ijk[0] - 1);
7,057,536✔
1507
  double r_max = this->r(ijk[0]);
1508

97,817,352✔
1509
  double theta_min = this->theta(ijk[1] - 1);
19,920,936✔
1510
  double theta_max = this->theta(ijk[1]);
77,896,416✔
1511

47,239,464✔
1512
  double phi_min = this->phi(ijk[2] - 1);
1513
  double phi_max = this->phi(ijk[2]);
30,656,952✔
1514

1515
  double cos_theta = uniform_distribution(theta_min, theta_max, seed);
1516
  double sin_theta = std::sin(std::acos(cos_theta));
72,236,472✔
1517
  double phi = uniform_distribution(phi_min, phi_max, seed);
1518
  double r_min_cub = std::pow(r_min, 3);
1519
  double r_max_cub = std::pow(r_max, 3);
1520
  // might be faster to do rejection here?
72,236,472✔
1521
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
32,466,432✔
1522

1523
  double x = r * std::cos(phi) * sin_theta;
39,770,040✔
1524
  double y = r * std::sin(phi) * sin_theta;
1525
  double z = r * cos_theta;
39,770,040✔
1526

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

1530
double SphericalMesh::find_r_crossing(
1531
  const Position& r, const Direction& u, double l, int shell) const
1532
{
39,770,040✔
1533
  if ((shell < 0) || (shell > shape_[0]))
39,770,040✔
1534
    return INFTY;
1535

39,770,040✔
1536
  // solve |r+s*u| = r0
1537
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
1538
  const double r0 = grid_[0][shell];
39,770,040✔
1539
  if (r0 == 0.0)
39,770,040✔
1540
    return INFTY;
1541
  const double p = r.dot(u);
1542
  double c = r.dot(r) - r0 * r0;
39,770,040✔
1543
  double D = p * p - c;
18,739,656✔
1544

1545
  if (std::abs(c) <= RADIAL_MESH_TOL)
1546
    return INFTY;
21,030,384✔
1547

1548
  if (D >= 0.0) {
1549
    D = std::sqrt(D);
39,212,208✔
1550
    // the solution -p - D is always smaller as -p + D : Check this one first
1551
    if (-p - D > l)
1552
      return -p - D;
39,212,208✔
1553
    if (-p + D > l)
39,212,208✔
1554
      return -p + D;
1555
  }
1556

39,212,208✔
1557
  return INFTY;
480,000✔
1558
}
1559

38,732,208✔
1560
double SphericalMesh::find_theta_crossing(
38,732,208✔
1561
  const Position& r, const Direction& u, double l, int shell) const
17,729,088✔
1562
{
17,729,088✔
1563
  // Theta grid is [0, π], thus there is no real surface to cross
21,003,120✔
1564
  if (full_theta_ && (shape_[1] == 1))
18,037,548✔
1565
    return INFTY;
18,037,548✔
1566

1567
  shell = sanitize_theta(shell);
38,732,208✔
1568

1569
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
1570
  // yields
148,644,744✔
1571
  // a*s^2 + 2*b*s + c == 0 with
1572
  // a = cos(theta)^2 - u.z * u.z
1573
  // b = r*u * cos(theta)^2 - u.z * r.z
1574
  // c = r*r * cos(theta)^2 - r.z^2
148,644,744✔
1575

1576
  const double cos_t = std::cos(grid_[1][shell]);
148,644,744✔
1577
  const bool sgn = std::signbit(cos_t);
1578
  const double cos_t_2 = cos_t * cos_t;
73,314,300✔
1579

73,314,300✔
1580
  const double a = cos_t_2 - u.z * u.z;
146,628,600✔
1581
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
1582
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
75,330,444✔
1583

1584
  // if factor of s^2 is zero, direction of flight is parallel to theta surface
36,118,236✔
1585
  if (std::abs(a) < FP_PRECISION) {
36,118,236✔
1586
    // if b vanishes, direction of flight is within theta surface and crossing
36,118,236✔
1587
    // is not possible
72,236,472✔
1588
    if (std::abs(b) < FP_PRECISION)
1589
      return INFTY;
1590

39,212,208✔
1591
    const double s = -0.5 * c / b;
1592
    // Check if solution is in positive direction of flight and has correct sign
1593
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1594
      return s;
425✔
1595

1596
    // no crossing is possible
425✔
1597
    return INFTY;
425✔
1598
  }
425✔
1599

1600
  const double p = b / a;
1,700✔
1601
  double D = p * p - c / a;
1,275✔
UNCOV
1602

×
1603
  if (D < 0.0)
UNCOV
1604
    return INFTY;
×
1605

1606
  D = std::sqrt(D);
1,275✔
1607

2,550✔
UNCOV
1608
  // the solution -p-D is always smaller as -p+D : Check this one first
×
1609
  double s = -p - D;
1610
  // Check if solution is in positive direction of flight and has correct sign
×
1611
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
1612
    return s;
1613

425✔
UNCOV
1614
  s = -p + D;
×
1615
  // Check if solution is in positive direction of flight and has correct sign
UNCOV
1616
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
1617
    return s;
1618

425✔
UNCOV
1619
  return INFTY;
×
1620
}
UNCOV
1621

×
1622
double SphericalMesh::find_phi_crossing(
1623
  const Position& r, const Direction& u, double l, int shell) const
425✔
UNCOV
1624
{
×
1625
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1626
  if (full_phi_ && (shape_[2] == 1))
UNCOV
1627
    return INFTY;
×
1628

1629
  shell = sanitize_phi(shell);
1630

425✔
1631
  const double p0 = grid_[2][shell];
1632

850✔
1633
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
850✔
1634
  // => x(s) * cos(p0) = y(s) * sin(p0)
850✔
1635
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
850✔
1636
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1637

425✔
1638
  const double c0 = std::cos(p0);
1639
  const double s0 = std::sin(p0);
1640

149,364,576✔
1641
  const double denominator = (u.x * s0 - u.y * c0);
1642

149,364,576✔
1643
  // Check if direction of flight is not parallel to phi surface
1644
  if (std::abs(denominator) > FP_PRECISION) {
UNCOV
1645
    const double s = -(r.x * s0 - r.y * c0) / denominator;
×
1646
    // Check if solution is in positive direction of flight and crosses the
1647
    // correct phi surface (not -phi)
UNCOV
1648
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
×
1649
      return s;
1650
  }
1651

1652
  return INFTY;
1653
}
1654

1655
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
396✔
1656
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1657
  double l) const
396✔
1658
{
396✔
1659

396✔
1660
  if (i == 0) {
396✔
1661
    return std::min(
396✔
1662
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
1663
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
336✔
1664

1665
  } else if (i == 1) {
336✔
1666
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
336✔
1667
                      find_theta_crossing(r0, u, l, ijk[i])),
1668
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
336✔
1669
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
336✔
1670

1671
  } else {
336✔
1672
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
336✔
1673
                      find_phi_crossing(r0, u, l, ijk[i])),
1674
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
336✔
1675
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
1676
  }
1677
}
1678

1679
int SphericalMesh::set_grid()
1680
{
1681
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
317✔
1682
    static_cast<int>(grid_[1].size()) - 1,
317✔
1683
    static_cast<int>(grid_[2].size()) - 1};
1684

317✔
1685
  for (const auto& g : grid_) {
1686
    if (g.size() < 2) {
317✔
1687
      set_errmsg("x-, y-, and z- grids for spherical meshes "
317✔
1688
                 "must each have at least 2 points");
317✔
1689
      return OPENMC_E_INVALID_ARGUMENT;
317✔
1690
    }
1691
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
317✔
UNCOV
1692
        g.end()) {
×
1693
      set_errmsg("Values in for r-, theta-, and phi- grids for "
1694
                 "spherical meshes must be sorted and unique.");
317✔
1695
      return OPENMC_E_INVALID_ARGUMENT;
1696
    }
1697
    if (g.front() < 0.0) {
1698
      set_errmsg("r-, theta-, and phi- grids for "
372✔
1699
                 "spherical meshes must start at v >= 0.");
1700
      return OPENMC_E_INVALID_ARGUMENT;
372✔
1701
    }
1702
  }
1703
  if (grid_[1].back() > PI) {
73,258,044✔
1704
    set_errmsg("theta-grids for "
1705
               "spherical meshes must end with theta <= pi.");
1706

73,258,044✔
1707
    return OPENMC_E_INVALID_ARGUMENT;
1708
  }
73,258,044✔
1709
  if (grid_[2].back() > 2 * PI) {
73,258,044✔
1710
    set_errmsg("phi-grids for "
1711
               "spherical meshes must end with phi <= 2*pi.");
73,258,044✔
UNCOV
1712
    return OPENMC_E_INVALID_ARGUMENT;
×
UNCOV
1713
  }
×
1714

1715
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
73,258,044✔
1716
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
73,258,044✔
1717

73,258,044✔
1718
  double r = grid_[0].back();
36,598,944✔
1719
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
1720
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
1721

73,258,044✔
1722
  return 0;
1723
}
73,258,044✔
1724

73,258,044✔
1725
int SphericalMesh::get_index_in_direction(double r, int i) const
1726
{
73,258,044✔
1727
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
1728
}
1729

1,440,000✔
1730
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
1731
  Position plot_ll, Position plot_ur) const
1732
{
1,440,000✔
1733
  fatal_error("Plot of spherical Mesh not implemented");
1,440,000✔
1734

1735
  // Figure out which axes lie in the plane of the plot.
1,440,000✔
1736
  array<vector<double>, 2> axis_lines;
1,440,000✔
1737
  return {axis_lines[0], axis_lines[1]};
1738
}
1,440,000✔
1739

1,440,000✔
1740
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
1741
{
1,440,000✔
1742
  write_dataset(mesh_group, "r_grid", grid_[0]);
1,440,000✔
1743
  write_dataset(mesh_group, "theta_grid", grid_[1]);
1,440,000✔
1744
  write_dataset(mesh_group, "phi_grid", grid_[2]);
1,440,000✔
1745
  write_dataset(mesh_group, "origin", origin_);
1,440,000✔
1746
}
1747

1,440,000✔
1748
double SphericalMesh::volume(const MeshIndex& ijk) const
1749
{
1,440,000✔
1750
  double r_i = grid_[0][ijk[0] - 1];
1,440,000✔
1751
  double r_o = grid_[0][ijk[0]];
1,440,000✔
1752

1753
  double theta_i = grid_[1][ijk[1] - 1];
1,440,000✔
1754
  double theta_o = grid_[1][ijk[1]];
1755

1756
  double phi_i = grid_[2][ijk[2] - 1];
480,342,048✔
1757
  double phi_o = grid_[2][ijk[2]];
1758

1759
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
480,342,048✔
1760
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
43,677,828✔
1761
}
1762

1763
//==============================================================================
1764
// Helper functions for the C API
436,664,220✔
1765
//==============================================================================
436,664,220✔
1766

7,577,856✔
1767
int check_mesh(int32_t index)
429,086,364✔
1768
{
429,086,364✔
1769
  if (index < 0 || index >= model::meshes.size()) {
429,086,364✔
1770
    set_errmsg("Index in meshes array is out of bounds.");
1771
    return OPENMC_E_OUT_OF_BOUNDS;
429,086,364✔
1772
  }
11,548,560✔
1773
  return 0;
1774
}
417,537,804✔
1775

388,160,352✔
1776
template<class T>
1777
int check_mesh_type(int32_t index)
388,160,352✔
1778
{
69,316,164✔
1779
  if (int err = check_mesh(index))
318,844,188✔
1780
    return err;
192,088,092✔
1781

1782
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1783
  if (!mesh) {
156,133,548✔
1784
    set_errmsg("This function is not valid for input mesh.");
1785
    return OPENMC_E_INVALID_TYPE;
1786
  }
117,164,688✔
1787
  return 0;
1788
}
1789

1790
template<class T>
117,164,688✔
1791
bool is_mesh_type(int32_t index)
76,498,272✔
1792
{
1793
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
40,666,416✔
1794
  return mesh;
1795
}
1796

1797
//==============================================================================
1798
// C API functions
1799
//==============================================================================
1800

1801
// Return the type of mesh as a C string
1802
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
40,666,416✔
1803
{
40,666,416✔
1804
  if (int err = check_mesh(index))
40,666,416✔
1805
    return err;
1806

40,666,416✔
1807
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
40,666,416✔
1808

40,666,416✔
1809
  return 0;
1810
}
1811

40,666,416✔
1812
//! Extend the meshes array by n elements
1813
extern "C" int openmc_extend_meshes(
UNCOV
1814
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
×
1815
{
×
1816
  if (index_start)
UNCOV
1817
    *index_start = model::meshes.size();
×
1818
  std::string mesh_type;
1819

×
UNCOV
1820
  for (int i = 0; i < n; ++i) {
×
1821
    if (RegularMesh::mesh_type == type) {
1822
      model::meshes.push_back(make_unique<RegularMesh>());
UNCOV
1823
    } else if (RectilinearMesh::mesh_type == type) {
×
1824
      model::meshes.push_back(make_unique<RectilinearMesh>());
1825
    } else if (CylindricalMesh::mesh_type == type) {
1826
      model::meshes.push_back(make_unique<CylindricalMesh>());
40,666,416✔
1827
    } else if (SphericalMesh::mesh_type == type) {
40,666,416✔
1828
      model::meshes.push_back(make_unique<SphericalMesh>());
1829
    } else {
40,666,416✔
1830
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
11,532,864✔
1831
    }
1832
  }
29,133,552✔
1833
  if (index_end)
1834
    *index_end = model::meshes.size() - 1;
1835

29,133,552✔
1836
  return 0;
1837
}
29,133,552✔
1838

5,527,560✔
1839
//! Adds a new unstructured mesh to OpenMC
1840
extern "C" int openmc_add_unstructured_mesh(
23,605,992✔
1841
  const char filename[], const char library[], int* id)
1842
{
23,605,992✔
1843
  std::string lib_name(library);
11,064,504✔
1844
  std::string mesh_file(filename);
1845
  bool valid_lib = false;
12,541,488✔
1846

1847
#ifdef DAGMC
1848
  if (lib_name == MOABMesh::mesh_lib_type) {
118,858,440✔
1849
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
1850
    valid_lib = true;
1851
  }
1852
#endif
118,858,440✔
1853

76,498,272✔
1854
#ifdef LIBMESH
1855
  if (lib_name == LibMesh::mesh_lib_type) {
42,360,168✔
1856
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
1857
    valid_lib = true;
42,360,168✔
1858
  }
1859
#endif
1860

1861
  if (!valid_lib) {
1862
    set_errmsg(fmt::format("Mesh library {} is not supported "
1863
                           "by this build of OpenMC",
1864
      lib_name));
42,360,168✔
1865
    return OPENMC_E_INVALID_ARGUMENT;
42,360,168✔
1866
  }
1867

42,360,168✔
1868
  // auto-assign new ID
1869
  model::meshes.back()->set_id(-1);
1870
  *id = model::meshes.back()->id_;
42,360,168✔
1871

42,360,168✔
1872
  return 0;
1873
}
1874

42,360,168✔
1875
//! Return the index in the meshes array of a mesh with a given ID
18,707,712✔
1876
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
1877
{
1878
  auto pair = model::mesh_map.find(id);
23,652,456✔
1879
  if (pair == model::mesh_map.end()) {
1880
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
1881
    return OPENMC_E_INVALID_ID;
358,182,588✔
1882
  }
1883
  *index = pair->second;
1884
  return 0;
1885
}
1886

358,182,588✔
1887
//! Return the ID of a mesh
240,171,024✔
1888
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
240,171,024✔
1889
{
480,342,048✔
1890
  if (int err = check_mesh(index))
1891
    return err;
118,011,564✔
1892
  *id = model::meshes[index]->id_;
58,582,344✔
1893
  return 0;
58,582,344✔
1894
}
58,582,344✔
1895

117,164,688✔
1896
//! Set the ID of a mesh
1897
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
1898
{
59,429,220✔
1899
  if (int err = check_mesh(index))
59,429,220✔
1900
    return err;
59,429,220✔
1901
  model::meshes[index]->id_ = id;
118,858,440✔
1902
  model::mesh_map[id] = index;
1903
  return 0;
1904
}
1905

341✔
1906
//! Get the number of elements in a mesh
1907
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
341✔
1908
{
341✔
1909
  if (int err = check_mesh(index))
341✔
1910
    return err;
1911
  *n = model::meshes[index]->n_bins();
1,364✔
1912
  return 0;
1,023✔
UNCOV
1913
}
×
1914

1915
//! Get the volume of each element in the mesh
×
1916
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
1917
{
1,023✔
1918
  if (int err = check_mesh(index))
2,046✔
UNCOV
1919
    return err;
×
1920
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
UNCOV
1921
    volumes[i] = model::meshes[index]->volume(i);
×
1922
  }
1923
  return 0;
1,023✔
UNCOV
1924
}
×
1925

1926
//! Get the bounding box of a mesh
×
1927
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
1928
{
1929
  if (int err = check_mesh(index))
341✔
UNCOV
1930
    return err;
×
1931

1932
  BoundingBox bbox = model::meshes[index]->bounding_box();
UNCOV
1933

×
1934
  // set lower left corner values
1935
  ll[0] = bbox.xmin;
341✔
UNCOV
1936
  ll[1] = bbox.ymin;
×
1937
  ll[2] = bbox.zmin;
UNCOV
1938

×
1939
  // set upper right corner values
1940
  ur[0] = bbox.xmax;
1941
  ur[1] = bbox.ymax;
341✔
1942
  ur[2] = bbox.zmax;
341✔
1943
  return 0;
1944
}
341✔
1945

341✔
1946
extern "C" int openmc_mesh_material_volumes(int32_t index, int n_sample,
341✔
1947
  int bin, int result_size, void* result, int* hits, uint64_t* seed)
1948
{
341✔
1949
  auto result_ = reinterpret_cast<Mesh::MaterialVolume*>(result);
1950
  if (!result_) {
1951
    set_errmsg("Invalid result pointer passed to openmc_mesh_material_volumes");
219,774,132✔
1952
    return OPENMC_E_INVALID_ARGUMENT;
1953
  }
219,774,132✔
1954

1955
  if (int err = check_mesh(index))
UNCOV
1956
    return err;
×
1957

1958
  int n = model::meshes[index]->material_volumes(
UNCOV
1959
    n_sample, bin, {result_, result_ + result_size}, seed);
×
1960
  *hits = n;
1961
  return (n == -1) ? OPENMC_E_ALLOCATE : 0;
1962
}
1963

1964
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
1965
  Position width, int basis, int* pixels, int32_t* data)
1966
{
312✔
1967
  if (int err = check_mesh(index))
1968
    return err;
312✔
1969
  const auto& mesh = model::meshes[index].get();
312✔
1970

312✔
1971
  int pixel_width = pixels[0];
312✔
1972
  int pixel_height = pixels[1];
312✔
1973

1974
  // get pixel size
600✔
1975
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
1976
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
600✔
1977

600✔
1978
  // setup basis indices and initial position centered on pixel
1979
  int in_i, out_i;
600✔
1980
  Position xyz = origin;
600✔
1981
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
1982
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
600✔
1983
  switch (basis_enum) {
600✔
1984
  case PlotBasis::xy:
1985
    in_i = 0;
600✔
1986
    out_i = 1;
600✔
1987
    break;
1988
  case PlotBasis::xz:
1989
    in_i = 0;
1990
    out_i = 2;
1991
    break;
1992
  case PlotBasis::yz:
1993
    in_i = 1;
9,376✔
1994
    out_i = 2;
1995
    break;
9,376✔
UNCOV
1996
  default:
×
1997
    UNREACHABLE();
×
1998
  }
1999

9,376✔
2000
  // set initial position
2001
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
2002
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
2003

1,759✔
2004
#pragma omp parallel
2005
  {
1,759✔
UNCOV
2006
    Position r = xyz;
×
2007

2008
#pragma omp for
1,759✔
2009
    for (int y = 0; y < pixel_height; y++) {
1,759✔
UNCOV
2010
      r[out_i] = xyz[out_i] - out_pixel * y;
×
2011
      for (int x = 0; x < pixel_width; x++) {
×
2012
        r[in_i] = xyz[in_i] + in_pixel * x;
2013
        data[pixel_width * y + x] = mesh->get_bin(r);
1,759✔
2014
      }
2015
    }
156✔
2016
  }
2017

156✔
UNCOV
2018
  return 0;
×
2019
}
2020

156✔
2021
//! Get the dimension of a regular mesh
156✔
UNCOV
2022
extern "C" int openmc_regular_mesh_get_dimension(
×
2023
  int32_t index, int** dims, int* n)
×
2024
{
2025
  if (int err = check_mesh_type<RegularMesh>(index))
156✔
2026
    return err;
2027
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
156✔
2028
  *dims = mesh->shape_.data();
2029
  *n = mesh->n_dimension_;
156✔
UNCOV
2030
  return 0;
×
2031
}
2032

156✔
2033
//! Set the dimension of a regular mesh
156✔
UNCOV
2034
extern "C" int openmc_regular_mesh_set_dimension(
×
2035
  int32_t index, int n, const int* dims)
×
2036
{
2037
  if (int err = check_mesh_type<RegularMesh>(index))
156✔
2038
    return err;
2039
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
256✔
2040

2041
  // Copy dimension
256✔
UNCOV
2042
  mesh->n_dimension_ = n;
×
2043
  std::copy(dims, dims + n, mesh->shape_.begin());
2044
  return 0;
256✔
2045
}
256✔
UNCOV
2046

×
2047
//! Get the regular mesh parameters
×
2048
extern "C" int openmc_regular_mesh_get_params(
2049
  int32_t index, double** ll, double** ur, double** width, int* n)
256✔
2050
{
2051
  if (int err = check_mesh_type<RegularMesh>(index))
1,191✔
2052
    return err;
2053
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
1,191✔
UNCOV
2054

×
2055
  if (m->lower_left_.dimension() == 0) {
2056
    set_errmsg("Mesh parameters have not been set.");
1,191✔
2057
    return OPENMC_E_ALLOCATE;
1,191✔
UNCOV
2058
  }
×
2059

×
2060
  *ll = m->lower_left_.data();
2061
  *ur = m->upper_right_.data();
1,191✔
2062
  *width = m->width_.data();
2063
  *n = m->n_dimension_;
2064
  return 0;
2065
}
2066

2067
//! Set the regular mesh parameters
2068
extern "C" int openmc_regular_mesh_set_params(
2069
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2070
{
2071
  if (int err = check_mesh_type<RegularMesh>(index))
2072
    return err;
2073
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
2074

2075
  if (m->n_dimension_ == -1) {
2076
    set_errmsg("Need to set mesh dimension before setting parameters.");
2,073✔
2077
    return OPENMC_E_UNASSIGNED;
2078
  }
2,073✔
UNCOV
2079

×
2080
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
2081
  if (ll && ur) {
2,073✔
2082
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
2083
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
2,073✔
2084
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_x_shape();
2085
  } else if (ll && width) {
2086
    m->lower_left_ = xt::adapt(ll, n, xt::no_ownership(), shape);
2087
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
471✔
2088
    m->upper_right_ = m->lower_left_ + m->get_x_shape() * m->width_;
2089
  } else if (ur && width) {
2090
    m->upper_right_ = xt::adapt(ur, n, xt::no_ownership(), shape);
471✔
2091
    m->width_ = xt::adapt(width, n, xt::no_ownership(), shape);
471✔
2092
    m->lower_left_ = m->upper_right_ - m->get_x_shape() * m->width_;
471✔
2093
  } else {
2094
    set_errmsg("At least two parameters must be specified.");
942✔
2095
    return OPENMC_E_INVALID_ARGUMENT;
471✔
2096
  }
349✔
2097

122✔
2098
  // Set material volumes
74✔
2099

48✔
2100
  // TODO: incorporate this into method in RegularMesh that can be called from
24✔
2101
  // here and from constructor
24✔
2102
  m->volume_frac_ = 1.0 / xt::prod(m->get_x_shape())();
24✔
2103
  m->element_volume_ = 1.0;
UNCOV
2104
  for (int i = 0; i < m->n_dimension_; i++) {
×
2105
    m->element_volume_ *= m->width_[i];
2106
  }
2107

471✔
UNCOV
2108
  return 0;
×
2109
}
2110

471✔
2111
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
471✔
2112
template<class C>
2113
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
UNCOV
2114
  const int nx, const double* grid_y, const int ny, const double* grid_z,
×
2115
  const int nz)
2116
{
UNCOV
2117
  if (int err = check_mesh_type<C>(index))
×
2118
    return err;
×
2119

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

2122
  m->n_dimension_ = 3;
2123

2124
  m->grid_[0].reserve(nx);
2125
  m->grid_[1].reserve(ny);
2126
  m->grid_[2].reserve(nz);
2127

2128
  for (int i = 0; i < nx; i++) {
2129
    m->grid_[0].push_back(grid_x[i]);
2130
  }
2131
  for (int i = 0; i < ny; i++) {
2132
    m->grid_[1].push_back(grid_y[i]);
2133
  }
2134
  for (int i = 0; i < nz; i++) {
UNCOV
2135
    m->grid_[2].push_back(grid_z[i]);
×
2136
  }
×
2137

2138
  int err = m->set_grid();
UNCOV
2139
  return err;
×
2140
}
2141

2142
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
UNCOV
2143
template<class C>
×
2144
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
×
2145
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
UNCOV
2146
{
×
2147
  if (int err = check_mesh_type<C>(index))
2148
    return err;
2149
  C* m = dynamic_cast<C*>(model::meshes[index].get());
2150

663✔
2151
  if (m->lower_left_.dimension() == 0) {
2152
    set_errmsg("Mesh parameters have not been set.");
663✔
2153
    return OPENMC_E_ALLOCATE;
663✔
UNCOV
2154
  }
×
2155

×
2156
  *grid_x = m->grid_[0].data();
2157
  *nx = m->grid_[0].size();
663✔
2158
  *grid_y = m->grid_[1].data();
663✔
2159
  *ny = m->grid_[1].size();
2160
  *grid_z = m->grid_[2].data();
2161
  *nz = m->grid_[2].size();
2162

4,305✔
2163
  return 0;
2164
}
4,305✔
UNCOV
2165

×
2166
//! Get the rectilinear mesh grid
4,305✔
2167
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
4,305✔
2168
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2169
{
2170
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
2171
    index, grid_x, nx, grid_y, ny, grid_z, nz);
471✔
2172
}
2173

471✔
UNCOV
2174
//! Set the rectilienar mesh parameters
×
2175
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
471✔
2176
  const double* grid_x, const int nx, const double* grid_y, const int ny,
471✔
2177
  const double* grid_z, const int nz)
471✔
2178
{
2179
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
2180
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2181
}
192✔
2182

2183
//! Get the cylindrical mesh grid
192✔
UNCOV
2184
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
×
2185
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
192✔
2186
{
192✔
2187
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
2188
    index, grid_x, nx, grid_y, ny, grid_z, nz);
2189
}
2190

96✔
2191
//! Set the cylindrical mesh parameters
2192
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
96✔
UNCOV
2193
  const double* grid_x, const int nx, const double* grid_y, const int ny,
×
2194
  const double* grid_z, const int nz)
1,056✔
2195
{
960✔
2196
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
2197
    index, grid_x, nx, grid_y, ny, grid_z, nz);
96✔
2198
}
2199

2200
//! Get the spherical mesh grid
2201
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
48✔
2202
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2203
{
48✔
UNCOV
2204

×
2205
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
2206
    index, grid_x, nx, grid_y, ny, grid_z, nz);
48✔
2207
  ;
2208
}
2209

48✔
2210
//! Set the spherical mesh parameters
48✔
2211
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
48✔
2212
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2213
  const double* grid_z, const int nz)
2214
{
48✔
2215
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
48✔
2216
    index, grid_x, nx, grid_y, ny, grid_z, nz);
48✔
2217
}
48✔
2218

2219
#ifdef DAGMC
2220

384✔
2221
const std::string MOABMesh::mesh_lib_type = "moab";
2222

2223
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
384✔
2224
{
384✔
UNCOV
2225
  initialize();
×
2226
}
×
2227

2228
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2229
{
384✔
UNCOV
2230
  filename_ = filename;
×
2231
  set_length_multiplier(length_multiplier);
2232
  initialize();
768✔
2233
}
384✔
2234

384✔
2235
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
384✔
2236
{
2237
  mbi_ = external_mbi;
2238
  filename_ = "unknown (external file)";
48✔
2239
  this->initialize();
2240
}
2241

48✔
UNCOV
2242
void MOABMesh::initialize()
×
2243
{
48✔
2244

2245
  // Create the MOAB interface and load data from file
48✔
2246
  this->create_interface();
48✔
2247

2248
  // Initialise MOAB error code
2249
  moab::ErrorCode rval = moab::MB_SUCCESS;
48✔
2250

48✔
2251
  // Set the dimension
2252
  n_dimension_ = 3;
2253

2254
  // set member range of tetrahedral entities
48✔
2255
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2256
  if (rval != moab::MB_SUCCESS) {
48✔
2257
    fatal_error("Failed to get all tetrahedral elements");
48✔
2258
  }
48✔
2259

48✔
2260
  if (!ehs_.all_of_type(moab::MBTET)) {
48✔
2261
    warning("Non-tetrahedral elements found in unstructured "
48✔
UNCOV
2262
            "mesh file: " +
×
2263
            filename_);
×
2264
  }
×
2265

×
2266
  // set member range of vertices
×
2267
  int vertex_dim = 0;
×
2268
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
×
2269
  if (rval != moab::MB_SUCCESS) {
×
2270
    fatal_error("Failed to get all vertex handles");
×
2271
  }
×
2272

2273
  // make an entity set for all tetrahedra
2274
  // this is used for convenience later in output
2275
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
48✔
2276
  if (rval != moab::MB_SUCCESS) {
48✔
2277
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2278
  }
24✔
2279

2280
  rval = mbi_->add_entities(tetset_, ehs_);
24✔
2281
  if (rval != moab::MB_SUCCESS) {
2282
    fatal_error("Failed to add tetrahedra to an entity set.");
2283
  }
504✔
2284

480✔
2285
  if (length_multiplier_ > 0.0) {
10,080✔
2286
    // get the connectivity of all tets
9,600✔
2287
    moab::Range adj;
9,600✔
2288
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
2289
    if (rval != moab::MB_SUCCESS) {
2290
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2291
    }
2292
    // scale all vertex coords by multiplier (done individually so not all
48✔
2293
    // coordinates are in memory twice at once)
2294
    for (auto vert : adj) {
2295
      // retrieve coords
2296
      std::array<double, 3> coord;
12✔
2297
      rval = mbi_->get_coords(&vert, 1, coord.data());
2298
      if (rval != moab::MB_SUCCESS) {
2299
        fatal_error("Could not get coordinates of vertex.");
12✔
UNCOV
2300
      }
×
2301
      // scale coords
12✔
2302
      for (auto& c : coord) {
12✔
2303
        c *= length_multiplier_;
12✔
2304
      }
12✔
2305
      // set new coords
2306
      rval = mbi_->set_coords(&vert, 1, coord.data());
2307
      if (rval != moab::MB_SUCCESS) {
2308
        fatal_error("Failed to set new vertex coordinates");
373✔
2309
      }
2310
    }
2311
  }
373✔
UNCOV
2312

×
2313
  // Determine bounds of mesh
373✔
2314
  this->determine_bounds();
2315
}
2316

373✔
2317
void MOABMesh::prepare_for_point_location()
373✔
2318
{
373✔
2319
  // if the KDTree has already been constructed, do nothing
2320
  if (kdtree_)
2321
    return;
2322

397✔
2323
  // build acceleration data structures
2324
  compute_barycentric_data(ehs_);
2325
  build_kdtree(ehs_);
397✔
UNCOV
2326
}
×
2327

397✔
2328
void MOABMesh::create_interface()
2329
{
397✔
UNCOV
2330
  // Do not create a MOAB instance if one is already in memory
×
2331
  if (mbi_)
×
2332
    return;
2333

2334
  // create MOAB instance
397✔
2335
  mbi_ = std::make_shared<moab::Core>();
397✔
2336

397✔
2337
  // load unstructured mesh file
397✔
2338
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
397✔
2339
  if (rval != moab::MB_SUCCESS) {
2340
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2341
  }
2342
}
409✔
2343

2344
void MOABMesh::build_kdtree(const moab::Range& all_tets)
2345
{
409✔
UNCOV
2346
  moab::Range all_tris;
×
2347
  int adj_dim = 2;
409✔
2348
  write_message("Getting tet adjacencies...", 7);
2349
  moab::ErrorCode rval = mbi_->get_adjacencies(
409✔
UNCOV
2350
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
×
2351
  if (rval != moab::MB_SUCCESS) {
×
2352
    fatal_error("Failed to get adjacent triangles for tets");
2353
  }
2354

409✔
2355
  if (!all_tris.all_of_type(moab::MBTRI)) {
409✔
2356
    warning("Non-triangle elements found in tet adjacencies in "
385✔
2357
            "unstructured mesh file: " +
385✔
2358
            filename_);
385✔
2359
  }
24✔
2360

12✔
2361
  // combine into one range
12✔
2362
  moab::Range all_tets_and_tris;
12✔
2363
  all_tets_and_tris.merge(all_tets);
12✔
2364
  all_tets_and_tris.merge(all_tris);
12✔
2365

12✔
2366
  // create a kd-tree instance
12✔
2367
  write_message(
UNCOV
2368
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
×
2369
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
×
2370

2371
  // Determine what options to use
2372
  std::ostringstream options_stream;
2373
  if (options_.empty()) {
2374
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
2375
  } else {
2376
    options_stream << options_;
409✔
2377
  }
409✔
2378
  moab::FileOptions file_opts(options_stream.str().c_str());
1,636✔
2379

1,227✔
2380
  // Build the k-d tree
2381
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
2382
  if (rval != moab::MB_SUCCESS) {
409✔
2383
    fatal_error("Failed to construct KDTree for the "
409✔
2384
                "unstructured mesh file: " +
2385
                filename_);
2386
  }
2387
}
122✔
2388

2389
void MOABMesh::intersect_track(const moab::CartVect& start,
2390
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
2391
{
122✔
UNCOV
2392
  hits.clear();
×
2393

2394
  moab::ErrorCode rval;
122✔
2395
  vector<moab::EntityHandle> tris;
2396
  // get all intersections with triangles in the tet mesh
122✔
2397
  // (distances are relative to the start point, not the previous intersection)
2398
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
122✔
2399
    dir.array(), start.array(), tris, hits, 0, track_len);
122✔
2400
  if (rval != moab::MB_SUCCESS) {
122✔
2401
    fatal_error(
2402
      "Failed to compute intersections on unstructured mesh: " + filename_);
988✔
2403
  }
866✔
2404

2405
  // remove duplicate intersection distances
450✔
2406
  std::unique(hits.begin(), hits.end());
328✔
2407

2408
  // sorts by first component of std::pair by default
426✔
2409
  std::sort(hits.begin(), hits.end());
304✔
2410
}
2411

2412
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
122✔
2413
  vector<int>& bins, vector<double>& lengths) const
122✔
2414
{
2415
  moab::CartVect start(r0.x, r0.y, r0.z);
24✔
2416
  moab::CartVect end(r1.x, r1.y, r1.z);
2417
  moab::CartVect dir(u.x, u.y, u.z);
2418
  dir.normalize();
2419

24✔
UNCOV
2420
  double track_len = (end - start).length();
×
2421
  if (track_len == 0.0)
2422
    return;
24✔
2423

2424
  start -= TINY_BIT * dir;
24✔
2425
  end += TINY_BIT * dir;
2426

24✔
2427
  vector<double> hits;
24✔
2428
  intersect_track(start, dir, track_len, hits);
24✔
2429

2430
  bins.clear();
96✔
2431
  lengths.clear();
72✔
2432

2433
  // if there are no intersections the track may lie entirely
96✔
2434
  // within a single tet. If this is the case, apply entire
72✔
2435
  // score to that tet and return.
2436
  if (hits.size() == 0) {
108✔
2437
    Position midpoint = r0 + u * (track_len * 0.5);
84✔
2438
    int bin = this->get_bin(midpoint);
2439
    if (bin != -1) {
2440
      bins.push_back(bin);
24✔
2441
      lengths.push_back(1.0);
24✔
2442
    }
2443
    return;
24✔
2444
  }
2445

2446
  // for each segment in the set of tracks, try to look up a tet
2447
  // at the midpoint of the segment
24✔
UNCOV
2448
  Position current = r0;
×
2449
  double last_dist = 0.0;
2450
  for (const auto& hit : hits) {
24✔
2451
    // get the segment length
2452
    double segment_length = hit - last_dist;
24✔
2453
    last_dist = hit;
2454
    // find the midpoint of this segment
24✔
2455
    Position midpoint = current + u * (segment_length * 0.5);
24✔
2456
    // try to find a tet for this position
24✔
2457
    int bin = this->get_bin(midpoint);
2458

96✔
2459
    // determine the start point for this segment
72✔
2460
    current = r0 + u * hit;
2461

108✔
2462
    if (bin == -1) {
84✔
2463
      continue;
2464
    }
84✔
2465

60✔
2466
    bins.push_back(bin);
2467
    lengths.push_back(segment_length / track_len);
2468
  }
24✔
2469

24✔
2470
  // tally remaining portion of track after last hit if
2471
  // the last segment of the track is in the mesh but doesn't
74✔
2472
  // reach the other side of the tet
2473
  if (hits.back() < track_len) {
2474
    Position segment_start = r0 + u * hits.back();
2475
    double segment_length = track_len - hits.back();
74✔
UNCOV
2476
    Position midpoint = segment_start + u * (segment_length * 0.5);
×
2477
    int bin = this->get_bin(midpoint);
2478
    if (bin != -1) {
74✔
2479
      bins.push_back(bin);
2480
      lengths.push_back(segment_length / track_len);
74✔
2481
    }
2482
  }
74✔
2483
};
74✔
2484

74✔
2485
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
2486
{
796✔
2487
  moab::CartVect pos(r.x, r.y, r.z);
722✔
2488
  // find the leaf of the kd-tree for this position
2489
  moab::AdaptiveKDTreeIter kdtree_iter;
246✔
2490
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
172✔
2491
  if (rval != moab::MB_SUCCESS) {
2492
    return 0;
234✔
2493
  }
160✔
2494

2495
  // retrieve the tet elements of this leaf
2496
  moab::EntityHandle leaf = kdtree_iter.handle();
74✔
2497
  moab::Range tets;
74✔
2498
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
2499
  if (rval != moab::MB_SUCCESS) {
2500
    warning("MOAB error finding tets.");
2501
  }
2502

446✔
2503
  // loop over the tets in this leaf, returning the containing tet if found
2504
  for (const auto& tet : tets) {
2505
    if (point_in_tet(pos, tet)) {
446✔
UNCOV
2506
      return tet;
×
2507
    }
446✔
2508
  }
2509

446✔
UNCOV
2510
  // if no tet is found, return an invalid handle
×
2511
  return 0;
×
2512
}
2513

2514
double MOABMesh::volume(int bin) const
446✔
2515
{
446✔
2516
  return tet_volume(get_ent_handle_from_bin(bin));
446✔
2517
}
446✔
2518

446✔
2519
std::string MOABMesh::library() const
446✔
2520
{
2521
  return mesh_lib_type;
446✔
2522
}
2523

132✔
2524
// Sample position within a tet for MOAB type tets
2525
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
2526
{
132✔
UNCOV
2527

×
2528
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
132✔
2529

2530
  // Get vertex coordinates for MOAB tet
132✔
UNCOV
2531
  const moab::EntityHandle* conn1;
×
2532
  int conn1_size;
×
2533
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
2534
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
2535
    fatal_error(fmt::format(
132✔
2536
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
132✔
2537
      conn1_size));
132✔
2538
  }
132✔
2539
  moab::CartVect p[4];
132✔
2540
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
132✔
2541
  if (rval != moab::MB_SUCCESS) {
2542
    fatal_error("Failed to get tet coords");
132✔
2543
  }
2544

132✔
2545
  std::array<Position, 4> tet_verts;
2546
  for (int i = 0; i < 4; i++) {
2547
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
132✔
UNCOV
2548
  }
×
2549
  // Samples position within tet using Barycentric stuff
132✔
2550
  return this->sample_tet(tet_verts, seed);
2551
}
132✔
UNCOV
2552

×
2553
double MOABMesh::tet_volume(moab::EntityHandle tet) const
×
2554
{
2555
  vector<moab::EntityHandle> conn;
2556
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
132✔
2557
  if (rval != moab::MB_SUCCESS) {
132✔
2558
    fatal_error("Failed to get tet connectivity");
132✔
2559
  }
132✔
2560

132✔
2561
  moab::CartVect p[4];
132✔
2562
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
2563
  if (rval != moab::MB_SUCCESS) {
132✔
2564
    fatal_error("Failed to get tet coords");
2565
  }
182✔
2566

2567
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
2568
}
182✔
UNCOV
2569

×
2570
int MOABMesh::get_bin(Position r) const
182✔
2571
{
2572
  moab::EntityHandle tet = get_tet(r);
182✔
UNCOV
2573
  if (tet == 0) {
×
2574
    return -1;
×
2575
  } else {
2576
    return get_bin_from_ent_handle(tet);
2577
  }
182✔
2578
}
182✔
2579

182✔
2580
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
182✔
2581
{
182✔
2582
  moab::ErrorCode rval;
182✔
2583

2584
  baryc_data_.clear();
182✔
2585
  baryc_data_.resize(tets.size());
2586

2587
  // compute the barycentric data for each tet element
2588
  // and store it as a 3x3 matrix
182✔
2589
  for (auto& tet : tets) {
2590
    vector<moab::EntityHandle> verts;
2591
    rval = mbi_->get_connectivity(&tet, 1, verts);
182✔
2592
    if (rval != moab::MB_SUCCESS) {
182✔
2593
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
2594
    }
2595

2596
    moab::CartVect p[4];
74✔
2597
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
2598
    if (rval != moab::MB_SUCCESS) {
2599
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
2600
    }
74✔
2601

74✔
2602
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
2603

2604
    // invert now to avoid this cost later
2605
    a = a.transpose().inverse();
132✔
2606
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
2607
  }
2608
}
132✔
2609

132✔
2610
bool MOABMesh::point_in_tet(
2611
  const moab::CartVect& r, moab::EntityHandle tet) const
2612
{
2613

24✔
2614
  moab::ErrorCode rval;
2615

2616
  // get tet vertices
2617
  vector<moab::EntityHandle> verts;
24✔
2618
  rval = mbi_->get_connectivity(&tet, 1, verts);
24✔
2619
  if (rval != moab::MB_SUCCESS) {
2620
    warning("Failed to get vertices of tet in umesh: " + filename_);
2621
    return false;
2622
  }
132✔
2623

2624
  // first vertex is used as a reference point for the barycentric data -
2625
  // retrieve its coordinates
2626
  moab::CartVect p_zero;
132✔
2627
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
132✔
2628
  if (rval != moab::MB_SUCCESS) {
2629
    warning("Failed to get coordinates of a vertex in "
2630
            "unstructured mesh: " +
2631
            filename_);
2632
    return false;
24✔
2633
  }
2634

2635
  // look up barycentric data
2636
  int idx = get_bin_from_ent_handle(tet);
24✔
2637
  const moab::Matrix3& a_inv = baryc_data_[idx];
24✔
2638

2639
  moab::CartVect bary_coords = a_inv * (r - p_zero);
2640

2641
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
2642
          bary_coords[2] >= 0.0 &&
2643
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
2644
}
22✔
2645

2646
int MOABMesh::get_bin_from_index(int idx) const
22✔
2647
{
22✔
2648
  if (idx >= n_bins()) {
2649
    fatal_error(fmt::format("Invalid bin index: {}", idx));
2650
  }
2651
  return ehs_[idx] - ehs_[0];
2652
}
2653

2654
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
2655
{
2656
  int bin = get_bin(r);
1✔
2657
  *in_mesh = bin != -1;
2658
  return bin;
1✔
2659
}
1✔
2660

1✔
2661
int MOABMesh::get_index_from_bin(int bin) const
1✔
2662
{
2663
  return bin;
23✔
2664
}
2665

2666
std::pair<vector<double>, vector<double>> MOABMesh::plot(
2667
  Position plot_ll, Position plot_ur) const
23✔
2668
{
2669
  // TODO: Implement mesh lines
2670
  return {};
23✔
2671
}
2672

2673
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
23✔
2674
{
2675
  int idx = vert - verts_[0];
2676
  if (idx >= n_vertices()) {
23✔
2677
    fatal_error(
23✔
2678
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
2679
  }
2680
  return idx;
2681
}
23✔
2682

2683
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
2684
{
2685
  int bin = eh - ehs_[0];
2686
  if (bin >= n_bins()) {
2687
    fatal_error(fmt::format("Invalid bin: {}", bin));
2688
  }
23✔
2689
  return bin;
23✔
2690
}
23✔
2691

2692
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
2693
{
2694
  if (bin >= n_bins()) {
2695
    fatal_error(fmt::format("Invalid bin index: ", bin));
2696
  }
23✔
2697
  return ehs_[0] + bin;
23✔
2698
}
2699

2700
int MOABMesh::n_bins() const
2701
{
23✔
2702
  return ehs_.size();
23✔
2703
}
2704

2705
int MOABMesh::n_surface_bins() const
2706
{
23✔
2707
  // collect all triangles in the set of tets for this mesh
2708
  moab::Range tris;
2709
  moab::ErrorCode rval;
2710
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
2711
  if (rval != moab::MB_SUCCESS) {
2712
    warning("Failed to get all triangles in the mesh instance");
2713
    return -1;
2714
  }
2715
  return 2 * tris.size();
2716
}
2717

2718
Position MOABMesh::centroid(int bin) const
2719
{
2720
  moab::ErrorCode rval;
2721

2722
  auto tet = this->get_ent_handle_from_bin(bin);
2723

2724
  // look up the tet connectivity
2725
  vector<moab::EntityHandle> conn;
2726
  rval = mbi_->get_connectivity(&tet, 1, conn);
2727
  if (rval != moab::MB_SUCCESS) {
2728
    warning("Failed to get connectivity of a mesh element.");
2729
    return {};
2730
  }
2731

2732
  // get the coordinates
2733
  vector<moab::CartVect> coords(conn.size());
2734
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
2735
  if (rval != moab::MB_SUCCESS) {
23✔
2736
    warning("Failed to get the coordinates of a mesh element.");
23✔
2737
    return {};
2738
  }
19✔
2739

2740
  // compute the centroid of the element vertices
2741
  moab::CartVect centroid(0.0, 0.0, 0.0);
19✔
2742
  for (const auto& coord : coords) {
2743
    centroid += coord;
2744
  }
2745
  centroid /= double(coords.size());
19✔
2746

19✔
2747
  return {centroid[0], centroid[1], centroid[2]};
2748
}
2749

23✔
2750
int MOABMesh::n_vertices() const
2751
{
2752
  return verts_.size();
23✔
2753
}
1✔
2754

2755
Position MOABMesh::vertex(int id) const
2756
{
22✔
2757

2758
  moab::ErrorCode rval;
2759

22✔
2760
  moab::EntityHandle vert = verts_[id];
22✔
2761

2762
  moab::CartVect coords;
2763
  rval = mbi_->get_coords(&vert, 1, coords.array());
2764
  if (rval != moab::MB_SUCCESS) {
2765
    fatal_error("Failed to get the coordinates of a vertex.");
19✔
2766
  }
2767

19✔
2768
  return {coords[0], coords[1], coords[2]};
19✔
2769
}
19✔
2770

19✔
2771
std::vector<int> MOABMesh::connectivity(int bin) const
2772
{
19✔
2773
  moab::ErrorCode rval;
2774

2775
  auto tet = get_ent_handle_from_bin(bin);
2776

19✔
2777
  // look up the tet connectivity
2778
  vector<moab::EntityHandle> conn;
2779
  rval = mbi_->get_connectivity(&tet, 1, conn);
2780
  if (rval != moab::MB_SUCCESS) {
2781
    fatal_error("Failed to get connectivity of a mesh element.");
2782
    return {};
2783
  }
19✔
2784

19✔
2785
  std::vector<int> verts(4);
19✔
2786
  for (int i = 0; i < verts.size(); i++) {
2787
    verts[i] = get_vert_idx_from_handle(conn[i]);
2788
  }
19✔
2789

19✔
2790
  return verts;
19✔
2791
}
2792

2793
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
19✔
2794
  std::string score) const
19✔
2795
{
3✔
2796
  moab::ErrorCode rval;
2797
  // add a tag to the mesh
16✔
2798
  // all scores are treated as a single value
2799
  // with an uncertainty
19✔
2800
  moab::Tag value_tag;
2801

2802
  // create the value tag if not present and get handle
19✔
2803
  double default_val = 0.0;
19✔
2804
  auto val_string = score + "_mean";
2805
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
2806
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
2807
  if (rval != moab::MB_SUCCESS) {
2808
    auto msg =
19✔
2809
      fmt::format("Could not create or retrieve the value tag for the score {}"
2810
                  " on unstructured mesh {}",
1,519,602✔
2811
        score, id_);
2812
    fatal_error(msg);
2813
  }
1,519,602✔
2814

2815
  // create the std dev tag if not present and get handle
2816
  moab::Tag error_tag;
1,519,602✔
2817
  std::string err_string = score + "_std_dev";
2818
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
2819
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
1,519,602✔
2820
  if (rval != moab::MB_SUCCESS) {
2821
    auto msg =
1,519,602✔
2822
      fmt::format("Could not create or retrieve the error tag for the score {}"
2823
                  " on unstructured mesh {}",
2824
        score, id_);
2825
    fatal_error(msg);
2826
  }
2827

1,519,602✔
2828
  // return the populated tag handles
2829
  return {value_tag, error_tag};
2830
}
1,519,602✔
2831

1,519,602✔
2832
void MOABMesh::add_score(const std::string& score)
2833
{
1,519,602✔
2834
  auto score_tags = get_score_tags(score);
2835
  tag_names_.push_back(score);
2836
}
1,519,602✔
2837

1,519,602✔
2838
void MOABMesh::remove_scores()
1,519,602✔
2839
{
1,519,602✔
2840
  for (const auto& name : tag_names_) {
2841
    auto value_name = name + "_mean";
1,519,602✔
2842
    moab::Tag tag;
1,519,602✔
2843
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
701,483✔
2844
    if (rval != moab::MB_SUCCESS)
2845
      return;
1,519,602✔
2846

1,519,602✔
2847
    rval = mbi_->tag_delete(tag);
2848
    if (rval != moab::MB_SUCCESS) {
1,519,602✔
2849
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
1,519,602✔
2850
                             " on unstructured mesh {}",
2851
        name, id_);
1,519,602✔
2852
      fatal_error(msg);
1,519,602✔
2853
    }
2854

2855
    auto std_dev_name = name + "_std_dev";
2856
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
2857
    if (rval != moab::MB_SUCCESS) {
1,519,602✔
2858
      auto msg =
701,483✔
2859
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
701,483✔
2860
                    " on unstructured mesh {}",
701,483✔
2861
          name, id_);
223,515✔
2862
    }
223,515✔
2863

2864
    rval = mbi_->tag_delete(tag);
701,483✔
2865
    if (rval != moab::MB_SUCCESS) {
2866
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
2867
                             " on unstructured mesh {}",
2868
        name, id_);
2869
      fatal_error(msg);
818,119✔
2870
    }
818,119✔
2871
  }
5,506,248✔
2872
  tag_names_.clear();
2873
}
4,688,129✔
2874

4,688,129✔
2875
void MOABMesh::set_score_data(const std::string& score,
2876
  const vector<double>& values, const vector<double>& std_dev)
4,688,129✔
2877
{
2878
  auto score_tags = this->get_score_tags(score);
4,688,129✔
2879

2880
  moab::ErrorCode rval;
2881
  // set the score value
4,688,129✔
2882
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
2883
  if (rval != moab::MB_SUCCESS) {
4,688,129✔
2884
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
20,480✔
2885
                           "on unstructured mesh {}",
2886
      score, id_);
2887
    warning(msg);
4,667,649✔
2888
  }
4,667,649✔
2889

2890
  // set the error value
2891
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
2892
  if (rval != moab::MB_SUCCESS) {
2893
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
2894
                           "on unstructured mesh {}",
818,119✔
2895
      score, id_);
818,119✔
2896
    warning(msg);
818,119✔
2897
  }
818,119✔
2898
}
818,119✔
2899

818,119✔
2900
void MOABMesh::write(const std::string& base_filename) const
762,819✔
2901
{
762,819✔
2902
  // add extension to the base name
2903
  auto filename = base_filename + ".vtk";
2904
  write_message(5, "Writing unstructured mesh {}...", filename);
1,519,602✔
2905
  filename = settings::path_output + filename;
2906

7,279,728✔
2907
  // write the tetrahedral elements of the mesh only
2908
  // to avoid clutter from zero-value data on other
7,279,728✔
2909
  // elements during visualization
2910
  moab::ErrorCode rval;
7,279,728✔
2911
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
7,279,728✔
2912
  if (rval != moab::MB_SUCCESS) {
7,279,728✔
2913
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
1,010,077✔
2914
    warning(msg);
2915
  }
2916
}
2917

6,269,651✔
2918
#endif
6,269,651✔
2919

6,269,651✔
2920
#ifdef LIBMESH
6,269,651✔
2921

2922
const std::string LibMesh::mesh_lib_type = "libmesh";
2923

2924
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node), adaptive_(false)
2925
{
259,367,091✔
2926
  // filename_ and length_multiplier_ will already be set by the
259,364,245✔
2927
  // UnstructuredMesh constructor
6,266,805✔
2928
  set_mesh_pointer_from_filename(filename_);
2929
  set_length_multiplier(length_multiplier_);
2930
  initialize();
2931
}
2932

2,846✔
2933
// create the mesh from a pointer to a libMesh Mesh
7,279,728✔
2934
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
2935
  : adaptive_(input_mesh.n_active_elem() != input_mesh.n_elem())
155,856✔
2936
{
2937
  if (!dynamic_cast<libMesh::ReplicatedMesh*>(&input_mesh)) {
155,856✔
2938
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
2939
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
2940
  }
30✔
2941

2942
  m_ = &input_mesh;
30✔
2943
  set_length_multiplier(length_multiplier);
2944
  initialize();
2945
}
2946

200,410✔
2947
// create the mesh from an input file
2948
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
2949
  : adaptive_(false)
200,410✔
2950
{
2951
  set_mesh_pointer_from_filename(filename);
2952
  set_length_multiplier(length_multiplier);
2953
  initialize();
2954
}
200,410✔
2955

200,410✔
2956
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
2957
{
2958
  filename_ = filename;
2959
  unique_m_ =
2960
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
1,002,050✔
2961
  m_ = unique_m_.get();
200,410✔
2962
  m_->read(filename_);
200,410✔
2963
}
2964

2965
// build a libMesh equation system for storing values
2966
void LibMesh::build_eqn_sys()
200,410✔
2967
{
1,002,050✔
2968
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
801,640✔
2969
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
2970
  libMesh::ExplicitSystem& eq_sys =
2971
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
400,820✔
2972
}
2973

2974
// intialize from mesh file
155,856✔
2975
void LibMesh::initialize()
2976
{
155,856✔
2977
  if (!settings::libmesh_comm) {
155,856✔
2978
    fatal_error(
155,856✔
2979
      "Attempting to use an unstructured mesh without a libMesh communicator.");
2980
  }
2981

2982
  // assuming that unstructured meshes used in OpenMC are 3D
779,280✔
2983
  n_dimension_ = 3;
155,856✔
2984

155,856✔
2985
  if (length_multiplier_ > 0.0) {
2986
    libMesh::MeshTools::Modification::scale(*m_, length_multiplier_);
2987
  }
2988
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
311,712✔
2989
  // Otherwise assume that it is prepared by its owning application
155,856✔
2990
  if (unique_m_) {
2991
    m_->prepare_for_use();
7,279,728✔
2992
  }
2993

7,279,728✔
2994
  // ensure that the loaded mesh is 3 dimensional
7,279,728✔
2995
  if (m_->mesh_dimension() != n_dimension_) {
1,012,923✔
2996
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
2997
                            "mesh is not a 3D mesh.",
6,266,805✔
2998
      filename_));
2999
  }
3000

3001
  for (int i = 0; i < num_threads(); i++) {
19✔
3002
    pl_.emplace_back(m_->sub_point_locator());
3003
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3004
    pl_.back()->enable_out_of_mesh_mode();
3005
  }
19✔
3006

19✔
3007
  // store first element in the mesh to use as an offset for bin indices
3008
  auto first_elem = *m_->elements_begin();
3009
  first_element_id_ = first_elem->id();
3010

227,731✔
3011
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
227,712✔
3012
  // contiguous in ID space, so we need to map from bin indices (defined over
227,712✔
3013
  // active elements) to global dof ids
227,712✔
3014
  if (adaptive_) {
3015
    bin_to_elem_map_.reserve(m_->n_active_elem());
3016
    elem_to_bin_map_.resize(m_->n_elem(), -1);
3017
    for (auto it = m_->active_elements_begin(); it != m_->active_elements_end();
1,138,560✔
3018
         it++) {
227,712✔
3019
      auto elem = *it;
227,712✔
3020

3021
      bin_to_elem_map_.push_back(elem->id());
3022
      elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
3023
    }
227,712✔
3024
  }
3025

3026
  // bounding box for the mesh for quick rejection checks
227,712✔
3027
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
227,712✔
3028
  libMesh::Point ll = bbox_.min();
227,712✔
3029
  libMesh::Point ur = bbox_.max();
19✔
3030
  lower_left_ = {ll(0), ll(1), ll(2)};
3031
  upper_right_ = {ur(0), ur(1), ur(2)};
259,364,245✔
3032
}
3033

3034
// Sample position within a tet for LibMesh type tets
3035
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
3036
{
3037
  const auto& elem = get_element_from_bin(bin);
3038
  // Get tet vertex coordinates from LibMesh
259,364,245✔
3039
  std::array<Position, 4> tet_verts;
259,364,245✔
3040
  for (int i = 0; i < elem.n_nodes(); i++) {
259,364,245✔
3041
    auto node_ref = elem.node_ref(i);
3042
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3043
  }
3044
  // Samples position within tet using Barycentric coordinates
3045
  return this->sample_tet(tet_verts, seed);
3046
}
3047

259,364,245✔
3048
Position LibMesh::centroid(int bin) const
259,364,245✔
3049
{
259,364,245✔
3050
  const auto& elem = this->get_element_from_bin(bin);
3051
  auto centroid = elem.vertex_average();
3052
  return {centroid(0), centroid(1), centroid(2)};
3053
}
3054

3055
int LibMesh::n_vertices() const
3056
{
3057
  return m_->n_nodes();
259,364,245✔
3058
}
259,364,245✔
3059

3060
Position LibMesh::vertex(int vertex_id) const
259,364,245✔
3061
{
3062
  const auto node_ref = m_->node_ref(vertex_id);
420,046,390✔
3063
  return {node_ref(0), node_ref(1), node_ref(2)};
441,624,143✔
3064
}
280,941,998✔
3065

259,364,245✔
3066
std::vector<int> LibMesh::connectivity(int elem_id) const
3067
{
3068
  std::vector<int> conn;
3069
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3070
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3071
    conn.push_back(elem_ptr->node_id(i));
3072
  }
3073
  return conn;
3074
}
3075

3076
std::string LibMesh::library() const
3077
{
3078
  return mesh_lib_type;
3079
}
3080

3081
int LibMesh::n_bins() const
3082
{
3083
  return m_->n_active_elem();
3084
}
3085

3086
int LibMesh::n_surface_bins() const
3087
{
3088
  int n_bins = 0;
3089
  for (int i = 0; i < this->n_bins(); i++) {
3090
    const libMesh::Elem& e = get_element_from_bin(i);
3091
    n_bins += e.n_faces();
3092
    // if this is a boundary element, it will only be visited once,
3093
    // the number of surface bins is incremented to
3094
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
767,424✔
3095
      // null neighbor pointer indicates a boundary face
3096
      if (!neighbor_ptr) {
767,424✔
3097
        n_bins++;
767,424✔
3098
      }
3099
    }
3100
  }
3101
  return n_bins;
767,424✔
3102
}
3103

3104
void LibMesh::add_score(const std::string& var_name)
265,858,762✔
3105
{
3106
  if (adaptive_) {
265,858,762✔
3107
    warning(fmt::format(
265,858,762✔
3108
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3109
      this->id_));
3110

265,858,762✔
3111
    return;
3112
  }
3113

548,122✔
3114
  if (!equation_systems_) {
3115
    build_eqn_sys();
548,122✔
3116
  }
3117

3118
  // check if this is a new variable
548,122✔
3119
  std::string value_name = var_name + "_mean";
3120
  if (!variable_map_.count(value_name)) {
3121
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
266,598,805✔
3122
    auto var_num =
3123
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
266,598,805✔
3124
    variable_map_[value_name] = var_num;
3125
  }
3126

3127
  std::string std_dev_name = var_name + "_std_dev";
3128
  // check if this is a new variable
3129
  if (!variable_map_.count(std_dev_name)) {
3130
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3131
    auto var_num =
3132
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3133
    variable_map_[std_dev_name] = var_num;
3134
  }
3135
}
3136

3137
void LibMesh::remove_scores()
3138
{
3139
  if (equation_systems_) {
3140
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3141
    eqn_sys.clear();
3142
    variable_map_.clear();
3143
  }
3144
}
3145

3146
void LibMesh::set_score_data(const std::string& var_name,
3147
  const vector<double>& values, const vector<double>& std_dev)
3148
{
3149
  if (adaptive_) {
3150
    warning(fmt::format(
3151
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3152
      this->id_));
3153

3154
    return;
3155
  }
3156

3157
  if (!equation_systems_) {
3158
    build_eqn_sys();
3159
  }
3160

3161
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3162

3163
  if (!eqn_sys.is_initialized()) {
3164
    equation_systems_->init();
3165
  }
3166

3167
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3168

3169
  // look up the value variable
3170
  std::string value_name = var_name + "_mean";
3171
  unsigned int value_num = variable_map_.at(value_name);
795,427✔
3172
  // look up the std dev variable
3173
  std::string std_dev_name = var_name + "_std_dev";
795,427✔
3174
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3175

3176
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
81,537✔
3177
       it++) {
3178
    if (!(*it)->active()) {
3179
      continue;
3180
    }
3181

81,537✔
3182
    auto bin = get_bin_from_element(*it);
3183

81,537✔
3184
    // set value
81,537✔
3185
    vector<libMesh::dof_id_type> value_dof_indices;
81,537✔
3186
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3187
    Ensures(value_dof_indices.size() == 1);
3188
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3189

163,074✔
3190
    // set std dev
3191
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3192
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
191,856✔
3193
    Ensures(std_dev_dof_indices.size() == 1);
3194
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3195
  }
3196
}
191,856✔
3197

3198
void LibMesh::write(const std::string& filename) const
3199
{
191,856✔
3200
  if (adaptive_) {
191,856✔
3201
    warning(fmt::format(
191,856✔
3202
      "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3203
      this->id_));
3204

3205
    return;
3206
  }
191,856✔
3207

959,280✔
3208
  write_message(fmt::format(
767,424✔
3209
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3210
  libMesh::ExodusII_IO exo(*m_);
3211
  std::set<std::string> systems_out = {eq_system_name_};
191,856✔
3212
  exo.write_discontinuous_exodusII(
191,856✔
3213
    filename + ".e", *equation_systems_, &systems_out);
3214
}
3215

3216
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3217
  vector<int>& bins, vector<double>& lengths) const
3218
{
3219
  // TODO: Implement triangle crossings here
3220
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3221
}
3222

3223
int LibMesh::get_bin(Position r) const
3224
{
3225
  // look-up a tet using the point locator
3226
  libMesh::Point p(r.x, r.y, r.z);
3227

3228
  // quick rejection check
3229
  if (!bbox_.contains_point(p)) {
3230
    return -1;
3231
  }
3232

3233
  const auto& point_locator = pl_.at(thread_num());
3234

3235
  const auto elem_ptr = (*point_locator)(p);
3236
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3237
}
3238

3239
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3240
{
3241
  int bin =
3242
    adaptive_ ? elem_to_bin_map_[elem->id()] : elem->id() - first_element_id_;
3243
  if (bin >= n_bins() || bin < 0) {
3244
    fatal_error(fmt::format("Invalid bin: {}", bin));
3245
  }
3246
  return bin;
3247
}
3248

3249
std::pair<vector<double>, vector<double>> LibMesh::plot(
3250
  Position plot_ll, Position plot_ur) const
3251
{
3252
  return {};
3253
}
3254

3255
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3256
{
3257
  return adaptive_ ? m_->elem_ref(bin_to_elem_map_.at(bin)) : m_->elem_ref(bin);
3258
}
3259

3260
double LibMesh::volume(int bin) const
3261
{
3262
  return this->get_element_from_bin(bin).volume();
3263
}
3264

3265
#endif // LIBMESH
3266

3267
//==============================================================================
3268
// Non-member functions
3269
//==============================================================================
3270

3271
void read_meshes(pugi::xml_node root)
3272
{
3273
  std::unordered_set<int> mesh_ids;
3274

3275
  for (auto node : root.children("mesh")) {
3276
    // Check to make sure multiple meshes in the same file don't share IDs
3277
    int id = std::stoi(get_node_value(node, "id"));
3278
    if (contains(mesh_ids, id)) {
3279
      fatal_error(fmt::format(
3280
        "Two or more meshes use the same unique ID '{}' in the same input file",
3281
        id));
3282
    }
3283
    mesh_ids.insert(id);
3284

3285
    // If we've already read a mesh with the same ID in a *different* file,
3286
    // assume it is the same here
3287
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3288
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
3289
      continue;
3290
    }
3291

3292
    std::string mesh_type;
3293
    if (check_for_node(node, "type")) {
3294
      mesh_type = get_node_value(node, "type", true, true);
3295
    } else {
3296
      mesh_type = "regular";
3297
    }
3298

3299
    // determine the mesh library to use
3300
    std::string mesh_lib;
3301
    if (check_for_node(node, "library")) {
3302
      mesh_lib = get_node_value(node, "library", true, true);
3303
    }
3304

3305
    // Read mesh and add to vector
3306
    if (mesh_type == RegularMesh::mesh_type) {
3307
      model::meshes.push_back(make_unique<RegularMesh>(node));
3308
    } else if (mesh_type == RectilinearMesh::mesh_type) {
3309
      model::meshes.push_back(make_unique<RectilinearMesh>(node));
3310
    } else if (mesh_type == CylindricalMesh::mesh_type) {
3311
      model::meshes.push_back(make_unique<CylindricalMesh>(node));
3312
    } else if (mesh_type == SphericalMesh::mesh_type) {
3313
      model::meshes.push_back(make_unique<SphericalMesh>(node));
3314
#ifdef DAGMC
3315
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3316
               mesh_lib == MOABMesh::mesh_lib_type) {
3317
      model::meshes.push_back(make_unique<MOABMesh>(node));
3318
#endif
3319
#ifdef LIBMESH
3320
    } else if (mesh_type == UnstructuredMesh::mesh_type &&
3321
               mesh_lib == LibMesh::mesh_lib_type) {
3322
      model::meshes.push_back(make_unique<LibMesh>(node));
3323
#endif
3324
    } else if (mesh_type == UnstructuredMesh::mesh_type) {
3325
      fatal_error("Unstructured mesh support is not enabled or the mesh "
3326
                  "library is invalid.");
3327
    } else {
3328
      fatal_error("Invalid mesh type: " + mesh_type);
3329
    }
3330

3331
    // Map ID to position in vector
3332
    model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3333
  }
3334
}
3335

3336
void meshes_to_hdf5(hid_t group)
3337
{
3338
  // Write number of meshes
3339
  hid_t meshes_group = create_group(group, "meshes");
3340
  int32_t n_meshes = model::meshes.size();
3341
  write_attribute(meshes_group, "n_meshes", n_meshes);
3342

3343
  if (n_meshes > 0) {
3344
    // Write IDs of meshes
3345
    vector<int> ids;
23✔
3346
    for (const auto& m : model::meshes) {
3347
      m->to_hdf5(meshes_group);
3348
      ids.push_back(m->id_);
3349
    }
23✔
3350
    write_attribute(meshes_group, "ids", ids);
23✔
3351
  }
23✔
3352

23✔
3353
  close_group(meshes_group);
3354
}
3355

3356
void free_memory_mesh()
3357
{
3358
  model::meshes.clear();
3359
  model::mesh_map.clear();
3360
}
3361

3362
extern "C" int n_meshes()
3363
{
3364
  return model::meshes.size();
3365
}
3366

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

© 2025 Coveralls, Inc