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

openmc-dev / openmc / 12776996362

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

Pull #3133

github

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

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

1658 existing lines in 66 files now uncovered.

50402 of 59340 relevant lines covered (84.94%)

33987813.96 hits per line

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

79.49
/src/cell.cpp
1

2
#include "openmc/cell.h"
3

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

12
#include <fmt/core.h>
13
#include <gsl/gsl-lite.hpp>
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
void Cell::set_rotation(const vector<double>& rot)
478✔
44
{
45
  if (fill_ == C_NONE) {
478✔
46
    fatal_error(fmt::format("Cannot apply a rotation to cell {}"
×
47
                            " because it is not filled with another universe",
48
      id_));
×
49
  }
50

51
  if (rot.size() != 3 && rot.size() != 9) {
478✔
52
    fatal_error(fmt::format("Non-3D rotation vector applied to cell {}", id_));
×
53
  }
54

55
  // Compute and store the rotation matrix.
56
  rotation_.clear();
478✔
57
  rotation_.reserve(rot.size() == 9 ? 9 : 12);
478✔
58
  if (rot.size() == 3) {
478✔
59
    double phi = -rot[0] * PI / 180.0;
478✔
60
    double theta = -rot[1] * PI / 180.0;
478✔
61
    double psi = -rot[2] * PI / 180.0;
478✔
62
    rotation_.push_back(std::cos(theta) * std::cos(psi));
478✔
63
    rotation_.push_back(-std::cos(phi) * std::sin(psi) +
×
64
                        std::sin(phi) * std::sin(theta) * std::cos(psi));
478✔
65
    rotation_.push_back(std::sin(phi) * std::sin(psi) +
×
66
                        std::cos(phi) * std::sin(theta) * std::cos(psi));
478✔
67
    rotation_.push_back(std::cos(theta) * std::sin(psi));
478✔
68
    rotation_.push_back(std::cos(phi) * std::cos(psi) +
×
69
                        std::sin(phi) * std::sin(theta) * std::sin(psi));
478✔
70
    rotation_.push_back(-std::sin(phi) * std::cos(psi) +
×
71
                        std::cos(phi) * std::sin(theta) * std::sin(psi));
478✔
72
    rotation_.push_back(-std::sin(theta));
478✔
73
    rotation_.push_back(std::sin(phi) * std::cos(theta));
478✔
74
    rotation_.push_back(std::cos(phi) * std::cos(theta));
478✔
75

76
    // When user specifies angles, write them at end of vector
77
    rotation_.push_back(rot[0]);
478✔
78
    rotation_.push_back(rot[1]);
478✔
79
    rotation_.push_back(rot[2]);
478✔
80
  } else {
81
    std::copy(rot.begin(), rot.end(), std::back_inserter(rotation_));
×
82
  }
83
}
478✔
84

85
double Cell::temperature(int32_t instance) const
105✔
86
{
87
  if (sqrtkT_.size() < 1) {
105✔
88
    throw std::runtime_error {"Cell temperature has not yet been set."};
×
89
  }
90

91
  if (instance >= 0) {
105✔
92
    double sqrtkT = sqrtkT_.size() == 1 ? sqrtkT_.at(0) : sqrtkT_.at(instance);
12✔
93
    return sqrtkT * sqrtkT / K_BOLTZMANN;
12✔
94
  } else {
95
    return sqrtkT_[0] * sqrtkT_[0] / K_BOLTZMANN;
93✔
96
  }
97
}
98

99
void Cell::set_temperature(double T, int32_t instance, bool set_contained)
493✔
100
{
101
  if (settings::temperature_method == TemperatureMethod::INTERPOLATION) {
493✔
102
    if (T < (data::temperature_min - settings::temperature_tolerance)) {
×
103
      throw std::runtime_error {
×
104
        fmt::format("Temperature of {} K is below minimum temperature at "
×
105
                    "which data is available of {} K.",
106
          T, data::temperature_min)};
×
107
    } else if (T > (data::temperature_max + settings::temperature_tolerance)) {
×
108
      throw std::runtime_error {
×
109
        fmt::format("Temperature of {} K is above maximum temperature at "
×
110
                    "which data is available of {} K.",
111
          T, data::temperature_max)};
×
112
    }
113
  }
114

115
  if (type_ == Fill::MATERIAL) {
493✔
116
    if (instance >= 0) {
459✔
117
      // If temperature vector is not big enough, resize it first
118
      if (sqrtkT_.size() != n_instances_)
375✔
119
        sqrtkT_.resize(n_instances_, sqrtkT_[0]);
51✔
120

121
      // Set temperature for the corresponding instance
122
      sqrtkT_.at(instance) = std::sqrt(K_BOLTZMANN * T);
375✔
123
    } else {
124
      // Set temperature for all instances
125
      for (auto& T_ : sqrtkT_) {
168✔
126
        T_ = std::sqrt(K_BOLTZMANN * T);
84✔
127
      }
128
    }
129
  } else {
130
    if (!set_contained) {
34✔
131
      throw std::runtime_error {
×
132
        fmt::format("Attempted to set the temperature of cell {} "
×
133
                    "which is not filled by a material.",
134
          id_)};
×
135
    }
136

137
    auto contained_cells = this->get_contained_cells(instance);
34✔
138
    for (const auto& entry : contained_cells) {
136✔
139
      auto& cell = model::cells[entry.first];
102✔
140
      Expects(cell->type_ == Fill::MATERIAL);
102✔
141
      auto& instances = entry.second;
102✔
142
      for (auto instance : instances) {
357✔
143
        cell->set_temperature(T, instance);
255✔
144
      }
145
    }
146
  }
34✔
147
}
493✔
148

149
void Cell::export_properties_hdf5(hid_t group) const
132✔
150
{
151
  // Create a group for this cell.
152
  auto cell_group = create_group(group, fmt::format("cell {}", id_));
264✔
153

154
  // Write temperature in [K] for one or more cell instances
155
  vector<double> temps;
132✔
156
  for (auto sqrtkT_val : sqrtkT_)
240✔
157
    temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
108✔
158
  write_dataset(cell_group, "temperature", temps);
132✔
159

160
  close_group(cell_group);
132✔
161
}
132✔
162

163
void Cell::import_properties_hdf5(hid_t group)
156✔
164
{
165
  auto cell_group = open_group(group, fmt::format("cell {}", id_));
312✔
166

167
  // Read temperatures from file
168
  vector<double> temps;
156✔
169
  read_dataset(cell_group, "temperature", temps);
156✔
170

171
  // Ensure number of temperatures makes sense
172
  auto n_temps = temps.size();
156✔
173
  if (n_temps > 1 && n_temps != n_instances_) {
156✔
174
    throw std::runtime_error(fmt::format(
×
175
      "Number of temperatures for cell {} doesn't match number of instances",
176
      id_));
×
177
  }
178

179
  // Modify temperatures for the cell
180
  sqrtkT_.clear();
156✔
181
  sqrtkT_.resize(temps.size());
156✔
182
  for (gsl::index i = 0; i < temps.size(); ++i) {
264✔
183
    this->set_temperature(temps[i], i);
108✔
184
  }
185

186
  close_group(cell_group);
156✔
187
}
156✔
188

