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

openmc-dev / openmc / 17238478448

26 Aug 2025 12:42PM UTC coverage: 85.166% (-0.04%) from 85.204%
17238478448

Pull #3547

github

web-flow
Merge fd4740196 into d1df80a21
Pull Request #3547: Tally spectrum of secondary particles

31 of 61 new or added lines in 11 files covered. (50.82%)

1 existing line in 1 file now uncovered.

52956 of 62180 relevant lines covered (85.17%)

37781310.49 hits per line

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

92.49
/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
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

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

74
bool Particle::create_secondary(
107,392,843✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
107,392,843✔
80
    return false;
51,368,017✔
81
  }
82

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

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

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,082,163✔
106
    bank.surf_id = SURFACE_NONE;
4,082,143✔
107
  } else {
108
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
109
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20✔
110
  }
111
}
4,082,163✔
112

113
void Particle::from_source(const SourceSite* src, ParticleType particle)
220,349,043✔
114
{
115
  // Reset some attributes
116
  clear();
220,349,043✔
117
  surface() = SURFACE_NONE;
220,349,043✔
118
  cell_born() = C_NONE;
220,349,043✔
119
  material() = C_NONE;
220,349,043✔
120
  n_collision() = 0;
220,349,043✔
121
  fission() = false;
220,349,043✔
122
  zero_flux_derivs();
220,349,043✔
123
  lifetime() = 0.0;
220,349,043✔
124

125
  // Copy attributes from source bank site
126
  type() = src->particle;
220,349,043✔
127
  wgt() = src->wgt;
220,349,043✔
128
  wgt_last() = src->wgt;
220,349,043✔
129
  r() = src->r;
220,349,043✔
130
  u() = src->u;
220,349,043✔
131
  r_born() = src->r;
220,349,043✔
132
  r_last_current() = src->r;
220,349,043✔
133
  r_last() = src->r;
220,349,043✔
134
  u_last() = src->u;
220,349,043✔
135
  if (settings::run_CE) {
220,349,043✔
136
    E() = src->E;
104,718,226✔
137
    g() = 0;
104,718,226✔
138
  } else {
139
    g() = static_cast<int>(src->E);
115,630,817✔
140
    g_last() = static_cast<int>(src->E);
115,630,817✔
141
    E() = data::mg.energy_bin_avg_[g()];
115,630,817✔
142
  }
143
  E_last() = E();
220,349,043✔
144
  type_last() = particle;
220,349,043✔
145
  time() = src->time;
220,349,043✔
146
  time_last() = src->time;
220,349,043✔
147
  parent_nuclide() = src->parent_nuclide;
220,349,043✔
148

149
  // Convert signed surface ID to signed index
150
  if (src->surf_id != SURFACE_NONE) {
220,349,043✔
151
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
152
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020✔
153
  }
154
}
220,349,043✔
155

156
void Particle::event_calculate_xs()
2,147,483,647✔
157
{
158
  // Set the random number stream
159
  stream() = STREAM_TRACKING;
2,147,483,647✔
160

161
  // Store pre-collision particle properties
162
  wgt_last() = wgt();
2,147,483,647✔
163
  E_last() = E();
2,147,483,647✔
164
  type_last() = type();
2,147,483,647✔
165
  u_last() = u();
2,147,483,647✔
166
  r_last() = r();
2,147,483,647✔
167
  time_last() = time();
2,147,483,647✔
168

169
  // Reset event variables
170
  event() = TallyEvent::KILL;
2,147,483,647✔
171
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
172
  event_mt() = REACTION_NONE;
2,147,483,647✔
173

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

184
    // Set birth cell attribute
185
    if (cell_born() == C_NONE)
217,473,946✔
186
      cell_born() = lowest_coord().cell();
217,473,946✔
187

188
    // Initialize last cells from current cell
189
    for (int j = 0; j < n_coord(); ++j) {
450,857,973✔
190
      cell_last(j) = coord(j).cell();
233,384,027✔
191
    }
192
    n_coord_last() = n_coord();
217,473,946✔
193
  }
194

195
  // Write particle track.
196
  if (write_track())
2,147,483,647✔
197
    write_particle_track(*this);
