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

openmc-dev / openmc / 42411379612

07 Nov 2026 08:30PM UTC coverage: 81.831% (-0.2%) from 82.009%
42411379612

Pull #4215

github

web-flow
Merge 36e674ca2 into 93b147fa4
Pull Request #4215: XDG Mesh Geometry

19729 of 27802 branches covered (70.96%)

Branch coverage included in aggregate %.

117 of 222 new or added lines in 18 files covered. (52.7%)

514 existing lines in 31 files now uncovered.

62406 of 72570 relevant lines covered (85.99%)

39997221.18 hits per line

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

74.4
/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/xdg.h"
26
#include "openmc/xml_interface.h"
27

28
namespace openmc {
29

30
//==============================================================================
31
// Global variables
32
//==============================================================================
33

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

38
} // namespace model
39

40
//==============================================================================
41
// Cell implementation
42
//==============================================================================
43

44
int32_t Cell::n_instances() const
12,005 ✔
45
{
46
  return model::universes[universe_]->n_instances_;
12,005 ✔
47
}
48

49
void Cell::set_rotation(const vector<double>& rot)
269 ✔
50
{
51
  if (fill_ == C_NONE) {
269 !
52
    fatal_error(fmt::format("Cannot apply a rotation to cell {}"
×
53
                            " because it is not filled with another universe",
54
      id_));
×
55
  }
56

57
  if (rot.size() != 3 && rot.size() != 9) {
269 !
58
    fatal_error(fmt::format("Non-3D rotation vector applied to cell {}", id_));
×
59
  }
60

61
  // Compute and store the inverse rotation matrix for the angles given.
62
  rotation_.clear();
269 ✔
63
  rotation_.reserve(rot.size() == 9 ? 9 : 12);
538 !
64
  if (rot.size() == 3) {
269 !
65
    double phi = -rot[0] * PI / 180.0;
269 ✔
66
    double theta = -rot[1] * PI / 180.0;
269 ✔
67
    double psi = -rot[2] * PI / 180.0;
269 ✔
68
    rotation_.push_back(std::cos(theta) * std::cos(psi));
269 ✔
69
    rotation_.push_back(-std::cos(phi) * std::sin(psi) +
269 ✔
70
                        std::sin(phi) * std::sin(theta) * std::cos(psi));
269 ✔
71
    rotation_.push_back(std::sin(phi) * std::sin(psi) +
269 ✔
72
                        std::cos(phi) * std::sin(theta) * std::cos(psi));
269 ✔
73
    rotation_.push_back(std::cos(theta) * std::sin(psi));
269 ✔
74
    rotation_.push_back(std::cos(phi) * std::cos(psi) +
269 ✔
75
                        std::sin(phi) * std::sin(theta) * std::sin(psi));
269 ✔
76
    rotation_.push_back(-std::sin(phi) * std::cos(psi) +
269 ✔
77
                        std::cos(phi) * std::sin(theta) * std::sin(psi));
269 ✔
78
    rotation_.push_back(-std::sin(theta));
269 ✔
79
    rotation_.push_back(std::sin(phi) * std::cos(theta));
269 ✔
80
    rotation_.push_back(std::cos(phi) * std::cos(theta));
269 ✔
81

82
    // When user specifies angles, write them at end of vector
83
    rotation_.push_back(rot[0]);
269 ✔
84
    rotation_.push_back(rot[1]);
269 ✔
85
    rotation_.push_back(rot[2]);
269 ✔
86
  } else {
87
    std::copy(rot.begin(), rot.end(), std::back_inserter(rotation_));
×
88
  }
89
}
269 ✔
90

91
double Cell::temperature(int32_t instance) const
6,125 ✔
92
{
93
  if (sqrtkT_.size() < 1) {
6,125 !
94
    throw std::runtime_error {"Cell temperature has not yet been set."};
×
95
  }
96

97
  if (instance >= 0) {
6,125 ✔
98
    double sqrtkT = sqrtkT_.size() == 1 ? sqrtkT_.at(0) : sqrtkT_.at(instance);
6,076 ✔
99
    return sqrtkT * sqrtkT / K_BOLTZMANN;
6,076 ✔
100
  } else {
101
    return sqrtkT_[0] * sqrtkT_[0] / K_BOLTZMANN;
49 ✔
102
  }
103
}
104

105
double Cell::density_mult(int32_t instance) const
2,147,483,647 ✔
106
{
107
  if (instance >= 0) {
2,147,483,647 ✔
108
    return density_mult_.size() == 1 ? density_mult_.at(0)
2,147,483,647 ✔
109
                                     : density_mult_.at(instance);
3,221,271 ✔
110
  } else {
111
    return density_mult_[0];
49 ✔
112
  }
113
}
114

115
double Cell::density(int32_t instance) const
745,451 ✔
116
{
117
  const int32_t mat_index = material(instance);
745,451 ✔
118
  if (mat_index == MATERIAL_VOID)
745,451 !
119
    return 0.0;
120

121
  return density_mult(instance) * model::materials[mat_index]->density_gpcc();
1,490,902 ✔
122
}
123

124
void Cell::set_temperature(double T, int32_t instance, bool set_contained)
6,362 ✔
125
{
126
  if (settings::temperature_method == TemperatureMethod::INTERPOLATION) {
6,362 !
127
    if (T < (data::temperature_min - settings::temperature_tolerance)) {
×
128
      throw std::runtime_error {
×
129
        fmt::format("Temperature of {} K is below minimum temperature at "
×
130
                    "which data is available of {} K.",
131
          T, data::temperature_min)};
×
132
    } else if (T > (data::temperature_max + settings::temperature_tolerance)) {
×
133
      throw std::runtime_error {
×
134
        fmt::format("Temperature of {} K is above maximum temperature at "
×
135
                    "which data is available of {} K.",
136
          T, data::temperature_max)};
×
137
    }
138
  }
139

140
  if (type_ == Fill::MATERIAL) {
6,362 ✔
141
    if (instance >= 0) {
6,344 ✔
142
      // If temperature vector is not big enough, resize it first
143
      if (sqrtkT_.size() != n_instances())
6,295 ✔
144
        sqrtkT_.resize(n_instances(), sqrtkT_[0]);
27 ✔
145

146
      // Set temperature for the corresponding instance
147
      sqrtkT_.at(instance) = std::sqrt(K_BOLTZMANN * T);
6,295 ✔
148
    } else {
149
      // Set temperature for all instances
150
      for (auto& T_ : sqrtkT_) {
98 ✔
151
        T_ = std::sqrt(K_BOLTZMANN * T);
49 ✔
152
      }
153
    }
154
  } else {
155
    if (!set_contained) {
18 !
156
      throw std::runtime_error {
×
157
        fmt::format("Attempted to set the temperature of cell {} "
×
158
                    "which is not filled by a material.",
159
          id_)};
×
160
    }
161

162
    auto contained_cells = this->get_contained_cells(instance);
18 ✔
163
    for (const auto& entry : contained_cells) {
72 ✔
164
      auto& cell = model::cells[entry.first];
54 !
165
      assert(cell->type_ == Fill::MATERIAL);
54 !
166
      auto& instances = entry.second;
54 ✔
167
      for (auto instance : instances) {
189 ✔
168
        cell->set_temperature(T, instance);
135 ✔
169
      }
170
    }
171
  }
18 ✔
172
}
6,362 ✔
173

174
void Cell::set_density(double density, int32_t instance, bool set_contained)
218 ✔
175
{
176
  if (type_ != Fill::MATERIAL && !set_contained) {
218 !
177
    fatal_error(
×
178
      fmt::format("Attempted to set the density multiplier of cell {} "
×
179
                  "which is not filled by a material.",
180
        id_));
×
181
  }
182

183
  if (type_ == Fill::MATERIAL) {
218 ✔
184
    const int32_t mat_index = material(instance);
209 ✔
185
    if (mat_index == MATERIAL_VOID)
209 !
186
      return;
187

188
    if (instance >= 0) {
209 ✔
189
      // If density multiplier vector is not big enough, resize it first
190
      if (density_mult_.size() != n_instances())
160 ✔
191
        density_mult_.resize(n_instances(), density_mult_[0]);
69 ✔
192

193
      // Set density multiplier for the corresponding instance
194
      density_mult_.at(instance) =
160 ✔
195
        density / model::materials[mat_index]->density_gpcc();
320 !
196
    } else {
197
      // Set density multiplier for all instances
198
      for (auto& x : density_mult_) {
98 ✔
199
        x = density / model::materials[mat_index]->density_gpcc();
98 !
200
      }
201
    }
202
  } else {
203
    auto contained_cells = this->get_contained_cells(instance);
9 ✔
204
    for (const auto& entry : contained_cells) {
36 ✔
205
      auto& cell = model::cells[entry.first];
27 !
206
      assert(cell->type_ == Fill::MATERIAL);
27 !
207
      auto& instances = entry.second;
27 ✔
208
      for (auto instance : instances) {
54 ✔
209
        cell->set_density(density, instance);
27 ✔
210
      }
211
    }
212
  }
9 ✔
213
}
214

215
void Cell::export_properties_hdf5(hid_t group) const
147 ✔
216
{
217
  // Create a group for this cell.
218
  auto cell_group = create_group(group, fmt::format("cell {}", id_));
147 ✔
219

220
  // Write temperature in [K] for one or more cell instances
221
  vector<double> temps;
147 ✔
222
  for (auto sqrtkT_val : sqrtkT_)
273 ✔
223
    temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
126 ✔
224
  write_dataset(cell_group, "temperature", temps);
147 ✔
225

226
  // Write density for one or more cell instances
227
  if (type_ == Fill::MATERIAL && material_.size() > 0) {
147 ✔
228
    vector<double> density;
126 ✔
229
    for (int32_t i = 0; i < density_mult_.size(); ++i)
252 ✔
230
      density.push_back(this->density(i));
126 ✔
231

232
    write_dataset(cell_group, "density", density);
126 ✔
233
  }
126 ✔
234

235
  close_group(cell_group);
147 ✔
236
}
147 ✔
237