189
void Cell::to_hdf5(hid_t cell_group) const
25,332✔
190
{
191

192
  // Create a group for this cell.
193
  auto group = create_group(cell_group, fmt::format("cell {}", id_));
50,664✔
194

195
  if (!name_.empty()) {
25,332✔
196
    write_string(group, "name", name_, false);
4,240✔
197
  }
198

199
  write_dataset(group, "universe", model::universes[universe_]->id_);
25,332✔
200

201
  to_hdf5_inner(group);
25,332✔
202

203
  // Write fill information.
204
  if (type_ == Fill::MATERIAL) {
25,332✔
205
    write_dataset(group, "fill_type", "material");
20,573✔
206
    std::vector<int32_t> mat_ids;
20,573✔
207
    for (auto i_mat : material_) {
43,559✔
208
      if (i_mat != MATERIAL_VOID) {
22,986✔
209
        mat_ids.push_back(model::materials[i_mat]->id_);
15,085✔
210
      } else {
211
        mat_ids.push_back(MATERIAL_VOID);
7,901✔
212
      }
213
    }
214
    if (mat_ids.size() == 1) {
20,573✔
215
      write_dataset(group, "material", mat_ids[0]);
20,262✔
216
    } else {
217
      write_dataset(group, "material", mat_ids);
311✔
218
    }
219

220
    std::vector<double> temps;
20,573✔
221
    for (auto sqrtkT_val : sqrtkT_)
43,694✔
222
      temps.push_back(sqrtkT_val * sqrtkT_val / K_BOLTZMANN);
23,121✔
223
    write_dataset(group, "temperature", temps);
20,573✔
224

225
  } else if (type_ == Fill::UNIVERSE) {
25,332✔
226
    write_dataset(group, "fill_type", "universe");
3,600✔
227
    write_dataset(group, "fill", model::universes[fill_]->id_);
3,600✔
228
    if (translation_ != Position(0, 0, 0)) {
3,600✔
229
      write_dataset(group, "translation", translation_);
2,004✔
230
    }
231
    if (!rotation_.empty()) {
3,600✔
232
      if (rotation_.size() == 12) {
288✔
233
        std::array<double, 3> rot {rotation_[9], rotation_[10], rotation_[11]};
288✔
234
        write_dataset(group, "rotation", rot);
288✔
235
      } else {
236
        write_dataset(group, "rotation", rotation_);
×
237
      }
238
    }
239

240
  } else if (type_ == Fill::LATTICE) {
1,159✔
241
    write_dataset(group, "fill_type", "lattice");
1,159✔
242
    write_dataset(group, "lattice", model::lattices[fill_]->id_);
1,159✔
243
  }
244

245
  close_group(group);
25,332✔
246
}
25,332✔
247

248
//==============================================================================
249
// CSGCell implementation
250
//==============================================================================
251

252
// default constructor
253
CSGCell::CSGCell()
24✔
254
{
255
  geom_type() = GeometryType::CSG;
24✔
256
}
24✔
257

258
CSGCell::CSGCell(pugi::xml_node cell_node)
31,132✔
259
{
260
  geom_type() = GeometryType::CSG;
31,132✔
261

262
  if (check_for_node(cell_node, "id")) {
31,132✔
263
    id_ = std::stoi(get_node_value(cell_node, "id"));
31,132✔
264
  } else {
265
    fatal_error("Must specify id of cell in geometry XML file.");
×
266
  }
267

268
  if (check_for_node(cell_node, "name")) {
31,132✔
269
    name_ = get_node_value(cell_node, "name");
5,917✔
270
  }
271

272
  if (check_for_node(cell_node, "universe")) {
31,132✔
273
    universe_ = std::stoi(get_node_value(cell_node, "universe"));
29,805✔
274
  } else {
275
    universe_ = 0;
1,327✔
276
  }
277

278
  // Make sure that either material or fill was specified, but not both.
279
  bool fill_present = check_for_node(cell_node, "fill");
31,132✔
280
  bool material_present = check_for_node(cell_node, "material");
31,132✔
281
  if (!(fill_present || material_present)) {
31,132✔
282
    fatal_error(
×
283
      fmt::format("Neither material nor fill was specified for cell {}", id_));
×
284
  }
285
  if (fill_present && material_present) {
31,132✔
286
    fatal_error(fmt::format("Cell {} has both a material and a fill specified; "
×
287
                            "only one can be specified per cell",
288
      id_));
×
289
  }
290

291
  if (fill_present) {
31,132✔
292
    fill_ = std::stoi(get_node_value(cell_node, "fill"));
6,466✔
293
    if (fill_ == universe_) {
6,466✔
294
      fatal_error(fmt::format("Cell {} is filled with the same universe that "
×
295
                              "it is contained in.",
296
        id_));
×
297
    }
298
  } else {
299
    fill_ = C_NONE;
24,666✔
300
  }
301

302
  // Read the material element.  There can be zero materials (filled with a
303
  // universe), more than one material (distribmats), and some materials may
304
  // be "void".
305
  if (material_present) {
31,132✔
306
    vector<std::string> mats {
307
      get_node_array<std::string>(cell_node, "material", true)};
24,666✔
308
    if (mats.size() > 0) {
24,666✔
309
      material_.reserve(mats.size());
24,666✔
310
      for (std::string mat : mats) {
51,751✔
311
        if (mat.compare("void") == 0) {
27,085✔
312
          material_.push_back(MATERIAL_VOID);
8,175✔
313
        } else {
314
          material_.push_back(std::stoi(mat));
18,910✔
315
        }
316
      }
27,085✔
317
    } else {
318
      fatal_error(fmt::format(
×
319
        "An empty material element was specified for cell {}", id_));
×
320
    }
321
  }
24,666✔
322

323
  // Read the temperature element which may be distributed like materials.
324
  if (check_for_node(cell_node, "temperature")) {
31,132✔
325
    sqrtkT_ = get_node_array<double>(cell_node, "temperature");
335✔
326
    sqrtkT_.shrink_to_fit();
335✔
327

328
    // Make sure this is a material-filled cell.
329
    if (material_.size() == 0) {
335✔
330
      fatal_error(fmt::format(
×
331
        "Cell {} was specified with a temperature but no material. Temperature"
332
        "specification is only valid for cells filled with a material.",
333
        id_));
×
334
    }
335

336
    // Make sure all temperatures are non-negative.
337
    for (auto T : sqrtkT_) {
721✔
338
      if (T < 0) {
386✔
339
        fatal_error(fmt::format(
×
340
          "Cell {} was specified with a negative temperature", id_));
×
341
      }
342
    }
343

344
    // Convert to sqrt(k*T).
345
    for (auto& T : sqrtkT_) {
721✔
346
      T = std::sqrt(K_BOLTZMANN * T);
386✔
347
    }
348
  }
349

350
  // Read the region specification.
351
  std::string region_spec;
31,132✔
352
  if (check_for_node(cell_node, "region")) {
31,132✔
353
    region_spec = get_node_value(cell_node, "region");
22,921✔
354
  }
355

356
  // Get a tokenized representation of the region specification and apply De
357
  // Morgans law
358
  Region region(region_spec, id_);
31,132✔
359
  region_ = region;
31,132✔
360

361
  // Read the translation vector.
362
  if (check_for_node(cell_node, "translation")) {
31,132✔
363
    if (fill_ == C_NONE) {
2,897✔
364
      fatal_error(fmt::format("Cannot apply a translation to cell {}"
×
365
                              " because it is not filled with another universe",
366
        id_));
×
367
    }
368

369
    auto xyz {get_node_array<double>(cell_node, "translation")};
2,897✔
370
    if (xyz.size() != 3) {
2,897✔
371
      fatal_error(
×
372
        fmt::format("Non-3D translation vector applied to cell {}", id_));
×
373
    }
374
    translation_ = xyz;
2,897✔
375
  }
2,897✔
376

377
  // Read the rotation transform.
378
  if (check_for_node(cell_node, "rotation")) {
31,132✔
379
    auto rot {get_node_array<double>(cell_node, "rotation")};
442✔
380
    set_rotation(rot);
442✔
381
  }
442✔
382
}
31,132✔
383

384
//==============================================================================
385

386
void CSGCell::to_hdf5_inner(hid_t group_id) const
25,191✔
387
{
388
  write_string(group_id, "geom_type", "csg", false);
25,191✔
389
  write_string(group_id, "region", region_.str(), false);
25,191✔
390
}
25,191✔
391

392
//==============================================================================
393

394
vector<int32_t>::iterator CSGCell::find_left_parenthesis(
×
395
  vector<int32_t>::iterator start, const vector<int32_t>& infix)
396
{
397
  // start search at zero
398
  int parenthesis_level = 0;
×
399
  auto it = start;
×
400
  while (it != infix.begin()) {
×
401
    // look at two tokens at a time
402
    int32_t one = *it;
×
403
    int32_t two = *(it - 1);
×
404

405
    // decrement parenthesis level if there are two adjacent surfaces
406
    if (one < OP_UNION && two < OP_UNION) {
×
407
      parenthesis_level--;
×
408
      // increment if there are two adjacent operators
409
    } else if (one >= OP_UNION && two >= OP_UNION) {
×
410
      parenthesis_level++;
×
411
    }
412

413
    // if the level gets to zero, return the position
414
    if (parenthesis_level == 0) {
×
415
      // move the iterator back one before leaving the loop
416
      // so that all tokens in the parenthesis block are included
417
      it--;
×
418
      break;
×
419
    }
420

421
    // continue loop, one token at a time
422
    it--;
×
423
  }
424
  return it;
×
425
}
426

427
//==============================================================================
428
// Region implementation
429
//==============================================================================
430