10,836✔
198

199
  if (settings::check_overlaps)
2,147,483,647✔
200
    check_cell_overlap(*this);
×
201

202
  // Calculate microscopic and macroscopic cross sections
203
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
204
    if (settings::run_CE) {
2,147,483,647✔
205
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,639,356,479✔
206
        // If the material is the same as the last material and the
207
        // temperature hasn't changed, we don't need to lookup cross
208
        // sections again.
209
        model::materials[material()]->calculate_xs(*this);
1,310,832,167✔
210
      }
211
    } else {
212
      // Get the MG data; unlike the CE case above, we have to re-calculate
213
      // cross sections for every collision since the cross sections may
214
      // be angle-dependent
215
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,680,774✔
216

217
      // Update the particle's group while we know we are multi-group
218
      g_last() = g();
2,062,680,774✔
219
    }
220
  } else {
221
    macro_xs().total = 0.0;
67,283,582✔
222
    macro_xs().absorption = 0.0;
67,283,582✔
223
    macro_xs().fission = 0.0;
67,283,582✔
224
    macro_xs().nu_fission = 0.0;
67,283,582✔
225
  }
226
}
227

228
void Particle::event_advance()
2,147,483,647✔
229
{
230
  // Find the distance to the nearest boundary
231
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
232

233
  // Sample a distance to collision
234
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
235
    collision_distance() = 0.0;
51,417,819✔
236
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
237
    collision_distance() = INFINITY;
67,283,582✔
238
  } else {
239
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
240
  }
241

242
  double speed = this->speed();
2,147,483,647✔
243
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
244
  double distance_cutoff =
245
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
246

247
  // Select smaller of the three distances
248
  double distance =
249
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
250

251
  // Advance particle in space and time
252
  this->move_distance(distance);
2,147,483,647✔
253
  double dt = distance / speed;
2,147,483,647✔
254
  this->time() += dt;
2,147,483,647✔
255
  this->lifetime() += dt;
2,147,483,647✔
256

257
  // Score track-length tallies
258
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
259
    score_tracklength_tally(*this, distance);
1,242,765,649✔
260
  }
261

262
  // Score track-length estimate of k-eff
263
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
264
      type() == ParticleType::neutron) {
2,147,483,647✔
265
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
266
  }
267

268
  // Score flux derivative accumulators for differential tallies.
269
  if (!model::active_tallies.empty()) {
2,147,483,647✔
270
    score_track_derivative(*this, distance);
1,405,937,717✔
271
  }
272

273
  // Set particle weight to zero if it hit the time boundary
274
  if (distance == distance_cutoff) {
2,147,483,647✔
275
    wgt() = 0.0;
11,000✔
276
  }
277
}
2,147,483,647✔
278

279
void Particle::event_cross_surface()
2,029,660,939✔
280
{
281
  // Saving previous cell data
282
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
283
    cell_last(j) = coord(j).cell();
2,147,483,647✔
284
  }
285
  n_coord_last() = n_coord();
2,029,660,939✔
286

287
  // Set surface that particle is on and adjust coordinate levels
288
  surface() = boundary().surface();
2,029,660,939✔
289
  n_coord() = boundary().coord_level();
2,029,660,939✔
290

291
  if (boundary().lattice_translation()[0] != 0 ||
2,029,660,939✔
292
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
293
      boundary().lattice_translation()[2] != 0) {
1,536,509,978✔
294
    // Particle crosses lattice boundary
295

296
    bool verbose = settings::verbosity >= 10 || trace();
679,533,097✔
297
    cross_lattice(*this, boundary(), verbose);
679,533,097✔
298
    event() = TallyEvent::LATTICE;
679,533,097✔
299
  } else {
300
    // Particle crosses surface
301
    const auto& surf {model::surfaces[surface_index()].get()};
1,350,127,842✔
302
    // If BC, add particle to surface source before crossing surface
303
    if (surf->surf_source_ && surf->bc_) {
1,350,127,842✔
304
      add_surf_source_to_bank(*this, *surf);
632,592,861✔
305
    }
306
    this->cross_surface(*surf);
1,350,127,842✔
307
    // If no BC, add particle to surface source after crossing surface
308
    if (surf->surf_source_ && !surf->bc_) {
1,350,127,833✔
309
      add_surf_source_to_bank(*this, *surf);
716,301,563✔
310
    }
311
    if (settings::weight_window_checkpoint_surface) {
1,350,127,833✔
312
      apply_weight_windows(*this);
396✔
313
    }
314
    event() = TallyEvent::SURFACE;
1,350,127,833✔
315
  }