238
void Cell::import_properties_hdf5(hid_t group)
161 ✔
239
{
240
  auto cell_group = open_group(group, fmt::format("cell {}", id_));
161 ✔
241

242
  // Read temperatures from file
243
  vector<double> temps;
161 ✔
244
  read_dataset(cell_group, "temperature", temps);
161 ✔
245

246
  // Ensure number of temperatures makes sense
247
  auto n_temps = temps.size();
161 ✔
248
  if (n_temps > 1 && n_temps != n_instances()) {
161 !
249
    fatal_error(fmt::format(
×
250
      "Number of temperatures for cell {} doesn't match number of instances",
251
      id_));
×
252
  }
253

254
  // Modify temperatures for the cell
255
  sqrtkT_.clear();
161 ✔
256
  sqrtkT_.resize(temps.size());
161 ✔
257
  for (int64_t i = 0; i < temps.size(); ++i) {
6,314 ✔
258
    this->set_temperature(temps[i], i);
6,153 ✔
259
  }
260

261
  // Read densities
262
  if (object_exists(cell_group, "density")) {
161 ✔
263
    vector<double> density;
126 ✔
264
    read_dataset(cell_group, "density", density);
126 ✔
265

266
    // Ensure number of densities makes sense
267
    auto n_density = density.size();
126 !
268
    if (n_density > 1 && n_density != n_instances()) {
126 !
269
      fatal_error(fmt::format("Number of densities for cell {} "
×
270
                              "doesn't match number of instances",
271
        id_));
×
272
    }
273

274
    // Set densities.
275
    for (int32_t i = 0; i < n_density; ++i) {
252 ✔
276
      this->set_density(density[i], i);
126 ✔
277
    }
278
  }
126 ✔
279

280
  close_group(cell_group);
161 ✔
281
}
161 ✔
282

283
void Cell::to_hdf5(hid_t cell_group) const
16,632 ✔
284
{
285

286
  // Create a group for this cell.
287
  auto group = create_group(cell_group, fmt::format("cell {}", id_));
16,632 ✔
288

289
  if (!name_.empty()) {
16,632 ✔
290
    write_string(group, "name", name_, false);
5,380 ✔
291
  }
292

293
  write_dataset(group, "universe", model::universes[universe_]->id_);
16,632 ✔
294

295
  to_hdf5_inner(group);
16,632 ✔
296

297
  // Write fill information.
298
  if (type_ == Fill::MATERIAL) {
16,632 ✔
299
    write_dataset(group, "fill_type", "material");
12,719 ✔
300
    std::vector<int32_t> mat_ids;
12,719 ✔
301
    for (auto i_mat : material_) {
26,290 ✔
302
      if (i_mat != MATERIAL_VOID) {
13,571 ✔
303
        mat_ids.push_back(model::materials[i_mat]->id_);
11,771 ✔
304
      } else {
305
        mat_ids.push_back(MATERIAL_VOID);
1,800 ✔
306
      }
307
    }
308
    if (mat_ids.size() == 1) {
12,719 ✔
309
      write_dataset(group, "material", mat_ids[0]);
12,595 ✔
310
    } else {
311
      write_dataset(group, "material", mat_ids);
124 ✔
312
    }
313

314
    std::vector<double> temps;
12,719 ✔
315
    for (auto sqrtkT_val : sqrtkT_)
32,884 ✔
316
      temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
20,165 ✔
317
    write_dataset(group, "temperature", temps);
12,719 ✔
318

319
    write_dataset(group, "density_mult", density_mult_);
12,719 ✔
320

321
  } else if (type_ == Fill::UNIVERSE) {
16,632 ✔
322
    write_dataset(group, "fill_type", "universe");
2,809 ✔
323
    write_dataset(group, "fill", model::universes[fill_]->id_);
2,809 ✔
324
    if (translation_ != Position(0, 0, 0)) {
2,809 ✔
325
      write_dataset(group, "translation", translation_);
1,169 ✔
326
    }
327
    if (!rotation_.empty()) {
2,809 ✔
328
      if (rotation_.size() == 12) {
168 !
329
        std::array<double, 3> rot {rotation_[9], rotation_[10], rotation_[11]};
168 ✔
330
        write_dataset(group, "rotation", rot);
168 ✔
331
      } else {
332
        write_dataset(group, "rotation", rotation_);
×
333
      }
334
    }
335

336
  } else if (type_ == Fill::LATTICE) {
1,104 !
337
    write_dataset(group, "fill_type", "lattice");
1,104 ✔
338
    write_dataset(group, "lattice", model::lattices[fill_]->id_);
1,104 ✔
339
  }
340

341
  close_group(group);
16,632 ✔
342
}
16,632 ✔
343

344
//==============================================================================
345
// XML parsing helpers for <cell> nodes
346
//==============================================================================
347

348
vector<int32_t> parse_cell_material_xml(pugi::xml_node node, int32_t cell_id)
15,145 ✔
349
{
350
  vector<std::string> mats {
15,145 ✔
351
    get_node_array<std::string>(node, "material", true)};
15,145 ✔
352
  if (mats.empty()) {
15,145 !
353
    fatal_error(fmt::format(
×
354
      "An empty material element was specified for cell {}", cell_id));
355
  }
356
  vector<int32_t> material;
15,145 ✔
357
  material.reserve(mats.size());
15,145 ✔
358
  for (const auto& mat : mats) {
31,160 ✔
359
    if (mat == "void") {
16,015 ✔
360
      material.push_back(MATERIAL_VOID);
2,126 ✔
361
    } else {
362
      material.push_back(std::stoi(mat));
13,889 ✔
363
    }
364
  }
365
  return material;
15,145 ✔
366
}
15,145 ✔
367

368
vector<double> parse_cell_temperature_xml(pugi::xml_node node, int32_t cell_id)
259 ✔
369
{
370
  auto temperatures = get_node_array<double>(node, "temperature");
259 ✔
371
  if (temperatures.empty()) {
259 !
372
    fatal_error(fmt::format(
×
373
      "An empty temperature element was specified for cell {}", cell_id));
374
  }
375
  for (auto T : temperatures) {
1,166 ✔
376
    if (T < 0) {
907 !
377
      fatal_error(fmt::format(
×
378
        "Cell {} was specified with a negative temperature", cell_id));
379
    }
380
  }
381
  return temperatures;
259 ✔
382
}
×
383

384
vector<double> parse_cell_density_xml(pugi::xml_node node, int32_t cell_id)
45 ✔
385
{
386
  auto densities = get_node_array<double>(node, "density");
45 ✔
387
  if (densities.empty()) {
45 !
388
    fatal_error(fmt::format(
×
389
      "An empty density element was specified for cell {}", cell_id));
390
  }
391
  for (auto rho : densities) {
738 ✔
392
    if (rho <= 0) {
693 !
393
      fatal_error(fmt::format(
×
394
        "Cell {} was specified with a density less than or equal to zero",
395
        cell_id));
396
    }
397
  }
398
  return densities;
45 ✔
399
}
×
400

401
//==============================================================================
402
// CSGCell implementation
403
//==============================================================================
404

405
CSGCell::CSGCell(pugi::xml_node cell_node)
20,019 ✔
406
{
407
  if (check_for_node(cell_node, "id")) {
20,019 !
408
    id_ = std::stoi(get_node_value(cell_node, "id"));
40,038 ✔
409
  } else {
410
    fatal_error("Must specify id of cell in geometry XML file.");
×
411
  }
412

413
  if (check_for_node(cell_node, "name")) {
20,019 ✔
414
    name_ = get_node_value(cell_node, "name");
6,607 ✔
415
  }
416

417
  if (check_for_node(cell_node, "universe")) {
20,019 ✔
418
    universe_ = std::stoi(get_node_value(cell_node, "universe"));
38,580 ✔
419
  } else {
420
    universe_ = 0;
729 ✔
421
  }
422

423
  // Make sure that either material or fill was specified, but not both.
424
  bool fill_present = check_for_node(cell_node, "fill");
20,019 ✔
425
  bool material_present = check_for_node(cell_node, "material");
20,019 ✔
426
  if (!(fill_present || material_present)) {
20,019 !
427
    fatal_error(
×
428
      fmt::format("Neither material nor fill was specified for cell {}", id_));
×
429
  }
430
  if (fill_present && material_present) {
20,019 !
431
    fatal_error(fmt::format("Cell {} has both a material and a fill specified; "
×
432
                            "only one can be specified per cell",
433
      id_));
×
434
  }
435

436
  if (fill_present) {
20,019 ✔
437
    fill_ = std::stoi(get_node_value(cell_node, "fill"));
9,748 ✔
438
    if (fill_ == universe_) {
4,874 !
439
      fatal_error(fmt::format("Cell {} is filled with the same universe that "
×
440
                              "it is contained in.",
441
        id_));
×
442
    }
443
  } else {
444
    fill_ = C_NONE;
15,145 ✔
445
  }
446

447
  // Read the material element.  There can be zero materials (filled with a
448
  // universe), more than one material (distribmats), and some materials may
449
  // be "void".
450
  if (material_present) {
20,019 ✔
451
    material_ = parse_cell_material_xml(cell_node, id_);
15,145 ✔
452
  }
453

454
  // Read the temperature element which may be distributed like materials.
455
  if (check_for_node(cell_node, "temperature")) {
20,019 ✔
456
    sqrtkT_ = parse_cell_temperature_xml(cell_node, id_);
259 ✔
457
    sqrtkT_.shrink_to_fit();
259 ✔
458

459
    // Make sure this is a material-filled cell.
460
    if (material_.size() == 0) {
259 !
461
      fatal_error(fmt::format(
×
462
        "Cell {} was specified with a temperature but no material. Temperature"
463
        "specification is only valid for cells filled with a material.",
464
        id_));
×
465
    }
466

467
    // Convert to sqrt(k*T).
468
    for (auto& T : sqrtkT_) {
1,166 ✔
469
      T = std::sqrt(K_BOLTZMANN * T);
907 ✔
470
    }
471
  }
472

473
  // Read the density element which can be distributed similar to temperature.
474
  // These get assigned to the density multiplier, requiring a division by
475
  // the material density.
476
  // Note: calculating the actual density multiplier is deferred until materials
477
  // are finalized. density_mult_ contains the true density in the meantime.
478
  if (check_for_node(cell_node, "density")) {
20,019 ✔
479
    density_mult_ = parse_cell_density_xml(cell_node, id_);
45 ✔
480
    density_mult_.shrink_to_fit();
45 ✔
481

482
    // Make sure this is a material-filled cell.
483
    if (material_.size() == 0) {
45 !
484
      fatal_error(fmt::format(
×
485
        "Cell {} was specified with a density but no material. Density"
486
        "specification is only valid for cells filled with a material.",
487
        id_));
×
488
    }
489

490
    // Make sure this is a non-void material.
491
    for (auto mat_id : material_) {
90 ✔
492
      if (mat_id == MATERIAL_VOID) {
45 !
493
        fatal_error(fmt::format(
×
494
          "Cell {} was specified with a density, but contains a void "
495
          "material. Density specification is only valid for cells "
496
          "filled with a non-void material.",
497
          id_));
×
498
      }
499
    }
500
  }
501

502
  // Read the region specification.
503
  std::string region_spec;
20,019 ✔
504
  if (check_for_node(cell_node, "region")) {
20,019 ✔
505
    region_spec = get_node_value(cell_node, "region");
17,577 ✔
506
  }
507

508
  // Get a tokenized representation of the region specification and apply De
509
  // Morgans law
510
  Region region(region_spec, id_);
20,019 ✔
511
  region_ = region;
20,019 ✔
512

513
  // Read the translation vector.
514
  if (check_for_node(cell_node, "translation")) {
20,019 ✔
515
    if (fill_ == C_NONE) {
1,535 !
516
      fatal_error(fmt::format("Cannot apply a translation to cell {}"
×
517
                              " because it is not filled with another universe",
518
        id_));
×
519
    }
520

521
    auto xyz {get_node_array<double>(cell_node, "translation")};
1,535 ✔
522
    if (xyz.size() != 3) {
1,535 !
523
      fatal_error(
×
524
        fmt::format("Non-3D translation vector applied to cell {}", id_));
×
525
    }
526
    translation_ = xyz;
1,535 ✔
527
  }
1,535 ✔
528

529
  // Read the rotation transform.
530
  if (check_for_node(cell_node, "rotation")) {
20,019 ✔
531
    auto rot {get_node_array<double>(cell_node, "rotation")};
234 ✔
532
    set_rotation(rot);
234 ✔
533
  }
234 ✔
534
}
20,019 ✔
535