431
Region::Region(std::string region_spec, int32_t cell_id)
31,132✔
432
{
433
  // Check if region_spec is not empty.
434
  if (!region_spec.empty()) {
31,132✔
435
    // Parse all halfspaces and operators except for intersection (whitespace).
436
    for (int i = 0; i < region_spec.size();) {
129,836✔
437
      if (region_spec[i] == '(') {
106,915✔
438
        expression_.push_back(OP_LEFT_PAREN);
1,100✔
439
        i++;
1,100✔
440

441
      } else if (region_spec[i] == ')') {
105,815✔
442
        expression_.push_back(OP_RIGHT_PAREN);
1,100✔
443
        i++;
1,100✔
444

445
      } else if (region_spec[i] == '|') {
104,715✔
446
        expression_.push_back(OP_UNION);
2,830✔
447
        i++;
2,830✔
448

449
      } else if (region_spec[i] == '~') {
101,885✔
450
        expression_.push_back(OP_COMPLEMENT);
34✔
451
        i++;
34✔
452

453
      } else if (region_spec[i] == '-' || region_spec[i] == '+' ||
171,541✔
454
                 std::isdigit(region_spec[i])) {
69,690✔
455
        // This is the start of a halfspace specification.  Iterate j until we
456
        // find the end, then push-back everything between i and j.
457
        int j = i + 1;
60,126✔
458
        while (j < region_spec.size() && std::isdigit(region_spec[j])) {
122,733✔
459
          j++;
62,607✔
460
        }
461
        expression_.push_back(std::stoi(region_spec.substr(i, j - i)));
60,126✔
462
        i = j;
60,126✔
463

464
      } else if (std::isspace(region_spec[i])) {
41,725✔
465
        i++;
41,725✔
466

467
      } else {
468
        auto err_msg =
469
          fmt::format("Region specification contains invalid character, \"{}\"",
470
            region_spec[i]);
×
471
        fatal_error(err_msg);
×
472
      }
×
473
    }
474

475
    // Add in intersection operators where a missing operator is needed.
476
    int i = 0;
22,921✔
477
    while (i < expression_.size() - 1) {
99,565✔
478
      bool left_compat {
479
        (expression_[i] < OP_UNION) || (expression_[i] == OP_RIGHT_PAREN)};
76,644✔
480
      bool right_compat {(expression_[i + 1] < OP_UNION) ||
76,644✔
481
                         (expression_[i + 1] == OP_LEFT_PAREN) ||
80,642✔
482
                         (expression_[i + 1] == OP_COMPLEMENT)};
3,998✔
483
      if (left_compat && right_compat) {
76,644✔
484
        expression_.insert(expression_.begin() + i + 1, OP_INTERSECTION);
34,375✔
485
      }
486
      i++;
76,644✔
487
    }
488

489
    // Remove complement operators using DeMorgan's laws
490
    auto it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
22,921✔
491
    while (it != expression_.end()) {
22,955✔
492
      // Erase complement
493
      expression_.erase(it);
34✔
494

495
      // Define stop given left parenthesis or not
496
      auto stop = it;
34✔
497
      if (*it == OP_LEFT_PAREN) {
34✔
498
        int depth = 1;
34✔
499
        do {
500
          stop++;
272✔
501
          if (*stop > OP_COMPLEMENT) {
272✔
502
            if (*stop == OP_RIGHT_PAREN) {
34✔
503
              depth--;
34✔
504
            } else {
UNCOV
505
              depth++;
×
506
            }
507
          }
508
        } while (depth > 0);
272✔
509
        it++;
34✔
510
      }
511

512
      // apply DeMorgan's law to any surfaces/operators between these
513
      // positions in the RPN
514
      apply_demorgan(it, stop);
34✔
515
      // update iterator position
516
      it = std::find(expression_.begin(), expression_.end(), OP_COMPLEMENT);
34✔
517
    }
518

519
    // Convert user IDs to surface indices.
520
    for (auto& r : expression_) {
122,452✔
521
      if (r < OP_UNION) {
99,531✔
522
        const auto& it {model::surface_map.find(abs(r))};
60,126✔
523
        if (it == model::surface_map.end()) {
60,126✔
524
          throw std::runtime_error {
×
525
            "Invalid surface ID " + std::to_string(abs(r)) +
×
526
            " specified in region for cell " + std::to_string(cell_id) + "."};
×
527
        }
528
        r = (r > 0) ? it->second + 1 : -(it->second + 1);
60,126✔
529
      }
530
    }
531

532
    // Check if this is a simple cell.
533
    simple_ = true;
22,921✔
534
    for (int32_t token : expression_) {
111,798✔
535
      if (token == OP_UNION) {
89,761✔
536
        simple_ = false;
884✔
537
        // Ensure intersections have precedence over unions
538
        add_precedence();
884✔
539
        break;
884✔
540
      }
541
    }
542

543
    // If this cell is simple, remove all the superfluous operator tokens.
544
    if (simple_) {
22,921✔
545
      for (auto it = expression_.begin(); it != expression_.end(); it++) {
106,332✔
546
        if (*it == OP_INTERSECTION || *it > OP_COMPLEMENT) {
84,295✔
547
          expression_.erase(it);
31,129✔
548
          it--;
31,129✔
549
        }
550
      }
551
    }
552
    expression_.shrink_to_fit();
22,921✔
553

554
  } else {
555
    simple_ = true;
8,211✔
556
  }
557
}
31,132✔
558

559
//==============================================================================
560

561
void Region::apply_demorgan(
238✔
562
  vector<int32_t>::iterator start, vector<int32_t>::iterator stop)
563
{
564
  do {
565
    if (*start < OP_UNION) {
238✔
566
      *start *= -1;
136✔
567
    } else if (*start == OP_UNION) {
102✔
UNCOV
568
      *start = OP_INTERSECTION;
×
569
    } else if (*start == OP_INTERSECTION) {
102✔
570
      *start = OP_UNION;
102✔
571
    }
572
    start++;
238✔
573
  } while (start < stop);
238✔
574
}
34✔
575

576
//==============================================================================
577
//! Add precedence for infix regions so intersections have higher
578
//! precedence than unions using parentheses.
579
//==============================================================================
580

581
gsl::index Region::add_parentheses(gsl::index start)
34✔
582
{
583
  int32_t start_token = expression_[start];
34✔
584
  // Add left parenthesis and set new position to be after parenthesis
585
  if (start_token == OP_UNION) {
34✔
586
    start += 2;
×
587
  }
588
  expression_.insert(expression_.begin() + start - 1, OP_LEFT_PAREN);
34✔
589

590
  // Keep track of return iterator distance. If we don't encounter a left
591
  // parenthesis, we return an iterator corresponding to wherever the right
592
  // parenthesis is inserted. If a left parenthesis is encountered, an iterator
593
  // corresponding to the left parenthesis is returned. Also note that we keep
594
  // track of a *distance* instead of an iterator because the underlying memory
595
  // allocation may change.
596
  std::size_t return_it_dist = 0;
34✔
597

598
  // Add right parenthesis
599
  // While the start iterator is within the bounds of infix
600
  while (start + 1 < expression_.size()) {
238✔
601
    start++;
238✔
602

603
    // If the current token is an operator and is different than the start token
604
    if (expression_[start] >= OP_UNION && expression_[start] != start_token) {
238✔
605
      // Skip wrapped regions but save iterator position to check precedence and
606
      // add right parenthesis, right parenthesis position depends on the
607
      // operator, when the operator is a union then do not include the operator
608
      // in the region, when the operator is an intersection then include the
609
      // operator and next surface
610
      if (expression_[start] == OP_LEFT_PAREN) {
34✔
611
        return_it_dist = start;
×
612
        int depth = 1;
×
613
        do {
614
          start++;
×
615
          if (expression_[start] > OP_COMPLEMENT) {
×
616
            if (expression_[start] == OP_RIGHT_PAREN) {
×
617
              depth--;
×
618
            } else {
619
              depth++;
×
620
            }
621
          }
622
        } while (depth > 0);
×
623
      } else {
624
        if (start_token == OP_UNION) {
34✔
625
          --start;
×
626
        }
627
        expression_.insert(expression_.begin() + start, OP_RIGHT_PAREN);
34✔
628
        if (return_it_dist > 0) {
34✔
629
          return return_it_dist;
×
630
        } else {
631
          return start - 1;
34✔
632
        }
633
      }
634
    }
635
  }
636
  // If we get here a right parenthesis hasn't been placed,
637
  // return iterator
638
  expression_.push_back(OP_RIGHT_PAREN);
×
639
  if (return_it_dist > 0) {
×
640
    return return_it_dist;
×
641
  } else {
642
    return start - 1;
×
643
  }
644
}
645

