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

openmc-dev / openmc / 15976228366

30 Jun 2025 02:49PM UTC coverage: 85.251% (+0.09%) from 85.162%
15976228366

Pull #3453

github

web-flow
Merge b1fed47a9 into b939f9003
Pull Request #3453: Secondary energy filter

50 of 53 new or added lines in 6 files covered. (94.34%)

399 existing lines in 26 files now uncovered.

52638 of 61745 relevant lines covered (85.25%)

36736977.41 hits per line

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

92.46
/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/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef DAGMC
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  // Determine mass in eV/c^2
48
  double mass;
49
  switch (this->type()) {
2,147,483,647✔
50
  case ParticleType::neutron:
2,147,483,647✔
51
    mass = MASS_NEUTRON_EV;
2,147,483,647✔
52
    break;
2,147,483,647✔
53
  case ParticleType::photon:
17,338,035✔
54
    mass = 0.0;
17,338,035✔
55
    break;
17,338,035✔
56
  case ParticleType::electron:
51,300,172✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
51,300,172✔
59
    break;
51,300,172✔
60
  }
61

62
  if (this->E() < 1.0e-9 * mass) {
2,147,483,647✔
63
    // If the energy is much smaller than the mass, revert to non-relativistic
64
    // formula. The 1e-9 criterion is specifically chosen as the point below
65
    // which the error from using the non-relativistic formula is less than the
66
    // round-off eror when using the relativistic formula (see analysis at
67
    // https://gist.github.com/paulromano/da3b473fe3df33de94b265bdff0c7817)
68
    return C_LIGHT * std::sqrt(2 * this->E() / mass);
858,922,628✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

73
    // Calculate speed via v = c * sqrt(1 - γ^-2)
74
    return C_LIGHT * std::sqrt(1 - inv_gamma * inv_gamma);
2,147,483,647✔
75
  }
76
}
77

78
bool Particle::create_secondary(
107,159,248✔
79
  double wgt, Direction u, double E, ParticleType type)
80
{
81
  // If energy is below cutoff for this particle, don't create secondary
82
  // particle
83
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
107,159,248✔
84
    return false;
51,249,704✔
85
  }
86

87
  // This is used to count backward in the secondary source bank for tallying
88
  // outgoing photon energies from a neutron in the SecondaryPhotonEnergy
89
  // filter.
90
  secondaries_this_collision()++;
55,909,544✔
91

92
  auto& bank = secondary_bank().emplace_back();
55,909,544✔
93
  bank.particle = type;
55,909,544✔
94
  bank.wgt = wgt;
55,909,544✔
95
  bank.r = r();
55,909,544✔
96
  bank.u = u;
55,909,544✔
97
  bank.E = settings::run_CE ? E : g();
55,909,544✔
98
  bank.time = time();
55,909,544✔
99
  bank_second_E() += bank.E;
55,909,544✔
100
  return true;
55,909,544✔
101
}
102

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

113
  // Convert signed index to a singed surface ID
114
  if (surface() == SURFACE_NONE) {
4,085,518✔
115
    bank.surf_id = SURFACE_NONE;
4,085,518✔
116
  } else {
UNCOV
117
    int surf_id = model::surfaces[surface_index()]->id_;
×
UNCOV
118
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
×
119
  }
120
}
4,085,518✔
121

