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

openmc-dev / openmc / 23507153321

24 Mar 2026 06:58PM UTC coverage: 81.345% (-0.2%) from 81.556%
23507153321

Pull #3832

github

web-flow
Merge d5a5551bc into 6cd39073b
Pull Request #3832: Allowing multiple cells in surface source banking

17647 of 25494 branches covered (69.22%)

Branch coverage included in aggregate %.

94 of 97 new or added lines in 4 files covered. (96.91%)

868 existing lines in 32 files now uncovered.

58180 of 67723 relevant lines covered (85.91%)

44492259.78 hits per line

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

86.31
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/lattice.h"
18
#include "openmc/material.h"
19
#include "openmc/message_passing.h"
20
#include "openmc/mgxs_interface.h"
21
#include "openmc/nuclide.h"
22
#include "openmc/particle_data.h"
23
#include "openmc/photon.h"
24
#include "openmc/physics.h"
25
#include "openmc/physics_mg.h"
26
#include "openmc/random_lcg.h"
27
#include "openmc/settings.h"
28
#include "openmc/simulation.h"
29
#include "openmc/source.h"
30
#include "openmc/surface.h"
31
#include "openmc/tallies/derivative.h"
32
#include "openmc/tallies/tally.h"
33
#include "openmc/tallies/tally_scoring.h"
34
#include "openmc/track_output.h"
35
#include "openmc/weight_windows.h"
36

37
#ifdef OPENMC_DAGMC_ENABLED
38
#include "DagMC.hpp"
39
#endif
40