536
//==============================================================================
537

538
void CSGCell::to_hdf5_inner(hid_t group_id) const
16,632 ✔
539
{
540
  write_string(group_id, "geom_type", "csg", false);
16,632 ✔
541
  write_string(group_id, "region", region_.str(), false);
16,632 ✔
542
}
16,632 ✔
543

544
//==============================================================================
545

546
vector<int32_t>::iterator CSGCell::find_left_parenthesis(
×
547
  vector<int32_t>::iterator start, const vector<int32_t>& infix)
548
{
549
  // start search at zero
550
  int parenthesis_level = 0;
×
551
  auto it = start;
×
552
  while (it != infix.begin()) {
×
553
    // look at two tokens at a time
554
    int32_t one = *it;
×
555
    int32_t two = *(it - 1);
×
556

557
    // decrement parenthesis level if there are two adjacent surfaces
558
    if (one < OP_UNION && two < OP_UNION) {
×
559
      parenthesis_level--;
×
560
      // increment if there are two adjacent operators
561
    } else if (one >= OP_UNION && two >= OP_UNION) {
×
562
      parenthesis_level++;
×
563
    }
564

565
    // if the level gets to zero, return the position
566
    if (parenthesis_level == 0) {
×
567
      // move the iterator back one before leaving the loop
568
      // so that all tokens in the parenthesis block are included
569
      it--;
×
570
      break;
571
    }
572

573
    // continue loop, one token at a time
574
    it--;
575
  }
576
  return it;
×
577
}
578

579
//==============================================================================
580
// Region implementation
581
//==============================================================================
582

583
Region::Region(std::string region_spec, int32_t cell_id)
20,110 ✔
584
{
585
  // Check if region_spec is not empty.
586
  if (!region_spec.empty()) {
20,110 ✔
587
    // Parse all halfspaces and operators except for intersection (whitespace).
588
    for (int i = 0; i < region_spec.size();) {
105,702 ✔
589
      if (region_spec[i] == '(') {
88,034 ✔
590
        expression_.push_back(OP_LEFT_PAREN);
1,045 ✔
591
        i++;
1,045 ✔
592

593
      } else if (region_spec[i] == ')') {
86,989 ✔
594
        expression_.push_back(OP_RIGHT_PAREN);
1,045 ✔
595
        i++;
1,045 ✔
596

597
      } else if (region_spec[i] == '|') {
85,944 ✔
598
        expression_.push_back(OP_UNION);
2,747 ✔
599
        i++;
2,747 ✔
600

601
      } else if (region_spec[i] == '~') {
83,197 ✔
602
        expression_.push_back(OP_COMPLEMENT);
18 ✔
603
        i++;
18 ✔
604

605
      } else if (region_spec[i] == '-' || region_spec[i] == '+' ||
140,340 ✔
606
                 std::isdigit(region_spec[i])) {
57,161 ✔
607
        // This is the start of a halfspace specification.  Iterate j until we
608
        // find the end, then push-back everything between i and j.
609
        int j = i + 1;
48,602 ✔
610
        while (j < region_spec.size() && std::isdigit(region_spec[j])) {
97,788 ✔
611
          j++;
49,186 ✔
612
        }
613
        expression_.push_back(std::stoi(region_spec.substr(i, j - i)));
97,204 ✔
614
        i = j;
48,602 ✔
615

616
      } else if (std::isspace(region_spec[i])) {
34,577 !
617
        i++;
34,577 ✔
618

619
      } else {
620
        auto err_msg =
×
621
          fmt::format("Region specification contains invalid character, \"{}\"",
622
            region_spec[i]);
×
623
        fatal_error(err_msg);
×
624
      }
×
625
    }
626

627
    // Add in intersection operators where a missing operator is needed.
628
    int i = 0;
629
    while (i < expression_.size() - 1) {
81,644 ✔
630
      bool left_compat {
63,976 ✔
631
        (expression_[i] < OP_UNION) || (expression_[i] == OP_RIGHT_PAREN)};
63,976 ✔
632
      bool right_compat {(expression_[i + 1] < OP_UNION) ||
63,976 ✔
633
                         (expression_[i + 1] == OP_LEFT_PAREN) ||
63,976 ✔
634
                         (expression_[i + 1] == OP_COMPLEMENT)};
3,828 ✔
635
      if (left_compat && right_compat) {
63,976 ✔
636
        expression_.insert(expression_.begin() + i + 1, OP_INTERSECTION);
28,187 ✔
637
      }
638
      i++;
639
    }
640

641
    // Remove complement operators using DeMorgan's laws
642
    auto it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
17,668 ✔
643
    while (it != expression_.end()) {
17,686 ✔
644
      // Erase complement. Note that erase invalidates the iterator, so we have
645
      // to use the iterator it returns, which points to the token that
646
      // followed the complement operator.
647
      it = expression_.erase(it);
18 ✔
648
      if (it == expression_.end())
18 !
649
        break;
650

651
      // Define stop given left parenthesis or not
652
      auto stop = it;
18 ✔
653
      if (*it == OP_LEFT_PAREN) {
18 !
654
        int depth = 1;
655
        do {
144 ✔
656
          stop++;
144 ✔
657
          if (*stop > OP_COMPLEMENT) {
144 ✔
658
            if (*stop == OP_RIGHT_PAREN) {
18 !
659
              depth--;
18 ✔
660
            } else {
661
              depth++;
×
662
            }
663
          }
664
        } while (depth > 0);
144 ✔
665
        it++;
18 ✔
666
      }
667

668
      // apply DeMorgan's law to any surfaces/operators between these
669
      // positions in the RPN
670
      apply_demorgan(it, stop);
18 ✔
671
      // update iterator position
672
      it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
18 ✔
673
    }
674

675
    // Convert user IDs to surface indices.
676
    for (auto& r : expression_) {
99,294 ✔
677
      if (r < OP_UNION) {
81,626 ✔
678
        const auto& it {model::surface_map.find(abs(r))};
48,602 !
679
        if (it == model::surface_map.end()) {
48,602 !
680
          throw std::runtime_error {
×
681
            "Invalid surface ID " + std::to_string(abs(r)) +
×
682
            " specified in region for cell " + std::to_string(cell_id) + "."};
×
683
        }
684
        r = (r > 0) ? it->second + 1 : -(it->second + 1);
48,602 ✔
685
      }
686
    }
687

688
    // Check if this is a simple cell.
689
    simple_ = true;
17,668 ✔
690
    for (int32_t token : expression_) {
89,725 ✔
691
      if (token == OP_UNION) {
72,838 ✔
692
        simple_ = false;
781 ✔
693
        // Ensure intersections have precedence over unions
694
        enforce_precedence();
781 ✔
695
        break;
696
      }
697
    }
698

699
    // If this cell is simple, remove all the superfluous operator tokens.
700
    if (simple_) {
17,668 ✔
701
      expression_.erase(std::remove_if(expression_.begin(), expression_.end(),
16,887 ✔
702
                          [](int32_t token) {
67,611 ✔
703
                            return token == OP_INTERSECTION ||
67,611 ✔
704
                                   token > OP_COMPLEMENT;
62,360 !
705
                          }),
706
        expression_.end());
16,887 ✔
707
    }
708
    expression_.shrink_to_fit();
17,668 ✔
709

710
  } else {
711
    simple_ = true;
2,442 ✔
712
  }
713
}
20,110 ✔
714

715
//==============================================================================
716

717
void Region::apply_demorgan(
18 ✔
718
  vector<int32_t>::iterator start, vector<int32_t>::iterator stop)
719
{
720
  do {
126 ✔
721
    if (*start < OP_UNION) {
126 ✔
722
      *start *= -1;
72 ✔
723
    } else if (*start == OP_UNION) {
54 !
724
      *start = OP_INTERSECTION;
×
725
    } else if (*start == OP_INTERSECTION) {
54 !
726
      *start = OP_UNION;
54 ✔
727
    }
728
    start++;
126 ✔
729
  } while (start < stop);
126 ✔
730
}
18 ✔
731

732
//==============================================================================
733
//! Add precedence for infix regions so intersections have higher
734
//! precedence than unions using parentheses.
735
//==============================================================================
736

