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

openmc-dev / openmc / 17707962129

14 Sep 2025 07:15AM UTC coverage: 85.074% (-0.1%) from 85.218%
17707962129

Pull #3547

github

web-flow
Merge 07e1f2aef into afd9d0607
Pull Request #3547: Tally spectrum of secondary particles

23 of 58 new or added lines in 8 files covered. (39.66%)

31 existing lines in 2 files now uncovered.

52790 of 62052 relevant lines covered (85.07%)

38251650.85 hits per line

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

91.6
/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 OPENMC_DAGMC_ENABLED
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
namespace simulation {
42
thread_local Particle tmp_particle;
43
}
44

45
//==============================================================================
46
// Particle implementation
47
//==============================================================================
48

49
double Particle::speed() const
2,147,483,647✔
50
{
51
  if (settings::run_CE) {
2,147,483,647✔
52
    // Determine mass in eV/c^2
53
    double mass;
54
    switch (this->type()) {
1,845,778,428✔
55
    case ParticleType::neutron:
1,776,947,928✔
56
      mass = MASS_NEUTRON_EV;
1,776,947,928✔
57
      break;
1,776,947,928✔
58
    case ParticleType::photon:
17,442,209✔
59
      mass = 0.0;
17,442,209✔
60
      break;
17,442,209✔
61
    case ParticleType::electron:
51,388,291✔
62
    case ParticleType::positron:
63
      mass = MASS_ELECTRON_EV;
51,388,291✔
64
      break;
51,388,291✔
65
    }
66
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
67
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,845,778,428✔
68
           (this->E() + mass);
1,845,778,428✔
69
  } else {
70
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,062,680,774✔
71
    int macro_t = this->mg_xs_cache().t;
2,062,680,774✔
72
    int macro_a = macro_xs.get_angle_index(this->u());
2,062,680,774✔
73
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,062,680,774✔
74
                   nullptr, nullptr, macro_t, macro_a);
2,062,680,774✔
75
  }
76
}
77

78
bool Particle::create_secondary(
107,332,057✔
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,332,057✔
84
    return false;
51,338,201✔
85
  }
86

87
  auto& bank = secondary_bank().emplace_back();
55,993,856✔
88
  bank.particle = type;
55,993,856✔
89
  bank.wgt = wgt;
55,993,856✔
90
  bank.r = r();
55,993,856✔
91
  bank.u = u;
55,993,856✔
92
  bank.E = settings::run_CE ? E : g();
55,993,856✔
93
  bank.time = time();
55,993,856✔
94
  bank_second_E() += bank.E;
55,993,856✔
95

96
  // Score tallies affected by secondary particles
97
  if (!model::active_particleout_analog_tallies.empty()) {
55,993,856✔
98
    // Create secondary particle for tallying purposes only
NEW
99
    simulation::tmp_particle.from_source(&bank);
×
NEW
100
    simulation::tmp_particle.u_last() = this->u();
×
NEW
101
    simulation::tmp_particle.r_last() = this->r();
×
NEW
102
    simulation::tmp_particle.E_last() = this->E();
×
NEW
103
    simulation::tmp_particle.type_last() = this->type();
×
104

NEW
105
    if (settings::run_CE) {
×
NEW
106
      score_analog_tally_ce(
×
107
        simulation::tmp_particle, model::active_particleout_analog_tallies);
108
    } else {
NEW
109
      score_analog_tally_mg(
×
110
        simulation::tmp_particle, model::active_particleout_analog_tallies);
111
    }
112
  }
113
  return true;
55,993,856✔
114
}
115