41
namespace openmc {
42

43
//==============================================================================
44
// Particle implementation
45
//==============================================================================
46

47
double Particle::speed() const
2,147,483,647✔
48
{
49
  if (settings::run_CE) {
2,147,483,647✔
50
    // Determine mass in eV/c^2
51
    double mass;
2,147,483,647✔
52
    switch (type().pdg_number()) {
2,147,483,647✔
53
    case PDG_NEUTRON:
54
      mass = MASS_NEUTRON_EV;
55
    case PDG_ELECTRON:
56
    case PDG_POSITRON:
57
      mass = MASS_ELECTRON_EV;
2,147,483,647✔
58
    default:
2,147,483,647✔
59
      mass = this->type().mass() * AMU_EV;
2,147,483,647✔
60
    }
61

62
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
63
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
64
           (this->E() + mass);
2,147,483,647✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
67
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
71
  }
72
}
73

74
bool Particle::create_secondary(
112,692,033✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  int idx = type.transport_index();
112,692,033✔
80
  if (idx == C_NONE) {
112,692,033!
81
    return false;
82
  }
83
  if (E < settings::energy_cutoff[idx]) {
112,692,033✔
84
    return false;
85
  }
86

87
  // Increment number of secondaries created (for ParticleProductionFilter)
88
  n_secondaries()++;
58,919,874✔
89

90
  auto& bank = secondary_bank().emplace_back();
58,919,874✔
91
  bank.particle = type;
58,919,874✔
92
  bank.wgt = wgt;
58,919,874✔
93
  bank.r = r();
58,919,874!
94
  bank.u = u;
58,919,874✔
95
  bank.E = settings::run_CE ? E : g();
58,919,874!
96
  bank.time = time();
58,919,874✔
97
  bank_second_E() += bank.E;
58,919,874✔
98
  return true;
58,919,874✔
99
}
100

101
void Particle::split(double wgt)
4,249,893✔
102
{
103
  auto& bank = secondary_bank().emplace_back();
4,249,893✔
104
  bank.particle = type();
4,249,893✔
105
  bank.wgt = wgt;
4,249,893✔
106
  bank.r = r();
4,249,893✔
107
  bank.u = u();
4,249,893✔
108
  bank.E = settings::run_CE ? E() : g();
4,249,893✔
109
  bank.time = time();
4,249,893✔
110

111
  // Convert signed index to a signed surface ID
112
  if (surface() == SURFACE_NONE) {
4,249,893✔
113
    bank.surf_id = SURFACE_NONE;
4,249,348✔
114
  } else {
115
    int surf_id = model::surfaces[surface_index()]->id_;
545✔
116
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
545✔
117
  }
118
}
4,249,893✔
119

120
void Particle::from_source(const SourceSite* src)
240,965,570✔
121
{
122
  // Reset some attributes
123
  clear();
240,965,570✔
124
  surface() = SURFACE_NONE;
240,965,570✔
125
  cell_born() = C_NONE;
240,965,570✔
126
  material() = C_NONE;
240,965,570✔
127
  n_collision() = 0;
240,965,570✔
128
  fission() = false;
240,965,570✔
129
  zero_flux_derivs();
240,965,570✔
130
  lifetime() = 0.0;
240,965,570✔
131
#ifdef OPENMC_DAGMC_ENABLED
132
  history().reset();
22,067,679✔
133
#endif
134

135
  // Copy attributes from source bank site
136
  type() = src->particle;
240,965,570✔
137
  wgt() = src->wgt;
240,965,570✔
138
  wgt_last() = src->wgt;
240,965,570✔
139
  r() = src->r;
240,965,570✔
140
  u() = src->u;
240,965,570✔
141
  r_born() = src->r;
240,965,570✔
142
  r_last_current() = src->r;
240,965,570✔
143
  r_last() = src->r;
240,965,570✔
144
  u_last() = src->u;
240,965,570✔
145
  if (settings::run_CE) {
240,965,570✔
146
    E() = src->E;
125,039,953✔
147
    g() = 0;
125,039,953✔
148
  } else {
149
    g() = static_cast<int>(src->E);
115,925,617✔
150
    g_last() = static_cast<int>(src->E);
115,925,617✔
151
    E() = data::mg.energy_bin_avg_[g()];
115,925,617✔
152
  }
153
  E_last() = E();
240,965,570✔
154
  time() = src->time;
240,965,570✔
155
  time_last() = src->time;
240,965,570✔
156
  parent_nuclide() = src->parent_nuclide;
240,965,570✔
157
  delayed_group() = src->delayed_group;
240,965,570✔
158

159
  // Convert signed surface ID to signed index
160
  if (src->surf_id != SURFACE_NONE) {
240,965,570✔
161
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,545✔
162
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,545✔
163
  }
164
}
240,965,570✔
165

166
void Particle::event_calculate_xs()
2,147,483,647✔
167
{
168
  // Set the random number stream
169
  stream() = STREAM_TRACKING;
2,147,483,647✔
170

171
  // Store pre-collision particle properties
172
  wgt_last() = wgt();
2,147,483,647✔
173
  E_last() = E();
2,147,483,647✔
174
  u_last() = u();
2,147,483,647✔
175
  r_last() = r();
2,147,483,647✔
176
  time_last() = time();
2,147,483,647✔
177

178
  // Reset event variables
179
  event() = TallyEvent::KILL;
2,147,483,647✔
180
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
181
  event_mt() = REACTION_NONE;
2,147,483,647✔
182

183
  // If the cell hasn't been determined based on the particle's location,
184
  // initiate a search for the current cell. This generally happens at the
185
  // beginning of the history and again for any secondary particles
186
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
187
    if (!exhaustive_find_cell(*this)) {
232,294,661!
188
      mark_as_lost(
×
189
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
190
      return;
×
191
    }
192

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
232,294,661!
195
      cell_born() = lowest_coord().cell();
232,294,661✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
482,061,234✔
199
      cell_last(j) = coord(j).cell();
249,766,573✔
200
    }
201
    n_coord_last() = n_coord();
232,294,661✔
202
  }
203

204
  // Write particle track.
205
  if (write_track())
2,147,483,647✔
206
    write_particle_track(*this);
10,315✔
207

208
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
209
    check_cell_overlap(*this);
×
210

211
  // Calculate microscopic and macroscopic cross sections
212
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
213
    if (settings::run_CE) {
2,147,483,647✔
214
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
215
          density_mult() != density_mult_last()) {
385,347,046✔
216
        // If the material is the same as the last material and the
217
        // temperature hasn't changed, we don't need to lookup cross
218
        // sections again.
219
        model::materials[material()]->calculate_xs(*this);
1,781,635,461✔
220
      }
221
    } else {
222
      // Get the MG data; unlike the CE case above, we have to re-calculate
223
      // cross sections for every collision since the cross sections may
224
      // be angle-dependent
225
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
226

227
      // Update the particle's group while we know we are multi-group
228
      g_last() = g();
2,063,937,414✔
229
    }
230
  } else {
231
    macro_xs().total = 0.0;
111,868,699✔
232
    macro_xs().absorption = 0.0;
111,868,699✔
233
    macro_xs().fission = 0.0;
111,868,699✔
234
    macro_xs().nu_fission = 0.0;
111,868,699✔
235
  }
236
}
237