737
void Region::add_parentheses(int64_t start)
60 ✔
738
{
739
  int32_t start_token = expression_[start];
60 !
740
  // Add left parenthesis and set new position to be after parenthesis
741
  if (start_token == OP_UNION) {
60 !
742
    start += 2;
×
743
  }
744
  expression_.insert(expression_.begin() + start - 1, OP_LEFT_PAREN);
60 ✔
745

746
  // Add right parenthesis
747
  // While the start iterator is within the bounds of infix
748
  while (start + 1 < expression_.size()) {
266 ✔
749
    start++;
252 ✔
750

751
    // If the current token is an operator and is different than the start token
752
    if (expression_[start] >= OP_UNION && expression_[start] != start_token) {
252 ✔
753
      // Skip wrapped regions but save iterator position to check precedence and
754
      // add right parenthesis, right parenthesis position depends on the
755
      // operator, when the operator is a union then do not include the operator
756
      // in the region, when the operator is an intersection then include the
757
      // operator and next surface
758
      if (expression_[start] == OP_LEFT_PAREN) {
53 ✔
759
        int depth = 1;
760
        do {
28 ✔
761
          start++;
28 ✔
762
          if (expression_[start] > OP_COMPLEMENT) {
28 ✔
763
            if (expression_[start] == OP_RIGHT_PAREN) {
7 !
764
              depth--;
7 ✔
765
            } else {
766
              depth++;
×
767
            }
768
          }
769
        } while (depth > 0);
28 ✔
770
      } else {
771
        if (start_token == OP_UNION) {
46 !
772
          --start;
×
773
        }
774
        expression_.insert(expression_.begin() + start, OP_RIGHT_PAREN);
46 ✔
775
        return;
46 ✔
776
      }
777
    }
778
  }
779
  // If we get here a right parenthesis hasn't been placed
780
  expression_.push_back(OP_RIGHT_PAREN);
14 ✔
781
}
782

783
//==============================================================================
784
//! Add parentheses to enforce operator precedence in region expressions
785
//!
786
//! This function ensures that intersection operators have higher precedence
787
//! than union operators by adding parentheses where needed. For example:
788
//!   "1 2 | 3" becomes "(1 2) | 3"
789
//!   "1 | 2 3" becomes "1 | (2 3)"
790
//!
791
//! The algorithm uses stacks to track the current operator type and its
792
//! position at each parenthesis depth level. When it encounters a different
793
//! operator at the same depth, it adds parentheses to group the
794
//! higher-precedence operations.
795
//==============================================================================
796

797
void Region::enforce_precedence()
781 ✔
798
{
799
  // Stack tracking the operator type at each depth (0 = no operator seen yet)
800
  vector<int32_t> op_stack = {0};
781 ✔
801

802
  // Stack tracking where the operator sequence started at each depth
803
  vector<std::size_t> pos_stack = {0};
781 ✔
804

805
  for (int64_t i = 0; i < expression_.size(); ++i) {
15,429 ✔
806
    int32_t token = expression_[i];
14,648 ✔
807

808
    if (token == OP_LEFT_PAREN) {
14,648 ✔
809
      // Entering a new parenthesis level - push new tracking state
810
      op_stack.push_back(0);
1,167 ✔
811
      pos_stack.push_back(0);
1,167 ✔
812
      continue;
1,167 ✔
813
    } else if (token == OP_RIGHT_PAREN) {
13,481 ✔
814
      // Exiting a parenthesis level - pop tracking state (keep at least one)
815
      if (op_stack.size() > 1) {
1,142 !
816
        op_stack.pop_back();
1,142 ✔
817
        pos_stack.pop_back();
1,142 ✔
818
      }
819
      continue;
1,142 ✔
820
    }
821

822
    if (token == OP_UNION || token == OP_INTERSECTION) {
12,339 ✔
823
      if (op_stack.back() == 0) {
5,779 ✔
824
        // First operator at this depth - record it and its position
825
        op_stack.back() = token;
1,976 ✔
826
        pos_stack.back() = i;
1,976 ✔
827
      } else if (token != op_stack.back()) {
3,803 ✔
828
        // Encountered a different operator at the same depth - need to add
829
        // parentheses to enforce precedence. Intersection has higher
830
        // precedence, so we parenthesize the intersection terms.
831
        if (op_stack.back() == OP_INTERSECTION) {
60 ✔
832
          add_parentheses(pos_stack.back());
30 ✔
833
        } else {
834
          add_parentheses(i);
30 ✔
835
        }
836

837
        // Restart the scan since we modified the expression
838
        i = -1; // Will be incremented to 0 by the for loop
60 ✔
839
        op_stack = {0};
60 ✔
840
        pos_stack = {0};
60 ✔
841
      }
842
    }
843
  }
844
}
781 ✔
845

846
//==============================================================================
847
//! Convert infix region specification to Reverse Polish Notation (RPN)
848
//!
849
//! This function uses the shunting-yard algorithm.
850
//==============================================================================
851

852
vector<int32_t> Region::generate_postfix(int32_t cell_id) const
28 ✔
853
{
854
  vector<int32_t> rpn;
28 ✔
855
  vector<int32_t> stack;
28 ✔
856

857
  for (int32_t token : expression_) {
630 ✔
858
    if (token < OP_UNION) {
602 ✔
859
      // If token is not an operator, add it to output
860
      rpn.push_back(token);
252 ✔
861
    } else if (token < OP_RIGHT_PAREN) {
350 ✔
862
      // Regular operators union, intersection, complement
863
      while (stack.size() > 0) {
357 ✔
864
        int32_t op = stack.back();
294 ✔
865

866
        if (op < OP_RIGHT_PAREN && ((token == OP_COMPLEMENT && token < op) ||
294 !
867
                                     (token != OP_COMPLEMENT && token <= op))) {
133 !
868
          // While there is an operator, op, on top of the stack, if the token
869
          // is left-associative and its precedence is less than or equal to
870
          // that of op or if the token is right-associative and its precedence
871
          // is less than that of op, move op to the output queue and push the
872
          // token on to the stack. Note that only complement is
873
          // right-associative.
874
          rpn.push_back(op);
133 ✔
875
          stack.pop_back();
133 ✔
876
        } else {
877
          break;
878
        }
879
      }
880

881
      stack.push_back(token);
224 ✔
882

883
    } else if (token == OP_LEFT_PAREN) {
126 ✔
884
      // If the token is a left parenthesis, push it onto the stack
885
      stack.push_back(token);
63 ✔
886

887
    } else {
888
      // If the token is a right parenthesis, move operators from the stack to
889
      // the output queue until reaching the left parenthesis.
890
      for (auto it = stack.rbegin(); *it != OP_LEFT_PAREN; it++) {
126 ✔
891
        // If we run out of operators without finding a left parenthesis, it
892
        // means there are mismatched parentheses.
893
        if (it == stack.rend()) {
63 !
894
          fatal_error(fmt::format(
×
895
            "Mismatched parentheses in region specification for cell {}",
896
            cell_id));
897
        }
898
        rpn.push_back(stack.back());
63 ✔
899
        stack.pop_back();
63 ✔
900
      }
901

902
      // Pop the left parenthesis.
903
      stack.pop_back();
602 ✔
904
    }
905
  }
906

907
  while (stack.size() > 0) {
28 ✔
908
    int32_t op = stack.back();
28 !
909

910
    // If the operator is a parenthesis it is mismatched.
911
    if (op >= OP_RIGHT_PAREN) {
28 !
912
      fatal_error(fmt::format(
×
913
        "Mismatched parentheses in region specification for cell {}", cell_id));
914
    }
915

916
    rpn.push_back(stack.back());
28 ✔
917
    stack.pop_back();
56 ✔
918
  }
919

920
  return rpn;
28 ✔
921
}
28 ✔
922

923
//==============================================================================
924

925
std::string Region::str() const
16,695 ✔
926
{
927
  std::stringstream region_spec {};
16,695 ✔
928
  if (!expression_.empty()) {
16,695 ✔
929
    for (int32_t token : expression_) {
62,903 ✔
930
      if (token == OP_LEFT_PAREN) {
48,180 ✔
931
        region_spec << " (";
993 ✔
932
      } else if (token == OP_RIGHT_PAREN) {
47,187 ✔
933
        region_spec << " )";
993 ✔
934
      } else if (token == OP_COMPLEMENT) {
46,194 !
935
        region_spec << " ~";
×
936
      } else if (token == OP_INTERSECTION) {
46,194 ✔
937
      } else if (token == OP_UNION) {
43,721 ✔
938
        region_spec << " |";
2,549 ✔
939
      } else {
940
        // Note the off-by-one indexing
941
        auto surf_id = model::surfaces[abs(token) - 1]->id_;
41,172 ✔
942
        region_spec << " " << ((token > 0) ? surf_id : -surf_id);
41,172 ✔
943
      }
944
    }
945
  }
946
  return region_spec.str();
33,390 ✔
947
}
16,695 ✔
948

949
//==============================================================================
950

951
std::pair<double, int32_t> Region::distance(
2,147,483,647 ✔
952
  Position r, Direction u, int32_t on_surface) const
953
{
954
  if (simple_) {
2,147,483,647 ✔
955
    return distance_to_nearest_surface(r, u, on_surface, false);
2,147,483,647 ✔
956
  } else {
957
    return distance_complex(r, u, on_surface);
116,627,428 ✔
958
  }
959
}
960

961
//==============================================================================
962

963
std::pair<double, int32_t> Region::distance_to_nearest_surface(Position r,
2,147,483,647 ✔
964
  Direction u, int32_t on_surface, bool ignore_coincident_surfaces) const
965
{
966
  double min_dist {INFTY};
2,147,483,647 ✔
967
  int32_t i_surf {std::numeric_limits<int32_t>::max()};
2,147,483,647 ✔
968

969
  for (int32_t token : expression_) {
×
970
    // Ignore this token if it corresponds to an operator rather than a region.
971
    if (token >= OP_UNION)
✔
972
      continue;
2,147,483,647 ✔
973

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

979
    // Different surface definitions can represent the same geometric surface.
980
    // When the ray is already known to be on a surface, ignore intersections
981
    // with other surfaces at the same location to avoid repeatedly crossing
982
    // between them due to roundoff.
983
    if (ignore_coincident_surfaces && d < FP_COINCIDENT)
2,147,483,647 ✔
984
      continue;
7 ✔
985

986
    // Check if this distance is the new minimum.
987
    if (d < min_dist) {
2,147,483,647 ✔
988
      if (min_dist - d >= FP_PRECISION * min_dist) {
2,147,483,647 !
989
        min_dist = d;
2,147,483,647 ✔
990
        i_surf = -token;
2,147,483,647 ✔
991
      }
992
    }
993
  }
994

995
  return {min_dist, i_surf};
2,147,483,647 ✔
996
}
997