646
//==============================================================================
647

648
void Region::add_precedence()
884✔
649
{
650
  int32_t current_op = 0;
884✔
651
  std::size_t current_dist = 0;
884✔
652

653
  for (gsl::index i = 0; i < expression_.size(); i++) {
16,086✔
654
    int32_t token = expression_[i];
15,202✔
655

656
    if (token == OP_UNION || token == OP_INTERSECTION) {
15,202✔
657
      if (current_op == 0) {
6,059✔
658
        // Set the current operator if is hasn't been set
659
        current_op = token;
2,069✔
660
        current_dist = i;
2,069✔
661
      } else if (token != current_op) {
3,990✔
662
        // If the current operator doesn't match the token, add parenthesis to
663
        // assert precedence
664
        if (current_op == OP_INTERSECTION) {
34✔
665
          i = add_parentheses(current_dist);
17✔
666
        } else {
667
          i = add_parentheses(i);
17✔
668
        }
669
        current_op = 0;
34✔
670
        current_dist = 0;
34✔
671
      }
672
    } else if (token > OP_COMPLEMENT) {
9,143✔
673
      // If the token is a parenthesis reset the current operator
674
      current_op = 0;
2,234✔
675
      current_dist = 0;
2,234✔
676
    }
677
  }
678
}
884✔
679

680
//==============================================================================
681
//! Convert infix region specification to Reverse Polish Notation (RPN)
682
//!
683
//! This function uses the shunting-yard algorithm.
684
//==============================================================================
685

686
vector<int32_t> Region::generate_postfix(int32_t cell_id) const
48✔
687
{
688
  vector<int32_t> rpn;
48✔
689
  vector<int32_t> stack;
48✔
690

691
  for (int32_t token : expression_) {
1,080✔
692
    if (token < OP_UNION) {
1,032✔
693
      // If token is not an operator, add it to output
694
      rpn.push_back(token);
432✔
695
    } else if (token < OP_RIGHT_PAREN) {
600✔
696
      // Regular operators union, intersection, complement
697
      while (stack.size() > 0) {
612✔
698
        int32_t op = stack.back();
504✔
699

700
        if (op < OP_RIGHT_PAREN && ((token == OP_COMPLEMENT && token < op) ||
504✔
701
                                     (token != OP_COMPLEMENT && token <= op))) {
228✔
702
          // While there is an operator, op, on top of the stack, if the token
703
          // is left-associative and its precedence is less than or equal to
704
          // that of op or if the token is right-associative and its precedence
705
          // is less than that of op, move op to the output queue and push the
706
          // token on to the stack. Note that only complement is
707
          // right-associative.
708
          rpn.push_back(op);
228✔
709
          stack.pop_back();
228✔
710
        } else {
711
          break;
712
        }
713
      }
714

715
      stack.push_back(token);
384✔
716

717
    } else if (token == OP_LEFT_PAREN) {
216✔
718
      // If the token is a left parenthesis, push it onto the stack
719
      stack.push_back(token);
108✔
720

721
    } else {
722
      // If the token is a right parenthesis, move operators from the stack to
723
      // the output queue until reaching the left parenthesis.
724
      for (auto it = stack.rbegin(); *it != OP_LEFT_PAREN; it++) {
216✔
725
        // If we run out of operators without finding a left parenthesis, it
726
        // means there are mismatched parentheses.
727
        if (it == stack.rend()) {
108✔
728
          fatal_error(fmt::format(
×
729
            "Mismatched parentheses in region specification for cell {}",
730
            cell_id));
731
        }
732
        rpn.push_back(stack.back());
108✔
733
        stack.pop_back();
108✔
734
      }
735

736
      // Pop the left parenthesis.
737
      stack.pop_back();
108✔
738
    }
739
  }
740

741
  while (stack.size() > 0) {
96✔
742
    int32_t op = stack.back();
48✔
743

744
    // If the operator is a parenthesis it is mismatched.
745
    if (op >= OP_RIGHT_PAREN) {
48✔
746
      fatal_error(fmt::format(
×
747
        "Mismatched parentheses in region specification for cell {}", cell_id));
748
    }
749

750
    rpn.push_back(stack.back());
48✔
751
    stack.pop_back();
48✔
752
  }
753

754
  return rpn;
96✔
755
}
48✔
756

757
//==============================================================================
758

759
std::string Region::str() const
25,191✔
760
{
761
  std::stringstream region_spec {};
25,191✔
762
  if (!expression_.empty()) {
25,191✔
763
    for (int32_t token : expression_) {
72,144✔
764
      if (token == OP_LEFT_PAREN) {
54,562✔
765
        region_spec << " (";
988✔
766
      } else if (token == OP_RIGHT_PAREN) {
53,574✔
767
        region_spec << " )";
988✔
768
      } else if (token == OP_COMPLEMENT) {
52,586✔
769
        region_spec << " ~";
×
770
      } else if (token == OP_INTERSECTION) {
52,586✔
771
      } else if (token == OP_UNION) {
49,850✔
772
        region_spec << " |";
2,622✔
773
      } else {
774
        // Note the off-by-one indexing
775
        auto surf_id = model::surfaces[abs(token) - 1]->id_;
47,228✔
776
        region_spec << " " << ((token > 0) ? surf_id : -surf_id);
47,228✔
777
      }
778
    }
779
  }
780
  return region_spec.str();
50,382✔
781
}
25,191✔
782

783
//==============================================================================
784

785
std::pair<double, int32_t> Region::distance(
2,147,483,647✔
786
  Position r, Direction u, int32_t on_surface) const
787
{
788
  double min_dist {INFTY};
2,147,483,647✔
789
  int32_t i_surf {std::numeric_limits<int32_t>::max()};
2,147,483,647✔
790

791
  for (int32_t token : expression_) {
2,147,483,647✔
792
    // Ignore this token if it corresponds to an operator rather than a region.
793
    if (token >= OP_UNION)
2,147,483,647✔
794
      continue;
176,973,483✔
795

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

801
    // Check if this distance is the new minimum.
802
    if (d < min_dist) {
2,147,483,647✔
803
      if (min_dist - d >= FP_PRECISION * min_dist) {
2,147,483,647✔
804
        min_dist = d;
2,147,483,647✔
805
        i_surf = -token;
2,147,483,647✔
806
      }
807
    }
808
  }
809

810
  return {min_dist, i_surf};
2,147,483,647✔
811
}
812

813
//==============================================================================
814

815
bool Region::contains(Position r, Direction u, int32_t on_surface) const
2,147,483,647✔
816
{
817
  if (simple_) {
2,147,483,647✔
818
    return contains_simple(r, u, on_surface);
2,147,483,647✔
819
  } else {
820
    return contains_complex(r, u, on_surface);
6,337,874✔
821
  }
822
}
823

824
//==============================================================================
825

826
bool Region::contains_simple(Position r, Direction u, int32_t on_surface) const
2,147,483,647✔
827
{
828
  for (int32_t token : expression_) {
2,147,483,647✔
829
    // Assume that no tokens are operators. Evaluate the sense of particle with
830
    // respect to the surface and see if the token matches the sense. If the
831
    // particle's surface attribute is set and matches the token, that
832
    // overrides the determination based on sense().
833
    if (token == on_surface) {
2,147,483,647✔
834
    } else if (-token == on_surface) {
2,147,483,647✔
835
      return false;
1,031,125,336✔
836
    } else {
837
      // Note the off-by-one indexing
838
      bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
2,147,483,647✔
839
      if (sense != (token > 0)) {
2,147,483,647✔
840
        return false;
891,334,327✔
841
      }
842
    }
843
  }
844
  return true;
2,147,483,647✔
845
}
846

847
//==============================================================================
848