238
void Particle::event_advance()
2,147,483,647✔
239
{
240
  // Find the distance to the nearest boundary
241
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
242

243
  // Sample a distance to collision
244
  if (type() == ParticleType::electron() ||
2,147,483,647✔
245
      type() == ParticleType::positron()) {
2,147,483,647✔
246
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
108,330,656!
247
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
248
    collision_distance() = INFINITY;
111,868,699✔
249
  } else {
250
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
251
  }
252

253
  double speed = this->speed();
2,147,483,647✔
254
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
255
  double distance_cutoff =
2,147,483,647✔
256
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
257

258
  // Select smaller of the three distances
259
  double distance =
2,147,483,647✔
260
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
261

262
  // Advance particle in space and time
263
  this->move_distance(distance);
2,147,483,647✔
264
  double dt = distance / speed;
2,147,483,647✔
265
  this->time() += dt;
2,147,483,647✔
266
  this->lifetime() += dt;
2,147,483,647✔
267

268
  // Score timed track-length tallies
269
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
270
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
271
  }
272

273
  // Score track-length tallies
274
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
275
    score_tracklength_tally(*this, distance);
1,722,924,932✔
276
  }
277

278
  // Score track-length estimate of k-eff
279
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
280
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
281
  }
282

283
  // Score flux derivative accumulators for differential tallies.
284
  if (!model::active_tallies.empty()) {
2,147,483,647✔
285
    score_track_derivative(*this, distance);
1,893,190,773✔
286
  }
287

288
  // Set particle weight to zero if it hit the time boundary
289
  if (distance == distance_cutoff) {
2,147,483,647✔
290
    wgt() = 0.0;
224,928✔
291
  }
292
}
2,147,483,647✔
293

294
void Particle::event_cross_surface()
2,147,483,647✔
295
{
296
  // Saving previous cell data
297
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
298
    cell_last(j) = coord(j).cell();
2,147,483,647✔
299
  }
300
  n_coord_last() = n_coord();
2,147,483,647✔
301

302
  // Set surface that particle is on and adjust coordinate levels
303
  surface() = boundary().surface();
2,147,483,647✔
304
  n_coord() = boundary().coord_level();
2,147,483,647✔
305

306
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
307
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
308
      boundary().lattice_translation()[2] != 0) {
1,860,118,241✔
309
    // Particle crosses lattice boundary
310

311
    bool verbose = settings::verbosity >= 10 || trace();
750,250,885!
312
    cross_lattice(*this, boundary(), verbose);
750,250,885✔
313
    event() = TallyEvent::LATTICE;
750,250,885✔
314

315
    // Score cell to cell partial currents
316
    if (!model::active_surface_tallies.empty()) {
750,250,885!
UNCOV
317
      auto& lat {*model::lattices[lowest_coord().lattice()]};
×
UNCOV
318
      bool is_valid;
×
UNCOV
319
      Direction normal =
×
UNCOV
320
        lat.get_normal(boundary().lattice_translation(), is_valid);
×
UNCOV
321
      if (is_valid) {
×
UNCOV
322
        normal /= normal.norm();
×
UNCOV
323
        score_surface_tally(*this, model::active_surface_tallies, normal);
×
324
      }
325
    }
326

327
  } else {
328

329
    const auto& surf {*model::surfaces[surface_index()].get()};
1,671,576,345✔
330

331
    // Particle crosses surface
332
    // If BC, add particle to surface source before crossing surface
333
    if (surf.surf_source_ && surf.bc_) {
1,671,576,345✔
334
      add_surf_source_to_bank(*this, surf);
65,913,952✔
335
    }
336
    this->cross_surface(surf);
1,671,576,345✔
337
    // If no BC, add particle to surface source after crossing surface
338
    if (surf.surf_source_ && !surf.bc_) {
1,671,576,336✔
339
      add_surf_source_to_bank(*this, surf);
85,511,323✔
340
    }
341
    if (settings::weight_window_checkpoint_surface) {
1,671,576,336✔
342
      apply_weight_windows(*this);
74,912✔
343
    }
344
    event() = TallyEvent::SURFACE;
1,671,576,336✔
345

346
    // Score cell to cell partial currents
347
    if (!model::active_surface_tallies.empty()) {
1,671,576,336✔
348
      Direction normal = surf.normal(r());
34,931,567✔
349
      normal /= normal.norm();
34,931,567✔
350
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,931,567✔
351
    }
352
  }
353
}
2,147,483,647✔
354

355
void Particle::event_collide()
2,147,483,647✔
356
{
357

358
  // Score collision estimate of keff
359
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
360
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,139,391,242✔
361
  }
362

363
  // Score surface current tallies -- this has to be done before the collision
364
  // since the direction of the particle will change and we need to use the
365
  // pre-collision direction to figure out what mesh surfaces were crossed
366

367
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
368
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
369

370
  // Clear surface component
371
  surface() = SURFACE_NONE;
2,147,483,647✔
372