998
//==============================================================================
999

1000
std::pair<double, int32_t> Region::distance_complex(
116,627,428 ✔
1001
  Position r, Direction u, int32_t on_surface) const
1002
{
1003
  const bool in_region = contains_complex(r, u, on_surface);
116,627,428 ✔
1004
  double total_distance {0.0};
1005

1006
  while (true) {
665,788,184 ✔
1007
    auto [distance, i_surf] =
782,415,612 ✔
1008
      distance_to_nearest_surface(r, u, on_surface, on_surface != 0);
391,207,806 ✔
1009
    if (distance == INFTY) {
391,207,806 ✔
1010
      return {INFTY, std::numeric_limits<int32_t>::max()};
1,066,690 ✔
1011
    }
1012

1013
    // Move to the candidate surface and determine which side of it the ray is
1014
    // entering. The surface normal is used instead of evaluating the surface
1015
    // equation because accumulated roundoff may place the point slightly to
1016
    // the wrong side of a curved surface.
1017
    r += distance * u;
390,141,116 ✔
1018
    total_distance += distance;
390,141,116 ✔
1019
    i_surf = std::abs(i_surf);
390,141,116 ✔
1020
    const auto& surf {*model::surfaces[i_surf - 1]};
390,141,116 ✔
1021
    if (u.dot(surf.normal(r)) <= 0.0) {
390,141,116 ✔
1022
      i_surf = -i_surf;
134,648,635 ✔
1023
    }
1024

1025
    // If crossing the candidate changes the region membership, it is a true
1026
    // boundary. Otherwise, continue the search from the virtual crossing.
1027
    if (contains_complex(r, u, i_surf) != in_region) {
390,141,116 ✔
1028
      return {total_distance, i_surf};
115,560,738 ✔
1029
    }
1030
    on_surface = i_surf;
274,580,378 ✔
1031
  }
274,580,378 ✔
1032
}
1033

1034
//==============================================================================
1035

1036
bool Region::contains(Position r, Direction u, int32_t on_surface) const
2,147,483,647 ✔
1037
{
1038
  if (simple_) {
2,147,483,647 ✔
1039
    return contains_simple(r, u, on_surface);
2,147,483,647 ✔
1040
  } else {
1041
    return contains_complex(r, u, on_surface);
16,087,409 ✔
1042
  }
1043
}
1044

1045
//==============================================================================
1046

1047
bool Region::contains_simple(Position r, Direction u, int32_t on_surface) const
2,147,483,647 ✔
1048
{
1049
  for (int32_t token : expression_) {
2,147,483,647 ✔
1050
    // Assume that no tokens are operators. Evaluate the sense of particle with
1051
    // respect to the surface and see if the token matches the sense. If the
1052
    // particle's surface attribute is set and matches the token, that
1053
    // overrides the determination based on sense().
1054
    if (token == on_surface) {
2,147,483,647 ✔
1055
    } else if (-token == on_surface) {
2,147,483,647 ✔
1056
      return false;
1057
    } else {
1058
      // Note the off-by-one indexing
1059
      bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
2,147,483,647 ✔
1060
      if (sense != (token > 0)) {
2,147,483,647 ✔
1061
        return false;
1062
      }
1063
    }
1064
  }
1065
  return true;
1066
}
1067

1068
//==============================================================================
1069

1070
bool Region::contains_complex(Position r, Direction u, int32_t on_surface) const
522,855,953 ✔
1071
{
1072
  bool in_cell = true;
522,855,953 ✔
1073
  int total_depth = 0;
522,855,953 ✔
1074

1075
  // For each token
1076
  for (auto it = expression_.begin(); it != expression_.end(); it++) {
2,147,483,647 ✔
1077
    int32_t token = *it;
2,147,483,647 ✔
1078

1079
    // If the token is a surface evaluate the sense
1080
    // If the token is a union or intersection check to
1081
    // short circuit
1082
    if (token < OP_UNION) {
2,147,483,647 ✔
1083
      if (token == on_surface) {
2,005,551,668 ✔
1084
        in_cell = true;
1085
      } else if (-token == on_surface) {
1,976,638,976 ✔
1086
        in_cell = false;
1087
      } else {
1088
        // Note the off-by-one indexing
1089
        bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
1,827,009,402 ✔
1090
        in_cell = (sense == (token > 0));
1,827,009,402 ✔
1091
      }
1092
    } else if ((token == OP_UNION && in_cell == true) ||
2,147,483,647 ✔
1093
               (token == OP_INTERSECTION && in_cell == false)) {
1,035,022,112 ✔
1094
      // If the total depth is zero return
1095
      if (total_depth == 0) {
934,259,066 ✔
1096
        return in_cell;
120,372,561 ✔
1097
      }
1098

1099
      total_depth--;
813,886,505 ✔
1100

1101
      // While the iterator is within the bounds of the vector
1102
      int depth = 1;
813,886,505 ✔
1103
      do {
2,147,483,647 ✔
1104
        // Get next token
1105
        it++;
2,147,483,647 ✔
1106
        int32_t next_token = *it;
2,147,483,647 ✔
1107

1108
        // If the token is an a parenthesis
1109
        if (next_token > OP_COMPLEMENT) {
2,147,483,647 ✔
1110
          // Adjust depth accordingly
1111
          if (next_token == OP_RIGHT_PAREN) {
1,014,773,977 ✔
1112
            depth--;
914,330,241 ✔
1113
          } else {
1114
            depth++;
100,443,736 ✔
1115
          }
1116
        }
1117
      } while (depth > 0);
2,147,483,647 ✔
1118
    } else if (token == OP_LEFT_PAREN) {
2,147,483,647 ✔
1119
      total_depth++;
844,672,419 ✔
1120
    } else if (token == OP_RIGHT_PAREN) {
1,513,481,629 ✔
1121
      total_depth--;
30,785,914 ✔
1122
    }
1123
  }
1124
  return in_cell;
1125
}
1126

1127
//==============================================================================
1128

1129
BoundingBox Region::bounding_box(int32_t cell_id) const
63 ✔
1130
{
1131
  if (simple_) {
63 ✔
1132
    return bounding_box_simple();
35 ✔
1133
  } else {
1134
    auto postfix = generate_postfix(cell_id);
28 ✔
1135
    return bounding_box_complex(postfix);
56 ✔
1136
  }
28 ✔
1137
}
1138

1139
//==============================================================================
1140

1141
BoundingBox Region::bounding_box_simple() const
35 ✔
1142
{
1143
  BoundingBox bbox;
35 ✔
1144
  for (int32_t token : expression_) {
140 ✔
1145
    bbox &= model::surfaces[abs(token) - 1]->bounding_box(token > 0);
105 ✔
1146
  }
1147
  return bbox;
35 ✔
1148
}
1149

1150
//==============================================================================
1151

1152
BoundingBox Region::bounding_box_complex(vector<int32_t> postfix) const
28 ✔
1153
{
1154
  vector<BoundingBox> stack(postfix.size());
28 ✔
1155
  int i_stack = -1;
28 ✔
1156

1157
  for (auto& token : postfix) {
504 ✔
1158
    if (token == OP_UNION) {
476 ✔
1159
      stack[i_stack - 1] = stack[i_stack - 1] | stack[i_stack];
98 ✔
1160
      i_stack--;
98 ✔
1161
    } else if (token == OP_INTERSECTION) {
378 ✔
1162
      stack[i_stack - 1] = stack[i_stack - 1] & stack[i_stack];
126 ✔
1163
      i_stack--;
126 ✔
1164
    } else {
1165
      i_stack++;
252 ✔
1166
      stack[i_stack] = model::surfaces[abs(token) - 1]->bounding_box(token > 0);
252 ✔
1167
    }
1168
  }
1169

1170
  assert(i_stack == 0);
28 !
1171
  return stack.front();
28 ✔
1172
}
28 ✔
1173

1174
//==============================================================================
1175

1176
vector<int32_t> Region::surfaces() const
3,178 ✔
1177
{
1178
  if (simple_) {
3,178 ✔
1179
    return expression_;
3,166 ✔
1180
  }
1181

1182
  vector<int32_t> surfaces = expression_;
12 ✔
1183

1184
  auto it = std::find_if(surfaces.begin(), surfaces.end(),
12 ✔
1185
    [&](const auto& value) { return value >= OP_UNION; });
12 !
1186

1187
  while (it != surfaces.end()) {
36 ✔
1188
    surfaces.erase(it);
24 ✔
1189

1190
    it = std::find_if(surfaces.begin(), surfaces.end(),
24 ✔
1191
      [&](const auto& value) { return value >= OP_UNION; });
48 !
1192
  }
1193

1194
  return surfaces;
12 ✔
1195
}
3,178 ✔
1196

1197
//==============================================================================
1198
// Non-method functions
1199
//==============================================================================
1200

1201
void read_cells(pugi::xml_node node)
6,032 ✔
1202
{
1203
  // Count the number of cells.
1204
  auto cell_nodes = node.children("cell");
6,032 ✔
1205
  int n_cells = std::distance(cell_nodes.begin(), cell_nodes.end());
6,032 ✔
1206

1207
  // Loop over XML cell elements and populate the array.
1208
  model::cells.reserve(n_cells);
6,032 ✔
1209
  for (pugi::xml_node cell_node : node.children("cell")) {
26,030 ✔
1210
    model::cells.push_back(make_unique<CSGCell>(cell_node));
19,998 ✔
1211
  }
1212

1213
  // Fill the cell map.
1214
  for (int i = 0; i < model::cells.size(); i++) {
26,030 ✔
1215
    int32_t id = model::cells[i]->id_;
19,998 !
1216
    auto search = model::cell_map.find(id);
19,998 !
1217
    if (search == model::cell_map.end()) {
19,998 !
1218
      model::cell_map[id] = i;
19,998 ✔
1219
    } else {
1220
      fatal_error(
×
1221
        fmt::format("Two or more cells use the same unique ID: {}", id));
×
1222
    }
1223
  }
1224

1225
  read_dagmc_universes(node);
6,032 ✔
1226
  read_xdg_universes(node);
6,032 ✔
1227

1228
  populate_universes();
6,032 ✔
1229

1230
  // Allocate the cell overlap count if necessary.
1231
  if (settings::check_overlaps) {
6,032 ✔
1232
    model::overlap_check_count.resize(model::cells.size(), 0);
77 ✔
1233
  }
1234

1235
  if (model::cells.size() == 0) {
6,032 !
1236
    fatal_error("No cells were found in the geometry.xml file");
×
1237
  }
1238
}
6,032 ✔
1239