116
void Particle::split(double wgt)
4,163,186✔
117
{
118
  auto& bank = secondary_bank().emplace_back();
4,163,186✔
119
  bank.particle = type();
4,163,186✔
120
  bank.wgt = wgt;
4,163,186✔
121
  bank.r = r();
4,163,186✔
122
  bank.u = u();
4,163,186✔
123
  bank.E = settings::run_CE ? E() : g();
4,163,186✔
124
  bank.time = time();
4,163,186✔
125

126
  // Convert signed index to a signed surface ID
127
  if (surface() == SURFACE_NONE) {
4,163,186✔
128
    bank.surf_id = SURFACE_NONE;
4,163,166✔
129
  } else {
130
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
131
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20✔
132
  }
133
}
4,163,186✔
134

135
void Particle::from_source(const SourceSite* src)
223,879,606✔
136
{
137
  // Reset some attributes
138
  clear();
223,879,606✔
139
  surface() = SURFACE_NONE;
223,879,606✔
140
  cell_born() = C_NONE;
223,879,606✔
141
  material() = C_NONE;
223,879,606✔
142
  n_collision() = 0;
223,879,606✔
143
  fission() = false;
223,879,606✔
144
  zero_flux_derivs();
223,879,606✔
145
  lifetime() = 0.0;
223,879,606✔
146

147
  // Copy attributes from source bank site
148
  type() = src->particle;
223,879,606✔
149
  type_last() = src->particle;
223,879,606✔
150
  wgt() = src->wgt;
223,879,606✔
151
  wgt_last() = src->wgt;
223,879,606✔
152
  r() = src->r;
223,879,606✔
153
  u() = src->u;
223,879,606✔
154
  r_born() = src->r;
223,879,606✔
155
  r_last_current() = src->r;
223,879,606✔
156
  r_last() = src->r;
223,879,606✔
157
  u_last() = src->u;
223,879,606✔
158
  if (settings::run_CE) {
223,879,606✔
159
    E() = src->E;
108,248,789✔
160
    g() = 0;
108,248,789✔
161
  } else {
162
    g() = static_cast<int>(src->E);
115,630,817✔
163
    g_last() = static_cast<int>(src->E);
115,630,817✔
164
    E() = data::mg.energy_bin_avg_[g()];
115,630,817✔
165
  }
166
  E_last() = E();
223,879,606✔
167
  time() = src->time;
223,879,606✔
168
  time_last() = src->time;
223,879,606✔
169
  parent_nuclide() = src->parent_nuclide;
223,879,606✔
170

171
  // Convert signed surface ID to signed index
172
  if (src->surf_id != SURFACE_NONE) {
223,879,606✔
173
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
174
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020✔
175
  }
176
}
223,879,606✔
177

178
void Particle::event_calculate_xs()
2,147,483,647✔
179
{
180
  // Set the random number stream
181
  stream() = STREAM_TRACKING;
2,147,483,647✔
182

183
  // Store pre-collision particle properties
184
  wgt_last() = wgt();
2,147,483,647✔
185
  E_last() = E();
2,147,483,647✔
186
  type_last() = type();
2,147,483,647✔
187
  u_last() = u();
2,147,483,647✔
188
  r_last() = r();
2,147,483,647✔
189
  time_last() = time();
2,147,483,647✔
190

191
  // Reset event variables
192
  event() = TallyEvent::KILL;
2,147,483,647✔
193
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
194
  event_mt() = REACTION_NONE;
2,147,483,647✔
195

196
  // If the cell hasn't been determined based on the particle's location,
197
  // initiate a search for the current cell. This generally happens at the
198
  // beginning of the history and again for any secondary particles
199
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
200
    if (!exhaustive_find_cell(*this)) {
220,689,599✔
201
      mark_as_lost(
×
202
        "Could not find the cell containing particle " + std::to_string(id()));
×
203
      return;
×
204
    }
205

206
    // Set birth cell attribute
207
    if (cell_born() == C_NONE)
220,689,599✔
208
      cell_born() = lowest_coord().cell();
220,689,599✔
209

210
    // Initialize last cells from current cell
211
    for (int j = 0; j < n_coord(); ++j) {
457,936,960✔
212
      cell_last(j) = coord(j).cell();
237,247,361✔
213
    }
214
    n_coord_last() = n_coord();
220,689,599✔
215
  }
