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

openmc-dev / openmc / 21269449529

23 Jan 2026 12:05AM UTC coverage: 81.986% (-0.01%) from 81.998%
21269449529

Pull #3742

github

web-flow
Merge ead91cc98 into 049a852e5
Pull Request #3742: Implement surface flux tallies

17250 of 24017 branches covered (71.82%)

Branch coverage included in aggregate %.

88 of 112 new or added lines in 5 files covered. (78.57%)

209 existing lines in 4 files now uncovered.

55705 of 64968 relevant lines covered (85.74%)

43383355.55 hits per line

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

85.43
/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/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

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

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (this->type()) {
2,021,273,770!
52
    case ParticleType::neutron:
1,945,145,310✔
53
      mass = MASS_NEUTRON_EV;
1,945,145,310✔
54
      break;
1,945,145,310✔
55
    case ParticleType::photon:
22,134,785✔
56
      mass = 0.0;
22,134,785✔
57
      break;
22,134,785✔
58
    case ParticleType::electron:
53,993,675✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
53,993,675✔
61
      break;
53,993,675✔
62
    }
63
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
64
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,021,273,770✔
65
           (this->E() + mass);
2,021,273,770✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
68
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
71
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
72
  }
73
}
74

75
bool Particle::create_secondary(
112,599,937✔
76
  double wgt, Direction u, double E, ParticleType type)
77
{
78
  // If energy is below cutoff for this particle, don't create secondary
79
  // particle
80
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
112,599,937✔
81
    return false;
53,836,785✔
82
  }
83

84
  auto& bank = secondary_bank().emplace_back();
58,763,152✔
85
  bank.particle = type;
58,763,152✔
86
  bank.wgt = wgt;
58,763,152✔
87
  bank.r = r();
58,763,152✔
88
  bank.u = u;
58,763,152✔
89
  bank.E = settings::run_CE ? E : g();
58,763,152!
90
  bank.time = time();
58,763,152✔
91
  bank_second_E() += bank.E;
58,763,152✔
92
  return true;
58,763,152✔
93
}
94

95
void Particle::split(double wgt)
4,088,129✔
96
{
97
  auto& bank = secondary_bank().emplace_back();
4,088,129✔
98
  bank.particle = type();
4,088,129✔
99
  bank.wgt = wgt;
4,088,129✔
100
  bank.r = r();
4,088,129✔
101
  bank.u = u();
4,088,129✔
102
  bank.E = settings::run_CE ? E() : g();
4,088,129✔
103
  bank.time = time();
4,088,129✔
104

105
  // Convert signed index to a signed surface ID
106
  if (surface() == SURFACE_NONE) {
4,088,129✔
107
    bank.surf_id = SURFACE_NONE;
4,087,793✔
108
  } else {
109
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
110
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
111
  }
112
}
4,088,129✔
113

114
void Particle::from_source(const SourceSite* src)
232,532,194✔
115
{
116
  // Reset some attributes
117
  clear();
232,532,194✔
118
  surface() = SURFACE_NONE;
232,532,194✔
119
  cell_born() = C_NONE;
232,532,194✔
120
  material() = C_NONE;
232,532,194✔
121
  n_collision() = 0;
232,532,194✔
122
  fission() = false;
232,532,194✔
123
  zero_flux_derivs();
232,532,194✔
124
  lifetime() = 0.0;
232,532,194✔
125
#ifdef OPENMC_DAGMC_ENABLED
126
  history().reset();
21,299,062✔
127
#endif
128

129
  // Copy attributes from source bank site
130
  type() = src->particle;
232,532,194✔
131
  wgt() = src->wgt;
232,532,194✔
132
  wgt_last() = src->wgt;
232,532,194✔
133
  r() = src->r;
232,532,194✔
134
  u() = src->u;
232,532,194✔
135
  r_born() = src->r;
232,532,194✔
136
  r_last_current() = src->r;
232,532,194✔
137
  r_last() = src->r;
232,532,194✔
138
  u_last() = src->u;
232,532,194✔
139
  if (settings::run_CE) {
232,532,194✔
140
    E() = src->E;
116,826,577✔
141
    g() = 0;
116,826,577✔
142
  } else {
143
    g() = static_cast<int>(src->E);
115,705,617✔
144
    g_last() = static_cast<int>(src->E);
115,705,617✔
145
    E() = data::mg.energy_bin_avg_[g()];
115,705,617✔
146
  }
147
  E_last() = E();
232,532,194✔
148
  time() = src->time;
232,532,194✔
149
  time_last() = src->time;
232,532,194✔
150
  parent_nuclide() = src->parent_nuclide;
232,532,194✔
151
  delayed_group() = src->delayed_group;
232,532,194✔
152

153
  // Convert signed surface ID to signed index
154
  if (src->surf_id != SURFACE_NONE) {
232,532,194✔
155
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
156
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
157
  }
158
}
232,532,194✔
159

