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

openmc-dev / openmc / 35234388252

17 Sep 2026 02:33PM UTC coverage: 81.531% (+0.05%) from 81.477%
35234388252

Pull #3566

github

web-flow
Merge a71b610c1 into c66d748ca
Pull Request #3566: Resolve merge conflicts for PR #3516 - Implement Virtual Lattice Method for Efficient Simulation of Dispersed Fuels

20282 of 29358 branches covered (69.09%)

Branch coverage included in aggregate %.

388 of 443 new or added lines in 10 files covered. (87.58%)

2 existing lines in 1 file now uncovered.

62836 of 72589 relevant lines covered (86.56%)

49587992.13 hits per line

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

76.79
/src/cell.cpp
1

2
#include "openmc/cell.h"
3

4
#include <algorithm>
5
#include <cassert>
6
#include <cctype>
7
#include <cmath>
8
#include <iterator>
9
#include <set>
10
#include <sstream>
11
#include <string>
12

13
#include <fmt/core.h>
14

15
#include "openmc/capi.h"
16
#include "openmc/constants.h"
17
#include "openmc/dagmc.h"
18
#include "openmc/error.h"
19
#include "openmc/geometry.h"
20
#include "openmc/hdf5_interface.h"
21
#include "openmc/lattice.h"
22
#include "openmc/material.h"
23
#include "openmc/nuclide.h"
24
#include "openmc/settings.h"
25
#include "openmc/xml_interface.h"
26