373
  if (settings::run_CE) {
2,147,483,647✔
374
    collision(*this);
1,072,329,525✔
375
  } else {
376
    collision_mg(*this);
1,783,060,477✔
377
  }
378

379
  // Collision track feature to recording particle interaction
380
  if (settings::collision_track) {
2,147,483,647✔
381
    collision_track_record(*this);
150,087✔
382
  }
383

384
  // Score collision estimator tallies -- this is done after a collision
385
  // has occurred rather than before because we need information on the
386
  // outgoing energy for any tallies with an outgoing energy filter
387
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
388
    score_collision_tally(*this);
107,870,497✔
389
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
390
    if (settings::run_CE) {
406,034,945✔
391
      score_analog_tally_ce(*this);
404,826,683✔
392
    } else {
393
      score_analog_tally_mg(*this);
1,208,262✔
394
    }
395
  }
396

397
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
398
    pht_collision_energy();
2,024✔
399
  }
400

401
  // Reset banked weight during collision
402
  n_bank() = 0;
2,147,483,647✔
403
  bank_second_E() = 0.0;
2,147,483,647✔
404
  wgt_bank() = 0.0;
2,147,483,647✔
405

406
  // Clear number of secondaries in this collision. This is
407
  // distinct from the number of created neutrons n_bank() above!
408
  n_secondaries() = 0;
2,147,483,647✔
409

410
  zero_delayed_bank();
2,147,483,647✔
411

412
  // Reset fission logical
413
  fission() = false;
2,147,483,647✔
414

415
  // Save coordinates for tallying purposes
416
  r_last_current() = r();
2,147,483,647✔
417

418
  // Set last material to none since cross sections will need to be
419
  // re-evaluated
420
  material_last() = C_NONE;
2,147,483,647✔
421

422
  // Set all directions to base level -- right now, after a collision, only
423
  // the base level directions are changed
424
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
425
    if (coord(j + 1).rotated()) {
161,247,365✔
426
      // If next level is rotated, apply rotation matrix
427
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
428
      const auto& u {coord(j).u()};
10,426,614✔
429
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
430
    } else {
431
      // Otherwise, copy this level's direction
432
      coord(j + 1).u() = coord(j).u();
150,820,751✔
433
    }
434
  }
435

436
  // Score flux derivative accumulators for differential tallies.
437
  if (!model::active_tallies.empty())
2,147,483,647✔
438
    score_collision_derivative(*this);
937,715,918✔
439

440
#ifdef OPENMC_DAGMC_ENABLED
441
  history().reset();
261,988,404✔
442
#endif
443
}
2,147,483,647✔
444

445
void Particle::event_revive_from_secondary()
2,147,483,647✔
446
{
447
  // If particle has too many events, display warning and kill it
448
  ++n_event();
2,147,483,647✔
449
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
UNCOV
450
    warning("Particle " + std::to_string(id()) +
×
451
            " underwent maximum number of events.");
UNCOV
452
    wgt() = 0.0;
×
453
  }
454

455
  // Check for secondary particles if this particle is dead
456
  if (!alive()) {
2,147,483,647✔
457
    // Write final position for this particle
458
    if (write_track()) {
232,294,257✔
459
      write_particle_track(*this);
6,244✔
460
    }
461

462
    // If no secondary particles, break out of event loop
463
    if (secondary_bank().empty())
232,294,257✔
464
      return;
465

466
    from_source(&secondary_bank().back());
63,373,286✔
467
    secondary_bank().pop_back();
63,373,286✔
468
    n_event() = 0;
63,373,286✔
469
    bank_second_E() = 0.0;
63,373,286✔
470

471
    // Subtract secondary particle energy from interim pulse-height results
472
    if (!model::active_pulse_height_tallies.empty() &&
63,373,286✔
473
        this->type().is_photon()) {
15,499✔
474
      // Since the birth cell of the particle has not been set we
475
      // have to determine it before the energy of the secondary particle can be
476
      // removed from the pulse-height of this cell.
477
      if (lowest_coord().cell() == C_NONE) {
605!
478
        bool verbose = settings::verbosity >= 10 || trace();
605!
479
        if (!exhaustive_find_cell(*this, verbose)) {
605!
UNCOV
480
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
481
                       std::to_string(id()));
×
UNCOV
482
          return;
×
483
        }
484
        // Set birth cell attribute
485
        if (cell_born() == C_NONE)
605!
486
          cell_born() = lowest_coord().cell();
605✔
487

488
        // Initialize last cells from current cell
489
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
490
          cell_last(j) = coord(j).cell();
605✔
491
        }
492
        n_coord_last() = n_coord();
605✔
493
      }
494
      pht_secondary_particles();
605✔
495
    }
496