122
void Particle::from_source(const SourceSite* src)
219,529,216✔
123
{
124
  // Reset some attributes
125
  clear();
219,529,216✔
126
  surface() = SURFACE_NONE;
219,529,216✔
127
  cell_born() = C_NONE;
219,529,216✔
128
  material() = C_NONE;
219,529,216✔
129
  n_collision() = 0;
219,529,216✔
130
  fission() = false;
219,529,216✔
131
  zero_flux_derivs();
219,529,216✔
132
  lifetime() = 0.0;
219,529,216✔
133

134
  // Copy attributes from source bank site
135
  type() = src->particle;
219,529,216✔
136
  wgt() = src->wgt;
219,529,216✔
137
  wgt_last() = src->wgt;
219,529,216✔
138
  r() = src->r;
219,529,216✔
139
  u() = src->u;
219,529,216✔
140
  r_born() = src->r;
219,529,216✔
141
  r_last_current() = src->r;
219,529,216✔
142
  r_last() = src->r;
219,529,216✔
143
  u_last() = src->u;
219,529,216✔
144
  if (settings::run_CE) {
219,529,216✔
145
    E() = src->E;
103,899,042✔
146
    g() = 0;
103,899,042✔
147
  } else {
148
    g() = static_cast<int>(src->E);
115,630,174✔
149
    g_last() = static_cast<int>(src->E);
115,630,174✔
150
    E() = data::mg.energy_bin_avg_[g()];
115,630,174✔
151
  }
152
  E_last() = E();
219,529,216✔
153
  time() = src->time;
219,529,216✔
154
  time_last() = src->time;
219,529,216✔
155
  parent_nuclide() = src->parent_nuclide;
219,529,216✔
156

157
  // Convert signed surface ID to signed index
158
  if (src->surf_id != SURFACE_NONE) {
219,529,216✔
159
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,000✔
160
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,000✔
161
  }
162
}
219,529,216✔
163

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

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

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

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

191
    // Set birth cell attribute
192
    if (cell_born() == C_NONE)
216,654,839✔
193
      cell_born() = lowest_coord().cell;
216,654,839✔
194

195
    // Initialize last cells from current cell
196
    for (int j = 0; j < n_coord(); ++j) {
448,999,388✔
197
      cell_last(j) = coord(j).cell;
232,344,549✔
198
    }
199
    n_coord_last() = n_coord();
216,654,839✔
200
  }
201

202
  // Write particle track.
203
  if (write_track())
2,147,483,647✔
204
    write_particle_track(*this);
10,839✔
205

206
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
207
    check_cell_overlap(*this);
×
208

209
  // Calculate microscopic and macroscopic cross sections
210
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
211
    if (settings::run_CE) {
2,147,483,647✔
212
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,634,544,242✔
213
        // If the material is the same as the last material and the
214
        // temperature hasn't changed, we don't need to lookup cross
215
        // sections again.
216
        model::materials[material()]->calculate_xs(*this);
1,313,379,542✔
217
      }
218
    } else {
219
      // Get the MG data; unlike the CE case above, we have to re-calculate
220
      // cross sections for every collision since the cross sections may
221
      // be angle-dependent
222
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,702,466✔
223

224
      // Update the particle's group while we know we are multi-group
225
      g_last() = g();
2,062,702,466✔
226
    }
227
  } else {
228
    macro_xs().total = 0.0;
66,455,847✔
229
    macro_xs().absorption = 0.0;
66,455,847✔
230
    macro_xs().fission = 0.0;
66,455,847✔
231
    macro_xs().nu_fission = 0.0;
66,455,847✔
232
  }
233
}
234

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

240
  // Sample a distance to collision
241
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
242
    collision_distance() = 0.0;
51,300,172✔
243
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
244
    collision_distance() = INFINITY;
66,455,847✔
245
  } else {
246
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
247
  }
248

249
  // Select smaller of the two distances
250
  double distance = std::min(boundary().distance, collision_distance());
2,147,483,647✔
251

252
  // Advance particle in space and time
253
  // Short-term solution until the surface source is revised and we can use
254
  // this->move_distance(distance)
255
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
256
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
257
  }
258
  double dt = distance / this->speed();
2,147,483,647✔
259
  this->time() += dt;
2,147,483,647✔
260
  this->lifetime() += dt;
2,147,483,647✔
261

262
  // Kill particle if its time exceeds the cutoff
263
  bool hit_time_boundary = false;
2,147,483,647✔
264
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
265
  if (time() > time_cutoff) {
2,147,483,647✔
266
    double dt = time() - time_cutoff;
11,000✔
267
    time() = time_cutoff;
11,000✔
268
    lifetime() = time_cutoff;
11,000✔
269

270
    double push_back_distance = speed() * dt;
11,000✔
271
    this->move_distance(-push_back_distance);
11,000✔
272
    hit_time_boundary = true;
11,000✔
273
  }
274

275
  // Score track-length tallies
276
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
277
    score_tracklength_tally(*this, distance);
1,246,729,122✔
278
  }
279

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