849
bool Region::contains_complex(Position r, Direction u, int32_t on_surface) const
6,337,874✔
850
{
851
  bool in_cell = true;
6,337,874✔
852
  int total_depth = 0;
6,337,874✔
853

854
  // For each token
855
  for (auto it = expression_.begin(); it != expression_.end(); it++) {
101,554,376✔
856
    int32_t token = *it;
96,968,102✔
857

858
    // If the token is a surface evaluate the sense
859
    // If the token is a union or intersection check to
860
    // short circuit
861
    if (token < OP_UNION) {
96,968,102✔
862
      if (token == on_surface) {
42,419,990✔
863
        in_cell = true;
3,498,213✔
864
      } else if (-token == on_surface) {
38,921,777✔
865
        in_cell = false;
704,281✔
866
      } else {
867
        // Note the off-by-one indexing
868
        bool sense = model::surfaces[abs(token) - 1]->sense(r, u);
38,217,496✔
869
        in_cell = (sense == (token > 0));
38,217,496✔
870
      }
871
    } else if ((token == OP_UNION && in_cell == true) ||
54,548,112✔
872
               (token == OP_INTERSECTION && in_cell == false)) {
26,748,461✔
873
      // If the total depth is zero return
874
      if (total_depth == 0) {
5,925,562✔
875
        return in_cell;
1,751,600✔
876
      }
877

878
      total_depth--;
4,173,962✔
879

880
      // While the iterator is within the bounds of the vector
881
      int depth = 1;
4,173,962✔
882
      do {
883
        // Get next token
884
        it++;
25,274,294✔
885
        int32_t next_token = *it;
25,274,294✔
886

887
        // If the token is an a parenthesis
888
        if (next_token > OP_COMPLEMENT) {
25,274,294✔
889
          // Adjust depth accordingly
890
          if (next_token == OP_RIGHT_PAREN) {
4,380,828✔
891
            depth--;
4,277,395✔
892
          } else {
893
            depth++;
103,433✔
894
          }
895
        }
896
      } while (depth > 0);
25,274,294✔
897
    } else if (token == OP_LEFT_PAREN) {
52,796,512✔
898
      total_depth++;
8,357,198✔
899
    } else if (token == OP_RIGHT_PAREN) {
40,265,352✔
900
      total_depth--;
4,183,236✔
901
    }
902
  }
903
  return in_cell;
4,586,274✔
904
}
905

906
//==============================================================================
907

908
BoundingBox Region::bounding_box(int32_t cell_id) const
96✔
909
{
910
  if (simple_) {
96✔
911
    return bounding_box_simple();
48✔
912
  } else {
913
    auto postfix = generate_postfix(cell_id);
48✔
914
    return bounding_box_complex(postfix);
48✔
915
  }
48✔
916
}
917

918
//==============================================================================
919

920
BoundingBox Region::bounding_box_simple() const
48✔
921
{
922
  BoundingBox bbox;
48✔
923
  for (int32_t token : expression_) {
192✔
924
    bbox &= model::surfaces[abs(token) - 1]->bounding_box(token > 0);
144✔
925
  }
926
  return bbox;
48✔
927
}
928

929
//==============================================================================
930

931
BoundingBox Region::bounding_box_complex(vector<int32_t> postfix) const
48✔
932
{
933
  vector<BoundingBox> stack(postfix.size());
48✔
934
  int i_stack = -1;
48✔
935

936
  for (auto& token : postfix) {
864✔
937
    if (token == OP_UNION) {
816✔
938
      stack[i_stack - 1] = stack[i_stack - 1] | stack[i_stack];
168✔
939
      i_stack--;
168✔
940
    } else if (token == OP_INTERSECTION) {
648✔
941
      stack[i_stack - 1] = stack[i_stack - 1] & stack[i_stack];
216✔
942
      i_stack--;
216✔
943
    } else {
944
      i_stack++;
432✔
945
      stack[i_stack] = model::surfaces[abs(token) - 1]->bounding_box(token > 0);
432✔
946
    }
947
  }
948

949
  Ensures(i_stack == 0);
48✔
950
  return stack.front();
96✔
951
}
48✔
952

953
//==============================================================================
954

955
vector<int32_t> Region::surfaces() const
5,864✔
956
{
957
  if (simple_) {
5,864✔
958
    return expression_;
5,864✔
959
  }
960

961
  vector<int32_t> surfaces = expression_;
×
962

963
  auto it = std::find_if(surfaces.begin(), surfaces.end(),
×
964
    [&](const auto& value) { return value >= OP_UNION; });
×
965

966
  while (it != surfaces.end()) {
×
967
    surfaces.erase(it);
×
968

969
    it = std::find_if(surfaces.begin(), surfaces.end(),
×
970
      [&](const auto& value) { return value >= OP_UNION; });
×
971
  }
972

973
  return surfaces;
×
974
}
975

976
//==============================================================================
977
// Non-method functions
978
//==============================================================================
979

980
void read_cells(pugi::xml_node node)
6,811✔
981
{
982
  // Count the number of cells.
983
  int n_cells = 0;
6,811✔
984
  for (pugi::xml_node cell_node : node.children("cell")) {
37,943✔
985
    n_cells++;
31,132✔
986
  }
987

988
  // Loop over XML cell elements and populate the array.
989
  model::cells.reserve(n_cells);
6,811✔
990
  for (pugi::xml_node cell_node : node.children("cell")) {
37,943✔
991
    model::cells.push_back(make_unique<CSGCell>(cell_node));
31,132✔
992
  }
993

994
  // Fill the cell map.
995
  for (int i = 0; i < model::cells.size(); i++) {
37,943✔
996
    int32_t id = model::cells[i]->id_;
31,132✔
997
    auto search = model::cell_map.find(id);
31,132✔
998
    if (search == model::cell_map.end()) {
31,132✔
999
      model::cell_map[id] = i;
31,132✔
1000
    } else {
1001
      fatal_error(
×
1002
        fmt::format("Two or more cells use the same unique ID: {}", id));
×
1003
    }
1004
  }
1005

1006
  read_dagmc_universes(node);
6,811✔
1007

1008
  populate_universes();
6,809✔
1009

1010
  // Allocate the cell overlap count if necessary.
1011
  if (settings::check_overlaps) {
6,809✔
1012
    model::overlap_check_count.resize(model::cells.size(), 0);
286✔
1013
  }
1014

1015
  if (model::cells.size() == 0) {
6,809✔
1016
    fatal_error("No cells were found in the geometry.xml file");
×
1017
  }
1018
}
6,809✔
1019

1020
void populate_universes()
6,811✔
1021
{
1022
  // Used to map universe index to the index of an implicit complement cell for
1023
  // DAGMC universes
1024
  std::unordered_map<int, int> implicit_comp_cells;
6,811✔
1025

1026
  // Populate the Universe vector and map.
1027
  for (int index_cell = 0; index_cell < model::cells.size(); index_cell++) {
38,130✔
1028
    int32_t uid = model::cells[index_cell]->universe_;
31,319✔
1029
    auto it = model::universe_map.find(uid);
31,319✔
1030
    if (it == model::universe_map.end()) {
31,319✔
1031
      model::universes.push_back(make_unique<Universe>());
17,569✔
1032
      model::universes.back()->id_ = uid;
17,569✔
1033
      model::universes.back()->cells_.push_back(index_cell);
17,569✔
1034
      model::universe_map[uid] = model::universes.size() - 1;
17,569✔
1035
    } else {
1036
#ifdef DAGMC
1037
      // Skip implicit complement cells for now
1038
      Universe* univ = model::universes[it->second].get();
1,699✔
1039
      DAGUniverse* dag_univ = dynamic_cast<DAGUniverse*>(univ);
1,699✔
1040
      if (dag_univ && (dag_univ->implicit_complement_idx() == index_cell)) {
1,699✔
1041
        implicit_comp_cells[it->second] = index_cell;
37✔
1042
        continue;
37✔
1043
      }
1044
#endif
1045

1046
      model::universes[it->second]->cells_.push_back(index_cell);
13,713✔
1047
    }
1048
  }
1049

1050
  // Add DAGUniverse implicit complement cells last
1051
  for (const auto& it : implicit_comp_cells) {
6,848✔
1052
    int index_univ = it.first;
37✔
1053
    int index_cell = it.second;
37✔
1054
    model::universes[index_univ]->cells_.push_back(index_cell);
37✔
1055
  }
1056

1057
  model::universes.shrink_to_fit();
6,811✔
1058
}
6,811✔
1059

1060
//==============================================================================
1061
// C-API functions
1062
//==============================================================================
1063

1064
extern "C" int openmc_cell_get_fill(
177✔
1065
  int32_t index, int* type, int32_t** indices, int32_t* n)