216

217
  // Write particle track.
218
  if (write_track())
2,147,483,647✔
219
    write_particle_track(*this);
10,836✔
220

221
  if (settings::check_overlaps)
2,147,483,647✔
222
    check_cell_overlap(*this);
×
223

224
  // Calculate microscopic and macroscopic cross sections
225
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
226
    if (settings::run_CE) {
2,147,483,647✔
227
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,751,406,231✔
228
        // If the material is the same as the last material and the
229
        // temperature hasn't changed, we don't need to lookup cross
230
        // sections again.
231
        model::materials[material()]->calculate_xs(*this);
1,398,651,433✔
232
      }
233
    } else {
234
      // Get the MG data; unlike the CE case above, we have to re-calculate
235
      // cross sections for every collision since the cross sections may
236
      // be angle-dependent
237
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,680,774✔
238

239
      // Update the particle's group while we know we are multi-group
240
      g_last() = g();
2,062,680,774✔
241
    }
242
  } else {
243
    macro_xs().total = 0.0;
67,289,240✔
244
    macro_xs().absorption = 0.0;
67,289,240✔
245
    macro_xs().fission = 0.0;
67,289,240✔
246
    macro_xs().nu_fission = 0.0;
67,289,240✔
247
  }
248
}
249

250
void Particle::event_advance()
2,147,483,647✔
251
{
252
  // Find the distance to the nearest boundary
253
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
254

255
  // Sample a distance to collision
256
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
257
    collision_distance() = 0.0;
51,388,291✔
258
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
259
    collision_distance() = INFINITY;
67,289,240✔
260
  } else {
261
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
262
  }
263

264
  double speed = this->speed();
2,147,483,647✔
265
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
266
  double distance_cutoff =
267
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
268

269
  // Select smaller of the three distances
270
  double distance =
271
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
272

273
  // Advance particle in space and time
274
  this->move_distance(distance);
2,147,483,647✔
275
  double dt = distance / speed;
2,147,483,647✔
276
  this->time() += dt;
2,147,483,647✔
277
  this->lifetime() += dt;
2,147,483,647✔
278

279
  // Score timed track-length tallies
280
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
281
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
282
  }
283

284
  // Score track-length tallies
285
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
286
    score_tracklength_tally(*this, distance);
1,340,254,250✔
287
  }
288

289
  // Score track-length estimate of k-eff
290
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
291
      type() == ParticleType::neutron) {
2,147,483,647✔
292
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
293
  }
294

295
  // Score flux derivative accumulators for differential tallies.
296
  if (!model::active_tallies.empty()) {
2,147,483,647✔
297
    score_track_derivative(*this, distance);
1,507,054,635✔
298
  }
299

300
  // Set particle weight to zero if it hit the time boundary
301
  if (distance == distance_cutoff) {
2,147,483,647✔
302
    wgt() = 0.0;
224,928✔
303
  }
304
}
2,147,483,647✔
305

306
void Particle::event_cross_surface()
2,106,805,836✔
307
{
308
  // Saving previous cell data
309
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
310
    cell_last(j) = coord(j).cell();
2,147,483,647✔
311
  }
312
  n_coord_last() = n_coord();
2,106,805,836✔
313

314
  // Set surface that particle is on and adjust coordinate levels
315
  surface() = boundary().surface();
2,106,805,836✔
316
  n_coord() = boundary().coord_level();
2,106,805,836✔
317

