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

openmc-dev / openmc / 31914628940

15 Aug 2026 11:24PM UTC coverage: 81.333% (-0.09%) from 81.419%
31914628940

Pull #4065

github

web-flow
Merge e5bf0590a into f53364e9b
Pull Request #4065: Replace exported C API error globals

18557 of 27007 branches covered (68.71%)

Branch coverage included in aggregate %.

34 of 59 new or added lines in 9 files covered. (57.63%)

60317 of 69970 relevant lines covered (86.2%)

49998653.75 hits per line

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

74.66
/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
//==============================================================================
40
// Cell implementation
41
//==============================================================================
42

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

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

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

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

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

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

96
  if (instance >= 0) {
9,634✔
97
    double sqrtkT = sqrtkT_.size() == 1 ? sqrtkT_.at(0) : sqrtkT_.at(instance);
9,548✔
98
    return sqrtkT * sqrtkT / K_BOLTZMANN;
9,548✔
99
  } else {
100
    return sqrtkT_[0] * sqrtkT_[0] / K_BOLTZMANN;
86✔
101
  }
102
}
103

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

114
double Cell::density(int32_t instance) const
1,199,827✔
115
{
116
  const int32_t mat_index = material(instance);
1,199,827✔
117
  if (mat_index == MATERIAL_VOID)
1,199,827!
118
    return 0.0;
119

120
  return density_mult(instance) * model::materials[mat_index]->density_gpcc();
2,399,654✔
121
}
122

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

139
  if (type_ == Fill::MATERIAL) {
10,012✔
140
    if (instance >= 0) {
9,982✔
141
      // If temperature vector is not big enough, resize it first
142
      if (sqrtkT_.size() != n_instances())
9,905✔
143
        sqrtkT_.resize(n_instances(), sqrtkT_[0]);
45✔
144

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

161
    auto contained_cells = this->get_contained_cells(instance);
30✔
162
    for (const auto& entry : contained_cells) {
120✔
163
      auto& cell = model::cells[entry.first];
90!
164
      assert(cell->type_ == Fill::MATERIAL);
90!
165
      auto& instances = entry.second;
90✔
166
      for (auto instance : instances) {
315✔
167
        cell->set_temperature(T, instance);
225✔
168
      }
169
    }
170
  }
30✔
171
}
10,012✔
172

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

182
  if (type_ == Fill::MATERIAL) {
346✔
183
    const int32_t mat_index = material(instance);
331!
184
    if (mat_index == MATERIAL_VOID)
331!
185
      return;
186

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

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

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

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

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

231
    write_dataset(cell_group, "density", density);
198✔
232
  }
198✔
233

234
  close_group(cell_group);
231✔
235
}
231✔
236

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

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

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

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

260
  // Read densities
261
  if (object_exists(cell_group, "density")) {
253✔
262
    vector<double> density;
198✔
263
    read_dataset(cell_group, "density", density);
198✔
264

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

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

279
  close_group(cell_group);
253✔
280
}
253✔
281