286
  // Score flux derivative accumulators for differential tallies.
287
  if (!model::active_tallies.empty()) {
2,147,483,647✔
288
    score_track_derivative(*this, distance);
1,409,901,190✔
289
  }
290

291
  // Set particle weight to zero if it hit the time boundary
292
  if (hit_time_boundary) {
2,147,483,647✔
293
    wgt() = 0.0;
11,000✔
294
  }
295
}
2,147,483,647✔
296

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

305
  // Set surface that particle is on and adjust coordinate levels
306
  surface() = boundary().surface;
2,024,137,567✔
307
  n_coord() = boundary().coord_level;
2,024,137,567✔
308

309
  if (boundary().lattice_translation[0] != 0 ||
2,024,137,567✔
310
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
311
      boundary().lattice_translation[2] != 0) {
1,539,063,240✔
312
    // Particle crosses lattice boundary
313

314
    bool verbose = settings::verbosity >= 10 || trace();
671,462,543✔
315
    cross_lattice(*this, boundary(), verbose);
671,462,543✔
316
    event() = TallyEvent::LATTICE;
671,462,543✔
317
  } else {
318
    // Particle crosses surface
319
    const auto& surf {model::surfaces[surface_index()].get()};
1,352,675,024✔
320
    // If BC, add particle to surface source before crossing surface
321
    if (surf->surf_source_ && surf->bc_) {
1,352,675,024✔
322
      add_surf_source_to_bank(*this, *surf);
634,087,078✔
323
    }
324
    this->cross_surface(*surf);
1,352,675,024✔
325
    // If no BC, add particle to surface source after crossing surface
326
    if (surf->surf_source_ && !surf->bc_) {
1,352,675,015✔
327
      add_surf_source_to_bank(*this, *surf);
717,684,528✔
328
    }
329
    if (settings::weight_window_checkpoint_surface) {
1,352,675,015✔
UNCOV
330
      apply_weight_windows(*this);
×
331
    }
332
    event() = TallyEvent::SURFACE;
1,352,675,015✔
333
  }
334
  // Score cell to cell partial currents
335
  if (!model::active_surface_tallies.empty()) {
2,024,137,558✔
336
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
337
  }
338
}
2,024,137,558✔
339

340
void Particle::event_collide()
2,147,483,647✔
341
{
342

343
  // Score collision estimate of keff
344
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
345
      type() == ParticleType::neutron) {
2,136,103,053✔
346
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,096,780,869✔
347
  }
348

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

353
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
354
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
355

356
  // Clear surface component
357
  surface() = SURFACE_NONE;
2,147,483,647✔
358

359
  if (settings::run_CE) {
2,147,483,647✔
360
    collision(*this);
722,714,186✔
361
  } else {
362
    collision_mg(*this);
1,781,765,117✔
363
  }
364

365
  // Score collision estimator tallies -- this is done after a collision
366
  // has occurred rather than before because we need information on the
367
  // outgoing energy for any tallies with an outgoing energy filter
368
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
369
    score_collision_tally(*this);
97,535,094✔
370
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
371
    if (settings::run_CE) {
113,305,951✔
372
      score_analog_tally_ce(*this);
112,104,740✔
373
    } else {
374
      score_analog_tally_mg(*this);
1,201,211✔
375
    }
376
  }
377

378
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
379
      type() == ParticleType::photon) {
16,918✔
380
    pht_collision_energy();
2,024✔
381
  }
382

383
  // Reset banked weight during collision
384
  n_bank() = 0;
2,147,483,647✔
385
  bank_second_E() = 0.0;
2,147,483,647✔
386
  wgt_bank() = 0.0;
2,147,483,647✔
387

388
  // Clear number of secondaries in this collision. This is
389
  // distinct from the number of created neutrons n_bank() above!
390
  secondaries_this_collision() = 0;
2,147,483,647✔
391

392
  zero_delayed_bank();
2,147,483,647✔
393

394
  // Reset fission logical
395
  fission() = false;
2,147,483,647✔
396

397
  // Save coordinates for tallying purposes
398
  r_last_current() = r();
2,147,483,647✔
399

400
  // Set last material to none since cross sections will need to be
401
  // re-evaluated
402
  material_last() = C_NONE;