1240
void populate_universes()
6,032 ✔
1241
{
1242
  // Used to map universe index to the index of an implicit complement cell for
1243
  // DAGMC universes
1244
  std::unordered_map<int, int> implicit_comp_cells;
6,032 ✔
1245

1246
  // Populate the Universe vector and map.
1247
  for (int index_cell = 0; index_cell < model::cells.size(); index_cell++) {
26,030 ✔
1248
    int32_t uid = model::cells[index_cell]->universe_;
19,998 ✔
1249
    auto it = model::universe_map.find(uid);
19,998 ✔
1250
    if (it == model::universe_map.end()) {
19,998 ✔
1251
      model::universes.push_back(make_unique<Universe>());
20,282 ✔
1252
      model::universes.back()->id_ = uid;
10,141 ✔
1253
      model::universes.back()->cells_.push_back(index_cell);
10,141 ✔
1254
      model::universe_map[uid] = model::universes.size() - 1;
10,141 ✔
1255
    } else {
1256
#ifdef OPENMC_DAGMC_ENABLED
1257
      // Skip implicit complement cells for now
1258
      Universe* univ = model::universes[it->second].get();
1259
      DAGUniverse* dag_univ = dynamic_cast<DAGUniverse*>(univ);
1260
      if (dag_univ && (dag_univ->implicit_complement_idx() == index_cell)) {
1261
        implicit_comp_cells[it->second] = index_cell;
1262
        continue;
1263
      }
1264
#endif
1265

1266
      model::universes[it->second]->cells_.push_back(index_cell);
9,857 ✔
1267
    }
1268
  }
1269

1270
  // Add DAGUniverse implicit complement cells last
1271
  for (const auto& it : implicit_comp_cells) {
6,032 !
UNCOV
1272
    int index_univ = it.first;
×
UNCOV
1273
    int index_cell = it.second;
×
UNCOV
1274
    model::universes[index_univ]->cells_.push_back(index_cell);
×
1275
  }
1276

1277
  model::universes.shrink_to_fit();
6,032 ✔
1278
}
6,032 ✔
1279

1280
//==============================================================================
1281
// C-API functions
1282
//==============================================================================
1283

1284
extern "C" int openmc_cell_get_fill(
84 ✔
1285
  int32_t index, int* type, int32_t** indices, int32_t* n)
1286
{
1287
  if (index >= 0 && index < model::cells.size()) {
84 !
1288
    Cell& c {*model::cells[index]};
84 ✔
1289
    *type = static_cast<int>(c.type_);
84 ✔
1290
    if (c.type_ == Fill::MATERIAL) {
84 ✔
1291
      *indices = c.material_.data();
77 ✔
1292
      *n = c.material_.size();
77 ✔
1293
    } else {
1294
      *indices = &c.fill_;
7 ✔
1295
      *n = 1;
7 ✔
1296
    }
1297
  } else {
1298
    set_errmsg("Index in cells array is out of bounds.");
×
1299
    return OPENMC_E_OUT_OF_BOUNDS;
×
1300
  }
1301
  return 0;
1302
}
1303

1304
extern "C" int openmc_cell_set_fill(
7 ✔
1305
  int32_t index, int type, int32_t n, const int32_t* indices)
1306
{
1307
  Fill filltype = static_cast<Fill>(type);
7 ✔
1308
  if (index >= 0 && index < model::cells.size()) {
7 !
1309
    Cell& c {*model::cells[index]};
7 !
1310
    if (filltype == Fill::MATERIAL) {
7 !
1311
      c.type_ = Fill::MATERIAL;
7 ✔
1312
      c.material_.clear();
7 !
1313
      for (int i = 0; i < n; i++) {
14 ✔
1314
        int i_mat = indices[i];
7 ✔
1315
        if (i_mat == MATERIAL_VOID) {
7 !
1316
          c.material_.push_back(MATERIAL_VOID);
×
1317
        } else if (i_mat >= 0 && i_mat < model::materials.size()) {
7 !
1318
          c.material_.push_back(i_mat);
7 ✔
1319
        } else {
1320
          set_errmsg("Index in materials array is out of bounds.");
×
1321
          return OPENMC_E_OUT_OF_BOUNDS;
×
1322
        }
1323
      }
1324
      c.material_.shrink_to_fit();
7 ✔
1325
    } else if (filltype == Fill::UNIVERSE) {
×
1326
      c.type_ = Fill::UNIVERSE;
×
1327
    } else {
1328
      c.type_ = Fill::LATTICE;
×
1329
    }
1330
  } else {
1331
    set_errmsg("Index in cells array is out of bounds.");
×
1332
    return OPENMC_E_OUT_OF_BOUNDS;
×
1333
  }
1334
  return 0;
1335
}
1336

1337
extern "C" int openmc_cell_set_temperature(
56 ✔
1338
  int32_t index, double T, const int32_t* instance, bool set_contained)
1339
{
1340
  if (index < 0 || index >= model::cells.size()) {
56 !
1341
    set_errmsg("Index in cells array is out of bounds.");
×
1342
    return OPENMC_E_OUT_OF_BOUNDS;
×
1343
  }
1344

1345
  int32_t instance_index = instance ? *instance : -1;
56 ✔
1346
  try {
56 ✔
1347
    model::cells[index]->set_temperature(T, instance_index, set_contained);
56 ✔
1348
  } catch (const std::exception& e) {
×
1349
    set_errmsg(e.what());
×
1350
    return OPENMC_E_UNASSIGNED;
×
1351
  }
×
1352
  return 0;
1353
}
1354

1355
extern "C" int openmc_cell_set_density(
56 ✔
1356
  int32_t index, double density, const int32_t* instance, bool set_contained)
1357
{
1358
  if (index < 0 || index >= model::cells.size()) {
56 !
1359
    set_errmsg("Index in cells array is out of bounds.");
×
1360
    return OPENMC_E_OUT_OF_BOUNDS;
×
1361
  }
1362

1363
  int32_t instance_index = instance ? *instance : -1;
56 ✔
1364
  try {
56 ✔
1365
    model::cells[index]->set_density(density, instance_index, set_contained);
56 ✔
1366
  } catch (const std::exception& e) {
×
1367
    set_errmsg(e.what());
×
1368
    return OPENMC_E_UNASSIGNED;
×
1369
  }
×
1370
  return 0;
1371
}
1372

1373
extern "C" int openmc_cell_get_temperature(
6,125 ✔
1374
  int32_t index, const int32_t* instance, double* T)
1375
{
1376
  if (index < 0 || index >= model::cells.size()) {
6,125 !
1377
    set_errmsg("Index in cells array is out of bounds.");
×
1378
    return OPENMC_E_OUT_OF_BOUNDS;
×
1379
  }
1380

1381
  int32_t instance_index = instance ? *instance : -1;
6,125 ✔
1382
  try {
6,125 ✔
1383
    *T = model::cells[index]->temperature(instance_index);
6,125 ✔
1384
  } catch (const std::exception& e) {
×
1385
    set_errmsg(e.what());
×
1386
    return OPENMC_E_UNASSIGNED;
×
1387
  }
×
1388
  return 0;
6,125 ✔
1389
}
1390

1391
extern "C" int openmc_cell_get_density(
56 ✔
1392
  int32_t index, const int32_t* instance, double* density)
1393
{
1394
  if (index < 0 || index >= model::cells.size()) {
56 !
1395
    set_errmsg("Index in cells array is out of bounds.");
×
1396
    return OPENMC_E_OUT_OF_BOUNDS;
×
1397
  }
1398

1399
  int32_t instance_index = instance ? *instance : -1;
56 ✔
1400
  try {
56 ✔
1401
    if (model::cells[index]->type_ != Fill::MATERIAL) {
56 !
1402
      fatal_error(
×
1403
        fmt::format("Cell {}, instance {} is not filled with a material.",
×
1404
          model::cells[index]->id_, instance_index));
×
1405
    }
1406

1407
    int32_t mat_index = model::cells[index]->material(instance_index);
56 ✔
1408
    if (mat_index == MATERIAL_VOID) {
56 !
1409
      *density = 0.0;
×
1410
    } else {
1411
      *density = model::cells[index]->density_mult(instance_index) *
56 ✔
1412
                 model::materials[mat_index]->density_gpcc();
112 !
1413
    }
1414
  } catch (const std::exception& e) {
×
1415
    set_errmsg(e.what());
×
1416
    return OPENMC_E_UNASSIGNED;
×
1417
  }
×
1418
  return 0;
1419
}
1420

1421
//! Get the bounding box of a cell
1422
extern "C" int openmc_cell_bounding_box(
42 ✔
1423
  const int32_t index, double* llc, double* urc)
1424
{
1425

1426
  BoundingBox bbox;
42 ✔
1427

1428
  const auto& c = model::cells[index];
42 ✔
1429
  bbox = c->bounding_box();
42 ✔
1430

1431
  // set lower left corner values
1432
  llc[0] = bbox.min.x;
42 ✔
1433
  llc[1] = bbox.min.y;
42 ✔
1434
  llc[2] = bbox.min.z;
42 ✔
1435

1436
  // set upper right corner values
1437
  urc[0] = bbox.max.x;
42 ✔
1438
  urc[1] = bbox.max.y;
42 ✔
1439
  urc[2] = bbox.max.z;
42 ✔
1440

1441
  return 0;
42 ✔
1442
}
1443

1444
//! Get the name of a cell
1445
extern "C" int openmc_cell_get_name(int32_t index, const char** name)
238 ✔
1446
{
1447
  if (index < 0 || index >= model::cells.size()) {
238 !
1448
    set_errmsg("Index in cells array is out of bounds.");
×
1449
    return OPENMC_E_OUT_OF_BOUNDS;
×
1450
  }
1451

1452
  *name = model::cells[index]->name().data();
238 ✔
1453

1454
  return 0;
238 ✔
1455
}
1456