497
    // Enter new particle in particle track file
498
    if (write_track())
63,373,286✔
499
      add_particle_track(*this);
5,234✔
500
  }
501
}
502

503
void Particle::event_death()
168,921,971✔
504
{
505
#ifdef OPENMC_DAGMC_ENABLED
506
  history().reset();
15,433,285✔
507
#endif
508

509
  // Finish particle track output.
510
  if (write_track()) {
168,921,971✔
511
    finalize_particle_track(*this);
1,010✔
512
  }
513

514
// Contribute tally reduction variables to global accumulator
515
#pragma omp atomic
93,069,822✔
516
  global_tally_absorption += keff_tally_absorption();
168,921,971✔
517
#pragma omp atomic
93,233,827✔
518
  global_tally_collision += keff_tally_collision();
168,921,971✔
519
#pragma omp atomic
92,941,427✔
520
  global_tally_tracklength += keff_tally_tracklength();
168,921,971✔
521
#pragma omp atomic
92,421,645✔
522
  global_tally_leakage += keff_tally_leakage();
168,921,971✔
523

524
  // Reset particle tallies once accumulated
525
  keff_tally_absorption() = 0.0;
168,921,971✔
526
  keff_tally_collision() = 0.0;
168,921,971✔
527
  keff_tally_tracklength() = 0.0;
168,921,971✔
528
  keff_tally_leakage() = 0.0;
168,921,971✔
529

530
  if (!model::active_pulse_height_tallies.empty()) {
168,921,971✔
531
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
532
  }
533

534
  // Record the number of progeny created by this particle.
535
  // This data will be used to efficiently sort the fission bank.
536
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,921,971✔
537
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,534,700✔
538
    simulation::progeny_per_particle[offset] = n_progeny();
141,534,700✔
539
  }
540
}
168,921,971✔
541

542
void Particle::pht_collision_energy()
2,024✔
543
{
544
  // Adds the energy particles lose in a collision to the pulse-height
545

546
  // determine index of cell in pulse_height_cells
547
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
548
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
549

550
  if (it != model::pulse_height_cells.end()) {
2,024!
551
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
552
    pht_storage()[index] += E_last() - E();
2,024✔
553

554
    // If the energy of the particle is below the cutoff, it will not be sampled
555
    // so its energy is added to the pulse-height in the cell
556
    int photon = ParticleType::photon().transport_index();
2,024✔
557
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
558
      pht_storage()[index] += E();
825✔
559
    }
560
  }
561
}
2,024✔
562

563
void Particle::pht_secondary_particles()
605✔
564
{
565
  // Removes the energy of secondary produced particles from the pulse-height
566

567
  // determine index of cell in pulse_height_cells
568
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
569
    model::pulse_height_cells.end(), cell_born());
605!
570

571
  if (it != model::pulse_height_cells.end()) {
605!
572
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
573
    pht_storage()[index] -= E();
605✔
574
  }
575
}
605✔
576

577
void Particle::cross_surface(const Surface& surf)
1,673,517,187✔
578
{
579

580
  if (settings::verbosity >= 10 || trace()) {
1,673,517,187✔
581
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
582
  }
583

584
// if we're crossing a CSG surface, make sure the DAG history is reset
585
#ifdef OPENMC_DAGMC_ENABLED
586
  if (surf.geom_type() == GeometryType::CSG)
152,808,981✔
587
    history().reset();
152,751,822✔
588
#endif
589

590
  // Handle any applicable boundary conditions.
591
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,517,187!
592
      settings::run_mode != RunMode::VOLUME) {
593
    surf.bc_->handle_particle(*this, surf);
720,664,771✔
594
    return;
720,664,771✔
595
  }
596

597
  // ==========================================================================
598
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
599

600
#ifdef OPENMC_DAGMC_ENABLED
601
  // in DAGMC, we know what the next cell should be
602
  if (surf.geom_type() == GeometryType::DAG) {
86,853,750✔
603
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
604
                       lowest_coord().universe()) -
46,350✔
605
                     1;
46,350✔
606
    // save material, temperature, and density multiplier
607
    material_last() = material();
46,350✔
608
    sqrtkT_last() = sqrtkT();
46,350✔
609
    density_mult_last() = density_mult();
46,350✔
610
    // set new cell value
611
    lowest_coord().cell() = i_cell;
46,350✔
612
    auto& cell = model::cells[i_cell];
46,350✔
613

614
    cell_instance() = 0;
46,350✔
615
    if (cell->distribcell_index_ >= 0)
46,350✔
616
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
617

618
    material() = cell->material(cell_instance());
46,350!
619
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
620
    density_mult() = cell->density_mult(cell_instance());