2,147,483,647✔
403

404
  // Set all directions to base level -- right now, after a collision, only
405
  // the base level directions are changed
406
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
407
    if (coord(j + 1).rotated) {
113,090,568✔
408
      // If next level is rotated, apply rotation matrix
409
      const auto& m {model::cells[coord(j).cell]->rotation_};
10,394,285✔
410
      const auto& u {coord(j).u};
10,394,285✔
411
      coord(j + 1).u = u.rotate(m);
10,394,285✔
412
    } else {
413
      // Otherwise, copy this level's direction
414
      coord(j + 1).u = coord(j).u;
102,696,283✔
415
    }
416
  }
417

418
  // Score flux derivative accumulators for differential tallies.
419
  if (!model::active_tallies.empty())
2,147,483,647✔
420
    score_collision_derivative(*this);
622,607,822✔
421

422
#ifdef DAGMC
423
  history().reset();
228,981,357✔
424
#endif
425
}
2,147,483,647✔
426

427
void Particle::event_revive_from_secondary()
2,147,483,647✔
428
{
429
  // If particle has too many events, display warning and kill it
430
  ++n_event();
2,147,483,647✔
431
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
UNCOV
432
    warning("Particle " + std::to_string(id()) +
×
433
            " underwent maximum number of events.");
UNCOV
434
    wgt() = 0.0;
×
435
  }
436

437
  // Check for secondary particles if this particle is dead
438
  if (!alive()) {
2,147,483,647✔
439
    // Write final position for this particle
440
    if (write_track()) {
216,654,435✔
441
      write_particle_track(*this);
6,676✔
442
    }
443

444
    // If no secondary particles, break out of event loop
445
    if (secondary_bank().empty())
216,654,435✔
446
      return;
156,320,618✔
447

448
    from_source(&secondary_bank().back());
60,333,817✔
449
    secondary_bank().pop_back();
60,333,817✔
450
    n_event() = 0;
60,333,817✔
451
    bank_second_E() = 0.0;
60,333,817✔
452

453
    // Subtract secondary particle energy from interim pulse-height results
454
    if (!model::active_pulse_height_tallies.empty() &&
60,349,316✔
455
        this->type() == ParticleType::photon) {
15,499✔
456
      // Since the birth cell of the particle has not been set we
457
      // have to determine it before the energy of the secondary particle can be
458
      // removed from the pulse-height of this cell.
459
      if (lowest_coord().cell == C_NONE) {
605✔
460
        bool verbose = settings::verbosity >= 10 || trace();
605✔
461
        if (!exhaustive_find_cell(*this, verbose)) {
605✔
UNCOV
462
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
463
                       std::to_string(id()));
×
UNCOV
464
          return;
×
465
        }
466
        // Set birth cell attribute
467
        if (cell_born() == C_NONE)
605✔
468
          cell_born() = lowest_coord().cell;
605✔
469

470
        // Initialize last cells from current cell
471
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
472
          cell_last(j) = coord(j).cell;
605✔
473
        }
474
        n_coord_last() = n_coord();
605✔
475
      }
476
      pht_secondary_particles();
605✔
477
    }
478

479
    // Enter new particle in particle track file
480
    if (write_track())
60,333,817✔
481
      add_particle_track(*this);
5,606✔
482
  }
483
}
484

485
void Particle::event_death()
156,321,618✔
486
{
487
#ifdef DAGMC
488
  history().reset();
14,259,502✔
489
#endif
490

491
  // Finish particle track output.
492
  if (write_track()) {
156,321,618✔
493
    finalize_particle_track(*this);
1,070✔
494
  }
495

496
// Contribute tally reduction variables to global accumulator
497
#pragma omp atomic
85,676,871✔
498
  global_tally_absorption += keff_tally_absorption();
156,321,618✔
499
#pragma omp atomic
85,478,269✔
500
  global_tally_collision += keff_tally_collision();
156,321,618✔
501
#pragma omp atomic
85,482,768✔
502
  global_tally_tracklength += keff_tally_tracklength();
156,321,618✔
503
#pragma omp atomic
85,303,957✔
504
  global_tally_leakage += keff_tally_leakage();
156,321,618✔
505

506
  // Reset particle tallies once accumulated
507
  keff_tally_absorption() = 0.0;
156,321,618✔
508
  keff_tally_collision() = 0.0;
156,321,618✔
509
  keff_tally_tracklength() = 0.0;
156,321,618✔
510
  keff_tally_leakage() = 0.0;
156,321,618✔
511

512
  if (!model::active_pulse_height_tallies.empty()) {
156,321,618✔
513
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
514
  }
515

516
  // Record the number of progeny created by this particle.
517
  // This data will be used to efficiently sort the fission bank.
518
  if (settings::run_mode == RunMode::EIGENVALUE) {
156,321,618✔
519
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,407,800✔
520
    simulation::progeny_per_particle[offset] = n_progeny();
133,407,800✔
521
  }
522
}
156,321,618✔
523