1457
//! Set the name of a cell
1458
extern "C" int openmc_cell_set_name(int32_t index, const char* name)
7 ✔
1459
{
1460
  if (index < 0 || index >= model::cells.size()) {
7 !
1461
    set_errmsg("Index in cells array is out of bounds.");
×
1462
    return OPENMC_E_OUT_OF_BOUNDS;
×
1463
  }
1464

1465
  model::cells[index]->set_name(name);
14 ✔
1466

1467
  return 0;
7 ✔
1468
}
1469

1470
//==============================================================================
1471
//! Define a containing (parent) cell
1472
//==============================================================================
1473

1474
//! Used to locate a universe fill in the geometry
1475
struct ParentCell {
1476
  bool operator==(const ParentCell& other) const
81 ✔
1477
  {
1478
    return cell_index == other.cell_index &&
81 !
1479
           lattice_index == other.lattice_index;
81 !
1480
  }
1481

1482
  bool operator<(const ParentCell& other) const
1483
  {
1484
    return cell_index < other.cell_index ||
1485
           (cell_index == other.cell_index &&
1486
             lattice_index < other.lattice_index);
1487
  }
1488

1489
  int64_t cell_index;
1490
  int64_t lattice_index;
1491
};
1492

1493
//! Structure used to insert ParentCell into hashed STL data structures
1494
struct ParentCellHash {
1495
  std::size_t operator()(const ParentCell& p) const
468 ✔
1496
  {
1497
    return 4096 * p.cell_index + p.lattice_index;
468 !
1498
  }
1499
};
1500

1501
//! Used to manage a traversal stack when locating parent cells of a cell
1502
//! instance in the model
1503
struct ParentCellStack {
90 ✔
1504

1505
  //! push method that adds to the parent_cells visited cells for this search
1506
  //! universe
1507
  void push(int32_t search_universe, const ParentCell& pc)
63 ✔
1508
  {
1509
    parent_cells_.push_back(pc);
63 ✔
1510
    // add parent cell to the set of cells we've visited for this search
1511
    // universe
1512
    visited_cells_[search_universe].insert(pc);
63 ✔
1513
  }
63 ✔
1514

1515
  //! removes the last parent_cell and clears the visited cells for the popped
1516
  //! cell's universe
1517
  void pop()
45 ✔
1518
  {
1519
    visited_cells_[this->current_univ()].clear();
45 ✔
1520
    parent_cells_.pop_back();
45 ✔
1521
  }
45 ✔
1522

1523
  //! checks whether or not the parent cell has been visited already for this
1524
  //! search universe
1525
  bool visited(int32_t search_universe, const ParentCell& parent_cell)
405 ✔
1526
  {
1527
    return visited_cells_[search_universe].count(parent_cell) != 0;
405 ✔
1528
  }
1529

1530
  //! return the next universe to search for a parent cell
1531
  int32_t current_univ() const
45 ✔
1532
  {
1533
    return model::cells[parent_cells_.back().cell_index]->universe_;
45 ✔
1534
  }
1535

1536
  //! indicates whether nor not parent cells are present on the stack
1537
  bool empty() const { return parent_cells_.empty(); }
45 ✔
1538

1539
  //! compute an instance for the provided distribcell index
1540
  int32_t compute_instance(int32_t distribcell_index) const
135 ✔
1541
  {
1542
    if (distribcell_index == C_NONE)
135 ✔
1543
      return 0;
1544

1545
    int32_t instance = 0;
72 ✔
1546
    for (const auto& parent_cell : this->parent_cells_) {
135 ✔
1547
      auto& cell = model::cells[parent_cell.cell_index];
63 !
1548
      if (cell->type_ == Fill::UNIVERSE) {
63 !
1549
        instance += cell->offset_[distribcell_index];
×
1550
      } else if (cell->type_ == Fill::LATTICE) {
63 !
1551
        auto& lattice = model::lattices[cell->fill_];
63 ✔
1552
        instance +=
63 ✔
1553
          lattice->offset(distribcell_index, parent_cell.lattice_index);
63 ✔
1554
      }
1555
    }
1556
    return instance;
1557
  }
1558

1559
  // Accessors
1560
  vector<ParentCell>& parent_cells() { return parent_cells_; }
90 ✔
1561
  const vector<ParentCell>& parent_cells() const { return parent_cells_; }
1562

1563
  // Data Members
1564
  vector<ParentCell> parent_cells_;
1565
  std::unordered_map<int32_t, std::unordered_set<ParentCell, ParentCellHash>>
1566
    visited_cells_;
1567
};
1568

1569
vector<ParentCell> Cell::find_parent_cells(
×
1570
  int32_t instance, const Position& r) const
1571
{
1572

1573
  // create a temporary particle
1574
  GeometryState dummy_particle {};
×
1575
  dummy_particle.r() = r;
×
1576
  dummy_particle.u() = {0., 0., 1.};
×
1577

1578
  return find_parent_cells(instance, dummy_particle);
×
1579
}
×
1580

1581
vector<ParentCell> Cell::find_parent_cells(
×
1582
  int32_t instance, GeometryState& p) const
1583
{
1584
  // look up the particle's location
1585
  exhaustive_find_cell(p);
×
1586
  const auto& coords = p.coord();
×
1587

1588
  // build a parent cell stack from the particle coordinates
1589
  ParentCellStack stack;
×
1590
  bool cell_found = false;
×
1591
  for (auto it = coords.begin(); it != coords.end(); it++) {
×
1592
    const auto& coord = *it;
×
1593
    const auto& cell = model::cells[coord.cell()];
×
1594
    // if the cell at this level matches the current cell, stop adding to the
1595
    // stack
1596
    if (coord.cell() == model::cell_map[this->id_]) {
×
1597
      cell_found = true;
1598
      break;
1599
    }
1600

1601
    // if filled with a lattice, get the lattice index from the next
1602
    // level in the coordinates to push to the stack
1603
    int lattice_idx = C_NONE;
×
1604
    if (cell->type_ == Fill::LATTICE) {
×
1605
      const auto& next_coord = *(it + 1);
×
1606
      lattice_idx = model::lattices[next_coord.lattice()]->get_flat_index(
×
UNCOV
1607
        next_coord.lattice_index());
×
1608
    }
1609
    stack.push(coord.universe(), {coord.cell(), lattice_idx});
×
1610
  }
1611

1612
  // if this loop finished because the cell was found and
1613
  // the instance matches the one requested in the call
1614
  // we have the correct path and can return the stack
1615
  if (cell_found &&
×
1616
      stack.compute_instance(this->distribcell_index_) == instance) {
×
1617
    return stack.parent_cells();
×
1618
  }
1619

1620
  // fall back on an exhaustive search for the cell's parents
1621
  return exhaustive_find_parent_cells(instance);
×
1622
}
×
1623

1624
vector<ParentCell> Cell::exhaustive_find_parent_cells(int32_t instance) const
90 ✔
1625
{
1626
  ParentCellStack stack;
90 ✔
1627
  // start with this cell's universe
1628
  int32_t prev_univ_idx;
90 ✔
1629
  int32_t univ_idx = this->universe_;
90 ✔
1630

1631
  while (true) {
135 ✔
1632
    prev_univ_idx = univ_idx;
135 ✔
1633

1634
    // search for a cell that is filled w/ this universe
1635
    for (const auto& cell : model::cells) {
1,017 ✔
1636
      // if this is a material-filled cell, move on
1637
      if (cell->type_ == Fill::MATERIAL)
945 ✔
1638
        continue;
531 ✔
1639

1640
      if (cell->type_ == Fill::UNIVERSE) {
414 ✔
1641
        // if this is in the set of cells previously visited for this universe,
1642
        // move on
1643
        if (stack.visited(univ_idx, {model::cell_map[cell->id_], C_NONE}))
261 !
1644
          continue;
×
1645

1646
        // if this cell contains the universe we're searching for, add it to the
1647
        // stack
1648
        if (cell->fill_ == univ_idx) {
261 !
1649
          stack.push(univ_idx, {model::cell_map[cell->id_], C_NONE});
×
1650
          univ_idx = cell->universe_;
×
1651
        }
1652
      } else if (cell->type_ == Fill::LATTICE) {
153 !
1653
        // retrieve the lattice and lattice universes
1654
        const auto& lattice = model::lattices[cell->fill_];
153 ✔
1655
        const auto& lattice_univs = lattice->universes_;
153 ✔
1656

1657
        // start search for universe
1658
        auto lat_it = lattice_univs.begin();
153 ✔
1659
        while (true) {
315 ✔
1660
          // find the next lattice cell with this universe
1661
          lat_it = std::find(lat_it, lattice_univs.end(), univ_idx);
234 ✔
1662
          if (lat_it == lattice_univs.end())
234 ✔
1663
            break;
1664

1665
          int lattice_idx = lat_it - lattice_univs.begin();
144 ✔
1666

1667
          // move iterator forward one to avoid finding the same entry
1668
          lat_it++;
144 ✔
1669
          if (stack.visited(
288 ✔
1670
                univ_idx, {model::cell_map[cell->id_], lattice_idx}))
144 ✔
1671
            continue;
81 ✔
1672

1673
          // add this cell and lattice index to the stack and exit loop
1674
          stack.push(univ_idx, {model::cell_map[cell->id_], lattice_idx});
63 ✔
1675
          univ_idx = cell->universe_;
63 ✔
1676
          break;
63 ✔
1677
        }
81 ✔
1678
      }
1679
      // if we've updated the universe, break
1680
      if (prev_univ_idx != univ_idx)
414 ✔
1681
        break;
1682
    } // end cell loop search for universe
1683

1684
    // if we're at the top of the geometry and the instance matches, we're done
1685
    if (univ_idx == model::root_universe &&
135 !
1686
        stack.compute_instance(this->distribcell_index_) == instance)
135 ✔
1687
      break;
1688

1689
    // if there is no match on the original cell's universe, report an error
1690
    if (univ_idx == this->universe_) {
45 !
1691
      fatal_error(
×
1692
        fmt::format("Could not find the parent cells for cell {}, instance {}.",
×
1693
          this->id_, instance));
×
1694
    }
1695

1696
    // if we don't find a suitable update, adjust the stack and continue
1697
    if (univ_idx == model::root_universe || univ_idx == prev_univ_idx) {
45 !
1698
      stack.pop();
45 ✔
1699
      univ_idx = stack.empty() ? this->universe_ : stack.current_univ();
45 !
1700
    }
1701

1702
  } // end while
1703

1704
  // reverse the stack so the highest cell comes first
1705
  std::reverse(stack.parent_cells().begin(), stack.parent_cells().end());
90 ✔
1706
  return stack.parent_cells();
180 ✔
1707
}
90 ✔
1708