282
void Cell::to_hdf5(hid_t cell_group) const
30,609✔
283
{
284

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

288
  if (!name_.empty()) {
30,609✔
289
    write_string(group, "name", name_, false);
7,301✔
290
  }
291

292
  write_dataset(group, "universe", model::universes[universe_]->id_);
30,609✔
293

294
  to_hdf5_inner(group);
30,609✔
295

296
  // Write fill information.
297
  if (type_ == Fill::MATERIAL) {
30,609✔
298
    write_dataset(group, "fill_type", "material");
25,039✔
299
    std::vector<int32_t> mat_ids;
25,039✔
300
    for (auto i_mat : material_) {
51,371✔
301
      if (i_mat != MATERIAL_VOID) {
26,332✔
302
        mat_ids.push_back(model::materials[i_mat]->id_);
17,600✔
303
      } else {
304
        mat_ids.push_back(MATERIAL_VOID);
8,732✔
305
      }
306
    }
307
    if (mat_ids.size() == 1) {
25,039✔
308
      write_dataset(group, "material", mat_ids[0]);
24,848✔
309
    } else {
310
      write_dataset(group, "material", mat_ids);
191✔
311
    }
312

313
    std::vector<double> temps;
25,039✔
314
    for (auto sqrtkT_val : sqrtkT_)
61,724✔
315
      temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
36,685✔
316
    write_dataset(group, "temperature", temps);
25,039✔
317

318
    write_dataset(group, "density_mult", density_mult_);
25,039✔
319

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

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

340
  close_group(group);
30,609✔
341
}
30,609✔
342

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

347
vector<int32_t> parse_cell_material_xml(pugi::xml_node node, int32_t cell_id)
29,200✔
348
{
349
  vector<std::string> mats {
29,200✔
350
    get_node_array<std::string>(node, "material", true)};
29,200✔
351
  if (mats.empty()) {
29,200!
352
    fatal_error(fmt::format(
×
353
      "An empty material element was specified for cell {}", cell_id));
354
  }
355
  vector<int32_t> material;
29,200✔
356
  material.reserve(mats.size());
29,200✔
357
  for (const auto& mat : mats) {
59,729✔
358
    if (mat == "void") {
30,529✔
359
      material.push_back(MATERIAL_VOID);
9,207✔
360
    } else {
361
      material.push_back(std::stoi(mat));
21,322✔
362
    }
363
  }
364
  return material;
29,200✔
365
}
29,200✔
366

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

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

400
//==============================================================================
401
// CSGCell implementation
402
//==============================================================================
403

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

412
  if (check_for_node(cell_node, "name")) {
36,475✔
413
    name_ = get_node_value(cell_node, "name");
9,289✔
414
  }
415

416
  if (check_for_node(cell_node, "universe")) {
36,475✔
417
    universe_ = std::stoi(get_node_value(cell_node, "universe"));
70,532✔
418
  } else {
419
    universe_ = 0;
1,209✔
420
  }
421

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

435
  if (fill_present) {
36,475✔
436
    fill_ = std::stoi(get_node_value(cell_node, "fill"));
14,568✔
437
    if (fill_ == universe_) {
7,284!
438
      fatal_error(fmt::format("Cell {} is filled with the same universe that "
×
439
                              "it is contained in.",
440
        id_));
×
441
    }
442
  } else {
443
    fill_ = C_NONE;
29,191✔
444
  }
445

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

453
  // Read the temperature element which may be distributed like materials.
454
  if (check_for_node(cell_node, "temperature")) {
36,475✔
455
    sqrtkT_ = parse_cell_temperature_xml(cell_node, id_);
431✔
456
    sqrtkT_.shrink_to_fit();
431✔
457

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

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

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

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

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

501
  // Read the region specification.
502
  std::string region_spec;
36,475✔
503
  if (check_for_node(cell_node, "region")) {
36,475✔
504
    region_spec = get_node_value(cell_node, "region");
27,280✔
505
  }
506

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

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

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

528
  // Read the rotation transform.
529
  if (check_for_node(cell_node, "rotation")) {
36,475✔
530
    auto rot {get_node_array<double>(cell_node, "rotation")};
390✔
531
    set_rotation(rot);
390✔
532
  }
390✔
533
}
36,475✔
534

535
//==============================================================================
536

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

543
//==============================================================================
544

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

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

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

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

578
//==============================================================================
579
// Region implementation
580
//==============================================================================
581

582
Region::Region(std::string region_spec, int32_t cell_id)
36,618✔
583
{
584
  // Check if region_spec is not empty.
585
  if (!region_spec.empty()) {
36,618✔
586
    // Parse all halfspaces and operators except for intersection (whitespace).
587
    for (int i = 0; i < region_spec.size();) {
165,414✔
588
      if (region_spec[i] == '(') {
137,991✔
589
        expression_.push_back(OP_LEFT_PAREN);
1,777✔
590
        i++;
1,777✔
591

592
      } else if (region_spec[i] == ')') {
136,214✔
593
        expression_.push_back(OP_RIGHT_PAREN);
1,777✔
594
        i++;
1,777✔
595

596
      } else if (region_spec[i] == '|') {
134,437✔
597
        expression_.push_back(OP_UNION);
4,560✔
598
        i++;
4,560✔
599

600
      } else if (region_spec[i] == '~') {
129,877✔
601
        expression_.push_back(OP_COMPLEMENT);
30✔
602
        i++;
30✔
603

604
      } else if (region_spec[i] == '-' || region_spec[i] == '+' ||
219,265✔
605
                 std::isdigit(region_spec[i])) {
89,418✔
606
        // This is the start of a halfspace specification.  Iterate j until we
607
        // find the end, then push-back everything between i and j.
608
        int j = i + 1;
75,609✔
609
        while (j < region_spec.size() && std::isdigit(region_spec[j])) {
151,699✔
610
          j++;
76,090✔
611
        }
612
        expression_.push_back(std::stoi(region_spec.substr(i, j - i)));
151,218✔
613
        i = j;
75,609✔
614

615
      } else if (std::isspace(region_spec[i])) {
54,238!
616
        i++;
54,238✔
617

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

626
    // Add in intersection operators where a missing operator is needed.
627
    int i = 0;
628
    while (i < expression_.size() - 1) {
127,379✔
629
      bool left_compat {
99,956✔
630
        (expression_[i] < OP_UNION) || (expression_[i] == OP_RIGHT_PAREN)};
99,956✔
631
      bool right_compat {(expression_[i + 1] < OP_UNION) ||
99,956✔
632
                         (expression_[i + 1] == OP_LEFT_PAREN) ||
99,956✔
633
                         (expression_[i + 1] == OP_COMPLEMENT)};
6,397✔
634
      if (left_compat && right_compat) {
99,956✔
635
        expression_.insert(expression_.begin() + i + 1, OP_INTERSECTION);
43,626✔
636
      }
637
      i++;
638
    }
639

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

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

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

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

687
    // Check if this is a simple cell.
688
    simple_ = true;
27,423✔
689
    for (int32_t token : expression_) {
138,167✔
690
      if (token == OP_UNION) {
112,045✔
691
        simple_ = false;
1,301✔
692
        // Ensure intersections have precedence over unions
693
        enforce_precedence();
1,301✔
694
        break;
695
      }
696
    }
697

698
    // If this cell is simple, remove all the superfluous operator tokens.
699
    if (simple_) {
27,423✔
700
      expression_.erase(std::remove_if(expression_.begin(), expression_.end(),
26,122✔
701
                          [](int32_t token) {
103,806✔
702
                            return token == OP_INTERSECTION ||
103,806✔
703
                                   token > OP_COMPLEMENT;
95,642!
704
                          }),
705
        expression_.end());
26,122✔
706
    }
707
    expression_.shrink_to_fit();
27,423✔
708

709
  } else {
710
    simple_ = true;
9,195✔
711
  }
712
}
36,618✔
713

714
//==============================================================================
715

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

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

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

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

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

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

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

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

804
  for (int64_t i = 0; i < expression_.size(); ++i) {
25,861✔
805
    int32_t token = expression_[i];
24,560✔
806

807
    if (token == OP_LEFT_PAREN) {
24,560✔
808
      // Entering a new parenthesis level - push new tracking state
809
      op_stack.push_back(0);
1,973✔
810
      pos_stack.push_back(0);
1,973✔
811
      continue;
1,973✔
812
    } else if (token == OP_RIGHT_PAREN) {
22,587✔
813
      // Exiting a parenthesis level - pop tracking state (keep at least one)
814
      if (op_stack.size() > 1) {
1,932!
815
        op_stack.pop_back();
1,932✔
816
        pos_stack.pop_back();
1,932✔
817
      }
818
      continue;
1,932✔
819
    }
820

821
    if (token == OP_UNION || token == OP_INTERSECTION) {
20,655✔
822
      if (op_stack.back() == 0) {
9,677✔
823
        // First operator at this depth - record it and its position
824
        op_stack.back() = token;
3,318✔
825
        pos_stack.back() = i;
3,318✔
826
      } else if (token != op_stack.back()) {
6,359✔
827
        // Encountered a different operator at the same depth - need to add
828
        // parentheses to enforce precedence. Intersection has higher
829
        // precedence, so we parenthesize the intersection terms.
830
        if (op_stack.back() == OP_INTERSECTION) {
96✔
831
          add_parentheses(pos_stack.back());
48✔
832
        } else {
833
          add_parentheses(i);
48✔
834
        }
835

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

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

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

856
  for (int32_t token : expression_) {
990✔
857
    if (token < OP_UNION) {
946✔
858
      // If token is not an operator, add it to output
859
      rpn.push_back(token);
396✔
860
    } else if (token < OP_RIGHT_PAREN) {
550✔
861
      // Regular operators union, intersection, complement
862
      while (stack.size() > 0) {
561✔
863
        int32_t op = stack.back();
462✔
864

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

880
      stack.push_back(token);
352✔
881

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

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

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

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

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

915
    rpn.push_back(stack.back());
44✔
916
    stack.pop_back();
88✔
917
  }
918

919
  return rpn;
44✔
920
}
44✔
921

922
//==============================================================================
923

924
std::string Region::str() const
30,553✔
925
{
926
  std::stringstream region_spec {};
30,553✔
927
  if (!expression_.empty()) {
30,553✔
928
    for (int32_t token : expression_) {
95,064✔
929
      if (token == OP_LEFT_PAREN) {
72,972✔
930
        region_spec << " (";
1,593✔
931
      } else if (token == OP_RIGHT_PAREN) {
71,379✔
932
        region_spec << " )";
1,593✔
933
      } else if (token == OP_COMPLEMENT) {
69,786!
934
        region_spec << " ~";
×
935
      } else if (token == OP_INTERSECTION) {
69,786✔
936
      } else if (token == OP_UNION) {
65,856✔
937
        region_spec << " |";
4,018✔
938
      } else {
939
        // Note the off-by-one indexing
940
        auto surf_id = model::surfaces[abs(token) - 1]->id_;
61,838✔
941
        region_spec << " " << ((token > 0) ? surf_id : -surf_id);
61,838✔
942
      }
943
    }
944
  }
945
  return region_spec.str();
61,106✔
946
}
30,553✔
947

948
//==============================================================================
949

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

960
//==============================================================================
961

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

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

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

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

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

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

997
//==============================================================================
998

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

1005
  while (true) {
1,060,409,372✔
1006
    auto [distance, i_surf] =
1,248,724,468✔
1007
      distance_to_nearest_surface(r, u, on_surface, on_surface != 0);
624,362,234✔
1008
    if (distance == INFTY) {
624,362,234✔
1009
      return {INFTY, std::numeric_limits<int32_t>::max()};
1,745,218✔
1010
    }
1011

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

1024
    // If crossing the candidate changes the region membership, it is a true
1025
    // boundary. Otherwise, continue the search from the virtual crossing.
1026
    if (contains_complex(r, u, i_surf) != in_region) {
622,617,016✔
1027
      return {total_distance, i_surf};
186,569,878✔
1028
    }
1029
    on_surface = i_surf;
436,047,138✔
1030
  }
436,047,138✔
1031
}
1032

1033
//==============================================================================
1034

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

1044
//==============================================================================
1045

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

1067
//==============================================================================
1068

1069
bool Region::contains_complex(Position r, Direction u, int32_t on_surface) const
836,767,801✔
1070
{
1071
  bool in_cell = true;
836,767,801✔
1072
  int total_depth = 0;
836,767,801✔
1073

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

1078
    // If the token is a surface evaluate the sense
1079
    // If the token is a union or intersection check to
1080
    // short circuit
1081
    if (token < OP_UNION) {
2,147,483,647✔
1082
      if (token == on_surface) {
2,147,483,647✔
1083
        in_cell = true;
1084
      } else if (-token == on_surface) {
2,147,483,647✔
1085
        in_cell = false;
1086
      } else {
1087
        // Note the off-by-one indexing
1088
        bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
2,147,483,647✔
1089
        in_cell = (sense == (token > 0));
2,147,483,647✔
1090
      }
1091
    } else if ((token == OP_UNION && in_cell == true) ||
2,147,483,647✔
1092
               (token == OP_INTERSECTION && in_cell == false)) {
1,704,780,643✔
1093
      // If the total depth is zero return
1094
      if (total_depth == 0) {
1,484,305,775✔
1095
        return in_cell;
189,955,784✔
1096
      }
1097

1098
      total_depth--;
1,294,349,991✔
1099

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

1107
        // If the token is an a parenthesis
1108
        if (next_token > OP_COMPLEMENT) {
2,147,483,647✔
1109
          // Adjust depth accordingly
1110
          if (next_token == OP_RIGHT_PAREN) {
1,596,022,233✔
1111
            depth--;
1,445,186,112✔
1112
          } else {
1113
            depth++;
150,836,121✔
1114
          }
1115
        }
1116
      } while (depth > 0);
2,147,483,647✔
1117
    } else if (token == OP_LEFT_PAREN) {
2,147,483,647✔
1118
      total_depth++;
1,355,086,508✔
1119
    } else if (token == OP_RIGHT_PAREN) {
2,147,483,647✔
1120
      total_depth--;
60,736,517✔
1121
    }
1122
  }
1123
  return in_cell;
1124
}
1125

1126
//==============================================================================
1127

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

1138
//==============================================================================
1139

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

1149
//==============================================================================
1150

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

1156
  for (auto& token : postfix) {
792✔
1157
    if (token == OP_UNION) {
748✔
1158
      stack[i_stack - 1] = stack[i_stack - 1] | stack[i_stack];
154✔
1159
      i_stack--;
154✔
1160
    } else if (token == OP_INTERSECTION) {
594✔
1161
      stack[i_stack - 1] = stack[i_stack - 1] & stack[i_stack];
198✔
1162
      i_stack--;
198✔
1163
    } else {
1164
      i_stack++;
396✔
1165
      stack[i_stack] = model::surfaces[abs(token) - 1]->bounding_box(token > 0);
396✔
1166
    }
1167
  }
1168

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

1173
//==============================================================================
1174

1175
vector<int32_t> Region::surfaces() const
5,270✔
1176
{
1177
  if (simple_) {
5,270✔
1178
    return expression_;
5,250✔
1179
  }
1180

1181
  vector<int32_t> surfaces = expression_;
20✔
1182

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

1186
  while (it != surfaces.end()) {
60✔
1187
    surfaces.erase(it);
40✔
1188

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

1193
  return surfaces;
20✔
1194
}
5,270✔
1195

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

1200
void read_cells(pugi::xml_node node)
9,117✔
1201
{
1202
  // Count the number of cells.
1203
  int n_cells = 0;
9,117✔
1204
  for (pugi::xml_node cell_node : node.children("cell")) {
45,559✔
1205
    n_cells++;
36,442✔
1206
  }
1207

1208
  // Loop over XML cell elements and populate the array.
1209
  model::cells.reserve(n_cells);
9,117✔
1210
  for (pugi::xml_node cell_node : node.children("cell")) {
45,559✔
1211
    model::cells.push_back(make_unique<CSGCell>(cell_node));
36,442✔
1212
  }
1213

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

1226
  read_dagmc_universes(node);
9,117✔
1227

1228
  populate_universes();
9,115✔
1229

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

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

1240
void populate_universes()
9,117✔
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;
9,117✔
1245

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

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

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

1277
  model::universes.shrink_to_fit();
9,117✔
1278
}
9,117✔
1279

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

1284
extern "C" int openmc_cell_get_fill(
235✔
1285
  int32_t index, int* type, int32_t** indices, int32_t* n)
1286
{
1287
  if (index >= 0 && index < model::cells.size()) {
235!
1288
    Cell& c {*model::cells[index]};
235✔
1289
    *type = static_cast<int>(c.type_);
235✔
1290
    if (c.type_ == Fill::MATERIAL) {
235✔
1291
      *indices = c.material_.data();
224✔
1292
      *n = c.material_.size();
224✔
1293
    } else {
1294
      *indices = &c.fill_;
11✔
1295
      *n = 1;
11✔
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(
11✔
1305
  int32_t index, int type, int32_t n, const int32_t* indices)
1306
{
1307
  Fill filltype = static_cast<Fill>(type);
11✔
1308
  if (index >= 0 && index < model::cells.size()) {
11!
1309
    Cell& c {*model::cells[index]};
11!
1310
    if (filltype == Fill::MATERIAL) {
11!
1311
      c.type_ = Fill::MATERIAL;
11✔
1312
      c.material_.clear();
11!
1313
      for (int i = 0; i < n; i++) {
22✔
1314
        int i_mat = indices[i];
11✔
1315
        if (i_mat == MATERIAL_VOID) {
11!
1316
          c.material_.push_back(MATERIAL_VOID);
×
1317
        } else if (i_mat >= 0 && i_mat < model::materials.size()) {
11!
1318
          c.material_.push_back(i_mat);
11✔
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();
11✔
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(
88✔
1338
  int32_t index, double T, const int32_t* instance, bool set_contained)
1339
{
1340
  if (index < 0 || index >= model::cells.size()) {
88!
NEW
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;
88✔
1346
  try {
88✔
1347
    model::cells[index]->set_temperature(T, instance_index, set_contained);
88✔
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(
88✔
1356
  int32_t index, double density, const int32_t* instance, bool set_contained)
1357
{
1358
  if (index < 0 || index >= model::cells.size()) {
88!
NEW
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;
88✔
1364
  try {
88✔
1365
    model::cells[index]->set_density(density, instance_index, set_contained);
88✔
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(
9,628✔
1374
  int32_t index, const int32_t* instance, double* T)
1375
{
1376
  if (index < 0 || index >= model::cells.size()) {
9,628!
NEW
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;
9,628✔
1382
  try {
9,628✔
1383
    *T = model::cells[index]->temperature(instance_index);
9,628✔
1384
  } catch (const std::exception& e) {
×
1385
    set_errmsg(e.what());
×
1386
    return OPENMC_E_UNASSIGNED;
×
1387
  }
×
1388
  return 0;
9,628✔
1389
}
1390

1391
extern "C" int openmc_cell_get_density(
88✔
1392
  int32_t index, const int32_t* instance, double* density)
1393
{
1394
  if (index < 0 || index >= model::cells.size()) {
88!
NEW
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;
88✔
1400
  try {
88✔
1401
    if (model::cells[index]->type_ != Fill::MATERIAL) {
88!
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);
88!
1408
    if (mat_index == MATERIAL_VOID) {
88!
1409
      *density = 0.0;
×
1410
    } else {
1411
      *density = model::cells[index]->density_mult(instance_index) *
88✔
1412
                 model::materials[mat_index]->density_gpcc();
176!
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(
55✔
1423
  const int32_t index, double* llc, double* urc)
1424
{
1425

1426
  BoundingBox bbox;
55✔
1427

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

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

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

1441
  return 0;
55✔
1442
}
1443

1444
//! Get the name of a cell
1445
extern "C" int openmc_cell_get_name(int32_t index, const char** name)
419✔
1446
{
1447
  if (index < 0 || index >= model::cells.size()) {
419!
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();
419✔
1453

1454
  return 0;
419✔
1455
}
1456

1457
//! Set the name of a cell
1458
extern "C" int openmc_cell_set_name(int32_t index, const char* name)
11✔
1459
{
1460
  if (index < 0 || index >= model::cells.size()) {
11!
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);
22✔
1466

1467
  return 0;
11✔
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
135✔
1477
  {
1478
    return cell_index == other.cell_index &&
135!
1479
           lattice_index == other.lattice_index;
135!
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
661✔
1496
  {
1497
    return 4096 * p.cell_index + p.lattice_index;
661!
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 {
136✔
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)
105✔
1508
  {
1509
    parent_cells_.push_back(pc);
105✔
1510
    // add parent cell to the set of cells we've visited for this search
1511
    // universe
1512
    visited_cells_[search_universe].insert(pc);
105✔
1513
  }
105✔
1514

1515
  //! removes the last parent_cell and clears the visited cells for the popped
1516
  //! cell's universe
1517
  void pop()
75✔
1518
  {
1519
    visited_cells_[this->current_univ()].clear();
75✔
1520
    parent_cells_.pop_back();
75✔
1521
  }
75✔
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)
556✔
1526
  {
1527
    return visited_cells_[search_universe].count(parent_cell) != 0;
556✔
1528
  }
1529

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

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

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

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

1559
  // Accessors
1560
  vector<ParentCell>& parent_cells() { return parent_cells_; }
136✔
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(
×
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
136✔
1625
{
1626
  ParentCellStack stack;
136✔
1627
  // start with this cell's universe
1628
  int32_t prev_univ_idx;
136✔
1629
  int32_t univ_idx = this->universe_;
136✔
1630

1631
  while (true) {
211✔
1632
    const auto& univ = model::universes[univ_idx];
211✔
1633
    prev_univ_idx = univ_idx;
211✔
1634

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

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

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

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

1666
          int lattice_idx = lat_it - lattice_univs.begin();
240✔
1667

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

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

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

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

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

1703
  } // end while
1704

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

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

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

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

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

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

1732
  return contained_cells;
136✔
1733
}
181✔
1734

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

1741
  // filled by material, determine instance based on parent cells
1742
  if (type_ == Fill::MATERIAL) {
134,178✔
1743
    int instance = 0;
133,532✔
1744
    if (this->distribcell_index_ >= 0) {
133,532!
1745
      for (auto& parent_cell : parent_cells) {
400,594✔
1746
        auto& cell = model::cells[parent_cell.cell_index];
267,062✔
1747
        if (cell->type_ == Fill::UNIVERSE) {
267,062✔
1748
          instance += cell->offset_[distribcell_index_];
132,032✔
1749
        } else if (cell->type_ == Fill::LATTICE) {
135,030!
1750
          auto& lattice = model::lattices[cell->fill_];
135,030✔
1751
          instance += lattice->offset(
135,030✔
1752
            this->distribcell_index_, parent_cell.lattice_index);
135,030✔
1753
        }
1754
      }
1755
    }
1756
    // add entry to contained cells
1757
    contained_cells[model::cell_map[id_]].push_back(instance);
133,532✔
1758
    // filled with universe, add the containing cell to the parent cells
1759
    // and recurse
1760
  } else if (type_ == Fill::UNIVERSE) {
646✔
1761
    parent_cells.push_back({model::cell_map[id_], -1});
526✔
1762
    auto& univ = model::universes[fill_];
526✔
1763
    for (auto cell_index : univ->cells_) {
3,033✔
1764
      auto& cell = model::cells[cell_index];
2,507✔
1765
      cell->get_contained_cells_inner(contained_cells, parent_cells);
2,507✔
1766
    }
1767
    parent_cells.pop_back();
526✔
1768
    // filled with a lattice, visit each universe in the lattice
1769
    // with a recursive call to collect the cell instances
1770
  } else if (type_ == Fill::LATTICE) {
120!
1771
    auto& lattice = model::lattices[fill_];
120✔
1772
    for (auto i = lattice->begin(); i != lattice->end(); ++i) {
131,340✔
1773
      auto& univ = model::universes[*i];
131,220✔
1774
      parent_cells.push_back({model::cell_map[id_], i.indx_});
131,220✔
1775
      for (auto cell_index : univ->cells_) {
262,755✔
1776
        auto& cell = model::cells[cell_index];
131,535✔
1777
        cell->get_contained_cells_inner(contained_cells, parent_cells);
131,535✔
1778
      }
1779
      parent_cells.pop_back();
131,220✔
1780
    }
1781
  }
1782
}
134,178✔
1783

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

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

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

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

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

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

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

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

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

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

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