160
void Particle::event_calculate_xs()
2,147,483,647✔
161
{
162
  // Set the random number stream
163
  stream() = STREAM_TRACKING;
2,147,483,647✔
164

165
  // Store pre-collision particle properties
166
  wgt_last() = wgt();
2,147,483,647✔
167
  E_last() = E();
2,147,483,647✔
168
  u_last() = u();
2,147,483,647✔
169
  r_last() = r();
2,147,483,647✔
170
  time_last() = time();
2,147,483,647✔
171

172
  // Reset event variables
173
  event() = TallyEvent::KILL;
2,147,483,647✔
174
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
175
  event_mt() = REACTION_NONE;
2,147,483,647✔
176

177
  // If the cell hasn't been determined based on the particle's location,
178
  // initiate a search for the current cell. This generally happens at the
179
  // beginning of the history and again for any secondary particles
180
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
181
    if (!exhaustive_find_cell(*this)) {
229,361,285!
182
      mark_as_lost(
×
183
        "Could not find the cell containing particle " + std::to_string(id()));
×
184
      return;
×
185
    }
186

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
229,361,285!
189
      cell_born() = lowest_coord().cell();
229,361,285✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
475,526,678✔
193
      cell_last(j) = coord(j).cell();
246,165,393✔
194
    }
195
    n_coord_last() = n_coord();
229,361,285✔
196
  }
197

198
  // Write particle track.
199
  if (write_track())
2,147,483,647✔
200
    write_particle_track(*this);
10,822✔
201

202
  if (settings::check_overlaps)
2,147,483,647!
203
    check_cell_overlap(*this);
×
204

205
  // Calculate microscopic and macroscopic cross sections
206
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
207
    if (settings::run_CE) {
2,147,483,647✔
208
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
209
          density_mult() != density_mult_last()) {
355,049,774✔
210
        // If the material is the same as the last material and the
211
        // temperature hasn't changed, we don't need to lookup cross
212
        // sections again.
213
        model::materials[material()]->calculate_xs(*this);
1,526,961,854✔
214
      }
215
    } else {
216
      // Get the MG data; unlike the CE case above, we have to re-calculate
217
      // cross sections for every collision since the cross sections may
218
      // be angle-dependent
219
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
220

221
      // Update the particle's group while we know we are multi-group
222
      g_last() = g();
2,063,937,414✔
223
    }
224
  } else {
225
    macro_xs().total = 0.0;
111,825,073✔
226
    macro_xs().absorption = 0.0;
111,825,073✔
227
    macro_xs().fission = 0.0;
111,825,073✔
228
    macro_xs().nu_fission = 0.0;
111,825,073✔
229
  }
230
}
231

232
void Particle::event_advance()
2,147,483,647✔
233
{
234
  // Find the distance to the nearest boundary
235
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
236

237
  // Sample a distance to collision
238
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
239
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
53,993,675!
240
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
241
    collision_distance() = INFINITY;
111,825,073✔
242
  } else {
243
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
244
  }
245

246
  double speed = this->speed();
2,147,483,647✔
247
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
248
  double distance_cutoff =
249
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
250

251
  // Select smaller of the three distances
252
  double distance =
253
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
254

255
  // Advance particle in space and time
256
  this->move_distance(distance);
2,147,483,647✔
257
  double dt = distance / speed;
2,147,483,647✔
258
  this->time() += dt;
2,147,483,647✔
259
  this->lifetime() += dt;
2,147,483,647✔
260

261
  // Score timed track-length tallies
262
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
264
  }
265

266
  // Score track-length tallies
267
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
268
    score_tracklength_tally(*this, distance);
1,486,554,302✔
269
  }
270

271
  // Score track-length estimate of k-eff