524
void Particle::pht_collision_energy()
2,024✔
525
{
526
  // Adds the energy particles lose in a collision to the pulse-height
527

528
  // determine index of cell in pulse_height_cells
529
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
530
    model::pulse_height_cells.end(), lowest_coord().cell);
2,024✔
531

532
  if (it != model::pulse_height_cells.end()) {
2,024✔
533
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
534
    pht_storage()[index] += E_last() - E();
2,024✔
535

536
    // If the energy of the particle is below the cutoff, it will not be sampled
537
    // so its energy is added to the pulse-height in the cell
538
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
539
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
540
      pht_storage()[index] += E();
825✔
541
    }
542
  }
543
}
2,024✔
544

545
void Particle::pht_secondary_particles()
605✔
546
{
547
  // Removes the energy of secondary produced particles from the pulse-height
548

549
  // determine index of cell in pulse_height_cells
550
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
551
    model::pulse_height_cells.end(), cell_born());
605✔
552

553
  if (it != model::pulse_height_cells.end()) {
605✔
554
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
555
    pht_storage()[index] -= E();
605✔
556
  }
557
}
605✔
558

559
void Particle::cross_surface(const Surface& surf)
1,353,658,292✔
560
{
561

562
  if (settings::verbosity >= 10 || trace()) {
1,353,658,292✔
563
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
564
  }
565

566
// if we're crossing a CSG surface, make sure the DAG history is reset
567
#ifdef DAGMC
568
  if (surf.geom_type() == GeometryType::CSG)
122,907,026✔
569
    history().reset();
122,871,710✔
570
#endif
571

572
  // Handle any applicable boundary conditions.
573
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,353,658,292✔
574
    surf.bc_->handle_particle(*this, surf);
634,324,695✔
575
    return;
634,324,695✔
576
  }
577

578
  // ==========================================================================
579
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
580

581
#ifdef DAGMC
582
  // in DAGMC, we know what the next cell should be
583
  if (surf.geom_type() == GeometryType::DAG) {
65,563,964✔
584
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
585
                       lowest_coord().universe) -
28,265✔
586
                     1;
28,265✔
587
    // save material and temp
588
    material_last() = material();
28,265✔
589
    sqrtkT_last() = sqrtkT();
28,265✔
590
    // set new cell value
591
    lowest_coord().cell = i_cell;
28,265✔
592
    auto& cell = model::cells[i_cell];
28,265✔
593

594
    cell_instance() = 0;
28,265✔
595
    if (cell->distribcell_index_ >= 0)
28,265✔
596
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
597

598
    material() = cell->material(cell_instance());
28,265✔
599
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
600
    return;
28,265✔
601
  }
602
#endif
603

604
  bool verbose = settings::verbosity >= 10 || trace();
719,305,332✔
605
  if (neighbor_list_find_cell(*this, verbose)) {
719,305,332✔
606
    return;
719,277,313✔
607
  }
608

609
  // ==========================================================================
610
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
611

612
  // Remove lower coordinate levels
613
  n_coord() = 1;
28,019✔
614
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
615

616
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
28,019✔
617
    // If a cell is still not found, there are two possible causes: 1) there is
618
    // a void in the model, and 2) the particle hit a surface at a tangent. If
619
    // the particle is really traveling tangent to a surface, if we move it
620
    // forward a tiny bit it should fix the problem.
621

622
    surface() = SURFACE_NONE;