318
  if (boundary().lattice_translation()[0] != 0 ||
2,106,805,836✔
319
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
320
      boundary().lattice_translation()[2] != 0) {
1,613,259,536✔
321
    // Particle crosses lattice boundary
322

323
    bool verbose = settings::verbosity >= 10 || trace();
679,930,013✔
324
    cross_lattice(*this, boundary(), verbose);
679,930,013✔
325
    event() = TallyEvent::LATTICE;
679,930,013✔
326
  } else {
327
    // Particle crosses surface
328
    const auto& surf {model::surfaces[surface_index()].get()};
1,426,875,823✔
329
    // If BC, add particle to surface source before crossing surface
330
    if (surf->surf_source_ && surf->bc_) {
1,426,875,823✔
331
      add_surf_source_to_bank(*this, *surf);
658,622,547✔
332
    }
333
    this->cross_surface(*surf);
1,426,875,823✔
334
    // If no BC, add particle to surface source after crossing surface
335
    if (surf->surf_source_ && !surf->bc_) {
1,426,875,814✔
336
      add_surf_source_to_bank(*this, *surf);
767,019,858✔
337
    }
338
    if (settings::weight_window_checkpoint_surface) {
1,426,875,814✔
339
      apply_weight_windows(*this);
396✔
340
    }
341
    event() = TallyEvent::SURFACE;
1,426,875,814✔
342
  }
343
  // Score cell to cell partial currents
344
  if (!model::active_surface_tallies.empty()) {
2,106,805,827✔
345
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
346
  }
347
}
2,106,805,827✔
348

349
void Particle::event_collide()
2,147,483,647✔
350
{
351
  // Score collision estimate of keff
352
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
353
      type() == ParticleType::neutron) {
2,147,483,647✔
354
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,115,810,760✔
355
  }
356

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

361
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
362
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
363

364
  // Clear surface component
365
  surface() = SURFACE_NONE;
2,147,483,647✔
366

367
  if (settings::run_CE) {
2,147,483,647✔
368
    collision(*this);
757,532,152✔
369
  } else {
370
    collision_mg(*this);
1,781,763,302✔
371
  }
372

373
  // Score collision estimator tallies -- this is done after a collision
374
  // has occurred rather than before because we need information on the
375
  // outgoing energy for any tallies with an outgoing energy filter
376
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
377
    score_collision_tally(*this);
101,724,566✔
378
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
379
    if (settings::run_CE) {
113,518,064✔
380
      score_analog_tally_ce(*this, model::active_analog_tallies);
112,316,853✔
381
    } else {
382
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,201,211✔
383
    }
384
  }
385

386
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
387
      type() == ParticleType::photon) {
16,918✔
388
    pht_collision_energy();
2,024✔
389
  }
390

391
  // Reset banked weight during collision
392
  n_bank() = 0;
2,147,483,647✔
393
  bank_second_E() = 0.0;
2,147,483,647✔
394
  wgt_bank() = 0.0;
2,147,483,647✔
395
  zero_delayed_bank();
2,147,483,647✔
396

397
  // Reset fission logical
398
  fission() = false;
2,147,483,647✔
399

400
  // Save coordinates for tallying purposes
401
  r_last_current() = r();
2,147,483,647✔
402

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

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

421
  // Score flux derivative accumulators for differential tallies.
422
  if (!model::active_tallies.empty())
2,147,483,647✔
423
    score_collision_derivative(*this);
653,223,349✔
424

425
#ifdef OPENMC_DAGMC_ENABLED
426
  history().reset();
230,273,451✔
427
#endif
428
}
2,147,483,647✔
429

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

440
  // Check for secondary particles if this particle is dead
441
  if (!alive()) {
2,147,483,647✔
442
    // Write final position for this particle
443
    if (write_track()) {
220,689,195✔
444
      write_particle_track(*this);
6,674✔
445
    }
446

447
    // If no secondary particles, break out of event loop
448
    if (secondary_bank().empty())
220,689,195✔
449
      return;
160,193,398✔
450

451
    from_source(&secondary_bank().back());
60,495,797✔
452
    secondary_bank().pop_back();
60,495,797✔
453
    n_event() = 0;
60,495,797✔
454
    bank_second_E() = 0.0;
60,495,797✔
455

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

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

482
    // Enter new particle in particle track file
483
    if (write_track())
60,495,797✔
484
      add_particle_track(*this);
5,604✔
485
  }