316
  // Score cell to cell partial currents
317
  if (!model::active_surface_tallies.empty()) {
2,029,660,930✔
318
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
319
  }
320
}
2,029,660,930✔
321

322
void Particle::event_collide()
2,147,483,647✔
323
{
324
  // Score collision estimate of keff
325
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
326
      type() == ParticleType::neutron) {
2,135,520,932✔
327
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,096,198,748✔
328
  }
329

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

334
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
335
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
336

337
  // Clear surface component
338
  surface() = SURFACE_NONE;
2,147,483,647✔
339

340
  if (settings::run_CE) {
2,147,483,647✔
341
    collision(*this);
722,835,567✔
342
  } else {
343
    collision_mg(*this);
1,781,763,302✔
344
  }
345

346
  // Score collision estimator tallies -- this is done after a collision
347
  // has occurred rather than before because we need information on the
348
  // outgoing energy for any tallies with an outgoing energy filter
349
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
350
    score_collision_tally(*this);
97,813,123✔
351
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
352
    if (settings::run_CE) {
113,518,064✔
353
      score_analog_tally_ce(*this, model::active_analog_tallies);
112,316,853✔
354
    } else {
355
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,201,211✔
356
    }
357
  }
358

359
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
360
      type() == ParticleType::photon) {
16,918✔
361
    pht_collision_energy();
2,024✔
362
  }
363

364
  // Reset banked weight during collision
365
  n_bank() = 0;
2,147,483,647✔
366
  bank_second_E() = 0.0;
2,147,483,647✔
367
  wgt_bank() = 0.0;
2,147,483,647✔
368
  zero_delayed_bank();
2,147,483,647✔
369

370
  // Reset fission logical
371
  fission() = false;
2,147,483,647✔
372

373
  // Save coordinates for tallying purposes
374
  r_last_current() = r();
2,147,483,647✔
375

376
  // Set last material to none since cross sections will need to be
377
  // re-evaluated
378
  material_last() = C_NONE;
2,147,483,647✔
379

380
  // Set all directions to base level -- right now, after a collision, only
381
  // the base level directions are changed
382
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
383
    if (coord(j + 1).rotated()) {
112,484,242✔
384
      // If next level is rotated, apply rotation matrix
385
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,394,285✔
386
      const auto& u {coord(j).u()};
10,394,285✔
387
      coord(j + 1).u() = u.rotate(m);
10,394,285✔
388
    } else {
389
      // Otherwise, copy this level's direction
390
      coord(j + 1).u() = coord(j).u();
102,089,957✔
391
    }
392
  }
393

394
  // Score flux derivative accumulators for differential tallies.
395
  if (!model::active_tallies.empty())
2,147,483,647✔
396
    score_collision_derivative(*this);
620,618,303✔
397

398
#ifdef OPENMC_DAGMC_ENABLED
399
  history().reset();
229,213,804✔
400
#endif
401
}
2,147,483,647✔
402

403
void Particle::event_revive_from_secondary()
2,147,483,647✔
404
{
405
  // If particle has too many events, display warning and kill it
406
  ++n_event();
2,147,483,647✔
407
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
408
    warning("Particle " + std::to_string(id()) +
×
409
            " underwent maximum number of events.");
410
    wgt() = 0.0;
×
411
  }
412

413
  auto type = this->type();
2,147,483,647✔
414

415
  // Check for secondary particles if this particle is dead