272
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
273
      type() == ParticleType::neutron) {
2,147,483,647✔
274
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
275
  }
276

277
  // Score flux derivative accumulators for differential tallies.
278
  if (!model::active_tallies.empty()) {
2,147,483,647✔
279
    score_track_derivative(*this, distance);
1,655,996,925✔
280
  }
281

282
  // Set particle weight to zero if it hit the time boundary
283
  if (distance == distance_cutoff) {
2,147,483,647✔
284
    wgt() = 0.0;
224,928✔
285
  }
286
}
2,147,483,647✔
287

288
void Particle::event_cross_surface()
2,147,483,647✔
289
{
290
  // Saving previous cell data
291
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
292
    cell_last(j) = coord(j).cell();
2,147,483,647✔
293
  }
294
  n_coord_last() = n_coord();
2,147,483,647✔
295

296
  // Set surface that particle is on and adjust coordinate levels
297
  surface() = boundary().surface();
2,147,483,647✔
298
  n_coord() = boundary().coord_level();
2,147,483,647✔
299

300
  const auto& surf {*model::surfaces[surface_index()].get()};
2,147,483,647✔
301

302
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
303
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
304
      boundary().lattice_translation()[2] != 0) {
1,657,057,351✔
305
    // Particle crosses lattice boundary
306

307
    bool verbose = settings::verbosity >= 10 || trace();
725,009,288!
308
    cross_lattice(*this, boundary(), verbose);
725,009,288✔
309
    event() = TallyEvent::LATTICE;
725,009,288✔
310
  } else {
311
    // Particle crosses surface
312
    // If BC, add particle to surface source before crossing surface
313
    if (surf.surf_source_ && surf.bc_) {
1,468,515,456✔
314
      add_surf_source_to_bank(*this, surf);
676,159,926✔
315
    }
316
    this->cross_surface(surf);
1,468,515,456✔
317
    // If no BC, add particle to surface source after crossing surface
318
    if (surf.surf_source_ && !surf.bc_) {
1,468,515,447✔
319
      add_surf_source_to_bank(*this, surf);
791,117,694✔
320
    }
321
    if (settings::weight_window_checkpoint_surface) {
1,468,515,447✔
322
      apply_weight_windows(*this);
10,738✔
323
    }
324
    event() = TallyEvent::SURFACE;
1,468,515,447✔
325
  }
326
  // Score cell to cell partial currents
327
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
328
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,922,767✔
329
  }
330
}
2,147,483,647✔
331

332
void Particle::event_collide()
2,147,483,647✔
333
{
334
  // Score collision estimate of keff
335
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
336
      type() == ParticleType::neutron) {
2,147,483,647✔
337
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,118,355,927✔
338
  }
339

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

344
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
345
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
346

347
  // Clear surface component
348
  surface() = SURFACE_NONE;
2,147,483,647✔
349

350
  if (settings::run_CE) {
2,147,483,647✔
351
    collision(*this);
882,273,867✔
352
  } else {
353
    collision_mg(*this);
1,783,060,477✔
354
  }
355

356
  // Collision track feature to recording particle interaction
357
  if (settings::collision_track) {
2,147,483,647✔
358
    collision_track_record(*this);
150,087✔
359
  }
360

361
  // Score collision estimator tallies -- this is done after a collision
362
  // has occurred rather than before because we need information on the
363
  // outgoing energy for any tallies with an outgoing energy filter
364
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
365
    score_collision_tally(*this);
107,059,198✔
366
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
367
    if (settings::run_CE) {
234,574,551✔
368
      score_analog_tally_ce(*this);
233,366,289✔
369
    } else {
370
      score_analog_tally_mg(*this);
1,208,262✔
371
    }
372
  }
373

374
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
375
      type() == ParticleType::photon) {
16,918✔
376
    pht_collision_energy();
2,024✔
377
  }
378

379
  // Reset banked weight during collision
380
  n_bank() = 0;
2,147,483,647✔
381
  bank_second_E() = 0.0;
2,147,483,647✔
382
  wgt_bank() = 0.0;
2,147,483,647✔
383
  zero_delayed_bank();
2,147,483,647✔
384

385
  // Reset fission logical
386
  fission() = false;
2,147,483,647✔
387

388
  // Save coordinates for tallying purposes
389
  r_last_current() = r();