486
}
487

488
void Particle::event_death()
160,194,398✔
489
{
490
#ifdef OPENMC_DAGMC_ENABLED
491
  history().reset();
14,550,682✔
492
#endif
493

494
  // Finish particle track output.
495
  if (write_track()) {
160,194,398✔
496
    finalize_particle_track(*this);
1,070✔
497
  }
498

499
// Contribute tally reduction variables to global accumulator
500
#pragma omp atomic
88,874,259✔
501
  global_tally_absorption += keff_tally_absorption();
160,194,398✔
502
#pragma omp atomic
89,121,687✔
503
  global_tally_collision += keff_tally_collision();
160,194,398✔
504
#pragma omp atomic
88,307,423✔
505
  global_tally_tracklength += keff_tally_tracklength();
160,194,398✔
506
#pragma omp atomic
88,176,742✔
507
  global_tally_leakage += keff_tally_leakage();
160,194,398✔
508

509
  // Reset particle tallies once accumulated
510
  keff_tally_absorption() = 0.0;
160,194,398✔
511
  keff_tally_collision() = 0.0;
160,194,398✔
512
  keff_tally_tracklength() = 0.0;
160,194,398✔
513
  keff_tally_leakage() = 0.0;
160,194,398✔
514

515
  if (!model::active_pulse_height_tallies.empty()) {
160,194,398✔
516
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
517
  }
518

519
  // Record the number of progeny created by this particle.
520
  // This data will be used to efficiently sort the fission bank.
521
  if (settings::run_mode == RunMode::EIGENVALUE) {
160,194,398✔
522
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
134,566,600✔
523
    simulation::progeny_per_particle[offset] = n_progeny();
134,566,600✔
524
  }
525
}
160,194,398✔
526

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

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

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

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

548
void Particle::pht_secondary_particles()
605✔
549
{
550
  // Removes the energy of secondary produced particles from the pulse-height
551

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

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

562
void Particle::cross_surface(const Surface& surf)
1,428,215,057✔
563
{
564

565
  if (settings::verbosity >= 10 || trace()) {
1,428,215,057✔
566
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
567
  }
568

569
// if we're crossing a CSG surface, make sure the DAG history is reset
570
#ifdef OPENMC_DAGMC_ENABLED
571
  if (surf.geom_type() == GeometryType::CSG)
123,388,601✔
572
    history().reset();
123,344,553✔
573
#endif
574

575
  // Handle any applicable boundary conditions.
576
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,087,326,973✔
577
      settings::run_mode != RunMode::VOLUME) {
659,111,916✔
578
    surf.bc_->handle_particle(*this, surf);
658,970,164✔
579
    return;
658,970,164✔
580
  }
581

582
  // ==========================================================================
583
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
584

585
#ifdef OPENMC_DAGMC_ENABLED
586
  // in DAGMC, we know what the next cell should be
587
  if (surf.geom_type() == GeometryType::DAG) {
65,661,279✔
588
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
36,997✔
589
                       lowest_coord().universe()) -
36,997✔
590
                     1;
36,997✔
591
    // save material and temp
592
    material_last() = material();
36,997✔
593
    sqrtkT_last() = sqrtkT();
36,997✔
594
    // set new cell value
595
    lowest_coord().cell() = i_cell;
36,997✔
596
    auto& cell = model::cells[i_cell];
36,997✔
597

598
    cell_instance() = 0;
36,997✔
599
    if (cell->distribcell_index_ >= 0)
36,997✔
600
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
601

602
    material() = cell->material(cell_instance());
36,997✔
603
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
604
    return;
36,997✔
605
  }
606
#endif
607

608
  bool verbose = settings::verbosity >= 10 || trace();