416
  if (!alive()) {
2,147,483,647✔
417
    // Write final position for this particle
418
    if (write_track()) {
217,473,542✔
419
      write_particle_track(*this);
6,674✔
420
    }
421

422
    // If no secondary particles, break out of event loop
423
    if (secondary_bank().empty())
217,473,542✔
424
      return;
157,027,798✔
425

426
    from_source(&secondary_bank().back(), type);
60,445,744✔
427
    secondary_bank().pop_back();
60,445,744✔
428
    n_event() = 0;
60,445,744✔
429
    bank_second_E() = 0.0;
60,445,744✔
430

431
    // Score tallies affected by secondary particles
432
    if (!model::active_particleout_analog_tallies.empty()) {
60,445,744✔
NEW
433
      if (settings::run_CE) {
×
NEW
434
        score_analog_tally_ce(*this, model::active_particleout_analog_tallies);
×
435
      } else {
NEW
436
        score_analog_tally_mg(*this, model::active_particleout_analog_tallies);
×
437
      }
438
    }
439

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

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

466
    // Enter new particle in particle track file
467
    if (write_track())
60,445,744✔
468
      add_particle_track(*this);
5,604✔
469
  }
470
}
471

472
void Particle::event_death()
157,028,798✔
473
{
474
#ifdef OPENMC_DAGMC_ENABLED
475
  history().reset();
14,326,682✔
476
#endif
477

478
  // Finish particle track output.
479
  if (write_track()) {
157,028,798✔
480
    finalize_particle_track(*this);
1,070✔
481
  }
482

483
// Contribute tally reduction variables to global accumulator
484
#pragma omp atomic
86,233,962✔
485
  global_tally_absorption += keff_tally_absorption();
157,028,798✔
486
#pragma omp atomic
86,688,739✔
487
  global_tally_collision += keff_tally_collision();
157,028,798✔
488
#pragma omp atomic
86,048,263✔
489
  global_tally_tracklength += keff_tally_tracklength();
157,028,798✔
490
#pragma omp atomic
85,755,005✔
491
  global_tally_leakage += keff_tally_leakage();
157,028,798✔
492

493
  // Reset particle tallies once accumulated
494
  keff_tally_absorption() = 0.0;
157,028,798✔
495
  keff_tally_collision() = 0.0;
157,028,798✔
496
  keff_tally_tracklength() = 0.0;
157,028,798✔
497
  keff_tally_leakage() = 0.0;
157,028,798✔
498

499
  if (!model::active_pulse_height_tallies.empty()) {
157,028,798✔
500
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
501
  }
502

503
  // Record the number of progeny created by this particle.
504
  // This data will be used to efficiently sort the fission bank.
505
  if (settings::run_mode == RunMode::EIGENVALUE) {
157,028,798✔
506
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,892,800✔
507
    simulation::progeny_per_particle[offset] = n_progeny();
133,892,800✔
508
  }
509
}
157,028,798✔
510

511
void Particle::pht_collision_energy()
2,024✔
512
{
513
  // Adds the energy particles lose in a collision to the pulse-height
514

515
  // determine index of cell in pulse_height_cells
516
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
517
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
518

519
  if (it != model::pulse_height_cells.end()) {
2,024✔
520
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
521
    pht_storage()[index] += E_last() - E();
2,024✔
522

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

532
void Particle::pht_secondary_particles()
605✔
533
{
534
  // Removes the energy of secondary produced particles from the pulse-height
535

536
  // determine index of cell in pulse_height_cells
537
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
538
    model::pulse_height_cells.end(), cell_born());
605✔
539

540
  if (it != model::pulse_height_cells.end()) {
605✔
541
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
542
    pht_storage()[index] -= E();
605✔
543
  }
544
}
605✔
545

546
void Particle::cross_surface(const Surface& surf)
1,351,111,110✔
547
{
548

549
  if (settings::verbosity >= 10 || trace()) {
1,351,111,110✔
550
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
551
  }
552

553
// if we're crossing a CSG surface, make sure the DAG history is reset
554
#ifdef OPENMC_DAGMC_ENABLED
555
  if (surf.geom_type() == GeometryType::CSG)
123,100,605✔
556
    history().reset();
123,056,557✔
557
#endif
558

559
  // Handle any applicable boundary conditions.
560
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,351,111,110✔
561
    surf.bc_->handle_particle(*this, surf);
632,940,478✔
562
    return;
632,940,478✔
563
  }
564

565
  // ==========================================================================
566
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
567

568
#ifdef OPENMC_DAGMC_ENABLED
569
  // in DAGMC, we know what the next cell should be
570
  if (surf.geom_type() == GeometryType::DAG) {
65,589,745✔
571
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
36,997✔
572
                       lowest_coord().universe()) -
36,997✔
573
                     1;
36,997✔
574
    // save material and temp
575
    material_last() = material();
36,997✔
576
    sqrtkT_last() = sqrtkT();
36,997✔
577
    // set new cell value
578
    lowest_coord().cell() = i_cell;
36,997✔
579
    auto& cell = model::cells[i_cell];
36,997✔
580

581
    cell_instance() = 0;
36,997✔
582
    if (cell->distribcell_index_ >= 0)
36,997✔
583
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
584

585
    material() = cell->material(cell_instance());
36,997✔
586
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
587
    return;
36,997✔
588
  }