2,147,483,647✔
390

391
  // Set last material to none since cross sections will need to be
392
  // re-evaluated
393
  material_last() = C_NONE;
2,147,483,647✔
394

395
  // Set all directions to base level -- right now, after a collision, only
396
  // the base level directions are changed
397
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
398
    if (coord(j + 1).rotated()) {
134,222,432✔
399
      // If next level is rotated, apply rotation matrix
400
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
401
      const auto& u {coord(j).u()};
10,426,614✔
402
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
403
    } else {
404
      // Otherwise, copy this level's direction
405
      coord(j + 1).u() = coord(j).u();
123,795,818✔
406
    }
407
  }
408

409
  // Score flux derivative accumulators for differential tallies.
410
  if (!model::active_tallies.empty())
2,147,483,647✔
411
    score_collision_derivative(*this);
759,538,296✔
412

413
#ifdef OPENMC_DAGMC_ENABLED
414
  history().reset();
244,367,103✔
415
#endif
416
}
2,147,483,647✔
417

418
void Particle::event_revive_from_secondary()
2,147,483,647✔
419
{
420
  // If particle has too many events, display warning and kill it
421
  ++n_event();
2,147,483,647✔
422
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
423
    warning("Particle " + std::to_string(id()) +
×
424
            " underwent maximum number of events.");
425
    wgt() = 0.0;
×
426
  }
427

428
  // Check for secondary particles if this particle is dead
429
  if (!alive()) {
2,147,483,647✔
430
    // Write final position for this particle
431
    if (write_track()) {
229,360,881✔
432
      write_particle_track(*this);
6,678✔
433
    }
434

435
    // If no secondary particles, break out of event loop
436
    if (secondary_bank().empty())
229,360,881✔
437
      return;
166,306,081✔
438

439
    from_source(&secondary_bank().back());
63,054,800✔
440
    secondary_bank().pop_back();
63,054,800✔
441
    n_event() = 0;
63,054,800✔
442
    bank_second_E() = 0.0;
63,054,800✔
443

444
    // Subtract secondary particle energy from interim pulse-height results
445
    if (!model::active_pulse_height_tallies.empty() &&
63,070,299✔
446
        this->type() == ParticleType::photon) {
15,499✔
447
      // Since the birth cell of the particle has not been set we
448
      // have to determine it before the energy of the secondary particle can be
449
      // removed from the pulse-height of this cell.
450
      if (lowest_coord().cell() == C_NONE) {
605!
451
        bool verbose = settings::verbosity >= 10 || trace();
605!
452
        if (!exhaustive_find_cell(*this, verbose)) {
605!
453
          mark_as_lost("Could not find the cell containing particle " +
×
454
                       std::to_string(id()));
×
455
          return;
×
456
        }
457
        // Set birth cell attribute
458
        if (cell_born() == C_NONE)
605!
459
          cell_born() = lowest_coord().cell();
605✔
460

461
        // Initialize last cells from current cell
462
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
463
          cell_last(j) = coord(j).cell();
605✔
464
        }
465
        n_coord_last() = n_coord();
605✔
466
      }
467
      pht_secondary_particles();
605✔
468
    }
469

470
    // Enter new particle in particle track file
471
    if (write_track())
63,054,800✔
472
      add_particle_track(*this);
5,608✔
473
  }
474
}
475

476
void Particle::event_death()
166,307,081✔
477
{
478
#ifdef OPENMC_DAGMC_ENABLED
479
  history().reset();
15,194,135✔
480
#endif
481

482
  // Finish particle track output.
483
  if (write_track()) {
166,307,081✔
484
    finalize_particle_track(*this);
1,070✔
485
  }
486

487
// Contribute tally reduction variables to global accumulator
488
#pragma omp atomic
91,429,811✔
489
  global_tally_absorption += keff_tally_absorption();
166,307,081✔
490
#pragma omp atomic
90,979,365✔
491
  global_tally_collision += keff_tally_collision();
166,307,081✔
492
#pragma omp atomic
90,957,393✔
493
  global_tally_tracklength += keff_tally_tracklength();
166,307,081✔
494
#pragma omp atomic
90,937,138✔
495
  global_tally_leakage += keff_tally_leakage();
166,307,081✔
496

497
  // Reset particle tallies once accumulated
498
  keff_tally_absorption() = 0.0;
166,307,081✔
499
  keff_tally_collision() = 0.0;
166,307,081✔
500
  keff_tally_tracklength() = 0.0;
166,307,081✔
501
  keff_tally_leakage() = 0.0;
166,307,081✔
502

503
  if (!model::active_pulse_height_tallies.empty()) {
166,307,081✔
504
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
505
  }
506

507
  // Record the number of progeny created by this particle.
508
  // This data will be used to efficiently sort the fission bank.
509
  if (settings::run_mode == RunMode::EIGENVALUE) {
166,307,081✔
510
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,705,700✔
511
    simulation::progeny_per_particle[offset] = n_progeny();
140,705,700✔
512
  }
513
}
166,307,081✔
514