27
namespace openmc {
28

29
//==============================================================================
30
// Global variables
31
//==============================================================================
32

33
namespace model {
34
std::unordered_map<int32_t, int32_t> cell_map;
35
vector<unique_ptr<Cell>> cells;
36

37
} // namespace model
38

39
vector<vector<int32_t>> generate_triso_distribution(vector<int> lattice_shape,
15 ✔
40
  vector<double> lattice_pitch, vector<double> lattice_lower_left,
41
  vector<std::int32_t> cell_rpn, int id)
42
{
43
  vector<vector<int32_t>> triso_distribution(
15 ✔
44
    lattice_shape[0] * lattice_shape[1] * lattice_shape[2]);
15 ✔
45
  vector<double> mesh_center(3);
15 ✔
46
  vector<int> mesh_ind(3);
15 ✔
47

48
  for (int32_t token : cell_rpn) {
1,515 ✔
49
    if (token >= OP_UNION)
1,500 !
NEW
50
      continue;
×
51
    vector<double> triso_center = model::surfaces[abs(token) - 1]->get_center();
1,500 ✔
52
    for (int i = 0; i < 3; i++) {
6,000 ✔
53
      mesh_ind[i] =
4,500 ✔
54
        floor((triso_center[i] - lattice_lower_left[i]) / lattice_pitch[i]);
4,500 ✔
55
    }
56
    for (int i = mesh_ind[0] - 1; i <= mesh_ind[0] + 1; i++) {
6,000 ✔
57
      for (int j = mesh_ind[1] - 1; j <= mesh_ind[1] + 1; j++) {
18,000 ✔
58
        for (int k = mesh_ind[2] - 1; k <= mesh_ind[2] + 1; k++) {
54,000 ✔
59
          if (i < 0 || i >= lattice_shape[0] || j < 0 ||
35,775 ✔
60
              j >= lattice_shape[1] || k < 0 || k >= lattice_shape[2])
68,715 ✔
61
            continue;
21,360 ✔
62
          mesh_center[0] = (i + 0.5) * lattice_pitch[0] + lattice_lower_left[0];
19,140 ✔
63
          mesh_center[1] = (j + 0.5) * lattice_pitch[1] + lattice_lower_left[1];
19,140 ✔
64
          mesh_center[2] = (k + 0.5) * lattice_pitch[2] + lattice_lower_left[2];
19,140 ✔
65
          if (model::surfaces[abs(token) - 1]->triso_in_mesh(
19,140 ✔
66
                mesh_center, lattice_pitch)) {
67
            triso_distribution[i + j * lattice_shape[0] +
2,415 ✔
68
                               k * lattice_shape[0] * lattice_shape[1]]
2,415 ✔
69
              .push_back(token);
2,415 ✔
70
            model::surfaces[abs(token) - 1]->connect_to_triso_base(id, "base");
4,830 ✔
71
          }
72
        }
73
      }
74
    }
75
  }
1,500 ✔
76

77
  return triso_distribution;
15 ✔
78
}
15 ✔
79

80
//==============================================================================
81
// Cell implementation
82
//==============================================================================
83

84
int32_t Cell::n_instances() const
19,252 ✔
85
{
86
  return model::universes[universe_]->n_instances_;
19,252 ✔
87
}
88

89
void Cell::set_rotation(const vector<double>& rot)
445 ✔
90
{
91
  if (fill_ == C_NONE) {
445 !
92
    fatal_error(fmt::format("Cannot apply a rotation to cell {}"
×
93
                            " because it is not filled with another universe",
94
      id_));
×
95
  }
96

97
  if (rot.size() != 3 && rot.size() != 9) {
445 !
98
    fatal_error(fmt::format("Non-3D rotation vector applied to cell {}", id_));
×
99
  }
100

101
  // Compute and store the inverse rotation matrix for the angles given.
102
  rotation_.clear();
445 ✔
103
  rotation_.reserve(rot.size() == 9 ? 9 : 12);
890 !
104
  if (rot.size() == 3) {
445 !
105
    double phi = -rot[0] * PI / 180.0;
445 ✔
106
    double theta = -rot[1] * PI / 180.0;
445 ✔
107
    double psi = -rot[2] * PI / 180.0;
445 ✔
108
    rotation_.push_back(std::cos(theta) * std::cos(psi));
445 ✔
109
    rotation_.push_back(-std::cos(phi) * std::sin(psi) +
445 ✔
110
                        std::sin(phi) * std::sin(theta) * std::cos(psi));
445 ✔
111
    rotation_.push_back(std::sin(phi) * std::sin(psi) +
445 ✔
112
                        std::cos(phi) * std::sin(theta) * std::cos(psi));
445 ✔
113
    rotation_.push_back(std::cos(theta) * std::sin(psi));
445 ✔
114
    rotation_.push_back(std::cos(phi) * std::cos(psi) +
445 ✔
115
                        std::sin(phi) * std::sin(theta) * std::sin(psi));
445 ✔
116
    rotation_.push_back(-std::sin(phi) * std::cos(psi) +
445 ✔
117
                        std::cos(phi) * std::sin(theta) * std::sin(psi));
445 ✔
118
    rotation_.push_back(-std::sin(theta));
445 ✔
119
    rotation_.push_back(std::sin(phi) * std::cos(theta));
445 ✔
120
    rotation_.push_back(std::cos(phi) * std::cos(theta));
445 ✔
121

122
    // When user specifies angles, write them at end of vector
123
    rotation_.push_back(rot[0]);
445 ✔
124
    rotation_.push_back(rot[1]);
445 ✔
125
    rotation_.push_back(rot[2]);
445 ✔
126
  } else {
127
    std::copy(rot.begin(), rot.end(), std::back_inserter(rotation_));
×
128
  }
129
}
445 ✔
130

131
double Cell::temperature(int32_t instance) const
9,634 ✔
132
{
133
  if (sqrtkT_.size() < 1) {
9,634 !
134
    throw std::runtime_error {"Cell temperature has not yet been set."};
×
135
  }
136

137
  if (instance >= 0) {
9,634 ✔
138
    double sqrtkT = sqrtkT_.size() == 1 ? sqrtkT_.at(0) : sqrtkT_.at(instance);
9,548 ✔
139
    return sqrtkT * sqrtkT / K_BOLTZMANN;
9,548 ✔
140
  } else {
141
    return sqrtkT_[0] * sqrtkT_[0] / K_BOLTZMANN;
86 ✔
142
  }
143
}
144

145
double Cell::density_mult(int32_t instance) const
2,147,483,647 ✔
146
{
147
  if (instance >= 0) {
2,147,483,647 ✔
148
    return density_mult_.size() == 1 ? density_mult_.at(0)
2,147,483,647 ✔
149
                                     : density_mult_.at(instance);
5,069,327 ✔
150
  } else {
151
    return density_mult_[0];
77 ✔
152
  }
153
}
154

155
double Cell::density(int32_t instance) const
1,199,827 ✔
156
{
157
  const int32_t mat_index = material(instance);
1,199,827 ✔
158
  if (mat_index == MATERIAL_VOID)
1,199,827 !
159
    return 0.0;
160

161
  return density_mult(instance) * model::materials[mat_index]->density_gpcc();
2,399,654 ✔
162
}
163

164
void Cell::set_temperature(double T, int32_t instance, bool set_contained)
10,012 ✔
165
{
166
  if (settings::temperature_method == TemperatureMethod::INTERPOLATION) {
10,012 !
167
    if (T < (data::temperature_min - settings::temperature_tolerance)) {
×
168
      throw std::runtime_error {
×
169
        fmt::format("Temperature of {} K is below minimum temperature at "
×
170
                    "which data is available of {} K.",
171
          T, data::temperature_min)};
×
172
    } else if (T > (data::temperature_max + settings::temperature_tolerance)) {
×
173
      throw std::runtime_error {
×
174
        fmt::format("Temperature of {} K is above maximum temperature at "
×
175
                    "which data is available of {} K.",
176
          T, data::temperature_max)};
×
177
    }
178
  }
179

180
  if (type_ == Fill::MATERIAL) {
10,012 ✔
181
    if (instance >= 0) {
9,982 ✔
182
      // If temperature vector is not big enough, resize it first
183
      if (sqrtkT_.size() != n_instances())
9,905 ✔
184
        sqrtkT_.resize(n_instances(), sqrtkT_[0]);
45 ✔
185

186
      // Set temperature for the corresponding instance
187
      sqrtkT_.at(instance) = std::sqrt(K_BOLTZMANN * T);
9,905 ✔
188
    } else {
189
      // Set temperature for all instances
190
      for (auto& T_ : sqrtkT_) {
154 ✔
191
        T_ = std::sqrt(K_BOLTZMANN * T);
77 ✔
192
      }
193
    }
194
  } else {
195
    if (!set_contained) {
30 !
196
      throw std::runtime_error {
×
197
        fmt::format("Attempted to set the temperature of cell {} "
×
198
                    "which is not filled by a material.",
199
          id_)};
×
200
    }
201

202
    auto contained_cells = this->get_contained_cells(instance);
30 ✔
203
    for (const auto& entry : contained_cells) {
120 ✔
204
      auto& cell = model::cells[entry.first];
90 !
205
      assert(cell->type_ == Fill::MATERIAL);
90 !
206
      auto& instances = entry.second;
90 ✔
207
      for (auto instance : instances) {
315 ✔
208
        cell->set_temperature(T, instance);
225 ✔
209
      }
210
    }
211
  }
30 ✔
212
}
10,012 ✔
213

214
void Cell::set_density(double density, int32_t instance, bool set_contained)
346 ✔
215
{
216
  if (type_ != Fill::MATERIAL && !set_contained) {
346 !
217
    fatal_error(
×
218
      fmt::format("Attempted to set the density multiplier of cell {} "
×
219
                  "which is not filled by a material.",
220
        id_));
×
221
  }
222

223
  if (type_ == Fill::MATERIAL) {
346 ✔
224
    const int32_t mat_index = material(instance);
331 !
225
    if (mat_index == MATERIAL_VOID)
331 !
226
      return;
227

228
    if (instance >= 0) {
331 ✔
229
      // If density multiplier vector is not big enough, resize it first
230
      if (density_mult_.size() != n_instances())
254 ✔
231
        density_mult_.resize(n_instances(), density_mult_[0]);
111 ✔
232

233
      // Set density multiplier for the corresponding instance
234
      density_mult_.at(instance) =
254 ✔
235
        density / model::materials[mat_index]->density_gpcc();
508 !
236
    } else {
237
      // Set density multiplier for all instances
238
      for (auto& x : density_mult_) {
154 ✔
239
        x = density / model::materials[mat_index]->density_gpcc();
154 !
240
      }
241
    }
242
  } else {
243
    auto contained_cells = this->get_contained_cells(instance);
15 ✔
244
    for (const auto& entry : contained_cells) {
60 ✔
245
      auto& cell = model::cells[entry.first];
45 !
246
      assert(cell->type_ == Fill::MATERIAL);
45 !
247
      auto& instances = entry.second;
45 ✔
248
      for (auto instance : instances) {
90 ✔
249
        cell->set_density(density, instance);
45 ✔
250
      }
251
    }
252
  }
15 ✔
253
}
254

255
void Cell::export_properties_hdf5(hid_t group) const
231 ✔
256
{
257
  // Create a group for this cell.
258
  auto cell_group = create_group(group, fmt::format("cell {}", id_));
231 ✔
259

260
  // Write temperature in [K] for one or more cell instances
261
  vector<double> temps;
231 ✔
262
  for (auto sqrtkT_val : sqrtkT_)
429 ✔
263
    temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
198 ✔
264
  write_dataset(cell_group, "temperature", temps);
231 ✔
265

266
  // Write density for one or more cell instances
267
  if (type_ == Fill::MATERIAL && material_.size() > 0) {
231 ✔
268
    vector<double> density;
198 ✔
269
    for (int32_t i = 0; i < density_mult_.size(); ++i)
396 ✔
270
      density.push_back(this->density(i));
198 ✔
271

272
    write_dataset(cell_group, "density", density);
198 ✔
273
  }
198 ✔
274

275
  close_group(cell_group);
231 ✔
276
}
231 ✔
277

278
void Cell::import_properties_hdf5(hid_t group)
253 ✔
279
{
280
  auto cell_group = open_group(group, fmt::format("cell {}", id_));
253 ✔
281

282
  // Read temperatures from file
283
  vector<double> temps;
253 ✔
284
  read_dataset(cell_group, "temperature", temps);
253 ✔
285

286
  // Ensure number of temperatures makes sense
287
  auto n_temps = temps.size();
253 ✔
288
  if (n_temps > 1 && n_temps != n_instances()) {
253 !
289
    fatal_error(fmt::format(
×
290
      "Number of temperatures for cell {} doesn't match number of instances",
291
      id_));
×
292
  }
293

294
  // Modify temperatures for the cell
295
  sqrtkT_.clear();
253 ✔
296
  sqrtkT_.resize(temps.size());
253 ✔
297
  for (int64_t i = 0; i < temps.size(); ++i) {
9,922 ✔
298
    this->set_temperature(temps[i], i);
9,669 ✔
299
  }
300

301
  // Read densities
302
  if (object_exists(cell_group, "density")) {
253 ✔
303
    vector<double> density;
198 ✔
304
    read_dataset(cell_group, "density", density);
198 ✔
305

306
    // Ensure number of densities makes sense
307
    auto n_density = density.size();
198 !
308
    if (n_density > 1 && n_density != n_instances()) {
198 !
309
      fatal_error(fmt::format("Number of densities for cell {} "
×
310
                              "doesn't match number of instances",
311
        id_));
×
312
    }
313

314
    // Set densities.
315
    for (int32_t i = 0; i < n_density; ++i) {
396 ✔
316
      this->set_density(density[i], i);
198 ✔
317
    }
318
  }
198 ✔
319

320
  close_group(cell_group);
253 ✔
321
}
253 ✔
322

323
void Cell::to_hdf5(hid_t cell_group) const
31,824 ✔
324
{
325

326
  // Create a group for this cell.
327
  auto group = create_group(cell_group, fmt::format("cell {}", id_));
31,824 ✔
328

329
  if (!name_.empty()) {
31,824 ✔
330
    write_string(group, "name", name_, false);
8,028 ✔
331
  }
332

333
  write_dataset(group, "universe", model::universes[universe_]->id_);
31,824 ✔
334

335
  to_hdf5_inner(group);
31,824 ✔
336

337
  // Write fill information.
338
  if (type_ == Fill::MATERIAL) {
31,824 ✔
339
    write_dataset(group, "fill_type", "material");
25,891 ✔
340
    std::vector<int32_t> mat_ids;
25,891 ✔
341
    for (auto i_mat : material_) {
53,075 ✔
342
      if (i_mat != MATERIAL_VOID) {
27,184 ✔
343
        mat_ids.push_back(model::materials[i_mat]->id_);
18,340 ✔
344
      } else {
345
        mat_ids.push_back(MATERIAL_VOID);
8,844 ✔
346
      }
347
    }
348
    if (mat_ids.size() == 1) {
25,891 ✔
349
      write_dataset(group, "material", mat_ids[0]);
25,700 ✔
350
    } else {
351
      write_dataset(group, "material", mat_ids);
191 ✔
352
    }
353

354
    std::vector<double> temps;
25,891 ✔
355
    for (auto sqrtkT_val : sqrtkT_)
63,428 ✔
356
      temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
37,537 ✔
357
    write_dataset(group, "temperature", temps);
25,891 ✔
358

359
    write_dataset(group, "density_mult", density_mult_);
25,891 ✔
360

361
  } else if (type_ == Fill::UNIVERSE) {
31,824 ✔
362
    write_dataset(group, "fill_type", "universe");
4,240 ✔
363
    write_dataset(group, "fill", model::universes[fill_]->id_);
4,240 ✔
364
    if (translation_ != Position(0, 0, 0)) {
4,240 ✔
365
      write_dataset(group, "translation", translation_);
1,837 ✔
366
    }
367
    if (!rotation_.empty()) {
4,240 ✔
368
      if (rotation_.size() == 12) {
264 !
369
        std::array<double, 3> rot {rotation_[9], rotation_[10], rotation_[11]};
264 ✔
370
        write_dataset(group, "rotation", rot);
264 ✔
371
      } else {
372
        write_dataset(group, "rotation", rotation_);
×
373
      }
374
    }
375

376
  } else if (type_ == Fill::LATTICE) {
1,693 !
377
    write_dataset(group, "fill_type", "lattice");
1,693 ✔
378
    write_dataset(group, "lattice", model::lattices[fill_]->id_);
1,693 ✔
379
  }
380

381
  close_group(group);
31,824 ✔
382
}
31,824 ✔
383

384
//==============================================================================
385
// XML parsing helpers for <cell> nodes
386
//==============================================================================
387

388
vector<int32_t> parse_cell_material_xml(pugi::xml_node node, int32_t cell_id)
30,298 ✔
389
{
390
  vector<std::string> mats {
30,298 ✔
391
    get_node_array<std::string>(node, "material", true)};
30,298 ✔
392
  if (mats.empty()) {
30,298 !
393
    fatal_error(fmt::format(
×
394
      "An empty material element was specified for cell {}", cell_id));
395
  }
396
  vector<int32_t> material;
30,298 ✔
397
  material.reserve(mats.size());
30,298 ✔
398
  for (const auto& mat : mats) {
61,925 ✔
399
    if (mat == "void") {
31,627 ✔
400
      material.push_back(MATERIAL_VOID);
9,353 ✔
401
    } else {
402
      material.push_back(std::stoi(mat));
22,274 ✔
403
    }
404
  }
405
  return material;
30,298 ✔
406
}
30,298 ✔
407

408
vector<double> parse_cell_temperature_xml(pugi::xml_node node, int32_t cell_id)
431 ✔
409
{
410
  auto temperatures = get_node_array<double>(node, "temperature");
431 ✔
411
  if (temperatures.empty()) {
431 !
412
    fatal_error(fmt::format(
×
413
      "An empty temperature element was specified for cell {}", cell_id));
414
  }
415
  for (auto T : temperatures) {
1,942 ✔
416
    if (T < 0) {
1,511 !
417
      fatal_error(fmt::format(
×
418
        "Cell {} was specified with a negative temperature", cell_id));
419
    }
420
  }
421
  return temperatures;
431 ✔
422
}
×
423

424
vector<double> parse_cell_density_xml(pugi::xml_node node, int32_t cell_id)
75 ✔
425
{
426
  auto densities = get_node_array<double>(node, "density");
75 ✔
427
  if (densities.empty()) {
75 !
428
    fatal_error(fmt::format(
×
429
      "An empty density element was specified for cell {}", cell_id));
430
  }
431
  for (auto rho : densities) {
1,230 ✔
432
    if (rho <= 0) {
1,155 !
433
      fatal_error(fmt::format(
×
434
        "Cell {} was specified with a density less than or equal to zero",
435
        cell_id));
436
    }
437
  }
438
  return densities;
75 ✔
439
}
×
440

441
//==============================================================================
442
// CSGCell implementation
443
//==============================================================================
444

445
CSGCell::CSGCell(pugi::xml_node cell_node)
39,552 ✔
446
{
447
  if (check_for_node(cell_node, "id")) {
39,552 !
448
    id_ = std::stoi(get_node_value(cell_node, "id"));
79,104 ✔
449
  } else {
450
    fatal_error("Must specify id of cell in geometry XML file.");
×
451
  }
452

453
  if (check_for_node(cell_node, "name")) {
39,552 ✔
454
    name_ = get_node_value(cell_node, "name");
10,235 ✔
455
  }
456

457
  if (check_for_node(cell_node, "universe")) {
39,552 ✔
458
    universe_ = std::stoi(get_node_value(cell_node, "universe"));
76,686 ✔
459
  } else {
460
    universe_ = 0;
1,209 ✔
461
  }
462

463
  // Check if the cell is the base of a virtual triso lattice
464
  bool virtual_lattice_present = check_for_node(cell_node, "virtual_lattice");
39,552 ✔
465
  if (virtual_lattice_present) {
39,552 ✔
466
    virtual_lattice_ = get_node_value_bool(cell_node, "virtual_lattice");
15 ✔
467
    if (virtual_lattice_) {
15 !
468
      if (check_for_node(cell_node, "lower_left") &&
30 !
469
          check_for_node(cell_node, "pitch") &&
30 !
470
          check_for_node(cell_node, "shape")) {
15 ✔
471
        vl_lower_left_ = get_node_array<double>(cell_node, "lower_left");
15 ✔
472
        vl_pitch_ = get_node_array<double>(cell_node, "pitch");
15 ✔
473
        vl_shape_ = get_node_array<int>(cell_node, "shape");
15 ✔
474
      } else {
NEW
475
        fatal_error(fmt::format("Lower_left, pitch and shape of the virtual "
×
476
                                "lattice must be specified for cell {}",
NEW
477
          id_));
×
478
      }
479
    }
480
  } else {
481
    virtual_lattice_ = false;
39,537 ✔
482
  }
483

484
  if (check_for_node(cell_node, "triso_particle")) {
39,552 ✔
485
    triso_particle_ = get_node_value_bool(cell_node, "triso_particle");
1,500 ✔
486
  } else {
487
    triso_particle_ = false;
38,052 ✔
488
  }
489

490
  // Make sure that either material or fill was specified, but not both.
491
  bool fill_present = check_for_node(cell_node, "fill");
39,552 ✔
492
  bool material_present = check_for_node(cell_node, "material");
39,552 ✔
493
  if (!(fill_present || material_present)) {
39,552 !
494
    fatal_error(
×
495
      fmt::format("Neither material nor fill was specified for cell {}", id_));
×
496
  }
497
  if (fill_present && material_present) {
39,552 !
498
    fatal_error(fmt::format("Cell {} has both a material and a fill specified; "
×
499
                            "only one can be specified per cell",
500
      id_));
×
501
  }
502

503
  if (fill_present) {
39,552 ✔
504
    fill_ = std::stoi(get_node_value(cell_node, "fill"));
18,526 ✔
505
    if (fill_ == universe_) {
9,263 !
506
      fatal_error(fmt::format("Cell {} is filled with the same universe that "
×
507
                              "it is contained in.",
508
        id_));
×
509
    }
510
  } else {
511
    fill_ = C_NONE;
30,289 ✔
512
  }
513

514
  // Read the material element.  There can be zero materials (filled with a
515
  // universe), more than one material (distribmats), and some materials may
516
  // be "void".
517
  if (material_present) {
39,552 ✔
518
    material_ = parse_cell_material_xml(cell_node, id_);
30,289 ✔
519
  }
520

521
  // Read the temperature element which may be distributed like materials.
522
  if (check_for_node(cell_node, "temperature")) {
39,552 ✔
523
    sqrtkT_ = parse_cell_temperature_xml(cell_node, id_);
431 ✔
524
    sqrtkT_.shrink_to_fit();
431 ✔
525

526
    // Make sure this is a material-filled cell.
527
    if (material_.size() == 0) {
431 !
528
      fatal_error(fmt::format(
×
529
        "Cell {} was specified with a temperature but no material. Temperature"
530
        "specification is only valid for cells filled with a material.",
531
        id_));
×
532
    }
533

534
    // Convert to sqrt(k*T).
535
    for (auto& T : sqrtkT_) {
1,942 ✔
536
      T = std::sqrt(K_BOLTZMANN * T);
1,511 ✔
537
    }
538
  }
539

540
  // Read the density element which can be distributed similar to temperature.
541
  // These get assigned to the density multiplier, requiring a division by
542
  // the material density.
543
  // Note: calculating the actual density multiplier is deferred until materials
544
  // are finalized. density_mult_ contains the true density in the meantime.
545
  if (check_for_node(cell_node, "density")) {
39,552 ✔
546
    density_mult_ = parse_cell_density_xml(cell_node, id_);
75 ✔
547
    density_mult_.shrink_to_fit();
75 ✔
548

549
    // Make sure this is a material-filled cell.
550
    if (material_.size() == 0) {
75 !
551
      fatal_error(fmt::format(
×
552
        "Cell {} was specified with a density but no material. Density"
553
        "specification is only valid for cells filled with a material.",
554
        id_));
×
555
    }
556

557
    // Make sure this is a non-void material.
558
    for (auto mat_id : material_) {
150 ✔
559
      if (mat_id == MATERIAL_VOID) {
75 !
560
        fatal_error(fmt::format(
×
561
          "Cell {} was specified with a density, but contains a void "
562
          "material. Density specification is only valid for cells "
563
          "filled with a non-void material.",
564
          id_));
×
565
      }
566
    }
567
  }
568

569
  // Read the region specification.
570
  std::string region_spec;
39,552 ✔
571
  if (check_for_node(cell_node, "region")) {
39,552 ✔
572
    region_spec = get_node_value(cell_node, "region");
29,684 ✔
573
  }
574

575
  // Get a tokenized representation of the region specification and apply De
576
  // Morgans law
577
  Region region(region_spec, id_);
39,552 ✔
578
  region_ = region;
39,552 ✔
579
  vector<int32_t> rpn = region_.generate_postfix(id_);
39,552 ✔
580

581
  if (virtual_lattice_) {
39,552 ✔
582
    vl_triso_distribution_ = generate_triso_distribution(
45 ✔
583
      vl_shape_, vl_pitch_, vl_lower_left_, rpn, id_);
30 ✔
584
  }
585

586
  if (triso_particle_) {
39,552 ✔
587
    if (rpn.size() != 1) {
1,500 !
NEW
588
      fatal_error(
×
NEW
589
        fmt::format("Wrong surface definition of triso particle cell {}", id_));
×
590
    } else {
591
      model::surfaces[abs(rpn[0]) - 1]->connect_to_triso_base(id_, "particle");
3,000 ✔
592
    }
593
  }
594

595
  // Read the translation vector.
596
  if (check_for_node(cell_node, "translation")) {
39,552 ✔
597
    if (fill_ == C_NONE) {
4,057 !
598
      fatal_error(fmt::format("Cannot apply a translation to cell {}"
×
599
                              " because it is not filled with another universe",
600
        id_));
×
601
    }
602

603
    auto xyz {get_node_array<double>(cell_node, "translation")};
4,057 ✔
604
    if (xyz.size() != 3) {
4,057 !
605
      fatal_error(
×
606
        fmt::format("Non-3D translation vector applied to cell {}", id_));
×
607
    }
608
    translation_ = xyz;
4,057 ✔
609
  }
4,057 ✔
610

611
  // Read the rotation transform.
612
  if (check_for_node(cell_node, "rotation")) {
39,552 ✔
613
    auto rot {get_node_array<double>(cell_node, "rotation")};
390 ✔
614
    set_rotation(rot);
390 ✔
615
  }
390 ✔
616
}
39,552 ✔
617

618
//==============================================================================
619

620
void CSGCell::to_hdf5_inner(hid_t group_id) const
31,664 ✔
621
{
622
  write_string(group_id, "geom_type", "csg", false);
31,664 ✔
623
  write_string(group_id, "region", region_.str(), false);
31,664 ✔
624
}
31,664 ✔
625

626
//==============================================================================
627

628
vector<int32_t>::iterator CSGCell::find_left_parenthesis(
×
629
  vector<int32_t>::iterator start, const vector<int32_t>& infix)
630
{
631
  // start search at zero
632
  int parenthesis_level = 0;
×
633
  auto it = start;
×
634
  while (it != infix.begin()) {
×
635
    // look at two tokens at a time
636
    int32_t one = *it;
×
637
    int32_t two = *(it - 1);
×
638

639
    // decrement parenthesis level if there are two adjacent surfaces
640
    if (one < OP_UNION && two < OP_UNION) {
×
641
      parenthesis_level--;
×
642
      // increment if there are two adjacent operators
643
    } else if (one >= OP_UNION && two >= OP_UNION) {
×
644
      parenthesis_level++;
×
645
    }
646

647
    // if the level gets to zero, return the position
648
    if (parenthesis_level == 0) {
×
649
      // move the iterator back one before leaving the loop
650
      // so that all tokens in the parenthesis block are included
651
      it--;
×
652
      break;
653
    }
654

655
    // continue loop, one token at a time
656
    it--;
657
  }
658
  return it;
×
659
}
660
std::pair<double, int32_t> CSGCell::distance(
2,147,483,647 ✔
661
  Position r, Direction u, int32_t on_surface, GeometryState* p) const
662
{
663
  if (virtual_lattice_) {
2,147,483,647 ✔
664
    return distance_in_virtual_lattice(r, u, on_surface, p);
4,899,400 ✔
665
  } else {
666
    return region_.distance(r, u, on_surface);
2,147,483,647 ✔
667
  }
668
}
669

670
std::pair<double, int32_t> CSGCell::distance_in_virtual_lattice(
4,899,400 ✔
671
  Position r, Direction u, int32_t on_surface, GeometryState* p) const
672
{
673
  double min_dist {INFTY};
4,899,400 ✔
674
  int32_t i_surf {std::numeric_limits<int32_t>::max()};
4,899,400 ✔
675
  double min_dis_vl;
4,899,400 ✔
676
  int32_t i_surf_vl;
4,899,400 ✔
677

678
  double max_dis = p->collision_distance();
4,899,400 ✔
679
  double tol_dis = 0;
4,899,400 ✔
680
  vector<double> dis_to_bou(3), dis_to_bou_max(3);
4,899,400 ✔
681
  double u_value = sqrt(pow(u.x, 2) + pow(u.y, 2) +
9,798,800 ✔
682
                        pow(u.z, 2)); // don't know if u has been normalized
4,899,400 ✔
683
  vector<double> norm_u = {u.x / u_value, u.y / u_value, u.z / u_value};
4,899,400 ✔
684
  vector<int> lat_ind(3);
4,899,400 ✔
685
  vector<double> temp_pos = {r.x, r.y, r.z};
4,899,400 ✔
686
  int loop_time;
4,899,400 ✔
687
  for (int i = 0; i < 3; i++) {
19,597,600 ✔
688
    lat_ind[i] = floor((temp_pos[i] - vl_lower_left_[i]) / vl_pitch_[i]);
14,698,200 ✔
689
    if (lat_ind[i] == vl_shape_[i] && norm_u[i] < 0) {
14,698,200 !
690
      lat_ind[i] = vl_shape_[i] - 1;
1,585,540 ✔
691
    }
692
    if (lat_ind[i] == -1 && norm_u[i] > 0) {
14,698,200 !
693
      lat_ind[i] = 0;
10,956 ✔
694
    }
695
  }
696

697
  dis_to_bou = {INFTY, INFTY, INFTY};
4,899,400 ✔
698
  for (int i = 0; i < 3; i++) {
19,597,600 ✔
699
    if (norm_u[i] > 0) {
14,698,200 ✔
700
      dis_to_bou[i] = std::abs(
7,353,841 ✔
701
        ((lat_ind[i] + 1) * vl_pitch_[i] + vl_lower_left_[i] - temp_pos[i]) /
7,353,841 ✔
702
        norm_u[i]);
7,353,841 ✔
703
      dis_to_bou_max[i] = vl_pitch_[i] / norm_u[i];
7,353,841 ✔
704
    } else if (norm_u[i] < 0) {
7,344,359 !
705
      dis_to_bou[i] =
7,344,359 ✔
706
        std::abs((lat_ind[i] * vl_pitch_[i] + vl_lower_left_[i] - temp_pos[i]) /
7,344,359 ✔
707
                 norm_u[i]);
7,344,359 ✔
708
      dis_to_bou_max[i] = -vl_pitch_[i] / norm_u[i];
7,344,359 ✔
709
    }
710
  }
711

712
  while (true) {
14,198,646 ✔
713
    if (lat_ind[0] < 0 || lat_ind[0] >= vl_shape_[0] || lat_ind[1] < 0 ||
14,198,646 ✔
714
        lat_ind[1] >= vl_shape_[1] || lat_ind[2] < 0 ||
26,807,880 ✔
715
        lat_ind[2] >= vl_shape_[2])
11,553,113 ✔
716
      break;
717

718
    for (int token :
66,449,009 ✔
719
      vl_triso_distribution_[lat_ind[0] + lat_ind[1] * vl_shape_[0] +
11,023,848 ✔
720
                             lat_ind[2] * vl_shape_[0] * vl_shape_[1]]) {
77,472,857 ✔
721
      bool coincident {std::abs(token) == std::abs(on_surface)};
66,449,009 ✔
722
      double d {model::surfaces[abs(token) - 1]->distance(r, u, coincident)};
66,449,009 ✔
723
      if (d < min_dist) {
66,449,009 ✔
724
        if (min_dist - d >= FP_PRECISION * min_dist) {
1,262,503 !
725
          min_dist = d;
1,262,503 ✔
726
          i_surf = -token;
1,262,503 ✔
727
        }
728
      }
729
    }
730

731
    int mes_bou_crossed = 0;
11,023,848 ✔
732
    if (dis_to_bou[1] < dis_to_bou[0]) {
11,023,848 ✔
733
      mes_bou_crossed = 1;
5,499,956 ✔
734
    }
735
    if (dis_to_bou[2] < dis_to_bou[mes_bou_crossed]) {
11,023,848 ✔
736
      mes_bou_crossed = 2;
3,669,820 ✔
737
    }
738

739
    tol_dis = dis_to_bou[mes_bou_crossed];
11,023,848 ✔
740

741
    if (min_dist < tol_dis) {
11,023,848 ✔
742
      break;
743
    }
744

745
    if (norm_u[mes_bou_crossed] > 0) {
9,800,450 ✔
746
      lat_ind[mes_bou_crossed] += 1;
4,899,433 ✔
747
    } else {
748
      lat_ind[mes_bou_crossed] += -1;
4,901,017 ✔
749
    }
750

751
    dis_to_bou[mes_bou_crossed] += dis_to_bou_max[mes_bou_crossed];
9,800,450 ✔
752

753
    if (tol_dis > max_dis) {
9,800,450 ✔
754
      break;
755
    }
756
  }
757
  return {min_dist, i_surf};
4,899,400 ✔
758
}
4,899,400 ✔
759

760
//==============================================================================
761
// Region implementation
762
//==============================================================================
763

764
Region::Region(std::string region_spec, int32_t cell_id)
39,695 ✔
765
{
766
  // Check if region_spec is not empty.
767
  if (!region_spec.empty()) {
39,695 ✔
768
    // Parse all halfspaces and operators except for intersection (whitespace).
769
    for (int i = 0; i < region_spec.size();) {
178,844 ✔
770
      if (region_spec[i] == '(') {
149,017 ✔
771
        expression_.push_back(OP_LEFT_PAREN);
1,821 ✔
772
        i++;
1,821 ✔
773

774
      } else if (region_spec[i] == ')') {
147,196 ✔
775
        expression_.push_back(OP_RIGHT_PAREN);
1,821 ✔
776
        i++;
1,821 ✔
777

778
      } else if (region_spec[i] == '|') {
145,375 ✔
779
        expression_.push_back(OP_UNION);
4,780 ✔
780
        i++;
4,780 ✔
781

782
      } else if (region_spec[i] == '~') {
140,595 ✔
783
        expression_.push_back(OP_COMPLEMENT);
30 ✔
784
        i++;
30 ✔
785

786
      } else if (region_spec[i] == '-' || region_spec[i] == '+' ||
237,406 ✔
787
                 std::isdigit(region_spec[i])) {
96,841 ✔
788
        // This is the start of a halfspace specification.  Iterate j until we
789
        // find the end, then push-back everything between i and j.
790
        int j = i + 1;
82,060 ✔
791
        while (j < region_spec.size() && std::isdigit(region_spec[j])) {
169,598 ✔
792
          j++;
87,538 ✔
793
        }
794
        expression_.push_back(std::stoi(region_spec.substr(i, j - i)));
164,120 ✔
795
        i = j;
82,060 ✔
796

797
      } else if (std::isspace(region_spec[i])) {
58,505 !
798
        i++;
58,505 ✔
799

800
      } else {
801
        auto err_msg =
×
802
          fmt::format("Region specification contains invalid character, \"{}\"",
803
            region_spec[i]);
×
804
        fatal_error(err_msg);
×
805
      }
×
806
    }
807

808
    // Add in intersection operators where a missing operator is needed.
809
    int i = 0;
810
    while (i < expression_.size() - 1) {
137,965 ✔
811
      bool left_compat {
108,138 ✔
812
        (expression_[i] < OP_UNION) || (expression_[i] == OP_RIGHT_PAREN)};
108,138 ✔
813
      bool right_compat {(expression_[i + 1] < OP_UNION) ||
108,138 ✔
814
                         (expression_[i + 1] == OP_LEFT_PAREN) ||
108,138 ✔
815
                         (expression_[i + 1] == OP_COMPLEMENT)};
6,661 ✔
816
      if (left_compat && right_compat) {
108,138 ✔
817
        expression_.insert(expression_.begin() + i + 1, OP_INTERSECTION);
47,453 ✔
818
      }
819
      i++;
820
    }
821

822
    // Remove complement operators using DeMorgan's laws
823
    auto it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
29,827 ✔
824
    while (it != expression_.end()) {
29,857 ✔
825
      // Erase complement. Note that erase invalidates the iterator, so we have
826
      // to use the iterator it returns, which points to the token that
827
      // followed the complement operator.
828
      it = expression_.erase(it);
30 ✔
829
      if (it == expression_.end())
30 !
830
        break;
831

832
      // Define stop given left parenthesis or not
833
      auto stop = it;
30 ✔
834
      if (*it == OP_LEFT_PAREN) {
30 !
835
        int depth = 1;
836
        do {
240 ✔
837
          stop++;
240 ✔
838
          if (*stop > OP_COMPLEMENT) {
240 ✔
839
            if (*stop == OP_RIGHT_PAREN) {
30 !
840
              depth--;
30 ✔
841
            } else {
842
              depth++;
×
843
            }
844
          }
845
        } while (depth > 0);
240 ✔
846
        it++;
30 ✔
847
      }
848

849
      // apply DeMorgan's law to any surfaces/operators between these
850
      // positions in the RPN
851
      apply_demorgan(it, stop);
30 ✔
852
      // update iterator position
853
      it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
30 ✔
854
    }
855

856
    // Convert user IDs to surface indices.
857
    for (auto& r : expression_) {
167,762 ✔
858
      if (r < OP_UNION) {
137,935 ✔
859
        const auto& it {model::surface_map.find(abs(r))};
82,060 !
860
        if (it == model::surface_map.end()) {
82,060 !
861
          throw std::runtime_error {
×
862
            "Invalid surface ID " + std::to_string(abs(r)) +
×
863
            " specified in region for cell " + std::to_string(cell_id) + "."};
×
864
        }
865
        r = (r > 0) ? it->second + 1 : -(it->second + 1);
82,060 ✔
866
      }
867
    }
868

869
    // Check if this is a simple cell.
870
    simple_ = true;
29,827 ✔
871
    for (int32_t token : expression_) {
150,640 ✔
872
      if (token == OP_UNION) {
122,147 ✔
873
        simple_ = false;
1,334 ✔
874
        // Ensure intersections have precedence over unions
875
        enforce_precedence();
1,334 ✔
876
        break;
877
      }
878
    }
879

880
    // If this cell is simple, remove all the superfluous operator tokens.
881
    if (simple_) {
29,827 ✔
882
      expression_.erase(std::remove_if(expression_.begin(), expression_.end(),
28,493 ✔
883
                          [](int32_t token) {
113,413 ✔
884
                            return token == OP_INTERSECTION ||
113,413 ✔
885
                                   token > OP_COMPLEMENT;
104,854 !
886
                          }),
887
        expression_.end());
28,493 ✔
888
    }
889
    expression_.shrink_to_fit();
29,827 ✔
890

891
  } else {
892
    simple_ = true;
9,868 ✔
893
  }
894
}
39,695 ✔
895

896
//==============================================================================
897

898
void Region::apply_demorgan(
30 ✔
899
  vector<int32_t>::iterator start, vector<int32_t>::iterator stop)
900
{
901
  do {
210 ✔
902
    if (*start < OP_UNION) {
210 ✔
903
      *start *= -1;
120 ✔
904
    } else if (*start == OP_UNION) {
90 !
905
      *start = OP_INTERSECTION;
×
906
    } else if (*start == OP_INTERSECTION) {
90 !
907
      *start = OP_UNION;
90 ✔
908
    }
909
    start++;
210 ✔
910
  } while (start < stop);
210 ✔
911
}
30 ✔
912

913
//==============================================================================
914
//! Add precedence for infix regions so intersections have higher
915
//! precedence than unions using parentheses.
916
//==============================================================================
917

918
void Region::add_parentheses(int64_t start)
96 ✔
919
{
920
  int32_t start_token = expression_[start];
96 !
921
  // Add left parenthesis and set new position to be after parenthesis
922
  if (start_token == OP_UNION) {
96 !
923
    start += 2;
×
924
  }
925
  expression_.insert(expression_.begin() + start - 1, OP_LEFT_PAREN);
96 ✔
926

927
  // Add right parenthesis
928
  // While the start iterator is within the bounds of infix
929
  while (start + 1 < expression_.size()) {
430 ✔
930
    start++;
408 ✔
931

932
    // If the current token is an operator and is different than the start token
933
    if (expression_[start] >= OP_UNION && expression_[start] != start_token) {
408 ✔
934
      // Skip wrapped regions but save iterator position to check precedence and
935
      // add right parenthesis, right parenthesis position depends on the
936
      // operator, when the operator is a union then do not include the operator
937
      // in the region, when the operator is an intersection then include the
938
      // operator and next surface
939
      if (expression_[start] == OP_LEFT_PAREN) {
85 ✔
940
        int depth = 1;
941
        do {
44 ✔
942
          start++;
44 ✔
943
          if (expression_[start] > OP_COMPLEMENT) {
44 ✔
944
            if (expression_[start] == OP_RIGHT_PAREN) {
11 !
945
              depth--;
11 ✔
946
            } else {
947
              depth++;
×
948
            }
949
          }
950
        } while (depth > 0);
44 ✔
951
      } else {
952
        if (start_token == OP_UNION) {
74 !
953
          --start;
×
954
        }
955
        expression_.insert(expression_.begin() + start, OP_RIGHT_PAREN);
74 ✔
956
        return;
74 ✔
957
      }
958
    }
959
  }
960
  // If we get here a right parenthesis hasn't been placed
961
  expression_.push_back(OP_RIGHT_PAREN);
22 ✔
962
}
963

964
//==============================================================================
965
//! Add parentheses to enforce operator precedence in region expressions
966
//!
967
//! This function ensures that intersection operators have higher precedence
968
//! than union operators by adding parentheses where needed. For example:
969
//!   "1 2 | 3" becomes "(1 2) | 3"
970
//!   "1 | 2 3" becomes "1 | (2 3)"
971
//!
972
//! The algorithm uses stacks to track the current operator type and its
973
//! position at each parenthesis depth level. When it encounters a different
974
//! operator at the same depth, it adds parentheses to group the
975
//! higher-precedence operations.
976
//==============================================================================
977

978
void Region::enforce_precedence()
1,334 ✔
979
{
980
  // Stack tracking the operator type at each depth (0 = no operator seen yet)
981
  vector<int32_t> op_stack = {0};
1,334 ✔
982

983
  // Stack tracking where the operator sequence started at each depth
984
  vector<std::size_t> pos_stack = {0};
1,334 ✔
985

986
  for (int64_t i = 0; i < expression_.size(); ++i) {
26,873 ✔
987
    int32_t token = expression_[i];
25,539 ✔
988

989
    if (token == OP_LEFT_PAREN) {
25,539 ✔
990
      // Entering a new parenthesis level - push new tracking state
991
      op_stack.push_back(0);
2,017 ✔
992
      pos_stack.push_back(0);
2,017 ✔
993
      continue;
2,017 ✔
994
    } else if (token == OP_RIGHT_PAREN) {
23,522 ✔
995
      // Exiting a parenthesis level - pop tracking state (keep at least one)
996
      if (op_stack.size() > 1) {
1,976 !
997
        op_stack.pop_back();
1,976 ✔
998
        pos_stack.pop_back();
1,976 ✔
999
      }
1000
      continue;
1,976 ✔
1001
    }
1002

1003
    if (token == OP_UNION || token == OP_INTERSECTION) {
21,546 ✔
1004
      if (op_stack.back() == 0) {
10,106 ✔
1005
        // First operator at this depth - record it and its position
1006
        op_stack.back() = token;
3,395 ✔
1007
        pos_stack.back() = i;
3,395 ✔
1008
      } else if (token != op_stack.back()) {
6,711 ✔
1009
        // Encountered a different operator at the same depth - need to add
1010
        // parentheses to enforce precedence. Intersection has higher
1011
        // precedence, so we parenthesize the intersection terms.
1012
        if (op_stack.back() == OP_INTERSECTION) {
96 ✔
1013
          add_parentheses(pos_stack.back());
48 ✔
1014
        } else {
1015
          add_parentheses(i);
48 ✔
1016
        }
1017

1018
        // Restart the scan since we modified the expression
1019
        i = -1; // Will be incremented to 0 by the for loop
96 ✔
1020
        op_stack = {0};
96 ✔
1021
        pos_stack = {0};
96 ✔
1022
      }
1023
    }
1024
  }
1025
}
1,334 ✔
1026

1027
//==============================================================================
1028
//! Convert infix region specification to Reverse Polish Notation (RPN)
1029
//!
1030
//! This function uses the shunting-yard algorithm.
1031
//==============================================================================
1032

1033
vector<int32_t> Region::generate_postfix(int32_t cell_id) const
39,596 ✔
1034
{
1035
  vector<int32_t> rpn;
39,596 ✔
1036
  vector<int32_t> stack;
39,596 ✔
1037

1038
  for (int32_t token : expression_) {
135,120 ✔
1039
    if (token < OP_UNION) {
95,524 ✔
1040
      // If token is not an operator, add it to output
1041
      rpn.push_back(token);
81,983 ✔
1042
    } else if (token < OP_RIGHT_PAREN) {
13,541 ✔
1043
      // Regular operators union, intersection, complement
1044
      while (stack.size() > 0) {
16,526 ✔
1045
        int32_t op = stack.back();
12,886 ✔
1046

1047
        if (op < OP_RIGHT_PAREN && ((token == OP_COMPLEMENT && token < op) ||
12,886 !
1048
                                     (token != OP_COMPLEMENT && token <= op))) {
6,709 !
1049
          // While there is an operator, op, on top of the stack, if the token
1050
          // is left-associative and its precedence is less than or equal to
1051
          // that of op or if the token is right-associative and its precedence
1052
          // is less than that of op, move op to the output queue and push the
1053
          // token on to the stack. Note that only complement is
1054
          // right-associative.
1055
          rpn.push_back(op);
6,709 ✔
1056
          stack.pop_back();
6,709 ✔
1057
        } else {
1058
          break;
1059
        }
1060
      }
1061

1062
      stack.push_back(token);
9,817 ✔
1063

1064
    } else if (token == OP_LEFT_PAREN) {
3,724 ✔
1065
      // If the token is a left parenthesis, push it onto the stack
1066
      stack.push_back(token);
1,862 ✔
1067

1068
    } else {
1069
      // If the token is a right parenthesis, move operators from the stack to
1070
      // the output queue until reaching the left parenthesis.
1071
      for (auto it = stack.rbegin(); *it != OP_LEFT_PAREN; it++) {
3,724 ✔
1072
        // If we run out of operators without finding a left parenthesis, it
1073
        // means there are mismatched parentheses.
1074
        if (it == stack.rend()) {
1,862 !
1075
          fatal_error(fmt::format(
×
1076
            "Mismatched parentheses in region specification for cell {}",
1077
            cell_id));
1078
        }
1079
        rpn.push_back(stack.back());
1,862 ✔
1080
        stack.pop_back();
1,862 ✔
1081
      }
1082

1083
      // Pop the left parenthesis.
1084
      stack.pop_back();
95,524 ✔
1085
    }
1086
  }
1087

1088
  while (stack.size() > 0) {
39,596 ✔
1089
    int32_t op = stack.back();
1,246 !
1090

1091
    // If the operator is a parenthesis it is mismatched.
1092
    if (op >= OP_RIGHT_PAREN) {
1,246 !
1093
      fatal_error(fmt::format(
×
1094
        "Mismatched parentheses in region specification for cell {}", cell_id));
1095
    }
1096

1097
    rpn.push_back(stack.back());
1,246 ✔
1098
    stack.pop_back();
40,842 ✔
1099
  }
1100

1101
  return rpn;
39,596 ✔
1102
}
39,596 ✔
1103

1104
//==============================================================================
1105

1106
std::string Region::str() const
31,763 ✔
1107
{
1108
  std::stringstream region_spec {};
31,763 ✔
1109
  if (!expression_.empty()) {
31,763 ✔
1110
    for (int32_t token : expression_) {
99,101 ✔
1111
      if (token == OP_LEFT_PAREN) {
76,316 ✔
1112
        region_spec << " (";
1,637 ✔
1113
      } else if (token == OP_RIGHT_PAREN) {
74,679 ✔
1114
        region_spec << " )";
1,637 ✔
1115
      } else if (token == OP_COMPLEMENT) {
73,042 !
1116
        region_spec << " ~";
×
1117
      } else if (token == OP_INTERSECTION) {
73,042 ✔
1118
      } else if (token == OP_UNION) {
68,903 ✔
1119
        region_spec << " |";
4,238 ✔
1120
      } else {
1121
        // Note the off-by-one indexing
1122
        auto surf_id = model::surfaces[abs(token) - 1]->id_;
64,665 ✔
1123
        region_spec << " " << ((token > 0) ? surf_id : -surf_id);
64,665 ✔
1124
      }
1125
    }
1126
  }
1127
  return region_spec.str();
63,526 ✔
1128
}
31,763 ✔
1129

1130
//==============================================================================
1131

1132
std::pair<double, int32_t> Region::distance(
2,147,483,647 ✔
1133
  Position r, Direction u, int32_t on_surface) const
1134
{
1135
  if (simple_) {
2,147,483,647 ✔
1136
    return distance_to_nearest_surface(r, u, on_surface, false);
2,147,483,647 ✔
1137
  } else {
1138
    return distance_complex(r, u, on_surface);
188,602,515 ✔
1139
  }
1140
}
1141

1142
//==============================================================================
1143

1144
std::pair<double, int32_t> Region::distance_to_nearest_surface(Position r,
2,147,483,647 ✔
1145
  Direction u, int32_t on_surface, bool ignore_coincident_surfaces) const
1146
{
1147
  double min_dist {INFTY};
2,147,483,647 ✔
1148
  int32_t i_surf {std::numeric_limits<int32_t>::max()};
2,147,483,647 ✔
1149

1150
  for (int32_t token : expression_) {
×
1151
    // Ignore this token if it corresponds to an operator rather than a region.
1152
    if (token >= OP_UNION)
✔
1153
      continue;
2,147,483,647 ✔
1154

1155
    // Calculate the distance to this surface.
1156
    // Note the off-by-one indexing
1157
    bool coincident {std::abs(token) == std::abs(on_surface)};
2,147,483,647 ✔
1158
    double d {model::surfaces[abs(token) - 1]->distance(r, u, coincident)};
2,147,483,647 ✔
1159

1160
    // Different surface definitions can represent the same geometric surface.
1161
    // When the ray is already known to be on a surface, ignore intersections
1162
    // with other surfaces at the same location to avoid repeatedly crossing
1163
    // between them due to roundoff.
1164
    if (ignore_coincident_surfaces && d < FP_COINCIDENT)
2,147,483,647 ✔
1165
      continue;
11 ✔
1166

1167
    // Check if this distance is the new minimum.
1168
    if (d < min_dist) {
2,147,483,647 ✔
1169
      if (min_dist - d >= FP_PRECISION * min_dist) {
2,147,483,647 !
1170
        min_dist = d;
2,147,483,647 ✔
1171
        i_surf = -token;
2,147,483,647 ✔
1172
      }
1173
    }
1174
  }
1175

1176
  return {min_dist, i_surf};
2,147,483,647 ✔
1177
}
1178

1179
//==============================================================================
1180

1181
std::pair<double, int32_t> Region::distance_complex(
188,602,515 ✔
1182
  Position r, Direction u, int32_t on_surface) const
1183
{
1184
  const bool in_region = contains_complex(r, u, on_surface);
188,602,515 ✔
1185
  double total_distance {0.0};
1186

1187
  while (true) {
1,060,852,577 ✔
1188
    auto [distance, i_surf] =
1,249,455,092 ✔
1189
      distance_to_nearest_surface(r, u, on_surface, on_surface != 0);
624,727,546 ✔
1190
    if (distance == INFTY) {
624,727,546 ✔
1191
      return {INFTY, std::numeric_limits<int32_t>::max()};
1,745,218 ✔
1192
    }
1193

1194
    // Move to the candidate surface and determine which side of it the ray is
1195
    // entering. The surface normal is used instead of evaluating the surface
1196
    // equation because accumulated roundoff may place the point slightly to
1197
    // the wrong side of a curved surface.
1198
    r += distance * u;
622,982,328 ✔
1199
    total_distance += distance;
622,982,328 ✔
1200
    i_surf = std::abs(i_surf);
622,982,328 ✔
1201
    const auto& surf {*model::surfaces[i_surf - 1]};
622,982,328 ✔
1202
    if (u.dot(surf.normal(r)) <= 0.0) {
622,982,328 ✔
1203
      i_surf = -i_surf;
216,553,355 ✔
1204
    }
1205

1206
    // If crossing the candidate changes the region membership, it is a true
1207
    // boundary. Otherwise, continue the search from the virtual crossing.
1208
    if (contains_complex(r, u, i_surf) != in_region) {
622,982,328 ✔
1209
      return {total_distance, i_surf};
186,857,297 ✔
1210
    }
1211
    on_surface = i_surf;
436,125,031 ✔
1212
  }
436,125,031 ✔
1213
}
1214

1215
//==============================================================================
1216

1217
bool Region::contains(Position r, Direction u, int32_t on_surface) const
2,147,483,647 ✔
1218
{
1219
  if (simple_) {
2,147,483,647 ✔
1220
    return contains_simple(r, u, on_surface);
2,147,483,647 ✔
1221
  } else {
1222
    return contains_complex(r, u, on_surface);
26,383,865 ✔
1223
  }
1224
}
1225

1226
//==============================================================================
1227

1228
bool Region::contains_simple(Position r, Direction u, int32_t on_surface) const
2,147,483,647 ✔
1229
{
1230
  for (int32_t token : expression_) {
2,147,483,647 ✔
1231
    // Assume that no tokens are operators. Evaluate the sense of particle with
1232
    // respect to the surface and see if the token matches the sense. If the
1233
    // particle's surface attribute is set and matches the token, that
1234
    // overrides the determination based on sense().
1235
    if (token == on_surface) {
2,147,483,647 ✔
1236
    } else if (-token == on_surface) {
2,147,483,647 ✔
1237
      return false;
1238
    } else {
1239
      // Note the off-by-one indexing
1240
      bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
2,147,483,647 ✔
1241
      if (sense != (token > 0)) {
2,147,483,647 ✔
1242
        return false;
1243
      }
1244
    }
1245
  }
1246
  return true;
1247
}
1248

1249
//==============================================================================
1250

1251
bool Region::contains_complex(Position r, Direction u, int32_t on_surface) const
837,968,708 ✔
1252
{
1253
  bool in_cell = true;
837,968,708 ✔
1254
  int total_depth = 0;
837,968,708 ✔
1255

1256
  // For each token
1257
  for (auto it = expression_.begin(); it != expression_.end(); it++) {
2,147,483,647 ✔
1258
    int32_t token = *it;
2,147,483,647 ✔
1259

1260
    // If the token is a surface evaluate the sense
1261
    // If the token is a union or intersection check to
1262
    // short circuit
1263
    if (token < OP_UNION) {
2,147,483,647 ✔
1264
      if (token == on_surface) {
2,147,483,647 ✔
1265
        in_cell = true;
1266
      } else if (-token == on_surface) {
2,147,483,647 ✔
1267
        in_cell = false;
1268
      } else {
1269
        // Note the off-by-one indexing
1270
        bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
2,147,483,647 ✔
1271
        in_cell = (sense == (token > 0));
2,147,483,647 ✔
1272
      }
1273
    } else if ((token == OP_UNION && in_cell == true) ||
2,147,483,647 ✔
1274
               (token == OP_INTERSECTION && in_cell == false)) {
1,711,682,239 ✔
1275
      // If the total depth is zero return
1276
      if (total_depth == 0) {
1,487,617,225 ✔
1277
        return in_cell;
190,161,445 ✔
1278
      }
1279

1280
      total_depth--;
1,297,455,780 ✔
1281

1282
      // While the iterator is within the bounds of the vector
1283
      int depth = 1;
1,297,455,780 ✔
1284
      do {
2,147,483,647 ✔
1285
        // Get next token
1286
        it++;
2,147,483,647 ✔
1287
        int32_t next_token = *it;
2,147,483,647 ✔
1288

1289
        // If the token is an a parenthesis
1290
        if (next_token > OP_COMPLEMENT) {
2,147,483,647 ✔
1291
          // Adjust depth accordingly
1292
          if (next_token == OP_RIGHT_PAREN) {
1,617,989,130 ✔
1293
            depth--;
1,457,722,455 ✔
1294
          } else {
1295
            depth++;
160,266,675 ✔
1296
          }
1297
        }
1298
      } while (depth > 0);
2,147,483,647 ✔
1299
    } else if (token == OP_LEFT_PAREN) {
2,147,483,647 ✔
1300
      total_depth++;
1,359,123,373 ✔
1301
    } else if (token == OP_RIGHT_PAREN) {
2,147,483,647 ✔
1302
      total_depth--;
61,667,593 ✔
1303
    }
1304
  }
1305
  return in_cell;
1306
}
1307

1308
//==============================================================================
1309

1310
BoundingBox Region::bounding_box(int32_t cell_id) const
99 ✔
1311
{
1312
  if (simple_) {
99 ✔
1313
    return bounding_box_simple();
55 ✔
1314
  } else {
1315
    auto postfix = generate_postfix(cell_id);
44 ✔
1316
    return bounding_box_complex(postfix);
88 ✔
1317
  }
44 ✔
1318
}
1319

1320
//==============================================================================
1321

1322
BoundingBox Region::bounding_box_simple() const
55 ✔
1323
{
1324
  BoundingBox bbox;
55 ✔
1325
  for (int32_t token : expression_) {
220 ✔
1326
    bbox &= model::surfaces[abs(token) - 1]->bounding_box(token > 0);
165 ✔
1327
  }
1328
  return bbox;
55 ✔
1329
}
1330

1331
//==============================================================================
1332

1333
BoundingBox Region::bounding_box_complex(vector<int32_t> postfix) const
44 ✔
1334
{
1335
  vector<BoundingBox> stack(postfix.size());
44 ✔
1336
  int i_stack = -1;
44 ✔
1337

1338
  for (auto& token : postfix) {
792 ✔
1339
    if (token == OP_UNION) {
748 ✔
1340
      stack[i_stack - 1] = stack[i_stack - 1] | stack[i_stack];
154 ✔
1341
      i_stack--;
154 ✔
1342
    } else if (token == OP_INTERSECTION) {
594 ✔
1343
      stack[i_stack - 1] = stack[i_stack - 1] & stack[i_stack];
198 ✔
1344
      i_stack--;
198 ✔
1345
    } else {
1346
      i_stack++;
396 ✔
1347
      stack[i_stack] = model::surfaces[abs(token) - 1]->bounding_box(token > 0);
396 ✔
1348
    }
1349
  }
1350

1351
  assert(i_stack == 0);
44 !
1352
  return stack.front();
44 ✔
1353
}
44 ✔
1354

1355
//==============================================================================
1356

1357
vector<int32_t> Region::surfaces() const
6,785 ✔
1358
{
1359
  if (simple_) {
6,785 ✔
1360
    return expression_;
6,765 ✔
1361
  }
1362

1363
  vector<int32_t> surfaces = expression_;
20 ✔
1364

1365
  auto it = std::find_if(surfaces.begin(), surfaces.end(),
20 ✔
1366
    [&](const auto& value) { return value >= OP_UNION; });
20 !
1367

1368
  while (it != surfaces.end()) {
60 ✔
1369
    surfaces.erase(it);
40 ✔
1370

1371
    it = std::find_if(surfaces.begin(), surfaces.end(),
40 ✔
1372
      [&](const auto& value) { return value >= OP_UNION; });
80 !
1373
  }
1374

1375
  return surfaces;
20 ✔
1376
}
6,785 ✔
1377

1378
//==============================================================================
1379
// Non-method functions
1380
//==============================================================================
1381

1382
void read_cells(pugi::xml_node node)
9,607 ✔
1383
{
1384
  // Count the number of cells.
1385
  int n_cells = 0;
9,607 ✔
1386
  for (pugi::xml_node cell_node : node.children("cell")) {
49,126 ✔
1387
    n_cells++;
39,519 ✔
1388
  }
1389

1390
  // Loop over XML cell elements and populate the array.
1391
  model::cells.reserve(n_cells);
9,607 ✔
1392
  for (pugi::xml_node cell_node : node.children("cell")) {
49,126 ✔
1393
    model::cells.push_back(make_unique<CSGCell>(cell_node));
39,519 ✔
1394
  }
1395

1396
  // Fill the cell map.
1397
  for (int i = 0; i < model::cells.size(); i++) {
49,126 ✔
1398
    int32_t id = model::cells[i]->id_;
39,519 !
1399
    auto search = model::cell_map.find(id);
39,519 !
1400
    if (search == model::cell_map.end()) {
39,519 !
1401
      model::cell_map[id] = i;
39,519 ✔
1402
    } else {
1403
      fatal_error(
×
1404
        fmt::format("Two or more cells use the same unique ID: {}", id));
×
1405
    }
1406
  }
1407

1408
  read_dagmc_universes(node);
9,607 ✔
1409

1410
  populate_universes();
9,605 ✔
1411

1412
  // Allocate the cell overlap count if necessary.
1413
  if (settings::check_overlaps) {
9,605 ✔
1414
    model::overlap_check_count.resize(model::cells.size(), 0);
119 ✔
1415
  }
1416

1417
  if (model::cells.size() == 0) {
9,605 !
1418
    fatal_error("No cells were found in the geometry.xml file");
×
1419
  }
1420
}
9,605 ✔
1421

1422
void populate_universes()
9,607 ✔
1423
{
1424
  // Used to map universe index to the index of an implicit complement cell for
1425
  // DAGMC universes
1426
  std::unordered_map<int, int> implicit_comp_cells;
9,607 ✔
1427

1428
  // Populate the Universe vector and map.
1429
  for (int index_cell = 0; index_cell < model::cells.size(); index_cell++) {
49,338 ✔
1430
    int32_t uid = model::cells[index_cell]->universe_;
39,731 ✔
1431
    auto it = model::universe_map.find(uid);
39,731 ✔
1432
    if (it == model::universe_map.end()) {
39,731 ✔
1433
      model::universes.push_back(make_unique<Universe>());
44,360 ✔
1434
      model::universes.back()->id_ = uid;
22,180 ✔
1435
      model::universes.back()->cells_.push_back(index_cell);
22,180 ✔
1436
      model::universe_map[uid] = model::universes.size() - 1;
22,180 ✔
1437
    } else {
1438
#ifdef OPENMC_DAGMC_ENABLED
1439
      // Skip implicit complement cells for now
1440
      Universe* univ = model::universes[it->second].get();
2,329 !
1441
      DAGUniverse* dag_univ = dynamic_cast<DAGUniverse*>(univ);
2,329 !
1442
      if (dag_univ && (dag_univ->implicit_complement_idx() == index_cell)) {
2,329 ✔
1443
        implicit_comp_cells[it->second] = index_cell;
47 ✔
1444
        continue;
47 ✔
1445
      }
1446
#endif
1447

1448
      model::universes[it->second]->cells_.push_back(index_cell);
17,504 ✔
1449
    }
1450
    if (model::cells[index_cell]->virtual_lattice_) {
39,684 ✔
1451
      model::universes[it->second]->filled_with_triso_base_ =
15 ✔
1452
        model::cells[index_cell]->id_;
15 ✔
1453
    }
1454
  }
1455

1456
  // Add DAGUniverse implicit complement cells last
1457
  for (const auto& it : implicit_comp_cells) {
9,654 ✔
1458
    int index_univ = it.first;
47 ✔
1459
    int index_cell = it.second;
47 ✔
1460
    model::universes[index_univ]->cells_.push_back(index_cell);
47 !
1461
  }
1462

1463
  model::universes.shrink_to_fit();
9,607 ✔
1464
}
9,607 ✔
1465

1466
//==============================================================================
1467
// C-API functions
1468
//==============================================================================
1469

1470
extern "C" int openmc_cell_get_fill(
235 ✔
1471
  int32_t index, int* type, int32_t** indices, int32_t* n)
1472
{
1473
  if (index >= 0 && index < model::cells.size()) {
235 !
1474
    Cell& c {*model::cells[index]};
235 ✔
1475
    *type = static_cast<int>(c.type_);
235 ✔
1476
    if (c.type_ == Fill::MATERIAL) {
235 ✔
1477
      *indices = c.material_.data();
224 ✔
1478
      *n = c.material_.size();
224 ✔
1479
    } else {
1480
      *indices = &c.fill_;
11 ✔
1481
      *n = 1;
11 ✔
1482
    }
1483
  } else {
1484
    set_errmsg("Index in cells array is out of bounds.");
×
1485
    return OPENMC_E_OUT_OF_BOUNDS;
×
1486
  }
1487
  return 0;
1488
}
1489

1490
extern "C" int openmc_cell_set_fill(
11 ✔
1491
  int32_t index, int type, int32_t n, const int32_t* indices)
1492
{
1493
  Fill filltype = static_cast<Fill>(type);
11 ✔
1494
  if (index >= 0 && index < model::cells.size()) {
11 !
1495
    Cell& c {*model::cells[index]};
11 !
1496
    if (filltype == Fill::MATERIAL) {
11 !
1497
      c.type_ = Fill::MATERIAL;
11 ✔
1498
      c.material_.clear();
11 !
1499
      for (int i = 0; i < n; i++) {
22 ✔
1500
        int i_mat = indices[i];
11 ✔
1501
        if (i_mat == MATERIAL_VOID) {
11 !
1502
          c.material_.push_back(MATERIAL_VOID);
×
1503
        } else if (i_mat >= 0 && i_mat < model::materials.size()) {
11 !
1504
          c.material_.push_back(i_mat);
11 ✔
1505
        } else {
1506
          set_errmsg("Index in materials array is out of bounds.");
×
1507
          return OPENMC_E_OUT_OF_BOUNDS;
×
1508
        }
1509
      }
1510
      c.material_.shrink_to_fit();
11 ✔
1511
    } else if (filltype == Fill::UNIVERSE) {
×
1512
      c.type_ = Fill::UNIVERSE;
×
1513
    } else {
1514
      c.type_ = Fill::LATTICE;
×
1515
    }
1516
  } else {
1517
    set_errmsg("Index in cells array is out of bounds.");
×
1518
    return OPENMC_E_OUT_OF_BOUNDS;
×
1519
  }
1520
  return 0;
1521
}
1522

1523
extern "C" int openmc_cell_set_temperature(
88 ✔
1524
  int32_t index, double T, const int32_t* instance, bool set_contained)
1525
{
1526
  if (index < 0 || index >= model::cells.size()) {
88 !
1527
    set_errmsg("Index in cells array is out of bounds.");
×
1528
    return OPENMC_E_OUT_OF_BOUNDS;
×
1529
  }
1530

1531
  int32_t instance_index = instance ? *instance : -1;
88 ✔
1532
  try {
88 ✔
1533
    model::cells[index]->set_temperature(T, instance_index, set_contained);
88 ✔
1534
  } catch (const std::exception& e) {
×
1535
    set_errmsg(e.what());
×
1536
    return OPENMC_E_UNASSIGNED;
×
1537
  }
×
1538
  return 0;
1539
}
1540

1541
extern "C" int openmc_cell_set_density(
88 ✔
1542
  int32_t index, double density, const int32_t* instance, bool set_contained)
1543
{
1544
  if (index < 0 || index >= model::cells.size()) {
88 !
1545
    set_errmsg("Index in cells array is out of bounds.");
×
1546
    return OPENMC_E_OUT_OF_BOUNDS;
×
1547
  }
1548

1549
  int32_t instance_index = instance ? *instance : -1;
88 ✔
1550
  try {
88 ✔
1551
    model::cells[index]->set_density(density, instance_index, set_contained);
88 ✔
1552
  } catch (const std::exception& e) {
×
1553
    set_errmsg(e.what());
×
1554
    return OPENMC_E_UNASSIGNED;
×
1555
  }
×
1556
  return 0;
1557
}
1558

1559
extern "C" int openmc_cell_get_temperature(
9,628 ✔
1560
  int32_t index, const int32_t* instance, double* T)
1561
{
1562
  if (index < 0 || index >= model::cells.size()) {
9,628 !
1563
    set_errmsg("Index in cells array is out of bounds.");
×
1564
    return OPENMC_E_OUT_OF_BOUNDS;
×
1565
  }
1566

1567
  int32_t instance_index = instance ? *instance : -1;
9,628 ✔
1568
  try {
9,628 ✔
1569
    *T = model::cells[index]->temperature(instance_index);
9,628 ✔
1570
  } catch (const std::exception& e) {
×
1571
    set_errmsg(e.what());
×
1572
    return OPENMC_E_UNASSIGNED;
×
1573
  }
×
1574
  return 0;
9,628 ✔
1575
}
1576

1577
extern "C" int openmc_cell_get_density(
88 ✔
1578
  int32_t index, const int32_t* instance, double* density)
1579
{
1580
  if (index < 0 || index >= model::cells.size()) {
88 !
1581
    set_errmsg("Index in cells array is out of bounds.");
×
1582
    return OPENMC_E_OUT_OF_BOUNDS;
×
1583
  }
1584

1585
  int32_t instance_index = instance ? *instance : -1;
88 ✔
1586
  try {
88 ✔
1587
    if (model::cells[index]->type_ != Fill::MATERIAL) {
88 !
1588
      fatal_error(
×
1589
        fmt::format("Cell {}, instance {} is not filled with a material.",
×
1590
          model::cells[index]->id_, instance_index));
×
1591
    }
1592

1593
    int32_t mat_index = model::cells[index]->material(instance_index);
88 !
1594
    if (mat_index == MATERIAL_VOID) {
88 !
1595
      *density = 0.0;
×
1596
    } else {
1597
      *density = model::cells[index]->density_mult(instance_index) *
88 ✔
1598
                 model::materials[mat_index]->density_gpcc();
176 !
1599
    }
1600
  } catch (const std::exception& e) {
×
1601
    set_errmsg(e.what());
×
1602
    return OPENMC_E_UNASSIGNED;
×
1603
  }
×
1604
  return 0;
1605
}
1606

1607
//! Get the bounding box of a cell
1608
extern "C" int openmc_cell_bounding_box(
66 ✔
1609
  const int32_t index, double* llc, double* urc)
1610
{
1611

1612
  BoundingBox bbox;
66 ✔
1613

1614
  const auto& c = model::cells[index];
66 ✔
1615
  bbox = c->bounding_box();
66 ✔
1616

1617
  // set lower left corner values
1618
  llc[0] = bbox.min.x;
66 ✔
1619
  llc[1] = bbox.min.y;
66 ✔
1620
  llc[2] = bbox.min.z;
66 ✔
1621

1622
  // set upper right corner values
1623
  urc[0] = bbox.max.x;
66 ✔
1624
  urc[1] = bbox.max.y;
66 ✔
1625
  urc[2] = bbox.max.z;
66 ✔
1626

1627
  return 0;
66 ✔
1628
}
1629

1630
//! Get the name of a cell
1631
extern "C" int openmc_cell_get_name(int32_t index, const char** name)
419 ✔
1632
{
1633
  if (index < 0 || index >= model::cells.size()) {
419 !
1634
    set_errmsg("Index in cells array is out of bounds.");
×
1635
    return OPENMC_E_OUT_OF_BOUNDS;
×
1636
  }
1637

1638
  *name = model::cells[index]->name().data();
419 ✔
1639

1640
  return 0;
419 ✔
1641
}
1642

1643
//! Set the name of a cell
1644
extern "C" int openmc_cell_set_name(int32_t index, const char* name)
11 ✔
1645
{
1646
  if (index < 0 || index >= model::cells.size()) {
11 !
1647
    set_errmsg("Index in cells array is out of bounds.");
×
1648
    return OPENMC_E_OUT_OF_BOUNDS;
×
1649
  }
1650

1651
  model::cells[index]->set_name(name);
22 ✔
1652

1653
  return 0;
11 ✔
1654
}
1655

1656
//==============================================================================
1657
//! Define a containing (parent) cell
1658
//==============================================================================
1659

1660
//! Used to locate a universe fill in the geometry
1661
struct ParentCell {
1662
  bool operator==(const ParentCell& other) const
135 ✔
1663
  {
1664
    return cell_index == other.cell_index &&
135 !
1665
           lattice_index == other.lattice_index;
135 !
1666
  }
1667

1668
  bool operator<(const ParentCell& other) const
1669
  {
1670
    return cell_index < other.cell_index ||
1671
           (cell_index == other.cell_index &&
1672
             lattice_index < other.lattice_index);
1673
  }
1674

1675
  int64_t cell_index;
1676
  int64_t lattice_index;
1677
};
1678

1679
//! Structure used to insert ParentCell into hashed STL data structures
1680
struct ParentCellHash {
1681
  std::size_t operator()(const ParentCell& p) const
781 ✔
1682
  {
1683
    return 4096 * p.cell_index + p.lattice_index;
781 !
1684
  }
1685
};
1686

1687
//! Used to manage a traversal stack when locating parent cells of a cell
1688
//! instance in the model
1689
struct ParentCellStack {
151 ✔
1690

1691
  //! push method that adds to the parent_cells visited cells for this search
1692
  //! universe
1693
  void push(int32_t search_universe, const ParentCell& pc)
105 ✔
1694
  {
1695
    parent_cells_.push_back(pc);
105 ✔
1696
    // add parent cell to the set of cells we've visited for this search
1697
    // universe
1698
    visited_cells_[search_universe].insert(pc);
105 ✔
1699
  }
105 ✔
1700

1701
  //! removes the last parent_cell and clears the visited cells for the popped
1702
  //! cell's universe
1703
  void pop()
75 ✔
1704
  {
1705
    visited_cells_[this->current_univ()].clear();
75 ✔
1706
    parent_cells_.pop_back();
75 ✔
1707
  }
75 ✔
1708

1709
  //! checks whether or not the parent cell has been visited already for this
1710
  //! search universe
1711
  bool visited(int32_t search_universe, const ParentCell& parent_cell)
676 ✔
1712
  {
1713
    return visited_cells_[search_universe].count(parent_cell) != 0;
676 ✔
1714
  }
1715

1716
  //! return the next universe to search for a parent cell
1717
  int32_t current_univ() const
75 ✔
1718
  {
1719
    return model::cells[parent_cells_.back().cell_index]->universe_;
75 ✔
1720
  }
1721

1722
  //! indicates whether nor not parent cells are present on the stack
1723
  bool empty() const { return parent_cells_.empty(); }
75 ✔
1724

1725
  //! compute an instance for the provided distribcell index
1726
  int32_t compute_instance(int32_t distribcell_index) const
226 ✔
1727
  {
1728
    if (distribcell_index == C_NONE)
226 ✔
1729
      return 0;
1730

1731
    int32_t instance = 0;
120 ✔
1732
    for (const auto& parent_cell : this->parent_cells_) {
225 ✔
1733
      auto& cell = model::cells[parent_cell.cell_index];
105 !
1734
      if (cell->type_ == Fill::UNIVERSE) {
105 !
1735
        instance += cell->offset_[distribcell_index];
×
1736
      } else if (cell->type_ == Fill::LATTICE) {
105 !
1737
        auto& lattice = model::lattices[cell->fill_];
105 ✔
1738
        instance +=
105 ✔
1739
          lattice->offset(distribcell_index, parent_cell.lattice_index);
105 ✔
1740
      }
1741
    }
1742
    return instance;
1743
  }
1744

1745
  // Accessors
1746
  vector<ParentCell>& parent_cells() { return parent_cells_; }
151 ✔
1747
  const vector<ParentCell>& parent_cells() const { return parent_cells_; }
1748

1749
  // Data Members
1750
  vector<ParentCell> parent_cells_;
1751
  std::unordered_map<int32_t, std::unordered_set<ParentCell, ParentCellHash>>
1752
    visited_cells_;
1753
};
1754

1755
vector<ParentCell> Cell::find_parent_cells(
×
1756
  int32_t instance, const Position& r) const
1757
{
1758

1759
  // create a temporary particle
1760
  GeometryState dummy_particle {};
×
1761
  dummy_particle.r() = r;
×
1762
  dummy_particle.u() = {0., 0., 1.};
×
1763

1764
  return find_parent_cells(instance, dummy_particle);
×
1765
}
×
1766

1767
vector<ParentCell> Cell::find_parent_cells(
×
1768
  int32_t instance, GeometryState& p) const
1769
{
1770
  // look up the particle's location
1771
  exhaustive_find_cell(p);
×
1772
  const auto& coords = p.coord();
×
1773

1774
  // build a parent cell stack from the particle coordinates
1775
  ParentCellStack stack;
×
1776
  bool cell_found = false;
×
1777
  for (auto it = coords.begin(); it != coords.end(); it++) {
×
1778
    const auto& coord = *it;
×
1779
    const auto& cell = model::cells[coord.cell()];
×
1780
    // if the cell at this level matches the current cell, stop adding to the
1781
    // stack
1782
    if (coord.cell() == model::cell_map[this->id_]) {
×
1783
      cell_found = true;
1784
      break;
1785
    }
1786

1787
    // if filled with a lattice, get the lattice index from the next
1788
    // level in the coordinates to push to the stack
1789
    int lattice_idx = C_NONE;
×
1790
    if (cell->type_ == Fill::LATTICE) {
×
1791
      const auto& next_coord = *(it + 1);
×
1792
      lattice_idx = model::lattices[next_coord.lattice()]->get_flat_index(
×
1793
        next_coord.lattice_index());
1794
    }
1795
    stack.push(coord.universe(), {coord.cell(), lattice_idx});
×
1796
  }
1797

1798
  // if this loop finished because the cell was found and
1799
  // the instance matches the one requested in the call
1800
  // we have the correct path and can return the stack
1801
  if (cell_found &&
×
1802
      stack.compute_instance(this->distribcell_index_) == instance) {
×
1803
    return stack.parent_cells();
×
1804
  }
1805

1806
  // fall back on an exhaustive search for the cell's parents
1807
  return exhaustive_find_parent_cells(instance);
×
1808
}
×
1809

1810
vector<ParentCell> Cell::exhaustive_find_parent_cells(int32_t instance) const
151 ✔
1811
{
1812
  ParentCellStack stack;
151 ✔
1813
  // start with this cell's universe
1814
  int32_t prev_univ_idx;
151 ✔
1815
  int32_t univ_idx = this->universe_;
151 ✔
1816

1817
  while (true) {
226 ✔
1818
    const auto& univ = model::universes[univ_idx];
226 ✔
1819
    prev_univ_idx = univ_idx;
226 ✔
1820

1821
    // search for a cell that is filled w/ this universe
1822
    for (const auto& cell : model::cells) {
1,699 ✔
1823
      // if this is a material-filled cell, move on
1824
      if (cell->type_ == Fill::MATERIAL)
1,578 ✔
1825
        continue;
887 ✔
1826

1827
      if (cell->type_ == Fill::UNIVERSE) {
691 ✔
1828
        // if this is in the set of cells previously visited for this universe,
1829
        // move on
1830
        if (stack.visited(univ_idx, {model::cell_map[cell->id_], C_NONE}))
436 !
1831
          continue;
×
1832

1833
        // if this cell contains the universe we're searching for, add it to the
1834
        // stack
1835
        if (cell->fill_ == univ_idx) {
436 !
1836
          stack.push(univ_idx, {model::cell_map[cell->id_], C_NONE});
×
1837
          univ_idx = cell->universe_;
×
1838
        }
1839
      } else if (cell->type_ == Fill::LATTICE) {
255 !
1840
        // retrieve the lattice and lattice universes
1841
        const auto& lattice = model::lattices[cell->fill_];
255 ✔
1842
        const auto& lattice_univs = lattice->universes_;
255 ✔
1843

1844
        // start search for universe
1845
        auto lat_it = lattice_univs.begin();
255 ✔
1846
        while (true) {
525 ✔
1847
          // find the next lattice cell with this universe
1848
          lat_it = std::find(lat_it, lattice_univs.end(), univ_idx);
390 ✔
1849
          if (lat_it == lattice_univs.end())
390 ✔
1850
            break;
1851

1852
          int lattice_idx = lat_it - lattice_univs.begin();
240 ✔
1853

1854
          // move iterator forward one to avoid finding the same entry
1855
          lat_it++;
240 ✔
1856
          if (stack.visited(
480 ✔
1857
                univ_idx, {model::cell_map[cell->id_], lattice_idx}))
240 ✔
1858
            continue;
135 ✔
1859

1860
          // add this cell and lattice index to the stack and exit loop
1861
          stack.push(univ_idx, {model::cell_map[cell->id_], lattice_idx});
105 ✔
1862
          univ_idx = cell->universe_;
105 ✔
1863
          break;
105 ✔
1864
        }
135 ✔
1865
      }
1866
      // if we've updated the universe, break
1867
      if (prev_univ_idx != univ_idx)
691 ✔
1868
        break;
1869
    } // end cell loop search for universe
1870

1871
    // if we're at the top of the geometry and the instance matches, we're done
1872
    if (univ_idx == model::root_universe &&
271 !
1873
        stack.compute_instance(this->distribcell_index_) == instance)
226 ✔
1874
      break;
1875

1876
    // if there is no match on the original cell's universe, report an error
1877
    if (univ_idx == this->universe_) {
75 !
1878
      fatal_error(
×
1879
        fmt::format("Could not find the parent cells for cell {}, instance {}.",
×
1880
          this->id_, instance));
×
1881
    }
1882

1883
    // if we don't find a suitable update, adjust the stack and continue
1884
    if (univ_idx == model::root_universe || univ_idx == prev_univ_idx) {
75 !
1885
      stack.pop();
75 ✔
1886
      univ_idx = stack.empty() ? this->universe_ : stack.current_univ();
75 !
1887
    }
1888

1889
  } // end while
1890

1891
  // reverse the stack so the highest cell comes first
1892
  std::reverse(stack.parent_cells().begin(), stack.parent_cells().end());
151 ✔
1893
  return stack.parent_cells();
302 ✔
1894
}
151 ✔
1895

1896
std::unordered_map<int32_t, vector<int32_t>> Cell::get_contained_cells(
196 ✔
1897
  int32_t instance, Position* hint) const
1898
{
1899
  std::unordered_map<int32_t, vector<int32_t>> contained_cells;
196 ✔
1900

1901
  // if this is a material-filled cell it has no contained cells
1902
  if (this->type_ == Fill::MATERIAL)
196 ✔
1903
    return contained_cells;
1904

1905
  // find the pathway through the geometry to this cell
1906
  vector<ParentCell> parent_cells;
151 !
1907

1908
  // if a positional hint is provided, attempt to do a fast lookup
1909
  // of the parent cells
1910
  parent_cells = hint ? find_parent_cells(instance, *hint)
151 !
1911
                      : exhaustive_find_parent_cells(instance);
151 ✔
1912

1913
  // if this cell is filled w/ a material, it contains no other cells
1914
  if (type_ != Fill::MATERIAL) {
151 !
1915
    this->get_contained_cells_inner(contained_cells, parent_cells);
151 ✔
1916
  }
1917

1918
  return contained_cells;
151 ✔
1919
}
196 ✔
1920

1921
//! Get all cells within this cell
1922
void Cell::get_contained_cells_inner(
138,228 ✔
1923
  std::unordered_map<int32_t, vector<int32_t>>& contained_cells,
1924
  vector<ParentCell>& parent_cells) const
1925
{
1926

1927
  // filled by material, determine instance based on parent cells
1928
  if (type_ == Fill::MATERIAL) {
138,228 ✔
1929
    int instance = 0;
137,192 ✔
1930
    if (this->distribcell_index_ >= 0) {
137,192 !
1931
      for (auto& parent_cell : parent_cells) {
411,574 ✔
1932
        auto& cell = model::cells[parent_cell.cell_index];
274,382 ✔
1933
        if (cell->type_ == Fill::UNIVERSE) {
274,382 ✔
1934
          instance += cell->offset_[distribcell_index_];
134,192 ✔
1935
        } else if (cell->type_ == Fill::LATTICE) {
140,190 !
1936
          auto& lattice = model::lattices[cell->fill_];
140,190 ✔
1937
          instance += lattice->offset(
140,190 ✔
1938
            this->distribcell_index_, parent_cell.lattice_index);
140,190 ✔
1939
        }
1940
      }
1941
    }
1942
    // add entry to contained cells
1943
    contained_cells[model::cell_map[id_]].push_back(instance);
137,192 ✔
1944
    // filled with universe, add the containing cell to the parent cells
1945
    // and recurse
1946
  } else if (type_ == Fill::UNIVERSE) {
1,036 ✔
1947
    parent_cells.push_back({model::cell_map[id_], -1});
886 ✔
1948
    auto& univ = model::universes[fill_];
886 ✔
1949
    for (auto cell_index : univ->cells_) {
5,553 ✔
1950
      auto& cell = model::cells[cell_index];
4,667 ✔
1951
      cell->get_contained_cells_inner(contained_cells, parent_cells);
4,667 ✔
1952
    }
1953
    parent_cells.pop_back();
886 ✔
1954
    // filled with a lattice, visit each universe in the lattice
1955
    // with a recursive call to collect the cell instances
1956
  } else if (type_ == Fill::LATTICE) {
150 !
1957
    auto& lattice = model::lattices[fill_];
150 ✔
1958
    for (auto i = lattice->begin(); i != lattice->end(); ++i) {
132,930 ✔
1959
      auto& univ = model::universes[*i];
132,780 ✔
1960
      parent_cells.push_back({model::cell_map[id_], i.indx_});
132,780 ✔
1961
      for (auto cell_index : univ->cells_) {
266,190 ✔
1962
        auto& cell = model::cells[cell_index];
133,410 ✔
1963
        cell->get_contained_cells_inner(contained_cells, parent_cells);
133,410 ✔
1964
      }
1965
      parent_cells.pop_back();
132,780 ✔
1966
    }
1967
  }
1968
}
138,228 ✔
1969

1970
//! Return the index in the cells array of a cell with a given ID
1971
extern "C" int openmc_get_cell_index(int32_t id, int32_t* index)
1,038 ✔
1972
{
1973
  auto it = model::cell_map.find(id);
1,038 ✔
1974
  if (it != model::cell_map.end()) {
1,038 ✔
1975
    *index = it->second;
1,027 ✔
1976
    return 0;
1,027 ✔
1977
  } else {
1978
    set_errmsg("No cell exists with ID=" + std::to_string(id) + ".");
22 ✔
1979
    return OPENMC_E_INVALID_ID;
11 ✔
1980
  }
1981
}
1982

1983
//! Return the ID of a cell
1984
extern "C" int openmc_cell_get_id(int32_t index, int32_t* id)
602,424 ✔
1985
{
1986
  if (index >= 0 && index < model::cells.size()) {
602,424 !
1987
    *id = model::cells[index]->id_;
602,424 ✔
1988
    return 0;
602,424 ✔
1989
  } else {
1990
    set_errmsg("Index in cells array is out of bounds.");
×
1991
    return OPENMC_E_OUT_OF_BOUNDS;
×
1992
  }
1993
}
1994

1995
//! Set the ID of a cell
1996
extern "C" int openmc_cell_set_id(int32_t index, int32_t id)
22 ✔
1997
{
1998
  if (index >= 0 && index < model::cells.size()) {
22 !
1999
    model::cells[index]->id_ = id;
22 ✔
2000
    model::cell_map[id] = index;
22 ✔
2001
    return 0;
22 ✔
2002
  } else {
2003
    set_errmsg("Index in cells array is out of bounds.");
×
2004
    return OPENMC_E_OUT_OF_BOUNDS;
×
2005
  }
2006
}
2007

2008
//! Return the translation vector of a cell
2009
extern "C" int openmc_cell_get_translation(int32_t index, double xyz[])
55 ✔
2010
{
2011
  if (index >= 0 && index < model::cells.size()) {
55 !
2012
    auto& cell = model::cells[index];
55 ✔
2013
    xyz[0] = cell->translation_.x;
55 ✔
2014
    xyz[1] = cell->translation_.y;
55 ✔
2015
    xyz[2] = cell->translation_.z;
55 ✔
2016
    return 0;
55 ✔
2017
  } else {
2018
    set_errmsg("Index in cells array is out of bounds.");
×
2019
    return OPENMC_E_OUT_OF_BOUNDS;
×
2020
  }
2021
}
2022

2023
//! Set the translation vector of a cell
2024
extern "C" int openmc_cell_set_translation(int32_t index, const double xyz[])
55 ✔
2025
{
2026
  if (index >= 0 && index < model::cells.size()) {
55 !
2027
    if (model::cells[index]->fill_ == C_NONE) {
55 ✔
2028
      set_errmsg(fmt::format("Cannot apply a translation to cell {}"
11 ✔
2029
                             " because it is not filled with another universe",
2030
        index));
2031
      return OPENMC_E_GEOMETRY;
11 ✔
2032
    }
2033
    model::cells[index]->translation_ = Position(xyz);
44 ✔
2034
    return 0;
44 ✔
2035
  } else {
2036
    set_errmsg("Index in cells array is out of bounds.");
×
2037
    return OPENMC_E_OUT_OF_BOUNDS;
×
2038
  }
2039
}
2040

2041
//! Return the rotation matrix of a cell
2042
extern "C" int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n)
55 ✔
2043
{
2044
  if (index >= 0 && index < model::cells.size()) {
55 !
2045
    auto& cell = model::cells[index];
55 ✔
2046
    *n = cell->rotation_.size();
55 ✔
2047
    std::memcpy(rot, cell->rotation_.data(), *n * sizeof(cell->rotation_[0]));
55 ✔
2048
    return 0;
55 ✔
2049
  } else {
2050
    set_errmsg("Index in cells array is out of bounds.");
×
2051
    return OPENMC_E_OUT_OF_BOUNDS;
×
2052
  }
2053
}
2054