589
#endif
590

591
  bool verbose = settings::verbosity >= 10 || trace();
718,133,635✔
592
  if (neighbor_list_find_cell(*this, verbose)) {
718,133,635✔
593
    return;
718,105,616✔
594
  }
595

596
  // ==========================================================================
597
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
598

599
  // Remove lower coordinate levels
600
  n_coord() = 1;
28,019✔
601
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
602

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

609
    surface() = SURFACE_NONE;
5,744✔
610
    n_coord() = 1;
5,744✔
611
    r() += TINY_BIT * u();
5,744✔
612

613
    // Couldn't find next cell anywhere! This probably means there is an actual
614
    // undefined region in the geometry.
615

616
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
617
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
618
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
619
                   " it could not be located in any cell and it did not leak.");
620
      return;
5,735✔
621
    }
622
  }
623
}
624

625
void Particle::cross_vacuum_bc(const Surface& surf)
30,978,165✔
626
{
627
  // Score any surface current tallies -- note that the particle is moved
628
  // forward slightly so that if the mesh boundary is on the surface, it is
629
  // still processed
630

631
  if (!model::active_meshsurf_tallies.empty()) {
30,978,165✔
632
    // TODO: Find a better solution to score surface currents than
633
    // physically moving the particle forward slightly
634

635
    r() += TINY_BIT * u();
1,021,265✔
636
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
637
  }
638

639
  // Score to global leakage tally
640
  keff_tally_leakage() += wgt();
30,978,165✔
641

642
  // Kill the particle
643
  wgt() = 0.0;
30,978,165✔
644

645
  // Display message
646
  if (settings::verbosity >= 10 || trace()) {
30,978,165✔
647
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
648
  }
649
}
30,978,165✔
650

651
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
602,323,351✔
652
{
653
  // Do not handle reflective boundary conditions on lower universes
654
  if (n_coord() != 1) {
602,323,351✔
655
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
656
                 " off surface in a lower universe.");
657
    return;
×
658
  }
659

660
  // Score surface currents since reflection causes the direction of the
661
  // particle to change. For surface filters, we need to score the tallies
662
  // twice, once before the particle's surface attribute has changed and
663
  // once after. For mesh surface filters, we need to artificially move
664
  // the particle slightly back in case the surface crossing is coincident
665
  // with a mesh boundary
666

667
  if (!model::active_surface_tallies.empty()) {
602,323,351✔
668
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
669
  }
670

671
  if (!model::active_meshsurf_tallies.empty()) {
602,323,351✔
672
    Position r {this->r()};
50,811,809✔
673
    this->r() -= TINY_BIT * u();
50,811,809✔
674
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
675
    this->r() = r;
50,811,809✔
676
  }
677

678
  // Set the new particle direction
679
  u() = new_u;
602,323,351✔
680

681
  // Reassign particle's cell and surface
682
  coord(0).cell() = cell_last(0);
602,323,351✔
683
  surface() = -surface();
602,323,351✔
684

685
  // If a reflective surface is coincident with a lattice or universe
686
  // boundary, it is necessary to redetermine the particle's coordinates in
687
  // the lower universes.
688
  // (unless we're using a dagmc model, which has exactly one universe)
689
  n_coord() = 1;