515
void Particle::pht_collision_energy()
2,024✔
516
{
517
  // Adds the energy particles lose in a collision to the pulse-height
518

519
  // determine index of cell in pulse_height_cells
520
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
521
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
522

523
  if (it != model::pulse_height_cells.end()) {
2,024!
524
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
525
    pht_storage()[index] += E_last() - E();
2,024✔
526

527
    // If the energy of the particle is below the cutoff, it will not be sampled
528
    // so its energy is added to the pulse-height in the cell
529
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
530
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
531
      pht_storage()[index] += E();
825✔
532
    }
533
  }
534
}
2,024✔
535

536
void Particle::pht_secondary_particles()
605✔
537
{
538
  // Removes the energy of secondary produced particles from the pulse-height
539

540
  // determine index of cell in pulse_height_cells
541
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
542
    model::pulse_height_cells.end(), cell_born());
605✔
543

544
  if (it != model::pulse_height_cells.end()) {
605!
545
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
546
    pht_storage()[index] -= E();
605✔
547
  }
548
}
605✔
549

550
void Particle::cross_surface(const Surface& surf)
1,469,685,658✔
551
{
552

553
  if (settings::verbosity >= 10 || trace()) {
1,469,685,658✔
554
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
555
  }
556

557
// if we're crossing a CSG surface, make sure the DAG history is reset
558
#ifdef OPENMC_DAGMC_ENABLED
559
  if (surf.geom_type() == GeometryType::CSG)
134,347,661✔
560
    history().reset();
134,292,542✔
561
#endif
562

563
  // Handle any applicable boundary conditions.
564
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,146,317,636!
565
      settings::run_mode != RunMode::VOLUME) {
676,631,978✔
566
    surf.bc_->handle_particle(*this, surf);
676,512,034✔
567
    return;
676,512,034✔
568
  }
569

570
  // ==========================================================================
571
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
572

573
#ifdef OPENMC_DAGMC_ENABLED
574
  // in DAGMC, we know what the next cell should be
575
  if (surf.geom_type() == GeometryType::DAG) {
72,400,632✔
576
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
577
                       lowest_coord().universe()) -
44,310✔
578
                     1;
44,310✔
579
    // save material, temperature, and density multiplier
580
    material_last() = material();
44,310✔
581
    sqrtkT_last() = sqrtkT();
44,310✔
582
    density_mult_last() = density_mult();
44,310✔
583
    // set new cell value
584
    lowest_coord().cell() = i_cell;
44,310✔
585
    auto& cell = model::cells[i_cell];
44,310✔
586

587
    cell_instance() = 0;
44,310✔
588
    if (cell->distribcell_index_ >= 0)
44,310✔
589
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
590

591
    material() = cell->material(cell_instance());
44,310✔
592
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
593
    density_mult() = cell->density_mult(cell_instance());
44,310✔
594
    return;
44,310✔
595
  }
596
#endif
597

598
  bool verbose = settings::verbosity >= 10 || trace();
793,129,314!
599
  if (neighbor_list_find_cell(*this, verbose)) {
793,129,314✔
600
    return;
793,099,403✔
601
  }
602

603
  // ==========================================================================
604
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
605

606
  // Remove lower coordinate levels
607
  n_coord() = 1;
29,911✔
608
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
609

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

616
    surface() = SURFACE_NONE;
5,799✔
617
    n_coord() = 1;
5,799✔
618
    r() += TINY_BIT * u();
5,799✔
619

620
    // Couldn't find next cell anywhere! This probably means there is an actual
621
    // undefined region in the geometry.
622