5,744✔
623
    n_coord() = 1;
5,744✔
624
    r() += TINY_BIT * u();
5,744✔
625

626
    // Couldn't find next cell anywhere! This probably means there is an actual
627
    // undefined region in the geometry.
628

629
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
630
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
631
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
632
                   " it could not be located in any cell and it did not leak.");
633
      return;
5,735✔
634
    }
635
  }
636
}
637

638
void Particle::cross_vacuum_bc(const Surface& surf)
30,466,642✔
639
{
640
  // Score any surface current tallies -- note that the particle is moved
641
  // forward slightly so that if the mesh boundary is on the surface, it is
642
  // still processed
643

644
  if (!model::active_meshsurf_tallies.empty()) {
30,466,642✔
645
    // TODO: Find a better solution to score surface currents than
646
    // physically moving the particle forward slightly
647

648
    r() += TINY_BIT * u();
1,021,265✔
649
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
650
  }
651

652
  // Score to global leakage tally
653
  keff_tally_leakage() += wgt();
30,466,642✔
654

655
  // Kill the particle
656
  wgt() = 0.0;
30,466,642✔
657

658
  // Display message
659
  if (settings::verbosity >= 10 || trace()) {
30,466,642✔
660
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
661
  }
662
}
30,466,642✔
663

664
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
604,219,091✔
665
{
666
  // Do not handle reflective boundary conditions on lower universes
667
  if (n_coord() != 1) {
604,219,091✔
UNCOV
668
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
669
                 " off surface in a lower universe.");
UNCOV
670
    return;
×
671
  }
672

673
  // Score surface currents since reflection causes the direction of the
674
  // particle to change. For surface filters, we need to score the tallies
675
  // twice, once before the particle's surface attribute has changed and
676
  // once after. For mesh surface filters, we need to artificially move
677
  // the particle slightly back in case the surface crossing is coincident
678
  // with a mesh boundary
679

680
  if (!model::active_surface_tallies.empty()) {
604,219,091✔
681
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
682
  }
683

684
  if (!model::active_meshsurf_tallies.empty()) {
604,219,091✔
685
    Position r {this->r()};
50,811,809✔
686
    this->r() -= TINY_BIT * u();
50,811,809✔
687
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
688
    this->r() = r;
50,811,809✔
689
  }
690

691
  // Set the new particle direction
692
  u() = new_u;
604,219,091✔
693

694
  // Reassign particle's cell and surface
695
  coord(0).cell = cell_last(0);
604,219,091✔
696
  surface() = -surface();
604,219,091✔
697

698
  // If a reflective surface is coincident with a lattice or universe
699
  // boundary, it is necessary to redetermine the particle's coordinates in
700
  // the lower universes.
701
  // (unless we're using a dagmc model, which has exactly one universe)
702
  n_coord() = 1;
604,219,091✔
703
  if (surf.geom_type() != GeometryType::DAG &&
1,208,435,643✔
704
      !neighbor_list_find_cell(*this)) {
604,216,552✔
UNCOV
705
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
706
                 std::to_string(surf.id_) + ".");
×
UNCOV
707
    return;
×
708
  }
709

710
  // Set previous coordinate going slightly past surface crossing
711
  r_last_current() = r() + TINY_BIT * u();
604,219,091✔
712

713
  // Diagnostic message
714
  if (settings::verbosity >= 10 || trace()) {
604,219,091✔
UNCOV
715
    write_message(1, "    Reflected from surface {}", surf.id_);
×
716
  }
717
}
718