602,323,351✔
690
  if (surf.geom_type() != GeometryType::DAG &&
1,204,644,163✔
691
      !neighbor_list_find_cell(*this)) {
602,320,812✔
692
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
693
                 std::to_string(surf.id_) + ".");
×
694
    return;
×
695
  }
696

697
  // Set previous coordinate going slightly past surface crossing
698
  r_last_current() = r() + TINY_BIT * u();
602,323,351✔
699

700
  // Diagnostic message
701
  if (settings::verbosity >= 10 || trace()) {
602,323,351✔
702
    write_message(1, "    Reflected from surface {}", surf.id_);
×
703
  }
704
}
705

706
void Particle::cross_periodic_bc(
666,318✔
707
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
708
{
709
  // Do not handle periodic boundary conditions on lower universes
710
  if (n_coord() != 1) {
666,318✔
711
    mark_as_lost(
×
712
      "Cannot transfer particle " + std::to_string(id()) +
×
713
      " across surface in a lower universe. Boundary conditions must be "
714
      "applied to root universe.");
715
    return;
×
716
  }
717

718
  // Score surface currents since reflection causes the direction of the
719
  // particle to change -- artificially move the particle slightly back in
720
  // case the surface crossing is coincident with a mesh boundary
721
  if (!model::active_meshsurf_tallies.empty()) {
666,318✔
722
    Position r {this->r()};
×
723
    this->r() -= TINY_BIT * u();
×
724
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
725
    this->r() = r;
×
726
  }
727

728
  // Adjust the particle's location and direction.
729
  r() = new_r;
666,318✔
730
  u() = new_u;
666,318✔
731

732
  // Reassign particle's surface
733
  surface() = new_surface;
666,318✔
734

735
  // Figure out what cell particle is in now
736
  n_coord() = 1;
666,318✔
737

738
  if (!neighbor_list_find_cell(*this)) {
666,318✔
739
    mark_as_lost("Couldn't find particle after hitting periodic "
×
740
                 "boundary on surface " +
×
741
                 std::to_string(surf.id_) +
×
742
                 ". The normal vector "
743
                 "of one periodic surface may need to be reversed.");
744
    return;
×
745
  }
746

747
  // Set previous coordinate going slightly past surface crossing
748
  r_last_current() = r() + TINY_BIT * u();
666,318✔
749

750
  // Diagnostic message
751
  if (settings::verbosity >= 10 || trace()) {
666,318✔
752
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
753
  }
754
}
755

756
void Particle::mark_as_lost(const char* message)
5,744✔
757
{
758
  // Print warning and write lost particle file
759
  warning(message);
5,744✔
760
  if (settings::max_write_lost_particles < 0 ||
5,744✔
761
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
762
    write_restart();
324✔
763
  }
764
  // Increment number of lost particles
765
  wgt() = 0.0;
5,744✔
766
#pragma omp atomic
3,124✔
767
  simulation::n_lost_particles += 1;
2,620✔
768

769
  // Count the total number of simulated particles (on this processor)
770
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
771
           simulation::work_per_rank;
772

773
  // Abort the simulation if the maximum number of lost particles has been
774
  // reached
775
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
776
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
777
    fatal_error("Maximum number of lost particles has been reached.");
9✔
778
  }
779
}
5,735✔
780

781
void Particle::write_restart() const
324✔
782
{
783
  // Dont write another restart file if in particle restart mode
784
  if (settings::run_mode == RunMode::PARTICLE)
324✔
785
    return;
22✔
786

787
  // Set up file name
788
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
789
    simulation::current_batch, id());
565✔
790

791
#pragma omp critical(WriteParticleRestart)
314✔
792
  {
793
    // Create file
794
    hid_t file_id = file_open(filename, 'w');
302✔
795

796
    // Write filetype and version info
797
    write_attribute(file_id, "filetype", "particle restart");
302✔
798
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
799
    write_attribute(file_id, "openmc_version", VERSION);
302✔
800
#ifdef GIT_SHA1
801
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
802
#endif
803

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

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

848
    // Close file
849
    file_close(file_id);
302✔
850
  } // #pragma omp critical
851
}
302✔
852