1066
{
1067
  if (index >= 0 && index < model::cells.size()) {
177✔
1068
    Cell& c {*model::cells[index]};
177✔
1069
    *type = static_cast<int>(c.type_);
177✔
1070
    if (c.type_ == Fill::MATERIAL) {
177✔
1071
      *indices = c.material_.data();
177✔
1072
      *n = c.material_.size();
177✔
1073
    } else {
1074
      *indices = &c.fill_;
×
1075
      *n = 1;
×
1076
    }
1077
  } else {
1078
    set_errmsg("Index in cells array is out of bounds.");
×
1079
    return OPENMC_E_OUT_OF_BOUNDS;
×
1080
  }
1081
  return 0;
177✔
1082
}
1083

1084
extern "C" int openmc_cell_set_fill(
12✔
1085
  int32_t index, int type, int32_t n, const int32_t* indices)
1086
{
1087
  Fill filltype = static_cast<Fill>(type);
12✔
1088
  if (index >= 0 && index < model::cells.size()) {
12✔
1089
    Cell& c {*model::cells[index]};
12✔
1090
    if (filltype == Fill::MATERIAL) {
12✔
1091
      c.type_ = Fill::MATERIAL;
12✔
1092
      c.material_.clear();
12✔
1093
      for (int i = 0; i < n; i++) {
24✔
1094
        int i_mat = indices[i];
12✔
1095
        if (i_mat == MATERIAL_VOID) {
12✔
1096
          c.material_.push_back(MATERIAL_VOID);
×
1097
        } else if (i_mat >= 0 && i_mat < model::materials.size()) {
12✔
1098
          c.material_.push_back(i_mat);
12✔
1099
        } else {
1100
          set_errmsg("Index in materials array is out of bounds.");
×
1101
          return OPENMC_E_OUT_OF_BOUNDS;
×
1102
        }
1103
      }
1104
      c.material_.shrink_to_fit();
12✔
1105
    } else if (filltype == Fill::UNIVERSE) {
×
1106
      c.type_ = Fill::UNIVERSE;
×
1107
    } else {
1108
      c.type_ = Fill::LATTICE;
×
1109
    }
1110
  } else {
1111
    set_errmsg("Index in cells array is out of bounds.");
×
1112
    return OPENMC_E_OUT_OF_BOUNDS;
×
1113
  }
1114
  return 0;
12✔
1115
}
1116

1117
extern "C" int openmc_cell_set_temperature(
96✔
1118
  int32_t index, double T, const int32_t* instance, bool set_contained)
1119
{
1120
  if (index < 0 || index >= model::cells.size()) {
96✔
1121
    strcpy(openmc_err_msg, "Index in cells array is out of bounds.");
×
1122
    return OPENMC_E_OUT_OF_BOUNDS;
×
1123
  }
1124

1125
  int32_t instance_index = instance ? *instance : -1;
96✔
1126
  try {
1127
    model::cells[index]->set_temperature(T, instance_index, set_contained);
96✔
1128
  } catch (const std::exception& e) {
×
1129
    set_errmsg(e.what());
×
1130
    return OPENMC_E_UNASSIGNED;
×
1131
  }
×
1132
  return 0;
96✔
1133
}
1134

1135
extern "C" int openmc_cell_get_temperature(
99✔
1136
  int32_t index, const int32_t* instance, double* T)
1137
{
1138
  if (index < 0 || index >= model::cells.size()) {
99✔
1139
    strcpy(openmc_err_msg, "Index in cells array is out of bounds.");
×
1140
    return OPENMC_E_OUT_OF_BOUNDS;
×
1141
  }
1142

1143
  int32_t instance_index = instance ? *instance : -1;
99✔
1144
  try {
1145
    *T = model::cells[index]->temperature(instance_index);
99✔
1146
  } catch (const std::exception& e) {
×
1147
    set_errmsg(e.what());
×
1148
    return OPENMC_E_UNASSIGNED;
×
1149
  }
×
1150
  return 0;
99✔
1151
}
1152

1153
//! Get the bounding box of a cell
1154
extern "C" int openmc_cell_bounding_box(
60✔
1155
  const int32_t index, double* llc, double* urc)
1156
{
1157

1158
  BoundingBox bbox;
60✔
1159

1160
  const auto& c = model::cells[index];
60✔
1161
  bbox = c->bounding_box();
60✔
1162

1163
  // set lower left corner values
1164
  llc[0] = bbox.xmin;
60✔
1165
  llc[1] = bbox.ymin;
60✔
1166
  llc[2] = bbox.zmin;
60✔
1167

1168
  // set upper right corner values
1169
  urc[0] = bbox.xmax;
60✔
1170
  urc[1] = bbox.ymax;
60✔
1171
  urc[2] = bbox.zmax;
60✔
1172

1173
  return 0;
60✔
1174
}
1175

1176
//! Get the name of a cell
1177
extern "C" int openmc_cell_get_name(int32_t index, const char** name)
24✔
1178
{
1179
  if (index < 0 || index >= model::cells.size()) {
24✔
1180
    set_errmsg("Index in cells array is out of bounds.");
×
1181
    return OPENMC_E_OUT_OF_BOUNDS;
×
1182
  }
1183

1184
  *name = model::cells[index]->name().data();
24✔
1185

1186
  return 0;
24✔
1187
}
1188

1189
//! Set the name of a cell
1190
extern "C" int openmc_cell_set_name(int32_t index, const char* name)
12✔
1191
{
1192
  if (index < 0 || index >= model::cells.size()) {
12✔
1193
    set_errmsg("Index in cells array is out of bounds.");
×
1194
    return OPENMC_E_OUT_OF_BOUNDS;
×
1195
  }
1196

1197
  model::cells[index]->set_name(name);
12✔
1198

1199
  return 0;
12✔
1200
}
1201

1202
//==============================================================================
1203
//! Define a containing (parent) cell
1204
//==============================================================================
1205

1206
//! Used to locate a universe fill in the geometry
1207
struct ParentCell {
1208
  bool operator==(const ParentCell& other) const
102✔
1209
  {
1210
    return cell_index == other.cell_index &&
204✔
1211
           lattice_index == other.lattice_index;
204✔
1212
  }
1213

1214
  bool operator<(const ParentCell& other) const
1215
  {
1216
    return cell_index < other.cell_index ||
1217
           (cell_index == other.cell_index &&
1218
             lattice_index < other.lattice_index);
1219
  }
1220

1221
  gsl::index cell_index;
1222
  gsl::index lattice_index;
1223
};
1224

1225
//! Structure used to insert ParentCell into hashed STL data structures
1226
struct ParentCellHash {
1227
  std::size_t operator()(const ParentCell& p) const
323✔
1228
  {
1229
    return 4096 * p.cell_index + p.lattice_index;
323✔
1230
  }
1231
};
1232

1233
//! Used to manage a traversal stack when locating parent cells of a cell
1234
//! instance in the model
1235
struct ParentCellStack {
1236

1237
  //! push method that adds to the parent_cells visited cells for this search
1238
  //! universe
1239
  void push(int32_t search_universe, const ParentCell& pc)
68✔
1240
  {
1241
    parent_cells_.push_back(pc);
68✔
1242
    // add parent cell to the set of cells we've visited for this search
1243
    // universe
1244
    visited_cells_[search_universe].insert(pc);
68✔
1245
  }
68✔
1246

1247
  //! removes the last parent_cell and clears the visited cells for the popped
1248
  //! cell's universe
1249
  void pop()
51✔
1250
  {
1251
    visited_cells_[this->current_univ()].clear();
51✔
1252
    parent_cells_.pop_back();
51✔
1253
  }
51✔
1254

1255
  //! checks whether or not the parent cell has been visited already for this
1256
  //! search universe
1257
  bool visited(int32_t search_universe, const ParentCell& parent_cell)
255✔
1258
  {
1259
    return visited_cells_[search_universe].count(parent_cell) != 0;
255✔
1260
  }
1261

1262
  //! return the next universe to search for a parent cell
1263
  int32_t current_univ() const
51✔
1264
  {
1265
    return model::cells[parent_cells_.back().cell_index]->universe_;
51✔
1266
  }
1267

1268
  //! indicates whether nor not parent cells are present on the stack
1269
  bool empty() const { return parent_cells_.empty(); }
51✔
1270

1271
  //! compute an instance for the provided distribcell index
1272
  int32_t compute_instance(int32_t distribcell_index) const
85✔
1273
  {
1274
    if (distribcell_index == C_NONE)
85✔
1275
      return 0;
×
1276

1277
    int32_t instance = 0;
85✔
1278
    for (const auto& parent_cell : this->parent_cells_) {
153✔
1279
      auto& cell = model::cells[parent_cell.cell_index];
68✔
1280
      if (cell->type_ == Fill::UNIVERSE) {
68✔
1281
        instance += cell->offset_[distribcell_index];
×
1282
      } else if (cell->type_ == Fill::LATTICE) {
68✔
1283
        auto& lattice = model::lattices[cell->fill_];
68✔
1284
        instance +=
68✔
1285
          lattice->offset(distribcell_index, parent_cell.lattice_index);
68✔
1286
      }
1287
    }
1288
    return instance;
85✔
1289
  }
1290

1291
  // Accessors
1292
  vector<ParentCell>& parent_cells() { return parent_cells_; }
102✔
1293
  const vector<ParentCell>& parent_cells() const { return parent_cells_; }
1294

1295
  // Data Members
1296
  vector<ParentCell> parent_cells_;
1297
  std::unordered_map<int32_t, std::unordered_set<ParentCell, ParentCellHash>>
1298
    visited_cells_;
1299
};
1300