2055
//! Set the flattened rotation matrix of a cell
2056
extern "C" int openmc_cell_set_rotation(
66 ✔
2057
  int32_t index, const double rot[], size_t rot_len)
2058
{
2059
  if (index >= 0 && index < model::cells.size()) {
66 !
2060
    if (model::cells[index]->fill_ == C_NONE) {
66 ✔
2061
      set_errmsg(fmt::format("Cannot apply a rotation to cell {}"
11 ✔
2062
                             " because it is not filled with another universe",
2063
        index));
2064
      return OPENMC_E_GEOMETRY;
11 ✔
2065
    }
2066
    std::vector<double> vec_rot(rot, rot + rot_len);
55 ✔
2067
    model::cells[index]->set_rotation(vec_rot);
55 ✔
2068
    return 0;
55 ✔
2069
  } else {
66 ✔
2070
    set_errmsg("Index in cells array is out of bounds.");
×
2071
    return OPENMC_E_OUT_OF_BOUNDS;
×
2072
  }
2073
}
2074

2075
//! Get the number of instances of the requested cell
2076
extern "C" int openmc_cell_get_num_instances(
77 ✔
2077
  int32_t index, int32_t* num_instances)
2078
{
2079
  if (index < 0 || index >= model::cells.size()) {
77 !
2080
    set_errmsg("Index in cells array is out of bounds.");
×
2081
    return OPENMC_E_OUT_OF_BOUNDS;
×
2082
  }
2083
  *num_instances = model::cells[index]->n_instances();
77 ✔
2084
  return 0;
77 ✔
2085
}
2086

2087
//! Extend the cells array by n elements
2088
extern "C" int openmc_extend_cells(
22 ✔
2089
  int32_t n, int32_t* index_start, int32_t* index_end)
2090
{
2091
  if (index_start)
22 !
2092
    *index_start = model::cells.size();
22 ✔
2093
  if (index_end)
22 !
2094
    *index_end = model::cells.size() + n - 1;
×
2095
  for (int32_t i = 0; i < n; i++) {
44 ✔
2096
    model::cells.push_back(make_unique<CSGCell>());
22 ✔
2097
  }
2098
  return 0;
22 ✔
2099
}
2100

2101
extern "C" int cells_size()
99 ✔
2102
{
2103
  return model::cells.size();
99 ✔
2104
}
2105

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

© 2026 Coveralls, Inc