719
void Particle::cross_periodic_bc(
666,318✔
720
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
721
{
722
  // Do not handle periodic boundary conditions on lower universes
723
  if (n_coord() != 1) {
666,318✔
724
    mark_as_lost(
×
UNCOV
725
      "Cannot transfer particle " + std::to_string(id()) +
×
726
      " across surface in a lower universe. Boundary conditions must be "
727
      "applied to root universe.");
UNCOV
728
    return;
×
729
  }
730

731
  // Score surface currents since reflection causes the direction of the
732
  // particle to change -- artificially move the particle slightly back in
733
  // case the surface crossing is coincident with a mesh boundary
734
  if (!model::active_meshsurf_tallies.empty()) {
666,318✔
UNCOV
735
    Position r {this->r()};
×
UNCOV
736
    this->r() -= TINY_BIT * u();
×
UNCOV
737
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
738
    this->r() = r;
×
739
  }
740

741
  // Adjust the particle's location and direction.
742
  r() = new_r;
666,318✔
743
  u() = new_u;
666,318✔
744

745
  // Reassign particle's surface
746
  surface() = new_surface;
666,318✔
747

748
  // Figure out what cell particle is in now
749
  n_coord() = 1;
666,318✔
750

751
  if (!neighbor_list_find_cell(*this)) {
666,318✔
UNCOV
752
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
753
                 "boundary on surface " +
×
UNCOV
754
                 std::to_string(surf.id_) +
×
755
                 ". The normal vector "
756
                 "of one periodic surface may need to be reversed.");
UNCOV
757
    return;
×
758
  }
759

760
  // Set previous coordinate going slightly past surface crossing
761
  r_last_current() = r() + TINY_BIT * u();
666,318✔
762

763
  // Diagnostic message
764
  if (settings::verbosity >= 10 || trace()) {
666,318✔
UNCOV
765
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
766
  }
767
}
768

769
void Particle::mark_as_lost(const char* message)
5,744✔
770
{
771
  // Print warning and write lost particle file
772
  warning(message);
5,744✔
773
  if (settings::max_write_lost_particles < 0 ||
5,744✔
774
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
775
    write_restart();
324✔
776
  }
777
  // Increment number of lost particles
778
  wgt() = 0.0;
5,744✔
779
#pragma omp atomic
3,124✔
780
  simulation::n_lost_particles += 1;
2,620✔
781

782
  // Count the total number of simulated particles (on this processor)
783
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
784
           simulation::work_per_rank;
785

786
  // Abort the simulation if the maximum number of lost particles has been
787
  // reached
788
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
789
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
790
    fatal_error("Maximum number of lost particles has been reached.");
9✔
791
  }
792
}
5,735✔
793

794
void Particle::write_restart() const
324✔
795
{
796
  // Dont write another restart file if in particle restart mode
797
  if (settings::run_mode == RunMode::PARTICLE)
324✔
798
    return;
22✔
799

800
  // Set up file name
801
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
802
    simulation::current_batch, id());
565✔
803

804
#pragma omp critical(WriteParticleRestart)
314✔
805
  {
806
    // Create file
807
    hid_t file_id = file_open(filename, 'w');
302✔
808

809
    // Write filetype and version info
810
    write_attribute(file_id, "filetype", "particle restart");
302✔
811
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
812
    write_attribute(file_id, "openmc_version", VERSION);
302✔
813
#ifdef GIT_SHA1
814
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
815
#endif
816

817
    // Write data to file
818
    write_dataset(file_id, "current_batch", simulation::current_batch);
302✔
819
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
302✔
820
    write_dataset(file_id, "current_generation", simulation::current_gen);
302✔
821
    write_dataset(file_id, "n_particles", settings::n_particles);
302✔
822
    switch (settings::run_mode) {
302✔
823
    case RunMode::FIXED_SOURCE:
225✔
824
      write_dataset(file_id, "run_mode", "fixed source");
225✔
825
      break;
225✔
826
    case RunMode::EIGENVALUE:
77✔
827
      write_dataset(file_id, "run_mode", "eigenvalue");
77✔
828
      break;
77✔
UNCOV
829
    case RunMode::PARTICLE:
×
UNCOV
830
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
831
      break;
×
UNCOV
832
    default:
×
UNCOV
833
      break;
×
834
    }
835
    write_dataset(file_id, "id", id());
302✔
836
    write_dataset(file_id, "type", static_cast<int>(type()));
302✔
837

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

861
    // Close file
862
    file_close(file_id);
302✔
863
  } // #pragma omp critical
864
}
302✔
865

866
void Particle::update_neutron_xs(
2,147,483,647✔
867
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
868
{
869
  // Get microscopic cross section cache
870
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
871

872
  // If the cache doesn't match, recalculate micro xs
873
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
874
      i_sab != micro.index_sab || sab_frac != micro.sab_frac) {
2,147,483,647✔
875
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
876

877
    // If NCrystal is being used, update micro cross section cache
878
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
879
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
880
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
881
    }
882
  }