623
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
624
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
625
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
626
                   " it could not be located in any cell and it did not leak.");
627
      return;
5,790✔
628
    }
629
  }
630
}
631

632
void Particle::cross_vacuum_bc(const Surface& surf)
35,015,103✔
633
{
634
  // Score any surface current tallies -- note that the particle is moved
635
  // forward slightly so that if the mesh boundary is on the surface, it is
636
  // still processed
637

638
  if (!model::active_meshsurf_tallies.empty()) {
35,015,103✔
639
    // TODO: Find a better solution to score surface currents than
640
    // physically moving the particle forward slightly
641

642
    r() += TINY_BIT * u();
937,222✔
643
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
644
  }
645

646
  // Score to global leakage tally
647
  keff_tally_leakage() += wgt();
35,015,103✔
648

649
  // Kill the particle
650
  wgt() = 0.0;
35,015,103✔
651

652
  // Display message
653
  if (settings::verbosity >= 10 || trace()) {
35,015,103!
654
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
655
  }
656
}
35,015,103✔
657

658
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
640,256,852✔
659
{
660
  // Do not handle reflective boundary conditions on lower universes
661
  if (n_coord() != 1) {
640,256,852!
662
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
663
                 " off surface in a lower universe.");
664
    return;
×
665
  }
666

667
  // Score surface currents since reflection causes the direction of the
668
  // particle to change. For surface filters, we need to score the tallies
669
  // twice, once before the particle's surface attribute has changed and
670
  // once after. For mesh surface filters, we need to artificially move
671
  // the particle slightly back in case the surface crossing is coincident
672
  // with a mesh boundary
673

674
  if (!model::active_surface_tallies.empty()) {
640,256,852✔
675
    score_surface_tally(*this, model::active_surface_tallies, surf);
285,021✔
676
  }
677

678
  if (!model::active_meshsurf_tallies.empty()) {
640,256,852✔
679
    Position r {this->r()};
46,885,487✔
680
    this->r() -= TINY_BIT * u();
46,885,487✔
681
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
682
    this->r() = r;
46,885,487✔
683
  }
684

685
  // Set the new particle direction
686
  u() = new_u;
640,256,852✔
687

688
  // Reassign particle's cell and surface
689
  coord(0).cell() = cell_last(0);
640,256,852✔
690
  surface() = -surface();
640,256,852✔
691

692
  // If a reflective surface is coincident with a lattice or universe
693
  // boundary, it is necessary to redetermine the particle's coordinates in
694
  // the lower universes.
695
  // (unless we're using a dagmc model, which has exactly one universe)
696
  n_coord() = 1;
640,256,852✔
697
  if (surf.geom_type() != GeometryType::DAG &&
1,280,510,946!
698
      !neighbor_list_find_cell(*this)) {
640,254,094!
699
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
700
                 std::to_string(surf.id_) + ".");
×
701
    return;
×
702
  }
703

704
  // Set previous coordinate going slightly past surface crossing
705
  r_last_current() = r() + TINY_BIT * u();
640,256,852✔
706

707
  // Diagnostic message
708
  if (settings::verbosity >= 10 || trace()) {
640,256,852!
709
    write_message(1, "    Reflected from surface {}", surf.id_);
×
710
  }
711
}
712