853
void Particle::update_neutron_xs(
2,147,483,647✔
854
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
855
{
856
  // Get microscopic cross section cache
857
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
858

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

864
    // If NCrystal is being used, update micro cross section cache
865
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
866
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
867
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
868
    }
869
  }
870
}
2,147,483,647✔
871

872
//==============================================================================
873
// Non-method functions
874
//==============================================================================
875

876
std::string particle_type_to_str(ParticleType type)
3,130,197✔
877
{
878
  switch (type) {
3,130,197✔
879
  case ParticleType::neutron:
2,399,940✔
880
    return "neutron";
2,399,940✔
881
  case ParticleType::photon:
729,993✔
882
    return "photon";
729,993✔
883
  case ParticleType::electron:
132✔
884
    return "electron";
132✔
885
  case ParticleType::positron:
132✔
886
    return "positron";
132✔
887
  }
888
  UNREACHABLE();
×
889
}
890

891
ParticleType str_to_particle_type(std::string str)
2,988,936✔
892
{
893
  if (str == "neutron") {
2,988,936✔
894
    return ParticleType::neutron;
683,169✔
895
  } else if (str == "photon") {
2,305,767✔
896
    return ParticleType::photon;
2,305,681✔
897
  } else if (str == "electron") {
86✔
898
    return ParticleType::electron;
43✔
899
  } else if (str == "positron") {
43✔
900
    return ParticleType::positron;
43✔
901
  } else {
902
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
903
  }
904
}
905

906
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,348,894,424✔
907
{
908
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
909
      simulation::surf_source_bank.full()) {
1,059,995,464✔
910
    return;
1,348,765,659✔
911
  }
912

913
  // If a cell/cellfrom/cellto parameter is defined
914
  if (settings::ssw_cell_id != C_NONE) {
341,266✔
915

916
    // Retrieve cell index and storage type
917
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,705✔
918

919
    if (surf.bc_) {
258,705✔
920
      // Leave if cellto with vacuum boundary condition
921
      if (surf.bc_->type() == "vacuum" &&
184,448✔
922
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
923
        return;
11,953✔
924
      }
925

926
      // Leave if other boundary condition than vacuum
927
      if (surf.bc_->type() != "vacuum") {
140,281✔
928
        return;
120,020✔
929
      }
930
    }
931

932
    // Check if the cell of interest has been exited
933
    bool exited = false;
126,732✔
934
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,341✔
935
      if (p.cell_last(i) == cell_idx) {
208,609✔
936
        exited = true;
74,235✔
937
      }
938
    }
939

940
    // Check if the cell of interest has been entered
941
    bool entered = false;
126,732✔
942
    for (int i = 0; i < p.n_coord(); ++i) {
301,037✔
943
      if (p.coord(i).cell() == cell_idx) {
174,305✔
944
        entered = true;
59,098✔
945
      }
946
    }
947

948
    // Vacuum boundary conditions: return if cell is not exited
949
    if (surf.bc_) {
126,732✔
950
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
951
        return;
13,961✔
952
      }
953
    } else {
954

955
      // If we both enter and exit the cell of interest
956
      if (entered && exited) {
106,471✔
957
        return;
28,613✔
958
      }
959

960
      // If we did not enter nor exit the cell of interest
961
      if (!entered && !exited) {
77,858✔
962
        return;
14,351✔
963
      }
964

965
      // If cellfrom and the cell before crossing is not the cell of
966
      // interest
967
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,507✔
968
        return;
11,565✔
969
      }
970

971
      // If cellto and the cell after crossing is not the cell of interest
972
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
973
        return;
12,038✔
974
      }
975
    }
976
  }
977

978
  SourceSite site;
128,765✔
979
  site.r = p.r();
128,765✔
980
  site.u = p.u();
128,765✔
981
  site.E = p.E();
128,765✔
982
  site.time = p.time();
128,765✔
983
  site.wgt = p.wgt();
128,765✔
984
  site.delayed_group = p.delayed_group();
128,765✔
985
  site.surf_id = surf.id_;
128,765✔
986
  site.particle = p.type();
128,765✔
987
  site.parent_id = p.id();
128,765✔
988
  site.progeny_id = p.n_progeny();
128,765✔
989
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
128,765✔
990
}
991

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