883
}
2,147,483,647✔
884

885
//==============================================================================
886
// Non-method functions
887
//==============================================================================
888

889
std::string particle_type_to_str(ParticleType type)
3,130,237✔
890
{
891
  switch (type) {
3,130,237✔
892
  case ParticleType::neutron:
2,399,980✔
893
    return "neutron";
2,399,980✔
894
  case ParticleType::photon:
729,993✔
895
    return "photon";
729,993✔
896
  case ParticleType::electron:
132✔
897
    return "electron";
132✔
898
  case ParticleType::positron:
132✔
899
    return "positron";
132✔
900
  }
901
  UNREACHABLE();
×
902
}
903

904
ParticleType str_to_particle_type(std::string str)
2,976,101✔
905
{
906
  if (str == "neutron") {
2,976,101✔
907
    return ParticleType::neutron;
680,742✔
908
  } else if (str == "photon") {
2,295,359✔
909
    return ParticleType::photon;
2,295,273✔
910
  } else if (str == "electron") {
86✔
911
    return ParticleType::electron;
43✔
912
  } else if (str == "positron") {
43✔
913
    return ParticleType::positron;
43✔
914
  } else {
UNCOV
915
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
916
  }
917
}
918

919
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,351,771,606✔
920
{
921
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
922
      simulation::surf_source_bank.full()) {
1,061,423,619✔
923
    return;
1,351,664,841✔
924
  }
925

926
  // If a cell/cellfrom/cellto parameter is defined
927
  if (settings::ssw_cell_id != C_NONE) {
319,266✔
928

929
    // Retrieve cell index and storage type
930
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,705✔
931

932
    if (surf.bc_) {
258,705✔
933
      // Leave if cellto with vacuum boundary condition
934
      if (surf.bc_->type() == "vacuum" &&
184,448✔
935
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
936
        return;
11,953✔
937
      }
938

939
      // Leave if other boundary condition than vacuum
940
      if (surf.bc_->type() != "vacuum") {
140,281✔
941
        return;
120,020✔
942
      }
943
    }
944

945
    // Check if the cell of interest has been exited
946
    bool exited = false;
126,732✔
947
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,341✔
948
      if (p.cell_last(i) == cell_idx) {
208,609✔
949
        exited = true;
74,235✔
950
      }
951
    }
952

953
    // Check if the cell of interest has been entered
954
    bool entered = false;
126,732✔
955
    for (int i = 0; i < p.n_coord(); ++i) {
301,037✔
956
      if (p.coord(i).cell == cell_idx) {
174,305✔
957
        entered = true;
59,098✔
958
      }
959
    }
960

961
    // Vacuum boundary conditions: return if cell is not exited
962
    if (surf.bc_) {
126,732✔
963
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
964
        return;
13,961✔
965
      }
966
    } else {
967

968
      // If we both enter and exit the cell of interest
969
      if (entered && exited) {
106,471✔
970
        return;
28,613✔
971
      }
972

973
      // If we did not enter nor exit the cell of interest
974
      if (!entered && !exited) {
77,858✔
975
        return;
14,351✔
976
      }
977

978
      // If cellfrom and the cell before crossing is not the cell of
979
      // interest
980
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,507✔
981
        return;
11,565✔
982
      }
983

984
      // If cellto and the cell after crossing is not the cell of interest
985
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
986
        return;
12,038✔
987
      }
988
    }
989
  }
990

991
  SourceSite site;
106,765✔
992
  site.r = p.r();
106,765✔
993
  site.u = p.u();
106,765✔
994
  site.E = p.E();
106,765✔
995
  site.time = p.time();
106,765✔
996
  site.wgt = p.wgt();
106,765✔
997
  site.delayed_group = p.delayed_group();
106,765✔
998
  site.surf_id = surf.id_;
106,765✔
999
  site.particle = p.type();
106,765✔
1000
  site.parent_id = p.id();
106,765✔
1001
  site.progeny_id = p.n_progeny();
106,765✔
1002
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
106,765✔
1003
}
1004

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