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

openmc-dev / openmc / 18299973882

07 Oct 2025 02:14AM UTC coverage: 81.92% (-3.3%) from 85.194%
18299973882

push

github

web-flow
Switch to using coveralls github action for reporting (#3594)

16586 of 23090 branches covered (71.83%)

Branch coverage included in aggregate %.

53703 of 62712 relevant lines covered (85.63%)

43428488.21 hits per line

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

82.12
/src/geometry.cpp
1
#include "openmc/geometry.h"
2

3
#include <fmt/core.h>
4
#include <fmt/ostream.h>
5

6
#include "openmc/array.h"
7
#include "openmc/cell.h"
8
#include "openmc/constants.h"
9
#include "openmc/error.h"
10
#include "openmc/lattice.h"
11
#include "openmc/settings.h"
12
#include "openmc/simulation.h"
13
#include "openmc/string_utils.h"
14
#include "openmc/surface.h"
15

16
namespace openmc {
17

18
//==============================================================================
19
// Global variables
20
//==============================================================================
21

22
namespace model {
23

24
int root_universe {-1};
25
int n_coord_levels;
26

27
vector<int64_t> overlap_check_count;
28

29
} // namespace model
30

31
//==============================================================================
32
// Non-member functions
33
//==============================================================================
34

35
bool check_cell_overlap(GeometryState& p, bool error)
1,320,000✔
36
{
37
  int n_coord = p.n_coord();
1,320,000✔
38

39
  // Loop through each coordinate level
40
  for (int j = 0; j < n_coord; j++) {
2,266,044✔
41
    Universe& univ = *model::universes[p.coord(j).universe()];
1,320,000✔
42

43
    // Loop through each cell on this level
44
    for (auto index_cell : univ.cells_) {
4,466,044✔
45
      Cell& c = *model::cells[index_cell];
3,520,000✔
46
      if (c.contains(p.coord(j).r(), p.coord(j).u(), p.surface())) {
3,520,000✔
47
        if (index_cell != p.coord(j).cell()) {
1,249,622✔
48
          if (error) {
373,956!
49
            fatal_error(
×
50
              fmt::format("Overlapping cells detected: {}, {} on universe {}",
×
51
                c.id_, model::cells[p.coord(j).cell()]->id_, univ.id_));
×
52
          }
53
          return true;
373,956✔
54
        }
55
#pragma omp atomic
477,636✔
56
        ++model::overlap_check_count[index_cell];
875,666✔
57
      }
58
    }
59
  }
60

61
  return false;
946,044✔
62
}
63

64
//==============================================================================
65

66
int cell_instance_at_level(const GeometryState& p, int level)
2,147,483,647✔
67
{
68
  // throw error if the requested level is too deep for the geometry
69
  if (level > model::n_coord_levels) {
2,147,483,647!
70
    fatal_error(fmt::format("Cell instance at level {} requested, but only {} "
×
71
                            "levels exist in the geometry.",
72
      level, p.n_coord()));
73
  }
74

75
  // determine the cell instance
76
  Cell& c {*model::cells[p.coord(level).cell()]};
2,147,483,647✔
77

78
  // quick exit if this cell doesn't have distribcell instances
79
  if (c.distribcell_index_ == C_NONE)
2,147,483,647!
80
    return C_NONE;
×
81

82
  // compute the cell's instance
83
  int instance = 0;
2,147,483,647✔
84
  for (int i = 0; i < level; i++) {
2,147,483,647✔
85
    const auto& c_i {*model::cells[p.coord(i).cell()]};
2,025,238,143✔
86
    if (c_i.type_ == Fill::UNIVERSE) {
2,025,238,143✔
87
      instance += c_i.offset_[c.distribcell_index_];
871,039,473✔
88
    } else if (c_i.type_ == Fill::LATTICE) {
1,154,198,670!
89
      instance += c_i.offset_[c.distribcell_index_];
1,154,198,670✔
90
      auto& lat {*model::lattices[p.coord(i + 1).lattice()]};
1,154,198,670✔
91
      const auto& i_xyz {p.coord(i + 1).lattice_index()};
1,154,198,670✔
92
      if (lat.are_valid_indices(i_xyz)) {
1,154,198,670✔
93
        instance += lat.offset(c.distribcell_index_, i_xyz);
1,149,314,703✔
94
      }
95
    }
96
  }
97
  return instance;
2,147,483,647✔
98
}
99

100
//==============================================================================
101

102
bool find_cell_inner(
2,147,483,647✔
103
  GeometryState& p, const NeighborList* neighbor_list, bool verbose)
104
{
105
  // Find which cell of this universe the particle is in.  Use the neighbor list
106
  // to shorten the search if one was provided.
107
  bool found = false;
2,147,483,647✔
108
  int32_t i_cell = C_NONE;
2,147,483,647✔
109
  if (neighbor_list) {
2,147,483,647✔
110
    for (auto it = neighbor_list->cbegin(); it != neighbor_list->cend(); ++it) {
1,772,906,405✔
111
      i_cell = *it;
1,771,307,309✔
112

113
      // Make sure the search cell is in the same universe.
114
      int i_universe = p.lowest_coord().universe();
1,771,307,309✔
115
      if (model::cells[i_cell]->universe_ != i_universe)
1,771,307,309!
116
        continue;
×
117

118
      // Check if this cell contains the particle.
119
      Position r {p.r_local()};
1,771,307,309✔
120
      Direction u {p.u_local()};
1,771,307,309✔
121
      auto surf = p.surface();
1,771,307,309✔
122
      if (model::cells[i_cell]->contains(r, u, surf)) {
1,771,307,309✔
123
        p.lowest_coord().cell() = i_cell;
1,429,204,693✔
124
        found = true;
1,429,204,693✔
125
        break;
1,429,204,693✔
126
      }
127
    }
128

129
    // If we're attempting a neighbor list search and fail, we
130
    // now know we should return false. This will trigger an
131
    // exhaustive search from neighbor_list_find_cell and make
132
    // the result from that be appended to the neighbor list.
133
    if (!found) {
1,430,803,789✔
134
      return found;
1,599,096✔
135
    }
136
  }
137

138
  // Check successively lower coordinate levels until finding material fill
139
  for (;; ++p.n_coord()) {
739,599,048✔
140
    // If we did not attempt to use neighbor lists, i_cell is still C_NONE.  In
141
    // that case, we should now do an exhaustive search to find the right value
142
    // of i_cell.
143
    //
144
    // Alternatively, neighbor list searches could have succeeded, but we found
145
    // that the fill of the neighbor cell was another universe. As such, in the
146
    // code below this conditional, we set i_cell back to C_NONE to indicate
147
    // that.
148
    if (i_cell == C_NONE) {
2,147,483,647✔
149
      int i_universe = p.lowest_coord().universe();
1,577,876,960✔
150
      const auto& univ {model::universes[i_universe]};
1,577,876,960✔
151
      found = univ->find_cell(p);
1,577,876,960✔
152
    }
153

154
    if (!found) {
2,147,483,647✔
155
      return found;
173,122,950✔
156
    }
157
    i_cell = p.lowest_coord().cell();
2,147,483,647✔
158

159
    // Announce the cell that the particle is entering.
160
    if (found && verbose) {
2,147,483,647!
161
      auto msg = fmt::format("    Entering cell {}", model::cells[i_cell]->id_);
×
162
      write_message(msg, 1);
×
163
    }
×
164

165
    Cell& c {*model::cells[i_cell]};
2,147,483,647✔
166
    if (c.type_ == Fill::MATERIAL) {
2,147,483,647✔
167
      // Found a material cell which means this is the lowest coord level.
168

169
      p.cell_instance() = 0;
2,147,483,647✔
170
      // Find the distribcell instance number.
171
      if (c.distribcell_index_ >= 0) {
2,147,483,647✔
172
        p.cell_instance() = cell_instance_at_level(p, p.n_coord() - 1);
2,147,483,647✔
173
      }
174

175
      // Set the material, temperature and density multiplier.
176
      p.material_last() = p.material();
2,147,483,647✔
177
      p.material() = c.material(p.cell_instance());
2,147,483,647✔
178
      p.sqrtkT_last() = p.sqrtkT();
2,147,483,647✔
179
      p.sqrtkT() = c.sqrtkT(p.cell_instance());
2,147,483,647✔
180
      p.density_mult_last() = p.density_mult();
2,147,483,647✔
181
      p.density_mult() = c.density_mult(p.cell_instance());
2,147,483,647✔
182

183
      return true;
2,147,483,647✔
184

185
    } else if (c.type_ == Fill::UNIVERSE) {
369,799,524✔
186
      //========================================================================
187
      //! Found a lower universe, update this coord level then search the next.
188

189
      // Set the lower coordinate level universe.
190
      auto& coord {p.coord(p.n_coord())};
209,814,767✔
191
      coord.universe() = c.fill_;
209,814,767✔
192

193
      // Set the position and direction.
194
      coord.r() = p.r_local();
209,814,767✔
195
      coord.u() = p.u_local();
209,814,767✔
196

197
      // Apply translation.
198
      coord.r() -= c.translation_;
209,814,767✔
199

200
      // Apply rotation.
201
      if (!c.rotation_.empty()) {
209,814,767✔
202
        coord.rotate(c.rotation_);
2,211,858✔
203
      }
204

205
    } else if (c.type_ == Fill::LATTICE) {
159,984,757!
206
      //========================================================================
207
      //! Found a lower lattice, update this coord level then search the next.
208

209
      Lattice& lat {*model::lattices[c.fill_]};
159,984,757✔
210

211
      // Set the position and direction.
212
      auto& coord {p.coord(p.n_coord())};
159,984,757✔
213
      coord.r() = p.r_local();
159,984,757✔
214
      coord.u() = p.u_local();
159,984,757✔
215

216
      // Apply translation.
217
      coord.r() -= c.translation_;
159,984,757✔
218

219
      // Apply rotation.
220
      if (!c.rotation_.empty()) {
159,984,757✔
221
        coord.rotate(c.rotation_);
358,336✔
222
      }
223

224
      // Determine lattice indices.
225
      auto& i_xyz {coord.lattice_index()};
159,984,757✔
226
      lat.get_indices(coord.r(), coord.u(), i_xyz);
159,984,757✔
227

228
      // Get local position in appropriate lattice cell
229
      coord.r() = lat.get_local_position(coord.r(), i_xyz);
159,984,757✔
230

231
      // Set lattice indices.
232
      coord.lattice() = c.fill_;
159,984,757✔
233

234
      // Set the lower coordinate level universe.
235
      if (lat.are_valid_indices(i_xyz)) {
159,984,757✔
236
        coord.universe() = lat[i_xyz];
155,100,790✔
237
      } else {
238
        if (lat.outer_ != NO_OUTER_UNIVERSE) {
4,883,967!
239
          coord.universe() = lat.outer_;
4,883,967✔
240
        } else {
241
          p.mark_as_lost(fmt::format(
×
242
            "Particle {} left lattice {}, but it has no outer definition.",
243
            p.id(), lat.id_));
×
244
        }
245
      }
246
    }
247
    i_cell = C_NONE; // trip non-neighbor cell search at next iteration
369,799,524✔
248
    found = false;
369,799,524✔
249
  }
369,799,524✔
250

251
  return found;
252
}
253

254
//==============================================================================
255

256
bool neighbor_list_find_cell(GeometryState& p, bool verbose)
1,430,803,789✔
257
{
258

259
  // Reset all the deeper coordinate levels.
260
  for (int i = p.n_coord(); i < model::n_coord_levels; i++) {
2,147,483,647✔
261
    p.coord(i).reset();
755,808,111✔
262
  }
263

264
  // Get the cell this particle was in previously.
265
  auto coord_lvl = p.n_coord() - 1;
1,430,803,789✔
266
  auto i_cell = p.coord(coord_lvl).cell();
1,430,803,789✔
267
  Cell& c {*model::cells[i_cell]};
1,430,803,789✔
268

269
  // Search for the particle in that cell's neighbor list.  Return if we
270
  // found the particle.
271
  bool found = find_cell_inner(p, &c.neighbors_, verbose);
1,430,803,789✔
272
  if (found)
1,430,803,789✔
273
    return found;
1,429,204,693✔
274

275
  // The particle could not be found in the neighbor list.  Try searching all
276
  // cells in this universe, and update the neighbor list if we find a new
277
  // neighboring cell.
278
  found = find_cell_inner(p, nullptr, verbose);
1,599,096✔
279
  if (found)
1,599,096✔
280
    c.neighbors_.push_back(p.coord(coord_lvl).cell());
28,173✔
281
  return found;
1,599,096✔
282
}
283

284
bool exhaustive_find_cell(GeometryState& p, bool verbose)
1,206,478,340✔
285
{
286
  int i_universe = p.lowest_coord().universe();
1,206,478,340✔
287
  if (i_universe == C_NONE) {
1,206,478,340✔
288
    p.coord(0).universe() = model::root_universe;
272,342,355✔
289
    p.n_coord() = 1;
272,342,355✔
290
    i_universe = model::root_universe;
272,342,355✔
291
  }
292
  // Reset all the deeper coordinate levels.
293
  for (int i = p.n_coord(); i < model::n_coord_levels; i++) {
1,312,774,561✔
294
    p.coord(i).reset();
106,296,221✔
295
  }
296
  return find_cell_inner(p, nullptr, verbose);
1,206,478,340✔
297
}
298

299
//==============================================================================
300

301
void cross_lattice(GeometryState& p, const BoundaryInfo& boundary, bool verbose)
684,858,335✔
302
{
303
  auto& coord {p.lowest_coord()};
684,858,335✔
304
  auto& lat {*model::lattices[coord.lattice()]};
684,858,335✔
305

306
  if (verbose) {
684,858,335!
307
    write_message(
×
308
      fmt::format("    Crossing lattice {}. Current position ({},{},{}). r={}",
×
309
        lat.id_, coord.lattice_index()[0], coord.lattice_index()[1],
×
310
        coord.lattice_index()[2], p.r()),
×
311
      1);
312
  }
313

314
  // Set the lattice indices.
315
  coord.lattice_index()[0] += boundary.lattice_translation()[0];
684,858,335✔
316
  coord.lattice_index()[1] += boundary.lattice_translation()[1];
684,858,335✔
317
  coord.lattice_index()[2] += boundary.lattice_translation()[2];
684,858,335✔
318

319
  // Set the new coordinate position.
320
  const auto& upper_coord {p.coord(p.n_coord() - 2)};
684,858,335✔
321
  const auto& cell {model::cells[upper_coord.cell()]};
684,858,335✔
322
  Position r = upper_coord.r();
684,858,335✔
323
  r -= cell->translation_;
684,858,335✔
324
  if (!cell->rotation_.empty()) {
684,858,335✔
325
    r = r.rotate(cell->rotation_);
471,647✔
326
  }
327
  p.r_local() = lat.get_local_position(r, coord.lattice_index());
684,858,335✔
328

329
  if (!lat.are_valid_indices(coord.lattice_index())) {
684,858,335✔
330
    // The particle is outside the lattice.  Search for it from the base coords.
331
    p.n_coord() = 1;
3,714,425✔
332
    bool found = exhaustive_find_cell(p);
3,714,425✔
333

334
    if (!found) {
3,714,425!
335
      p.mark_as_lost(fmt::format("Particle {} could not be located after "
×
336
                                 "crossing a boundary of lattice {}",
337
        p.id(), lat.id_));
×
338
    }
339

340
  } else {
341
    // Find cell in next lattice element.
342
    p.lowest_coord().universe() = lat[coord.lattice_index()];
681,143,910✔
343
    bool found = exhaustive_find_cell(p);
681,143,910✔
344

345
    if (!found) {
681,143,910!
346
      // A particle crossing the corner of a lattice tile may not be found.  In
347
      // this case, search for it from the base coords.
348
      p.n_coord() = 1;
×
349
      bool found = exhaustive_find_cell(p);
×
350
      if (!found) {
×
351
        p.mark_as_lost(fmt::format("Particle {} could not be located after "
×
352
                                   "crossing a boundary of lattice {}",
353
          p.id(), lat.id_));
×
354
      }
355
    }
356
  }
357
}
684,858,335✔
358

359
//==============================================================================
360

361
BoundaryInfo distance_to_boundary(GeometryState& p)
2,147,483,647✔
362
{
363
  BoundaryInfo info;
2,147,483,647✔
364
  double d_lat = INFINITY;
2,147,483,647✔
365
  double d_surf = INFINITY;
2,147,483,647✔
366
  int32_t level_surf_cross;
367
  array<int, 3> level_lat_trans {};
2,147,483,647✔
368

369
  // Loop over each coordinate level.
370
  for (int i = 0; i < p.n_coord(); i++) {
2,147,483,647✔
371
    const auto& coord {p.coord(i)};
2,147,483,647✔
372
    const Position& r {coord.r()};
2,147,483,647✔
373
    const Direction& u {coord.u()};
2,147,483,647✔
374
    Cell& c {*model::cells[coord.cell()]};
2,147,483,647✔
375

376
    // Find the oncoming surface in this cell and the distance to it.
377
    auto surface_distance = c.distance(r, u, p.surface(), &p);
2,147,483,647✔
378
    d_surf = surface_distance.first;
2,147,483,647✔
379
    level_surf_cross = surface_distance.second;
2,147,483,647✔
380

381
    // Find the distance to the next lattice tile crossing.
382
    if (coord.lattice() != C_NONE) {
2,147,483,647✔
383
      auto& lat {*model::lattices[coord.lattice()]};
1,162,702,008✔
384
      // TODO: refactor so both lattice use the same position argument (which
385
      // also means the lat.type attribute can be removed)
386
      std::pair<double, array<int, 3>> lattice_distance;
1,162,702,008✔
387
      switch (lat.type_) {
1,162,702,008!
388
      case LatticeType::rect:
1,075,349,199✔
389
        lattice_distance = lat.distance(r, u, coord.lattice_index());
1,075,349,199✔
390
        break;
1,075,349,199✔
391
      case LatticeType::hex:
87,352,809✔
392
        auto& cell_above {model::cells[p.coord(i - 1).cell()]};
87,352,809✔
393
        Position r_hex {p.coord(i - 1).r()};
87,352,809✔
394
        r_hex -= cell_above->translation_;
87,352,809✔
395
        if (coord.rotated()) {
87,352,809✔
396
          r_hex = r_hex.rotate(cell_above->rotation_);
701,954✔
397
        }
398
        r_hex.z = coord.r().z;
87,352,809✔
399
        lattice_distance = lat.distance(r_hex, u, coord.lattice_index());
87,352,809✔
400
        break;
87,352,809✔
401
      }
402
      d_lat = lattice_distance.first;
1,162,702,008✔
403
      level_lat_trans = lattice_distance.second;
1,162,702,008✔
404

405
      if (d_lat < 0) {
1,162,702,008!
406
        p.mark_as_lost(fmt::format("Particle {} had a negative distance "
×
407
                                   "to a lattice boundary.",
408
          p.id()));
×
409
      }
410
    }
411

412
    // If the boundary on this coordinate level is coincident with a boundary on
413
    // a higher level then we need to make sure that the higher level boundary
414
    // is selected.  This logic must consider floating point precision.
415
    double& d = info.distance();
2,147,483,647✔
416
    if (d_surf < d_lat - FP_COINCIDENT) {
2,147,483,647✔
417
      if (d == INFINITY || (d - d_surf) / d >= FP_REL_PRECISION) {
2,147,483,647✔
418
        // Update closest distance
419
        d = d_surf;
2,147,483,647✔
420

421
        // If the cell is not simple, it is possible that both the negative and
422
        // positive half-space were given in the region specification. Thus, we
423
        // have to explicitly check which half-space the particle would be
424
        // traveling into if the surface is crossed
425
        if (c.is_simple() || d == INFTY) {
2,147,483,647✔
426
          info.surface() = level_surf_cross;
2,147,483,647✔
427
        } else {
428
          Position r_hit = r + d_surf * u;
12,702,448✔
429
          Surface& surf {*model::surfaces[std::abs(level_surf_cross) - 1]};
12,702,448✔
430
          Direction norm = surf.normal(r_hit);
12,702,448✔
431
          if (u.dot(norm) > 0) {
12,702,448✔
432
            info.surface() = std::abs(level_surf_cross);
6,285,519✔
433
          } else {
434
            info.surface() = -std::abs(level_surf_cross);
6,416,929✔
435
          }
436
        }
437

438
        info.lattice_translation()[0] = 0;
2,147,483,647✔
439
        info.lattice_translation()[1] = 0;
2,147,483,647✔
440
        info.lattice_translation()[2] = 0;
2,147,483,647✔
441
        info.coord_level() = i + 1;
2,147,483,647✔
442
      }
443
    } else {
444
      if (d == INFINITY || (d - d_lat) / d >= FP_REL_PRECISION) {
954,723,556!
445
        d = d_lat;
770,892,304✔
446
        info.surface() = SURFACE_NONE;
770,892,304✔
447
        info.lattice_translation() = level_lat_trans;
770,892,304✔
448
        info.coord_level() = i + 1;
770,892,304✔
449
      }
450
    }
451
  }
452
  return info;
2,147,483,647✔
453
}
454

455
//==============================================================================
456
// C API
457
//==============================================================================
458

459
extern "C" int openmc_find_cell(
600,946✔
460
  const double* xyz, int32_t* index, int32_t* instance)
461
{
462
  GeometryState geom_state;
600,946✔
463

464
  geom_state.r() = Position {xyz};
600,946✔
465
  geom_state.u() = {0.0, 0.0, 1.0};
600,946✔
466

467
  if (!exhaustive_find_cell(geom_state)) {
600,946✔
468
    set_errmsg(
15✔
469
      fmt::format("Could not find cell at position {}.", geom_state.r()));
43✔
470
    return OPENMC_E_GEOMETRY;
15✔
471
  }
472

473
  *index = geom_state.lowest_coord().cell();
600,931✔
474
  *instance = geom_state.cell_instance();
600,931✔
475
  return 0;
600,931✔
476
}
600,946✔
477

478
extern "C" int openmc_global_bounding_box(double* llc, double* urc)
15✔
479
{
480
  auto bbox = model::universes.at(model::root_universe)->bounding_box();
15✔
481

482
  // set lower left corner values
483
  llc[0] = bbox.xmin;
15✔
484
  llc[1] = bbox.ymin;
15✔
485
  llc[2] = bbox.zmin;
15✔
486

487
  // set upper right corner values
488
  urc[0] = bbox.xmax;
15✔
489
  urc[1] = bbox.ymax;
15✔
490
  urc[2] = bbox.zmax;
15✔
491

492
  return 0;
15✔
493
}
494

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