713
void Particle::cross_periodic_bc(
2,245,545✔
714
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
715
{
716
  // Do not handle periodic boundary conditions on lower universes
717
  if (n_coord() != 1) {
2,245,545!
718
    mark_as_lost(
×
719
      "Cannot transfer particle " + std::to_string(id()) +
×
720
      " across surface in a lower universe. Boundary conditions must be "
721
      "applied to root universe.");
722
    return;
×
723
  }
724

725
  // Score surface currents since reflection causes the direction of the
726
  // particle to change -- artificially move the particle slightly back in
727
  // case the surface crossing is coincident with a mesh boundary
728
  if (!model::active_meshsurf_tallies.empty()) {
2,245,545!
729
    Position r {this->r()};
×
730
    this->r() -= TINY_BIT * u();
×
NEW
731
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
732
    this->r() = r;
×
733
  }
734

735
  // Adjust the particle's location and direction.
736
  r() = new_r;
2,245,545✔
737
  u() = new_u;
2,245,545✔
738

739
  // Reassign particle's surface
740
  surface() = new_surface;
2,245,545✔
741

742
  // Figure out what cell particle is in now
743
  n_coord() = 1;
2,245,545✔
744

745
  if (!neighbor_list_find_cell(*this)) {
2,245,545!
746
    mark_as_lost("Couldn't find particle after hitting periodic "
×
747
                 "boundary on surface " +
×
748
                 std::to_string(surf.id_) + ".");
×
749
    return;
×
750
  }
751

752
  // Set previous coordinate going slightly past surface crossing
753
  r_last_current() = r() + TINY_BIT * u();
2,245,545✔
754

755
  // Diagnostic message
756
  if (settings::verbosity >= 10 || trace()) {
2,245,545!
757
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
758
  }
759
}
760

761
void Particle::mark_as_lost(const char* message)
5,799✔
762
{
763
  // Print warning and write lost particle file
764
  warning(message);
5,799✔
765
  if (settings::max_write_lost_particles < 0 ||
5,799✔
766
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
767
    write_restart();
379✔
768
  }
769
  // Increment number of lost particles
770
  wgt() = 0.0;
5,799✔
771
#pragma omp atomic
3,154✔
772
  simulation::n_lost_particles += 1;
2,645✔
773

774
  // Count the total number of simulated particles (on this processor)
775
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
776
           simulation::work_per_rank;
777

778
  // Abort the simulation if the maximum number of lost particles has been
779
  // reached
780
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
781
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
782
    fatal_error("Maximum number of lost particles has been reached.");
9✔
783
  }
784
}
5,790✔
785

786
void Particle::write_restart() const
379✔
787
{
788
  // Dont write another restart file if in particle restart mode
789
  if (settings::run_mode == RunMode::PARTICLE)
379✔
790
    return;
22✔
791

792
  // Set up file name
793
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
794
    simulation::current_batch, id());
665✔
795

796
#pragma omp critical(WriteParticleRestart)
374✔
797
  {
798
    // Create file
799
    hid_t file_id = file_open(filename, 'w');
357✔
800

801
    // Write filetype and version info
802
    write_attribute(file_id, "filetype", "particle restart");
357✔
803
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
357✔
804
    write_attribute(file_id, "openmc_version", VERSION);
357✔
805
#ifdef GIT_SHA1
806
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
807
#endif
808

809
    // Write data to file
810
    write_dataset(file_id, "current_batch", simulation::current_batch);
357✔
811
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
357✔
812
    write_dataset(file_id, "current_generation", simulation::current_gen);
357✔
813
    write_dataset(file_id, "n_particles", settings::n_particles);
357✔
814
    switch (settings::run_mode) {
357!
815
    case RunMode::FIXED_SOURCE:
225✔
816
      write_dataset(file_id, "run_mode", "fixed source");
225✔
817
      break;
225✔
818
    case RunMode::EIGENVALUE:
132✔
819
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
820
      break;
132✔
821
    case RunMode::PARTICLE:
×
822
      write_dataset(file_id, "run_mode", "particle restart");
×
823
      break;
×
824
    default:
×
825
      break;
×
826
    }
827
    write_dataset(file_id, "id", id());
357✔
828
    write_dataset(file_id, "type", static_cast<int>(type()));
357✔
829

830
    int64_t i = current_work();
357✔
831
    if (settings::run_mode == RunMode::EIGENVALUE) {
357✔
832
      // take source data from primary bank for eigenvalue simulation
833
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
834
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
835
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
836
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
837
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
838
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
839
      // re-sample using rng random number seed used to generate source particle
840
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
841
                     settings::n_particles +
225✔
842
                   simulation::work_index[mpi::rank] + i;
225✔
843
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
844
      // re-sample source site
845
      auto site = sample_external_source(&seed);
225✔
846
      write_dataset(file_id, "weight", site.wgt);
225✔
847
      write_dataset(file_id, "energy", site.E);
225✔
848
      write_dataset(file_id, "xyz", site.r);
225✔
849
      write_dataset(file_id, "uvw", site.u);
225✔
850
      write_dataset(file_id, "time", site.time);
225✔
851
    }
852

853
    // Close file
854
    file_close(file_id);
357✔
855
  } // #pragma omp critical
856
}
357✔
857