46,350✔
621
    return;
46,350✔
622
  }
623
#endif
624

625
  bool verbose = settings::verbosity >= 10 || trace();
952,806,066!
626
  if (neighbor_list_find_cell(*this, verbose)) {
952,806,066✔
627
    return;
628
  }
629

630
  // ==========================================================================
631
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
632

633
  // Remove lower coordinate levels
634
  n_coord() = 1;
29,911✔
635
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
636

637
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,911!
638
    // If a cell is still not found, there are two possible causes: 1) there is
639
    // a void in the model, and 2) the particle hit a surface at a tangent. If
640
    // the particle is really traveling tangent to a surface, if we move it
641
    // forward a tiny bit it should fix the problem.
642

643
    surface() = SURFACE_NONE;
5,799✔
644
    n_coord() = 1;
5,799✔
645
    r() += TINY_BIT * u();
5,799✔
646

647
    // Couldn't find next cell anywhere! This probably means there is an actual
648
    // undefined region in the geometry.
649

650
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
651
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
652
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
653
                   " it could not be located in any cell and it did not leak.");
654
      return;
5,790✔
655
    }
656
  }
657
}
658

659
void Particle::cross_vacuum_bc(const Surface& surf)
35,104,774✔
660
{
661
  // Score any surface current tallies -- note that the particle is moved
662
  // forward slightly so that if the mesh boundary is on the surface, it is
663
  // still processed
664

665
  if (!model::active_meshsurf_tallies.empty()) {
35,104,774✔
666
    // TODO: Find a better solution to score surface currents than
667
    // physically moving the particle forward slightly
668

669
    r() += TINY_BIT * u();
937,222✔
670
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
671
  }
672

673
  // Score to global leakage tally
674
  keff_tally_leakage() += wgt();
35,104,774✔
675

676
  // Kill the particle
677
  wgt() = 0.0;
35,104,774✔
678

679
  // Display message
680
  if (settings::verbosity >= 10 || trace()) {
35,104,774!
681
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
682
  }
683
}
35,104,774✔
684

685
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,318,903✔
686
{
687
  // Do not handle reflective boundary conditions on lower universes
688
  if (n_coord() != 1) {
684,318,903!
UNCOV
689
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
690
                 " off surface in a lower universe.");
UNCOV
691
    return;
×
692
  }
693

694
  // Score surface currents since reflection causes the direction of the
695
  // particle to change. For surface filters, we need to score the tallies
696
  // twice, once before the particle's surface attribute has changed and
697
  // once after. For mesh surface filters, we need to artificially move
698
  // the particle slightly back in case the surface crossing is coincident
699
  // with a mesh boundary
700

701
  if (!model::active_surface_tallies.empty()) {
684,318,903✔
702
    Direction normal = surf.normal(r());
285,021✔
703
    normal /= normal.norm();
285,021✔
704
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
705
  }
706

707
  if (!model::active_meshsurf_tallies.empty()) {
684,318,903✔
708
    Position r {this->r()};
46,885,487✔
709
    this->r() -= TINY_BIT * u();
46,885,487✔
710
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
711
    this->r() = r;
46,885,487✔
712
  }
713

714
  // Set the new particle direction
715
  u() = new_u;
684,318,903✔
716

717
  // Reassign particle's cell and surface
718
  coord(0).cell() = cell_last(0);
684,318,903✔
719
  surface() = -surface();
684,318,903✔
720

721
  // If a reflective surface is coincident with a lattice or universe
722
  // boundary, it is necessary to redetermine the particle's coordinates in
723
  // the lower universes.
724
  // (unless we're using a dagmc model, which has exactly one universe)
725
  n_coord() = 1;
684,318,903✔
726
  if (surf.geom_type() != GeometryType::DAG &&
1,368,635,048!
727
      !neighbor_list_find_cell(*this)) {
684,316,145✔
728
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
729
                 std::to_string(surf.id_) + ".");
×
UNCOV
730
    return;
×
731
  }
732

733
  // Set previous coordinate going slightly past surface crossing
734
  r_last_current() = r() + TINY_BIT * u();
684,318,903✔
735

736
  // Diagnostic message
737
  if (settings::verbosity >= 10 || trace()) {
684,318,903!
738
    write_message(1, "    Reflected from surface {}", surf.id_);
×
739
  }
740
}
741