769,207,896✔
609
  if (neighbor_list_find_cell(*this, verbose)) {
769,207,896✔
610
    return;
769,179,877✔
611
  }
612

613
  // ==========================================================================
614
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
615

616
  // Remove lower coordinate levels
617
  n_coord() = 1;
28,019✔
618
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
619

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

626
    surface() = SURFACE_NONE;
5,744✔
627
    n_coord() = 1;
5,744✔
628
    r() += TINY_BIT * u();
5,744✔
629

630
    // Couldn't find next cell anywhere! This probably means there is an actual
631
    // undefined region in the geometry.
632

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

642
void Particle::cross_vacuum_bc(const Surface& surf)
33,203,992✔
643
{
644
  // Score any surface current tallies -- note that the particle is moved
645
  // forward slightly so that if the mesh boundary is on the surface, it is
646
  // still processed
647

648
  if (!model::active_meshsurf_tallies.empty()) {
33,203,992✔
649
    // TODO: Find a better solution to score surface currents than
650
    // physically moving the particle forward slightly
651

652
    r() += TINY_BIT * u();
1,021,265✔
653
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
654
  }
655

656
  // Score to global leakage tally
657
  keff_tally_leakage() += wgt();
33,203,992✔
658

659
  // Kill the particle
660
  wgt() = 0.0;
33,203,992✔
661

662
  // Display message
663
  if (settings::verbosity >= 10 || trace()) {
33,203,992✔
664
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
665
  }
666
}
33,203,992✔
667

668
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
626,127,210✔
669
{
670
  // Do not handle reflective boundary conditions on lower universes
671
  if (n_coord() != 1) {
626,127,210✔
672
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
673
                 " off surface in a lower universe.");
674
    return;
×
675
  }
676

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

684
  if (!model::active_surface_tallies.empty()) {
626,127,210✔
685
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
686
  }
687

688
  if (!model::active_meshsurf_tallies.empty()) {
626,127,210✔
689
    Position r {this->r()};
50,811,809✔
690
    this->r() -= TINY_BIT * u();
50,811,809✔
691
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
692
    this->r() = r;
50,811,809✔
693
  }
694

695
  // Set the new particle direction
696
  u() = new_u;
626,127,210✔
697

698
  // Reassign particle's cell and surface
699
  coord(0).cell() = cell_last(0);
626,127,210✔
700
  surface() = -surface();
626,127,210✔
701

702
  // If a reflective surface is coincident with a lattice or universe
703
  // boundary, it is necessary to redetermine the particle's coordinates in
704
  // the lower universes.
705
  // (unless we're using a dagmc model, which has exactly one universe)
706
  n_coord() = 1;
626,127,210✔
707
  if (surf.geom_type() != GeometryType::DAG &&
1,252,251,881✔
708
      !neighbor_list_find_cell(*this)) {
626,124,671✔
709
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
710
                 std::to_string(surf.id_) + ".");
×
711
    return;
×
712
  }
713

714
  // Set previous coordinate going slightly past surface crossing
715
  r_last_current() = r() + TINY_BIT * u();
626,127,210✔
716

717
  // Diagnostic message
718
  if (settings::verbosity >= 10 || trace()) {
626,127,210✔
719
    write_message(1, "    Reflected from surface {}", surf.id_);
×
720
  }
721
}
722

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

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

745
  // Adjust the particle's location and direction.
746
  r() = new_r;
666,318✔
747
  u() = new_u;
666,318✔
748

749
  // Reassign particle's surface
750
  surface() = new_surface;
666,318✔
751

752
  // Figure out what cell particle is in now
753
  n_coord() = 1;
666,318✔
754

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

764
  // Set previous coordinate going slightly past surface crossing
765
  r_last_current() = r() + TINY_BIT * u();
666,318✔
766

767
  // Diagnostic message
768
  if (settings::verbosity >= 10 || trace()) {
666,318✔
769
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
770
  }