858
void Particle::update_neutron_xs(
2,147,483,647✔
859
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
860
{
861
  // Get microscopic cross section cache
862
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
863

864
  // If the cache doesn't match, recalculate micro xs
865
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
866
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
867
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
868
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
869

870
    // If NCrystal is being used, update micro cross section cache
871
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
872
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
873
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
874
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
875
    }
876
  }
877
}
2,147,483,647✔
878

879
//==============================================================================
880
// Non-method functions
881
//==============================================================================
882

883
std::string particle_type_to_str(ParticleType type)
3,130,197✔
884
{
885
  switch (type) {
3,130,197!
886
  case ParticleType::neutron:
2,399,940✔
887
    return "neutron";
2,399,940✔
888
  case ParticleType::photon:
729,993✔
889
    return "photon";
729,993✔
890
  case ParticleType::electron:
132✔
891
    return "electron";
132✔
892
  case ParticleType::positron:
132✔
893
    return "positron";
132✔
894
  }
895
  UNREACHABLE();
×
896
}
897

898
ParticleType str_to_particle_type(std::string str)
3,262,008✔
899
{
900
  if (str == "neutron") {
3,262,008✔
901
    return ParticleType::neutron;
763,443✔
902
  } else if (str == "photon") {
2,498,565✔
903
    return ParticleType::photon;
2,498,479✔
904
  } else if (str == "electron") {
86✔
905
    return ParticleType::electron;
43✔
906
  } else if (str == "positron") {
43!
907
    return ParticleType::positron;
43✔
908
  } else {
909
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
910
  }
911
}
912

913
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,467,277,620✔
914
{
915
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
916
      simulation::surf_source_bank.full()) {
1,159,316,789✔
917
    return;
1,467,147,967✔
918
  }
919

920
  // If a cell/cellfrom/cellto parameter is defined
921
  if (settings::ssw_cell_id != C_NONE) {
337,085✔
922

923
    // Retrieve cell index and storage type
924
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,440✔
925

926
    if (surf.bc_) {
254,440✔
927
      // Leave if cellto with vacuum boundary condition
928
      if (surf.bc_->type() == "vacuum" &&
182,558!
929
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
930
        return;
12,136✔
931
      }
932

933
      // Leave if other boundary condition than vacuum
934
      if (surf.bc_->type() != "vacuum") {
137,323✔
935
        return;
116,360✔
936
      }
937
    }
938

939
    // Check if the cell of interest has been exited
940
    bool exited = false;
125,944✔
941
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,677✔
942
      if (p.cell_last(i) == cell_idx) {
207,733✔
943
        exited = true;
73,766✔
944
      }
945
    }
946

947
    // Check if the cell of interest has been entered
948
    bool entered = false;
125,944✔
949
    for (int i = 0; i < p.n_coord(); ++i) {
297,979✔
950
      if (p.coord(i).cell() == cell_idx) {
172,035✔
951
        entered = true;
57,517✔
952
      }
953
    }
954

955
    // Vacuum boundary conditions: return if cell is not exited
956
    if (surf.bc_) {
125,944✔
957
      if (surf.bc_->type() == "vacuum" && !exited) {
20,963!
958
        return;
14,663✔
959
      }
960
    } else {
961

962
      // If we both enter and exit the cell of interest
963
      if (entered && exited) {
104,981✔
964
        return;
27,203✔
965
      }
966

967
      // If we did not enter nor exit the cell of interest
968
      if (!entered && !exited) {
77,778✔
969
        return;
13,501✔
970
      }
971

972
      // If cellfrom and the cell before crossing is not the cell of
973
      // interest
974
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,277✔
975
        return;
11,543✔
976
      }
977

978
      // If cellto and the cell after crossing is not the cell of interest
979
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,734✔
980
        return;
12,026✔
981
      }
982
    }
983
  }
984

985
  SourceSite site;
129,653✔
986
  site.r = p.r();
129,653✔
987
  site.u = p.u();
129,653✔
988
  site.E = p.E();
129,653✔
989
  site.time = p.time();
129,653✔
990
  site.wgt = p.wgt();
129,653✔
991
  site.delayed_group = p.delayed_group();
129,653✔
992
  site.surf_id = surf.id_;
129,653✔
993
  site.particle = p.type();
129,653✔
994
  site.parent_id = p.id();
129,653✔
995
  site.progeny_id = p.n_progeny();
129,653✔
996
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
997
}
998

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