742
void Particle::cross_periodic_bc(
2,246,560✔
743
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
744
{
745
  // Do not handle periodic boundary conditions on lower universes
746
  if (n_coord() != 1) {
2,246,560!
UNCOV
747
    mark_as_lost(
×
UNCOV
748
      "Cannot transfer particle " + std::to_string(id()) +
×
749
      " across surface in a lower universe. Boundary conditions must be "
750
      "applied to root universe.");
UNCOV
751
    return;
×
752
  }
753

754
  // Score surface currents since reflection causes the direction of the
755
  // particle to change -- artificially move the particle slightly back in
756
  // case the surface crossing is coincident with a mesh boundary
757
  if (!model::active_meshsurf_tallies.empty()) {
2,246,560!
758
    Position r {this->r()};
×
UNCOV
759
    this->r() -= TINY_BIT * u();
×
UNCOV
760
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
761
    this->r() = r;
×
762
  }
763

764
  // Adjust the particle's location and direction.
765
  r() = new_r;
2,246,560✔
766
  u() = new_u;
2,246,560✔
767

768
  // Reassign particle's surface
769
  surface() = new_surface;
2,246,560✔
770

771
  // Figure out what cell particle is in now
772
  n_coord() = 1;
2,246,560✔
773

774
  if (!neighbor_list_find_cell(*this)) {
2,246,560!
UNCOV
775
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
776
                 "boundary on surface " +
×
UNCOV
777
                 std::to_string(surf.id_) + ".");
×
UNCOV
778
    return;
×
779
  }
780

781
  // Set previous coordinate going slightly past surface crossing
782
  r_last_current() = r() + TINY_BIT * u();
2,246,560✔
783

784
  // Diagnostic message
785
  if (settings::verbosity >= 10 || trace()) {
2,246,560!
UNCOV
786
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
787
  }
788
}
789

790
void Particle::mark_as_lost(const char* message)
5,799✔
791
{
792
  // Print warning and write lost particle file
793
  warning(message);
5,799✔
794
  if (settings::max_write_lost_particles < 0 ||
5,799✔
795
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
796
    write_restart();
374✔
797
  }
798
  // Increment number of lost particles
799
  wgt() = 0.0;
5,799✔
800
#pragma omp atomic
3,154✔
801
  simulation::n_lost_particles += 1;
2,645✔
802

803
  // Count the total number of simulated particles (on this processor)
804
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
805
           simulation::work_per_rank;
806

807
  // Abort the simulation if the maximum number of lost particles has been
808
  // reached
809
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
810
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
811
    fatal_error("Maximum number of lost particles has been reached.");
9✔
812
  }
813
}
5,790✔
814

815
void Particle::write_restart() const
374✔
816
{
817
  // Dont write another restart file if in particle restart mode
818
  if (settings::run_mode == RunMode::PARTICLE)
374✔
819
    return;
22✔
820

821
  // Set up file name
822
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
823
    simulation::current_batch, id());
352✔
824

825
#pragma omp critical(WriteParticleRestart)
187✔
826
  {
352✔
827
    // Create file
828
    hid_t file_id = file_open(filename, 'w');
352✔
829

830
    // Write filetype and version info
831
    write_attribute(file_id, "filetype", "particle restart");
352✔
832
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
833
    write_attribute(file_id, "openmc_version", VERSION);
352✔
834
#ifdef GIT_SHA1
835
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
836
#endif
837

838
    // Write data to file
839
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
840
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
841
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
842
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
843
    switch (settings::run_mode) {
352!
844
    case RunMode::FIXED_SOURCE:
220✔
845
      write_dataset(file_id, "run_mode", "fixed source");
220✔
846
      break;
115✔
847
    case RunMode::EIGENVALUE:
132✔
848
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
849
      break;
72✔
UNCOV
850
    case RunMode::PARTICLE:
×
UNCOV
851
      write_dataset(file_id, "run_mode", "particle restart");
×
852
      break;
853
    default:
854
      break;
855
    }
856
    write_dataset(file_id, "id", id());
352✔
857
    write_dataset(file_id, "type", type().pdg_number());
352✔
858

859
    int64_t i = current_work();
352✔
860
    if (settings::run_mode == RunMode::EIGENVALUE) {
352✔
861
      // take source data from primary bank for eigenvalue simulation
862
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
863
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
864
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
865
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
866
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
867
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
220!
868
      // re-sample using rng random number seed used to generate source particle
869
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
220✔
870
                     settings::n_particles +
220✔
871
                   simulation::work_index[mpi::rank] + i;
220✔
872
      uint64_t seed = init_seed(id, STREAM_SOURCE);
220✔
873
      // re-sample source site
874
      auto site = sample_external_source(&seed);
220✔
875
      write_dataset(file_id, "weight", site.wgt);
220✔
876
      write_dataset(file_id, "energy", site.E);
220✔
877
      write_dataset(file_id, "xyz", site.r);
220✔
878
      write_dataset(file_id, "uvw", site.u);
220✔
879
      write_dataset(file_id, "time", site.time);
220✔
880
    }
881

882
    // Close file
883
    file_close(file_id);
352✔
884
  } // #pragma omp critical