1709
std::unordered_map<int32_t, vector<int32_t>> Cell::get_contained_cells(
117 ✔
1710
  int32_t instance, Position* hint) const
1711
{
1712
  std::unordered_map<int32_t, vector<int32_t>> contained_cells;
117 ✔
1713

1714
  // if this is a material-filled cell it has no contained cells
1715
  if (this->type_ == Fill::MATERIAL)
117 ✔
1716
    return contained_cells;
1717

1718
  // find the pathway through the geometry to this cell
1719
  vector<ParentCell> parent_cells;
90 !
1720

1721
  // if a positional hint is provided, attempt to do a fast lookup
1722
  // of the parent cells
1723
  parent_cells = hint ? find_parent_cells(instance, *hint)
90 !
1724
                      : exhaustive_find_parent_cells(instance);
90 ✔
1725

1726
  // if this cell is filled w/ a material, it contains no other cells
1727
  if (type_ != Fill::MATERIAL) {
90 !
1728
    this->get_contained_cells_inner(contained_cells, parent_cells);
90 ✔
1729
  }
1730

1731
  return contained_cells;
90 ✔
1732
}
117 ✔
1733

1734
//! Get all cells within this cell
1735
void Cell::get_contained_cells_inner(
82,935 ✔
1736
  std::unordered_map<int32_t, vector<int32_t>>& contained_cells,
1737
  vector<ParentCell>& parent_cells) const
1738
{
1739

1740
  // filled by material, determine instance based on parent cells
1741
  if (type_ == Fill::MATERIAL) {
82,935 ✔
1742
    int instance = 0;
82,314 ✔
1743
    if (this->distribcell_index_ >= 0) {
82,314 !
1744
      for (auto& parent_cell : parent_cells) {
246,942 ✔
1745
        auto& cell = model::cells[parent_cell.cell_index];
164,628 ✔
1746
        if (cell->type_ == Fill::UNIVERSE) {
164,628 ✔
1747
          instance += cell->offset_[distribcell_index_];
80,514 ✔
1748
        } else if (cell->type_ == Fill::LATTICE) {
84,114 !
1749
          auto& lattice = model::lattices[cell->fill_];
84,114 ✔
1750
          instance += lattice->offset(
84,114 ✔
1751
            this->distribcell_index_, parent_cell.lattice_index);
84,114 ✔
1752
        }
1753
      }
1754
    }
1755
    // add entry to contained cells
1756
    contained_cells[model::cell_map[id_]].push_back(instance);
82,314 ✔
1757
    // filled with universe, add the containing cell to the parent cells
1758
    // and recurse
1759
  } else if (type_ == Fill::UNIVERSE) {
621 ✔
1760
    parent_cells.push_back({model::cell_map[id_], -1});
531 ✔
1761
    auto& univ = model::universes[fill_];
531 ✔
1762
    for (auto cell_index : univ->cells_) {
3,330 ✔
1763
      auto& cell = model::cells[cell_index];
2,799 ✔
1764
      cell->get_contained_cells_inner(contained_cells, parent_cells);
2,799 ✔
1765
    }
1766
    parent_cells.pop_back();
531 ✔
1767
    // filled with a lattice, visit each universe in the lattice
1768
    // with a recursive call to collect the cell instances
1769
  } else if (type_ == Fill::LATTICE) {
90 !
1770
    auto& lattice = model::lattices[fill_];
90 ✔
1771
    for (auto i = lattice->begin(); i != lattice->end(); ++i) {
79,758 ✔
1772
      auto& univ = model::universes[*i];
79,668 ✔
1773
      parent_cells.push_back({model::cell_map[id_], i.indx_});
79,668 ✔
1774
      for (auto cell_index : univ->cells_) {
159,714 ✔
1775
        auto& cell = model::cells[cell_index];
80,046 ✔
1776
        cell->get_contained_cells_inner(contained_cells, parent_cells);
80,046 ✔
1777
      }
1778
      parent_cells.pop_back();
79,668 ✔
1779
    }
1780
  }
1781
}
82,935 ✔
1782

1783
//! Return the index in the cells array of a cell with a given ID
1784
extern "C" int openmc_get_cell_index(int32_t id, int32_t* index)
630 ✔
1785
{
1786
  auto it = model::cell_map.find(id);
630 ✔
1787
  if (it != model::cell_map.end()) {
630 ✔
1788
    *index = it->second;
623 ✔
1789
    return 0;
623 ✔
1790
  } else {
1791
    set_errmsg("No cell exists with ID=" + std::to_string(id) + ".");
14 ✔
1792
    return OPENMC_E_INVALID_ID;
7 ✔
1793
  }
1794
}
1795

1796
//! Return the ID of a cell
1797
extern "C" int openmc_cell_get_id(int32_t index, int32_t* id)
1,512 ✔
1798
{
1799
  if (index >= 0 && index < model::cells.size()) {
1,512 !
1800
    *id = model::cells[index]->id_;
1,512 ✔
1801
    return 0;
1,512 ✔
1802
  } else {
1803
    set_errmsg("Index in cells array is out of bounds.");
×
1804
    return OPENMC_E_OUT_OF_BOUNDS;
×
1805
  }
1806
}
1807

1808
//! Set the ID of a cell
1809
extern "C" int openmc_cell_set_id(int32_t index, int32_t id)
14 ✔
1810
{
1811
  if (index >= 0 && index < model::cells.size()) {
14 !
1812
    model::cells[index]->id_ = id;
14 ✔
1813
    model::cell_map[id] = index;
14 ✔
1814
    return 0;
14 ✔
1815
  } else {
1816
    set_errmsg("Index in cells array is out of bounds.");
×
1817
    return OPENMC_E_OUT_OF_BOUNDS;
×
1818
  }
1819
}
1820

1821
//! Return the translation vector of a cell
1822
extern "C" int openmc_cell_get_translation(int32_t index, double xyz[])
35 ✔
1823
{
1824
  if (index >= 0 && index < model::cells.size()) {
35 !
1825
    auto& cell = model::cells[index];
35 ✔
1826
    xyz[0] = cell->translation_.x;
35 ✔
1827
    xyz[1] = cell->translation_.y;
35 ✔
1828
    xyz[2] = cell->translation_.z;
35 ✔
1829
    return 0;
35 ✔
1830
  } else {
1831
    set_errmsg("Index in cells array is out of bounds.");
×
1832
    return OPENMC_E_OUT_OF_BOUNDS;
×
1833
  }
1834
}
1835

1836
//! Set the translation vector of a cell
1837
extern "C" int openmc_cell_set_translation(int32_t index, const double xyz[])
35 ✔
1838
{
1839
  if (index >= 0 && index < model::cells.size()) {
35 !
1840
    if (model::cells[index]->fill_ == C_NONE) {
35 ✔
1841
      set_errmsg(fmt::format("Cannot apply a translation to cell {}"
7 ✔
1842
                             " because it is not filled with another universe",
1843
        index));
1844
      return OPENMC_E_GEOMETRY;
7 ✔
1845
    }
1846
    model::cells[index]->translation_ = Position(xyz);
28 ✔
1847
    return 0;
28 ✔
1848
  } else {
1849
    set_errmsg("Index in cells array is out of bounds.");
×
1850
    return OPENMC_E_OUT_OF_BOUNDS;
×
1851
  }
1852
}
1853

1854
//! Return the rotation matrix of a cell
1855
extern "C" int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n)
35 ✔
1856
{
1857
  if (index >= 0 && index < model::cells.size()) {
35 !
1858
    auto& cell = model::cells[index];
35 ✔
1859
    *n = cell->rotation_.size();
35 ✔
1860
    std::memcpy(rot, cell->rotation_.data(), *n * sizeof(cell->rotation_[0]));
35 ✔
1861
    return 0;
35 ✔
1862
  } else {
1863
    set_errmsg("Index in cells array is out of bounds.");
×
1864
    return OPENMC_E_OUT_OF_BOUNDS;
×
1865
  }
1866
}
1867

1868
//! Set the flattened rotation matrix of a cell
1869
extern "C" int openmc_cell_set_rotation(
42 ✔
1870
  int32_t index, const double rot[], size_t rot_len)
1871
{
1872
  if (index >= 0 && index < model::cells.size()) {
42 !
1873
    if (model::cells[index]->fill_ == C_NONE) {
42 ✔
1874
      set_errmsg(fmt::format("Cannot apply a rotation to cell {}"
7 ✔
1875
                             " because it is not filled with another universe",
1876
        index));
1877
      return OPENMC_E_GEOMETRY;
7 ✔
1878
    }
1879
    std::vector<double> vec_rot(rot, rot + rot_len);
35 ✔
1880
    model::cells[index]->set_rotation(vec_rot);
35 ✔
1881
    return 0;
35 ✔
1882
  } else {
42 ✔
1883
    set_errmsg("Index in cells array is out of bounds.");
×
1884
    return OPENMC_E_OUT_OF_BOUNDS;
×
1885
  }
1886
}
1887

1888
//! Get the number of instances of the requested cell
1889
extern "C" int openmc_cell_get_num_instances(
49 ✔
1890
  int32_t index, int32_t* num_instances)
1891
{
1892
  if (index < 0 || index >= model::cells.size()) {
49 !
1893
    set_errmsg("Index in cells array is out of bounds.");
×
1894
    return OPENMC_E_OUT_OF_BOUNDS;
×
1895
  }
1896
  *num_instances = model::cells[index]->n_instances();
49 ✔
1897
  return 0;
49 ✔
1898
}
1899

1900
//! Extend the cells array by n elements
1901
extern "C" int openmc_extend_cells(
14 ✔
1902
  int32_t n, int32_t* index_start, int32_t* index_end)
1903
{
1904
  if (index_start)
14 !
1905
    *index_start = model::cells.size();
14 ✔
1906
  if (index_end)
14 !
1907
    *index_end = model::cells.size() + n - 1;
×
1908
  for (int32_t i = 0; i < n; i++) {
28 ✔
1909
    model::cells.push_back(make_unique<CSGCell>());
14 ✔
1910
  }
1911
  return 0;
14 ✔
1912
}
1913

1914
extern "C" int cells_size()
63 ✔
1915
{
1916
  return model::cells.size();
63 ✔
1917
}
1918

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