1301
vector<ParentCell> Cell::find_parent_cells(
×
1302
  int32_t instance, const Position& r) const
1303
{
1304

1305
  // create a temporary particle
1306
  GeometryState dummy_particle {};
×
1307
  dummy_particle.r() = r;
×
1308
  dummy_particle.u() = {0., 0., 1.};
×
1309

1310
  return find_parent_cells(instance, dummy_particle);
×
1311
}
1312

1313
vector<ParentCell> Cell::find_parent_cells(
×
1314
  int32_t instance, GeometryState& p) const
1315
{
1316
  // look up the particle's location
1317
  exhaustive_find_cell(p);
×
1318
  const auto& coords = p.coord();
×
1319

1320
  // build a parent cell stack from the particle coordinates
1321
  ParentCellStack stack;
×
1322
  bool cell_found = false;
×
1323
  for (auto it = coords.begin(); it != coords.end(); it++) {
×
1324
    const auto& coord = *it;
×
1325
    const auto& cell = model::cells[coord.cell];
×
1326
    // if the cell at this level matches the current cell, stop adding to the
1327
    // stack
1328
    if (coord.cell == model::cell_map[this->id_]) {
×
1329
      cell_found = true;
×
1330
      break;
×
1331
    }
1332

1333
    // if filled with a lattice, get the lattice index from the next
1334
    // level in the coordinates to push to the stack
1335
    int lattice_idx = C_NONE;
×
1336
    if (cell->type_ == Fill::LATTICE) {
×
1337
      const auto& next_coord = *(it + 1);
×
1338
      lattice_idx = model::lattices[next_coord.lattice]->get_flat_index(
×
1339
        next_coord.lattice_i);
×
1340
    }
1341
    stack.push(coord.universe, {coord.cell, lattice_idx});
×
1342
  }
1343

1344
  // if this loop finished because the cell was found and
1345
  // the instance matches the one requested in the call
1346
  // we have the correct path and can return the stack
1347
  if (cell_found &&
×
1348
      stack.compute_instance(this->distribcell_index_) == instance) {
×
1349
    return stack.parent_cells();
×
1350
  }
1351

1352
  // fall back on an exhaustive search for the cell's parents
1353
  return exhaustive_find_parent_cells(instance);
×
1354
}
1355

1356
vector<ParentCell> Cell::exhaustive_find_parent_cells(int32_t instance) const
34✔
1357
{
1358
  ParentCellStack stack;
34✔
1359
  // start with this cell's universe
1360
  int32_t prev_univ_idx;
1361
  int32_t univ_idx = this->universe_;
34✔
1362

1363
  while (true) {
1364
    const auto& univ = model::universes[univ_idx];
85✔
1365
    prev_univ_idx = univ_idx;
85✔
1366

1367
    // search for a cell that is filled w/ this universe
1368
    for (const auto& cell : model::cells) {
442✔
1369
      // if this is a material-filled cell, move on
1370
      if (cell->type_ == Fill::MATERIAL)
425✔
1371
        continue;
255✔
1372

1373
      if (cell->type_ == Fill::UNIVERSE) {
170✔
1374
        // if this is in the set of cells previously visited for this universe,
1375
        // move on
1376
        if (stack.visited(univ_idx, {model::cell_map[cell->id_], C_NONE}))
85✔
1377
          continue;
×
1378

1379
        // if this cell contains the universe we're searching for, add it to the
1380
        // stack
1381
        if (cell->fill_ == univ_idx) {
85✔
1382
          stack.push(univ_idx, {model::cell_map[cell->id_], C_NONE});
×
1383
          univ_idx = cell->universe_;
×
1384
        }
1385
      } else if (cell->type_ == Fill::LATTICE) {
85✔
1386
        // retrieve the lattice and lattice universes
1387
        const auto& lattice = model::lattices[cell->fill_];
85✔
1388
        const auto& lattice_univs = lattice->universes_;
85✔
1389

1390
        // start search for universe
1391
        auto lat_it = lattice_univs.begin();
85✔
1392
        while (true) {
1393
          // find the next lattice cell with this universe
1394
          lat_it = std::find(lat_it, lattice_univs.end(), univ_idx);
187✔
1395
          if (lat_it == lattice_univs.end())
187✔
1396
            break;
17✔
1397

1398
          int lattice_idx = lat_it - lattice_univs.begin();
170✔
1399

1400
          // move iterator forward one to avoid finding the same entry
1401
          lat_it++;
170✔
1402
          if (stack.visited(
170✔
1403
                univ_idx, {model::cell_map[cell->id_], lattice_idx}))
170✔
1404
            continue;
102✔
1405

1406
          // add this cell and lattice index to the stack and exit loop
1407
          stack.push(univ_idx, {model::cell_map[cell->id_], lattice_idx});
68✔
1408
          univ_idx = cell->universe_;
68✔
1409
          break;
68✔
1410
        }
102✔
1411
      }
1412
      // if we've updated the universe, break
1413
      if (prev_univ_idx != univ_idx)
170✔
1414
        break;
68✔
1415
    } // end cell loop search for universe
1416

1417
    // if we're at the top of the geometry and the instance matches, we're done
1418
    if (univ_idx == model::root_universe &&
170✔
1419
        stack.compute_instance(this->distribcell_index_) == instance)
85✔
1420
      break;
34✔
1421

1422
    // if there is no match on the original cell's universe, report an error
1423
    if (univ_idx == this->universe_) {
51✔
1424
      fatal_error(
×
1425
        fmt::format("Could not find the parent cells for cell {}, instance {}.",
×
1426
          this->id_, instance));
×
1427
    }
1428

1429
    // if we don't find a suitable update, adjust the stack and continue
1430
    if (univ_idx == model::root_universe || univ_idx == prev_univ_idx) {
51✔
1431
      stack.pop();
51✔
1432
      univ_idx = stack.empty() ? this->universe_ : stack.current_univ();
51✔
1433
    }
1434

1435
  } // end while
51✔
1436

1437
  // reverse the stack so the highest cell comes first
1438
  std::reverse(stack.parent_cells().begin(), stack.parent_cells().end());
34✔
1439
  return stack.parent_cells();
68✔
1440
}
34✔
1441

1442
std::unordered_map<int32_t, vector<int32_t>> Cell::get_contained_cells(
85✔
1443
  int32_t instance, Position* hint) const
1444
{
1445
  std::unordered_map<int32_t, vector<int32_t>> contained_cells;
85✔
1446

1447
  // if this is a material-filled cell it has no contained cells
1448
  if (this->type_ == Fill::MATERIAL)
85✔
1449
    return contained_cells;
51✔
1450

1451
  // find the pathway through the geometry to this cell
1452
  vector<ParentCell> parent_cells;
34✔
1453

1454
  // if a positional hint is provided, attempt to do a fast lookup
1455
  // of the parent cells
1456
  parent_cells = hint ? find_parent_cells(instance, *hint)
68✔
1457
                      : exhaustive_find_parent_cells(instance);
34✔
1458

1459
  // if this cell is filled w/ a material, it contains no other cells
1460
  if (type_ != Fill::MATERIAL) {
34✔
1461
    this->get_contained_cells_inner(contained_cells, parent_cells);
34✔
1462
  }
1463

1464
  return contained_cells;
34✔
1465
}
34✔
1466

1467
//! Get all cells within this cell
1468
void Cell::get_contained_cells_inner(
357✔
1469
  std::unordered_map<int32_t, vector<int32_t>>& contained_cells,
1470
  vector<ParentCell>& parent_cells) const