885
}
352✔
886

887
void Particle::update_neutron_xs(
2,147,483,647✔
888
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
889
{
890
  // Get microscopic cross section cache
891
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
892

893
  // If the cache doesn't match, recalculate micro xs
894
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
895
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
896
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
897
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
898

899
    // If NCrystal is being used, update micro cross section cache
900
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
901
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
902
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
903
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
904
    }
905
  }
906
}
2,147,483,647✔
907

908
//==============================================================================
909
// Non-method functions
910
//==============================================================================
911
void add_surf_source_to_bank(Particle& p, const Surface& surf)
151,425,275✔
912
{
913
  if (simulation::current_batch <= settings::n_inactive ||
151,425,275✔
914
      simulation::surf_source_bank.full()) {
108,321,766✔
915
    return;
916
  }
917

918
  // Add the site if no cells have been requested (via 'cells', 'cell',
919
  // 'cellfrom' or 'cellto')
920
  bool add_site = true;
355,070✔
921

922
  // If cells have been requested (via 'cells', 'cell', 'cellfrom' or 'cellto')
923
  if (!settings::ssw_cells.empty()) {
355,070✔
924

925
    // Leave if other boundary condition than vacuum
926
    if (surf.bc_ && surf.bc_->type() != "vacuum") {
421,883✔
927
      return;
928
    }
929

930
    // The site will only be added if at least one cell-direction pair is valid
931
    add_site = false;
156,065✔
932

933
    // Looping through all cell-direction pairs
934
    for (auto& cell : settings::ssw_cells) {
263,642✔
935
      // Retrieve cell index and storage type
936
      int cell_idx = model::cell_map[cell.first];
160,585✔
937
      SSWCellType direction = cell.second;
160,585✔
938

939
      // Skip if cellto with vacuum boundary condition
940
      if (surf.bc_ && surf.bc_->type() == "vacuum" &&
193,683!
941
          direction == SSWCellType::To) {
942
        continue;
12,135✔
943
      }
944

945
      // Check if the cell of interest has been exited
946
      bool exited = false;
947
      for (int i = 0; i < p.n_coord_last(); ++i) {
378,689✔
948
        if (p.cell_last(i) == cell_idx) {
230,239✔
949
          exited = true;
79,755✔
950
        }
951
      }
952

953
      // Check if the cell of interest has been entered
954
      bool entered = false;
955
      for (int i = 0; i < p.n_coord(); ++i) {
342,991✔
956
        if (p.coord(i).cell() == cell_idx) {
194,541✔
957
          entered = true;
63,517✔
958
        }
959
      }
960

961
      // Vacuum boundary conditions: return if cell is not exited
962
      if (surf.bc_) {
148,450✔
963
        if (surf.bc_->type() == "vacuum" && !exited) {
41,926!
964
          continue;
14,663✔
965
        }
966
      } else {
967

968
        // If we both enter and exit the cell of interest
969
        if (entered && exited) {
127,487✔
970
          continue;
27,203✔
971
        }
972

973
        // If we did not enter nor exit the cell of interest
974
        if (!entered && !exited) {
100,284✔
975
          continue;
24,018✔
976
        }
977

978
        // If cellfrom and the cell before crossing is not the cell of
979
        // interest
980
        if (direction == SSWCellType::From && !exited) {
76,266✔
981
          continue;
11,543✔
982
        }
983

984
        // If cellto and the cell after crossing is not the cell of interest
985
        if (direction == SSWCellType::To && !entered) {
64,723✔
986
          continue;
18,015✔
987
        }
988
      }
989
      // If a cell-direction pair survived all the checks we add the site and
990
      // terminate the loop
991
      add_site = true;
992
      break;
993
    }
994
  }
995

996
  if (add_site) {
997
    SourceSite site;
135,653✔
998
    site.r = p.r();
135,653✔
999
    site.u = p.u();
135,653✔
1000
    site.E = p.E();
135,653✔
1001
    site.time = p.time();
135,653✔
1002
    site.wgt = p.wgt();
135,653✔
1003
    site.delayed_group = p.delayed_group();
135,653✔
1004
    site.surf_id = surf.id_;
135,653✔
1005
    site.particle = p.type();
135,653✔
1006
    site.parent_id = p.id();
135,653✔
1007
    site.progeny_id = p.n_progeny();
135,653✔
1008
    int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
135,653✔
1009
  }
1010
}
1011

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

© 2026 Coveralls, Inc