771
}
772

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

786
  // Count the total number of simulated particles (on this processor)
787
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
788
           simulation::work_per_rank;
789

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

798
void Particle::write_restart() const
324✔
799
{
800
  // Dont write another restart file if in particle restart mode
801
  if (settings::run_mode == RunMode::PARTICLE)
324✔
802
    return;
22✔
803

804
  // Set up file name
805
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
806
    simulation::current_batch, id());
565✔
807

808
#pragma omp critical(WriteParticleRestart)
314✔
809
  {
810
    // Create file
811
    hid_t file_id = file_open(filename, 'w');
302✔
812

813
    // Write filetype and version info
814
    write_attribute(file_id, "filetype", "particle restart");
302✔
815
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
816
    write_attribute(file_id, "openmc_version", VERSION);
302✔
817
#ifdef GIT_SHA1
818
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
819
#endif
820

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

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

865
    // Close file
866
    file_close(file_id);
302✔
867
  } // #pragma omp critical
868
}
302✔
869

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

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

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

889
//==============================================================================
890
// Non-method functions
891
//==============================================================================
892

893
std::string particle_type_to_str(ParticleType type)
3,258,770✔
894
{
895
  switch (type) {
3,258,770✔
896
  case ParticleType::neutron:
2,464,228✔
897
    return "neutron";
2,464,228✔
898
  case ParticleType::photon:
794,278✔
899
    return "photon";
794,278✔
900
  case ParticleType::electron:
132✔
901
    return "electron";
132✔
902
  case ParticleType::positron:
132✔
903
    return "positron";
132✔
904
  }
905
  UNREACHABLE();
×
906
}
907

908
ParticleType str_to_particle_type(std::string str)
3,313,645✔
909
{
910
  if (str == "neutron") {
3,313,645✔
911
    return ParticleType::neutron;
763,438✔
912
  } else if (str == "photon") {
2,550,207✔
913
    return ParticleType::photon;
2,550,121✔
914
  } else if (str == "electron") {
86✔
915
    return ParticleType::electron;
43✔
916
  } else if (str == "positron") {
43✔
917
    return ParticleType::positron;
43✔
918
  } else {
919
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
920
  }
921
}
922

923
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,425,642,405✔
924
{
925
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
926
      simulation::surf_source_bank.full()) {
1,127,544,731✔
927
    return;
1,425,513,640✔
928
  }
929

930
  // If a cell/cellfrom/cellto parameter is defined
931
  if (settings::ssw_cell_id != C_NONE) {
341,267✔
932

933
    // Retrieve cell index and storage type
934
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
935

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

943
      // Leave if other boundary condition than vacuum
944
      if (surf.bc_->type() != "vacuum") {
140,281✔
945
        return;
120,020✔
946
      }
947
    }
948

949
    // Check if the cell of interest has been exited
950
    bool exited = false;
126,733✔
951
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,343✔
952
      if (p.cell_last(i) == cell_idx) {
208,610✔
953
        exited = true;
74,235✔
954
      }
955
    }
956

957
    // Check if the cell of interest has been entered
958
    bool entered = false;
126,733✔
959
    for (int i = 0; i < p.n_coord(); ++i) {
301,039✔
960
      if (p.coord(i).cell() == cell_idx) {
174,306✔
961
        entered = true;
59,099✔
962
      }
963
    }
964

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

972
      // If we both enter and exit the cell of interest
973
      if (entered && exited) {
106,472✔
974
        return;
28,613✔
975
      }
976

977
      // If we did not enter nor exit the cell of interest
978
      if (!entered && !exited) {
77,859✔
979
        return;
14,351✔
980
      }
981

982
      // If cellfrom and the cell before crossing is not the cell of
983
      // interest
984
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,508✔
985
        return;
11,566✔
986
      }
987

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

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

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

© 2025 Coveralls, Inc