1471
{
1472

1473
  // filled by material, determine instance based on parent cells
1474
  if (type_ == Fill::MATERIAL) {
357✔
1475
    int instance = 0;
255✔
1476
    if (this->distribcell_index_ >= 0) {
255✔
1477
      for (auto& parent_cell : parent_cells) {
765✔
1478
        auto& cell = model::cells[parent_cell.cell_index];
510✔
1479
        if (cell->type_ == Fill::UNIVERSE) {
510✔
1480
          instance += cell->offset_[distribcell_index_];
255✔
1481
        } else if (cell->type_ == Fill::LATTICE) {
255✔
1482
          auto& lattice = model::lattices[cell->fill_];
255✔
1483
          instance += lattice->offset(
510✔
1484
            this->distribcell_index_, parent_cell.lattice_index);
255✔
1485
        }
1486
      }
1487
    }
1488
    // add entry to contained cells
1489
    contained_cells[model::cell_map[id_]].push_back(instance);
255✔
1490
    // filled with universe, add the containing cell to the parent cells
1491
    // and recurse
1492
  } else if (type_ == Fill::UNIVERSE) {
102✔
1493
    parent_cells.push_back({model::cell_map[id_], -1});
85✔
1494
    auto& univ = model::universes[fill_];
85✔
1495
    for (auto cell_index : univ->cells_) {
340✔
1496
      auto& cell = model::cells[cell_index];
255✔
1497
      cell->get_contained_cells_inner(contained_cells, parent_cells);
255✔
1498
    }
1499
    parent_cells.pop_back();
85✔
1500
    // filled with a lattice, visit each universe in the lattice
1501
    // with a recursive call to collect the cell instances
1502
  } else if (type_ == Fill::LATTICE) {
17✔
1503
    auto& lattice = model::lattices[fill_];
17✔
1504
    for (auto i = lattice->begin(); i != lattice->end(); ++i) {
85✔
1505
      auto& univ = model::universes[*i];
68✔
1506
      parent_cells.push_back({model::cell_map[id_], i.indx_});
68✔
1507
      for (auto cell_index : univ->cells_) {
136✔
1508
        auto& cell = model::cells[cell_index];
68✔
1509
        cell->get_contained_cells_inner(contained_cells, parent_cells);
68✔
1510
      }
1511
      parent_cells.pop_back();
68✔
1512
    }
1513
  }
1514
}
357✔
1515

1516
//! Return the index in the cells array of a cell with a given ID
1517
extern "C" int openmc_get_cell_index(int32_t id, int32_t* index)
456✔
1518
{
1519
  auto it = model::cell_map.find(id);
456✔
1520
  if (it != model::cell_map.end()) {
456✔
1521
    *index = it->second;
444✔
1522
    return 0;
444✔
1523
  } else {
1524
    set_errmsg("No cell exists with ID=" + std::to_string(id) + ".");
12✔
1525
    return OPENMC_E_INVALID_ID;
12✔
1526
  }
1527
}
1528

1529
//! Return the ID of a cell
1530
extern "C" int openmc_cell_get_id(int32_t index, int32_t* id)
600,984✔
1531
{
1532
  if (index >= 0 && index < model::cells.size()) {
600,984✔
1533
    *id = model::cells[index]->id_;
600,984✔
1534
    return 0;
600,984✔
1535
  } else {
1536
    set_errmsg("Index in cells array is out of bounds.");
×
1537
    return OPENMC_E_OUT_OF_BOUNDS;
×
1538
  }
1539
}
1540

1541
//! Set the ID of a cell
1542
extern "C" int openmc_cell_set_id(int32_t index, int32_t id)
24✔
1543
{
1544
  if (index >= 0 && index < model::cells.size()) {
24✔
1545
    model::cells[index]->id_ = id;
24✔
1546
    model::cell_map[id] = index;
24✔
1547
    return 0;
24✔
1548
  } else {
1549
    set_errmsg("Index in cells array is out of bounds.");
×
1550
    return OPENMC_E_OUT_OF_BOUNDS;
×
1551
  }
1552
}
1553

1554
//! Return the translation vector of a cell
1555
extern "C" int openmc_cell_get_translation(int32_t index, double xyz[])
60✔
1556
{
1557
  if (index >= 0 && index < model::cells.size()) {
60✔
1558
    auto& cell = model::cells[index];
60✔
1559
    xyz[0] = cell->translation_.x;
60✔
1560
    xyz[1] = cell->translation_.y;
60✔
1561
    xyz[2] = cell->translation_.z;
60✔
1562
    return 0;
60✔
1563
  } else {
1564
    set_errmsg("Index in cells array is out of bounds.");
×
1565
    return OPENMC_E_OUT_OF_BOUNDS;
×
1566
  }
1567
}
1568

1569
//! Set the translation vector of a cell
1570
extern "C" int openmc_cell_set_translation(int32_t index, const double xyz[])
36✔
1571
{
1572
  if (index >= 0 && index < model::cells.size()) {
36✔
1573
    if (model::cells[index]->fill_ == C_NONE) {
36✔
1574
      set_errmsg(fmt::format("Cannot apply a translation to cell {}"
12✔
1575
                             " because it is not filled with another universe",
1576
        index));
1577
      return OPENMC_E_GEOMETRY;
12✔
1578
    }
1579
    model::cells[index]->translation_ = Position(xyz);
24✔
1580
    return 0;
24✔
1581
  } else {
1582
    set_errmsg("Index in cells array is out of bounds.");
×
1583
    return OPENMC_E_OUT_OF_BOUNDS;
×
1584
  }
1585
}
1586

1587
//! Return the rotation matrix of a cell
1588
extern "C" int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n)
60✔
1589
{
1590
  if (index >= 0 && index < model::cells.size()) {
60✔
1591
    auto& cell = model::cells[index];
60✔
1592
    *n = cell->rotation_.size();
60✔
1593
    std::memcpy(rot, cell->rotation_.data(), *n * sizeof(cell->rotation_[0]));
60✔
1594
    return 0;
60✔
1595
  } else {
1596
    set_errmsg("Index in cells array is out of bounds.");
×
1597
    return OPENMC_E_OUT_OF_BOUNDS;
×
1598
  }
1599
}
1600

1601
//! Set the flattened rotation matrix of a cell
1602
extern "C" int openmc_cell_set_rotation(
48✔
1603
  int32_t index, const double rot[], size_t rot_len)
1604
{
1605
  if (index >= 0 && index < model::cells.size()) {
48✔
1606
    if (model::cells[index]->fill_ == C_NONE) {
48✔
1607
      set_errmsg(fmt::format("Cannot apply a rotation to cell {}"
12✔
1608
                             " because it is not filled with another universe",
1609
        index));
1610
      return OPENMC_E_GEOMETRY;
12✔
1611
    }
1612
    std::vector<double> vec_rot(rot, rot + rot_len);
36✔
1613
    model::cells[index]->set_rotation(vec_rot);
36✔
1614
    return 0;
36✔
1615
  } else {
36✔
1616
    set_errmsg("Index in cells array is out of bounds.");
×
1617
    return OPENMC_E_OUT_OF_BOUNDS;
×
1618
  }
1619
}
1620

1621
//! Get the number of instances of the requested cell
1622
extern "C" int openmc_cell_get_num_instances(
12✔
1623
  int32_t index, int32_t* num_instances)
1624
{
1625
  if (index < 0 || index >= model::cells.size()) {
12✔
1626
    set_errmsg("Index in cells array is out of bounds.");
×
1627
    return OPENMC_E_OUT_OF_BOUNDS;
×
1628
  }
1629
  *num_instances = model::cells[index]->n_instances_;
12✔
1630
  return 0;
12✔
1631
}
1632

1633
//! Extend the cells array by n elements
1634
extern "C" int openmc_extend_cells(
24✔
1635
  int32_t n, int32_t* index_start, int32_t* index_end)
1636
{
1637
  if (index_start)
24✔
1638
    *index_start = model::cells.size();
24✔
1639
  if (index_end)
24✔
1640
    *index_end = model::cells.size() + n - 1;
×
1641
  for (int32_t i = 0; i < n; i++) {
48✔
1642
    model::cells.push_back(make_unique<CSGCell>());
24✔
1643
  }
1644
  return 0;
24✔
1645
}
1646

1647
extern "C" int cells_size()
48✔
1648
{
1649
  return model::cells.size();
48✔
1650
}
1651

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

© 2025 Coveralls, Inc