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

openmc-dev / openmc / 29123958173

10 Jul 2026 09:12PM UTC coverage: 80.472% (-0.8%) from 81.292%
29123958173

Pull #3951

github

web-flow
Merge 62dca9136 into 7256d5046
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16757 of 24275 branches covered (69.03%)

Branch coverage included in aggregate %.

70 of 138 new or added lines in 10 files covered. (50.72%)

876 existing lines in 50 files now uncovered.

57507 of 68010 relevant lines covered (84.56%)

23274270.93 hits per line

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

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

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

6
#include <fmt/core.h>
7

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

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

41
namespace openmc {
42

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

47
double Particle::speed() const
1,627,035,517✔
48
{
49
  if (settings::run_CE) {
1,627,035,517✔
50
    // Determine mass in eV/c^2
51
    double mass = this->mass();
1,058,990,272✔
52

53
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
54
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,058,990,272✔
55
           (this->E() + mass);
1,058,990,272✔
56
  } else {
57
    auto mat = this->material();
568,045,245✔
58
    if (mat == MATERIAL_VOID)
568,045,245!
59
      return 1.0 / data::mg.default_inverse_velocity_[this->g()];
×
60
    auto& macro_xs = data::mg.macro_xs_[mat];
568,045,245✔
61
    int macro_t = this->mg_xs_cache().t;
568,045,245✔
62
    int macro_a = macro_xs.get_angle_index(this->u());
568,045,245✔
63
    return 1.0 / macro_xs.get_xs(
1,136,090,490✔
64
                   MgxsType::INVERSE_VELOCITY, this->g(), macro_t, macro_a);
568,045,245✔
65
  }
66
}
67

68
double Particle::mass() const
1,058,990,272✔
69
{
70
  switch (type().pdg_number()) {
1,058,990,272✔
71
  case PDG_NEUTRON:
72
    return MASS_NEUTRON_EV;
73
  case PDG_ELECTRON:
26,129,561✔
74
  case PDG_POSITRON:
26,129,561✔
75
    return MASS_ELECTRON_EV;
26,129,561✔
76
  default:
12,160,643✔
77
    return this->type().mass() * AMU_EV;
12,160,643✔
78
  }
79
}
80

81
bool Particle::create_secondary(
54,239,175✔
82
  double wgt, Direction u, double E, ParticleType type)
83
{
84
  // If energy is below cutoff for this particle, don't create secondary
85
  // particle
86
  int idx = type.transport_index();
54,239,175✔
87
  if (idx == C_NONE) {
54,239,175!
88
    return false;
89
  }
90
  if (E < settings::energy_cutoff[idx]) {
54,239,175✔
91
    return false;
92
  }
93

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
28,238,652✔
96

97
  SourceSite bank;
28,238,652✔
98
  bank.particle = type;
28,238,652✔
99
  bank.wgt = wgt;
28,238,652✔
100
  bank.r = r();
28,238,652!
101
  bank.u = u;
28,238,652✔
102
  bank.E = settings::run_CE ? E : g();
28,238,652!
103
  bank.time = time();
28,238,652✔
104
  bank_second_E() += bank.E;
28,238,652✔
105
  bank.parent_id = current_work();
28,238,652✔
106
  if (settings::use_shared_secondary_bank) {
28,238,652✔
107
    bank.progeny_id = n_progeny()++;
4,194,258✔
108
  }
109
  bank.wgt_born = wgt_born();
28,238,652✔
110
  bank.wgt_ww_born = wgt_ww_born();
28,238,652✔
111
  bank.n_split = n_split();
28,238,652✔
112

113
  local_secondary_bank().emplace_back(bank);
28,238,652✔
114
  return true;
115
}
116

117
void Particle::split(double wgt)
2,958,456✔
118
{
119
  SourceSite bank;
2,958,456✔
120
  bank.particle = type();
2,958,456✔
121
  bank.wgt = wgt;
2,958,456✔
122
  bank.r = r();
2,958,456✔
123
  bank.u = u();
2,958,456✔
124
  bank.E = settings::run_CE ? E() : g();
2,958,456✔
125
  bank.time = time();
2,958,456✔
126

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
2,958,456✔
129
    bank.surf_id = SURFACE_NONE;
2,957,496✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
960✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
960✔
133
  }
134

135
  bank.wgt_born = wgt_born();
2,958,456✔
136
  bank.wgt_ww_born = wgt_ww_born();
2,958,456✔
137
  bank.n_split = n_split();
2,958,456✔
138
  bank.parent_id = current_work();
2,958,456✔
139
  if (settings::use_shared_secondary_bank) {
2,958,456✔
140
    bank.progeny_id = n_progeny()++;
1,420,212✔
141
  }
142

143
  local_secondary_bank().emplace_back(bank);
2,958,456✔
144
}
2,958,456✔
145

146
void Particle::from_source(const SourceSite* src)
82,389,852✔
147
{
148
  // Reset some attributes
149
  clear();
82,389,852✔
150
  surface() = SURFACE_NONE;
82,389,852✔
151
  cell_born() = C_NONE;
82,389,852✔
152
  material() = C_NONE;
82,389,852✔
153
  n_collision() = 0;
82,389,852✔
154
  fission() = false;
82,389,852✔
155
  zero_flux_derivs();
82,389,852✔
156
  lifetime() = 0.0;
82,389,852✔
157
#ifdef OPENMC_DAGMC_ENABLED
158
  history().reset();
159
#endif
160

161
  // Copy attributes from source bank site
162
  type() = src->particle;
82,389,852✔
163
  wgt() = src->wgt;
82,389,852✔
164
  wgt_last() = src->wgt;
82,389,852✔
165
  r() = src->r;
82,389,852✔
166
  u() = src->u;
82,389,852✔
167
  r_born() = src->r;
82,389,852✔
168
  r_last_current() = src->r;
82,389,852✔
169
  r_last() = src->r;
82,389,852✔
170
  u_last() = src->u;
82,389,852✔
171
  if (settings::run_CE) {
82,389,852✔
172
    E() = src->E;
50,517,540✔
173
    g() = 0;
50,517,540✔
174
  } else {
175
    g() = static_cast<int>(src->E);
31,872,312✔
176
    g_last() = static_cast<int>(src->E);
31,872,312✔
177
    E() = data::mg.energy_bin_avg_[g()];
31,872,312✔
178
  }
179
  E_last() = E();
82,389,852✔
180
  time() = src->time;
82,389,852✔
181
  time_last() = src->time;
82,389,852✔
182
  parent_nuclide() = src->parent_nuclide;
82,389,852✔
183
  delayed_group() = src->delayed_group;
82,389,852✔
184

185
  // Convert signed surface ID to signed index
186
  if (src->surf_id != SURFACE_NONE) {
82,389,852✔
187
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
30,960✔
188
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
30,960✔
189
  }
190

191
  wgt_born() = src->wgt_born;
82,389,852✔
192
  wgt_ww_born() = src->wgt_ww_born;
82,389,852✔
193
  n_split() = src->n_split;
82,389,852✔
194
}
82,389,852✔
195

196
void Particle::event_calculate_xs()
1,619,550,064✔
197
{
198
  // Set the random number stream
199
  stream() = STREAM_TRACKING;
1,619,550,064✔
200

201
  // Store pre-collision particle properties
202
  wgt_last() = wgt();
1,619,550,064✔
203
  E_last() = E();
1,619,550,064✔
204
  u_last() = u();
1,619,550,064✔
205
  r_last() = r();
1,619,550,064✔
206
  time_last() = time();
1,619,550,064✔
207

208
  // Reset event variables
209
  event() = TallyEvent::KILL;
1,619,550,064✔
210
  event_nuclide() = NUCLIDE_NONE;
1,619,550,064✔
211
  event_mt() = REACTION_NONE;
1,619,550,064✔
212

213
  // If the cell hasn't been determined based on the particle's location,
214
  // initiate a search for the current cell. This generally happens at the
215
  // beginning of the history and again for any secondary particles
216
  if (lowest_coord().cell() == C_NONE) {
1,619,550,064✔
217
    if (!exhaustive_find_cell(*this)) {
79,919,493!
218
      mark_as_lost(
×
219
        "Could not find the cell containing particle " + std::to_string(id()));
×
220
      return;
×
221
    }
222

223
    // Set birth cell attribute
224
    if (cell_born() == C_NONE)
79,919,493!
225
      cell_born() = lowest_coord().cell();
79,919,493✔
226

227
    // Initialize last cells from current cell
228
    for (int j = 0; j < n_coord(); ++j) {
164,614,683✔
229
      cell_last(j) = coord(j).cell();
84,695,190✔
230
    }
231
    n_coord_last() = n_coord();
79,919,493✔
232
  }
233

234
  // Write particle track.
235
  if (write_track())
1,619,550,064✔
236
    write_particle_track(*this);
2,262✔
237

238
  if (settings::check_overlaps)
1,619,550,064!
239
    check_cell_overlap(*this);
×
240

241
  // Calculate microscopic and macroscopic cross sections
242
  if (material() != MATERIAL_VOID) {
1,619,550,064✔
243
    if (settings::run_CE) {
1,589,017,834✔
244
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,020,972,589✔
245
          density_mult() != density_mult_last()) {
242,722,611✔
246
        // If the material is the same as the last material and the
247
        // temperature hasn't changed, we don't need to lookup cross
248
        // sections again.
249
        model::materials[material()]->calculate_xs(*this);
778,252,594✔
250
      }
251
    } else {
252
      // Get the MG data; unlike the CE case above, we have to re-calculate
253
      // cross sections for every collision since the cross sections may
254
      // be angle-dependent
255
      data::mg.macro_xs_[material()].calculate_xs(*this);
568,045,245✔
256

257
      // Update the particle's group while we know we are multi-group
258
      g_last() = g();
568,045,245✔
259
    }
260
  } else {
261
    macro_xs().total = 0.0;
30,532,230✔
262
    macro_xs().absorption = 0.0;
30,532,230✔
263
    macro_xs().fission = 0.0;
30,532,230✔
264
    macro_xs().nu_fission = 0.0;
30,532,230✔
265
  }
266
}
267

268
void Particle::event_advance()
1,619,550,064✔
269
{
270
  // Find the distance to the nearest boundary
271
  boundary() = distance_to_boundary(*this);
1,619,550,064✔
272

273
  // Sample a distance to collision
274
  if (type() == ParticleType::electron() ||
1,619,550,064✔
275
      type() == ParticleType::positron()) {
1,593,474,401✔
276
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
52,259,122!
277
  } else if (macro_xs().total == 0.0) {
1,593,420,503✔
278
    collision_distance() = INFINITY;
30,532,230✔
279
  } else {
280
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
1,562,888,273✔
281
  }
282

283
  double speed = this->speed();
1,619,550,064✔
284
  double time_cutoff = settings::time_cutoff[type().transport_index()];
1,619,550,064✔
285
  double distance_cutoff =
1,619,550,064✔
286
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
1,619,550,064✔
287

288
  // Select smaller of the three distances
289
  double distance =
1,619,550,064✔
290
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
1,619,550,064✔
291

292
  // Advance particle in space and time
293
  this->move_distance(distance);
1,619,550,064✔
294
  double dt = distance / speed;
1,619,550,064✔
295
  this->time() += dt;
1,619,550,064✔
296
  this->lifetime() += dt;
1,619,550,064✔
297

298
  // Score timed track-length tallies
299
  if (!model::active_timed_tracklength_tallies.empty()) {
1,619,550,064✔
300
    score_timed_tracklength_tally(*this, distance);
989,541✔
301
  }
302

303
  // Score track-length tallies
304
  if (!model::active_tracklength_tallies.empty()) {
1,619,550,064✔
305
    score_tracklength_tally(*this, distance);
822,554,465✔
306
  }
307

308
  // Score track-length estimate of k-eff
309
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
1,619,550,064✔
310
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
1,323,898,997✔
311
  }
312

313
  // Score flux derivative accumulators for differential tallies.
314
  if (!model::active_tallies.empty()) {
1,619,550,064✔
315
    score_track_derivative(*this, distance);
867,701,651✔
316
  }
317

318
  // Set particle weight to zero if it hit the time boundary
319
  if (distance == distance_cutoff) {
1,619,550,064✔
320
    wgt() = 0.0;
61,344✔
321
  }
322
}
1,619,550,064✔
323

324
void Particle::event_cross_surface()
995,877,769✔
325
{
326
  // Saving previous cell data
327
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
328
    cell_last(j) = coord(j).cell();
1,850,782,723✔
329
  }
330
  n_coord_last() = n_coord();
995,877,769✔
331

332
  // Set surface that particle is on and adjust coordinate levels
333
  surface() = boundary().surface();
995,877,769✔
334
  n_coord() = boundary().coord_level();
995,877,769✔
335

336
  if (boundary().lattice_translation()[0] != 0 ||
995,877,769✔
337
      boundary().lattice_translation()[1] != 0 ||
995,877,769✔
338
      boundary().lattice_translation()[2] != 0) {
836,622,091✔
339
    // Particle crosses lattice boundary
340

341
    int i_lattice = coord(boundary().coord_level() - 1).lattice();
215,384,217!
342
    bool verbose = settings::verbosity >= 10 || trace();
215,384,217!
343
    cross_lattice(*this, boundary(), verbose);
215,384,217✔
344
    event() = TallyEvent::LATTICE;
215,384,217✔
345

346
    // Score cell to cell partial currents
347
    if (!model::active_surface_tallies.empty()) {
215,384,217✔
348
      auto& lat {*model::lattices[i_lattice]};
15✔
349
      bool is_valid;
15✔
350
      Direction normal =
15✔
351
        lat.get_normal(boundary().lattice_translation(), is_valid);
15✔
352
      if (is_valid) {
15!
353
        normal /= normal.norm();
15✔
354
        score_surface_tally(*this, model::active_surface_tallies, normal);
15✔
355
      }
356
    }
357

358
  } else {
359

360
    const auto& surf {*model::surfaces[surface_index()].get()};
780,493,552✔
361

362
    // Particle crosses surface
363
    // If BC, add particle to surface source before crossing surface
364
    if (surf.surf_source_ && surf.bc_) {
780,493,552✔
365
      add_surf_source_to_bank(*this, surf);
274,963,258✔
366
    }
367
    this->cross_surface(surf);
780,493,552✔
368
    // If no BC, add particle to surface source after crossing surface
369
    if (surf.surf_source_ && !surf.bc_) {
780,493,549✔
370
      add_surf_source_to_bank(*this, surf);
505,179,861✔
371
    }
372
    if (settings::weight_window_checkpoint_surface) {
780,493,549✔
373
      apply_weight_windows(*this);
44,451✔
374
    }
375
    event() = TallyEvent::SURFACE;
780,493,549✔
376

377
    // Score cell to cell partial currents
378
    if (!model::active_surface_tallies.empty()) {
780,493,549✔
379
      Direction normal = surf.normal(r());
9,526,806✔
380
      normal /= normal.norm();
9,526,806✔
381
      score_surface_tally(*this, model::active_surface_tallies, normal);
9,526,806✔
382
    }
383
  }
384
}
995,877,766✔
385

386
void Particle::event_collide()
896,307,477✔
387
{
388

389
  // Score collision estimate of keff
390
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
896,307,477✔
391
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
636,965,812✔
392
  }
393

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

398
  if (!model::active_meshsurf_tallies.empty())
896,307,477✔
399
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
17,208,798✔
400

401
  // Clear surface component
402
  surface() = SURFACE_NONE;
896,307,477✔
403

404
  if (settings::run_CE) {
896,307,477✔
405
    collision(*this);
405,086,175✔
406
  } else {
407
    collision_mg(*this);
491,221,302✔
408
  }
409

410
  // Collision track feature to recording particle interaction
411
  if (settings::collision_track) {
896,307,477✔
412
    collision_track_record(*this);
198,729✔
413
  }
414

415
  // Score collision estimator tallies -- this is done after a collision
416
  // has occurred rather than before because we need information on the
417
  // outgoing energy for any tallies with an outgoing energy filter
418
  if (!model::active_collision_tallies.empty())
896,307,477✔
419
    score_collision_tally(*this);
28,791,373✔
420
  if (!model::active_analog_tallies.empty()) {
896,307,477✔
421
    if (settings::run_CE) {
110,725,728✔
422
      score_analog_tally_ce(*this);
110,396,202✔
423
    } else {
424
      score_analog_tally_mg(*this);
329,526✔
425
    }
426
  }
427

428
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
896,307,477✔
429
    pht_collision_energy();
2,364✔
430
  }
431

432
  // Reset banked weight during collision
433
  n_bank() = 0;
896,307,477✔
434
  bank_second_E() = 0.0;
896,307,477✔
435
  wgt_bank() = 0.0;
896,307,477✔
436

437
  // Clear number of secondaries in this collision. This is
438
  // distinct from the number of created neutrons n_bank() above!
439
  n_secondaries() = 0;
896,307,477✔
440

441
  zero_delayed_bank();
896,307,477✔
442

443
  // Reset fission logical
444
  fission() = false;
896,307,477✔
445

446
  // Save coordinates for tallying purposes
447
  r_last_current() = r();
896,307,477✔
448

449
  // Set last material to none since cross sections will need to be
450
  // re-evaluated
451
  material_last() = C_NONE;
896,307,477✔
452

453
  // Set all directions to base level -- right now, after a collision, only
454
  // the base level directions are changed
455
  for (int j = 0; j < n_coord() - 1; ++j) {
975,616,059✔
456
    if (coord(j + 1).rotated()) {
79,308,582✔
457
      // If next level is rotated, apply rotation matrix
458
      const auto& m {model::cells[coord(j).cell()]->rotation_};
3,197,517✔
459
      const auto& u {coord(j).u()};
3,197,517✔
460
      coord(j + 1).u() = u.rotate(m);
3,197,517✔
461
    } else {
462
      // Otherwise, copy this level's direction
463
      coord(j + 1).u() = coord(j).u();
76,111,065✔
464
    }
465
  }
466

467
  // Score flux derivative accumulators for differential tallies.
468
  if (!model::active_tallies.empty())
896,307,477✔
469
    score_collision_derivative(*this);
361,410,017✔
470

471
#ifdef OPENMC_DAGMC_ENABLED
472
  history().reset();
473
#endif
474
}
896,307,477✔
475

476
void Particle::event_revive_from_secondary(const SourceSite& site)
31,418,298✔
477
{
478
  // Write final position for the previous track (skip if this is a freshly
479
  // constructed particle with no prior track, e.g., Phase 2 of shared
480
  // secondary transport)
481
  if (write_track() && n_event() > 0) {
31,418,298!
482
    write_particle_track(*this);
1,014✔
483
  }
484

485
  from_source(&site);
31,418,298✔
486

487
  n_event() = 0;
31,418,298✔
488
  if (!settings::use_shared_secondary_bank) {
31,418,298✔
489
    n_tracks()++;
25,584,102✔
490
  }
491
  bank_second_E() = 0.0;
31,418,298✔
492

493
  // Subtract secondary particle energy from interim pulse-height results.
494
  // In shared secondary mode, this subtraction was already done on the parent
495
  // particle during create_secondary(), so skip it here.
496
  if (!settings::use_shared_secondary_bank &&
57,002,400✔
497
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
31,418,298✔
498
    // Since the birth cell of the particle has not been set we
499
    // have to determine it before the energy of the secondary particle can be
500
    // removed from the pulse-height of this cell.
501
    if (lowest_coord().cell() == C_NONE) {
864!
502
      bool verbose = settings::verbosity >= 10 || trace();
864!
503
      if (!exhaustive_find_cell(*this, verbose)) {
864!
504
        mark_as_lost("Could not find the cell containing particle " +
×
505
                     std::to_string(id()));
×
506
        return;
×
507
      }
508
      // Set birth cell attribute
509
      if (cell_born() == C_NONE)
864!
510
        cell_born() = lowest_coord().cell();
864✔
511

512
      // Initialize last cells from current cell
513
      for (int j = 0; j < n_coord(); ++j) {
1,728✔
514
        cell_last(j) = coord(j).cell();
864✔
515
      }
516
      n_coord_last() = n_coord();
864✔
517
    }
518
    pht_secondary_particles();
864✔
519
  }
520

521
  // Enter new particle in particle track file
522
  if (write_track())
31,418,298✔
523
    add_particle_track(*this);
1,014✔
524
}
525

526
void Particle::event_check_limit_and_revive()
1,619,550,061✔
527
{
528
  // If particle has too many events, display warning and kill it
529
  n_event()++;
1,619,550,061✔
530
  if (n_event() == settings::max_particle_events) {
1,619,550,061!
531
    warning("Particle " + std::to_string(id()) +
×
532
            " underwent maximum number of events.");
533
    wgt() = 0.0;
×
534
  }
535

536
  // In non-shared-secondary mode, revive from local secondary bank
537
  if (!alive() && !settings::use_shared_secondary_bank &&
1,619,550,061✔
538
      !local_secondary_bank().empty()) {
73,872,690✔
539
    SourceSite& site = local_secondary_bank().back();
25,584,102✔
540
    event_revive_from_secondary(site);
25,584,102✔
541
    local_secondary_bank().pop_back();
25,584,102✔
542
  }
543
}
1,619,550,061✔
544

545
void Particle::event_death()
54,336,252✔
546
{
547
#ifdef OPENMC_DAGMC_ENABLED
548
  history().reset();
549
#endif
550

551
  // Finish particle track output.
552
  if (write_track()) {
54,336,252✔
553
    write_particle_track(*this);
210✔
554
    finalize_particle_track(*this);
210✔
555
  }
556

557
  // Contribute tally reduction variables to global accumulator
558
  const auto k_absorption = keff_tally_absorption();
54,336,252✔
559
  const auto k_collision = keff_tally_collision();
54,336,252✔
560
  const auto k_tracklength = keff_tally_tracklength();
54,336,252✔
561
  const auto leakage = keff_tally_leakage();
54,336,252✔
562

563
  if (settings::run_mode == RunMode::EIGENVALUE) {
54,336,252✔
564
    if (k_absorption != 0.0) {
40,887,000✔
565
#pragma omp atomic
566
      global_tally_absorption += k_absorption;
36,392,285✔
567
    }
568
    if (k_collision != 0.0) {
40,887,000✔
569
#pragma omp atomic
570
      global_tally_collision += k_collision;
39,014,057✔
571
    }
572
    if (k_tracklength != 0.0) {
40,887,000✔
573
#pragma omp atomic
574
      global_tally_tracklength += k_tracklength;
40,859,049✔
575
    }
576
  }
577
  if (leakage != 0.0) {
54,336,252✔
578
#pragma omp atomic
579
    global_tally_leakage += leakage;
9,791,776✔
580
  }
581

582
  // Reset particle tallies once accumulated
583
  keff_tally_absorption() = 0.0;
54,336,252✔
584
  keff_tally_collision() = 0.0;
54,336,252✔
585
  keff_tally_tracklength() = 0.0;
54,336,252✔
586
  keff_tally_leakage() = 0.0;
54,336,252✔
587

588
  if (!model::active_pulse_height_tallies.empty()) {
54,336,252✔
589
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
9,000✔
590
  }
591

592
  // Accumulate track count for this particle history
593
  if (!settings::use_shared_secondary_bank) {
54,336,252✔
594
#pragma omp atomic
595
    simulation::simulation_tracks_completed += n_tracks();
48,288,588✔
596
  }
597

598
  // Record the number of progeny created by this particle.
599
  // This data will be used to efficiently sort the fission bank.
600
  if (settings::run_mode == RunMode::EIGENVALUE ||
54,336,252✔
601
      settings::use_shared_secondary_bank) {
602
    simulation::progeny_per_particle[current_work()] = n_progeny();
46,934,664✔
603
  }
604
}
54,336,252✔
605

606
void Particle::pht_collision_energy()
2,364✔
607
{
608
  // Adds the energy particles lose in a collision to the pulse-height
609

610
  // determine index of cell in pulse_height_cells
611
  auto it = std::find(model::pulse_height_cells.begin(),
2,364✔
612
    model::pulse_height_cells.end(), lowest_coord().cell());
2,364!
613

614
  if (it != model::pulse_height_cells.end()) {
2,364!
615
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,364✔
616
    pht_storage()[index] += E_last() - E();
2,364✔
617

618
    // If the energy of the particle is below the cutoff, it will not be sampled
619
    // so its energy is added to the pulse-height in the cell
620
    int photon = ParticleType::photon().transport_index();
2,364✔
621
    if (E() < settings::energy_cutoff[photon]) {
2,364✔
622
      pht_storage()[index] += E();
1,020✔
623
    }
624
  }
625
}
2,364✔
626

627
void Particle::pht_secondary_particles()
864✔
628
{
629
  // Removes the energy of secondary produced particles from the pulse-height
630

631
  // determine index of cell in pulse_height_cells
632
  auto it = std::find(model::pulse_height_cells.begin(),
864✔
633
    model::pulse_height_cells.end(), cell_born());
864!
634

635
  if (it != model::pulse_height_cells.end()) {
864!
636
    int index = std::distance(model::pulse_height_cells.begin(), it);
864✔
637
    pht_storage()[index] -= E();
864✔
638
  }
639
}
864✔
640

641
void Particle::cross_surface(const Surface& surf)
781,036,408✔
642
{
643

644
  if (settings::verbosity >= 10 || trace()) {
781,036,408✔
645
    write_message(1, "    Crossing surface {}", surf.id_);
24✔
646
  }
647

648
// if we're crossing a CSG surface, make sure the DAG history is reset
649
#ifdef OPENMC_DAGMC_ENABLED
650
  if (surf.geom_type() == GeometryType::CSG)
651
    history().reset();
652
#endif
653

654
  // Handle any applicable boundary conditions.
655
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
781,036,408!
656
      settings::run_mode != RunMode::VOLUME) {
657
    surf.bc_->handle_particle(*this, surf);
275,061,658✔
658
    return;
275,061,658✔
659
  }
660

661
  // ==========================================================================
662
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
663

664
#ifdef OPENMC_DAGMC_ENABLED
665
  // in DAGMC, we know what the next cell should be
666
  if (surf.geom_type() == GeometryType::DAG) {
667
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
668
                       lowest_coord().universe()) -
669
                     1;
670
    // save material, temperature, and density multiplier
671
    material_last() = material();
672
    sqrtkT_last() = sqrtkT();
673
    density_mult_last() = density_mult();
674
    // set new cell value
675
    lowest_coord().cell() = i_cell;
676
    auto& cell = model::cells[i_cell];
677

678
    cell_instance() = 0;
679
    if (cell->distribcell_index_ >= 0)
680
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
681

682
    material() = cell->material(cell_instance());
683
    sqrtkT() = cell->sqrtkT(cell_instance());
684
    density_mult() = cell->density_mult(cell_instance());
685
    return;
686
  }
687
#endif
688

689
  bool verbose = settings::verbosity >= 10 || trace();
505,974,750!
690
  if (neighbor_list_find_cell(*this, verbose)) {
505,974,750✔
691
    return;
692
  }
693

694
  // ==========================================================================
695
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
696

697
  // Remove lower coordinate levels
698
  n_coord() = 1;
8,181✔
699
  bool found = exhaustive_find_cell(*this, verbose);
8,181✔
700

701
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
8,181!
702
    // If a cell is still not found, there are two possible causes: 1) there is
703
    // a void in the model, and 2) the particle hit a surface at a tangent. If
704
    // the particle is really traveling tangent to a surface, if we move it
705
    // forward a tiny bit it should fix the problem.
706

707
    surface() = SURFACE_NONE;
1,605✔
708
    n_coord() = 1;
1,605✔
709
    r() += TINY_BIT * u();
1,605✔
710

711
    // Couldn't find next cell anywhere! This probably means there is an actual
712
    // undefined region in the geometry.
713

714
    if (!exhaustive_find_cell(*this, verbose)) {
1,605!
715
      mark_as_lost("After particle " + std::to_string(id()) +
4,812✔
716
                   " crossed surface " + std::to_string(surf.id_) +
4,812✔
717
                   " it could not be located in any cell and it did not leak.");
718
      return;
1,602✔
719
    }
720
  }
721
}
722

723
void Particle::cross_vacuum_bc(const Surface& surf)
10,102,999✔
724
{
725
  // Score any surface current tallies -- note that the particle is moved
726
  // forward slightly so that if the mesh boundary is on the surface, it is
727
  // still processed
728

729
  if (!model::active_meshsurf_tallies.empty()) {
10,102,999✔
730
    // TODO: Find a better solution to score surface currents than
731
    // physically moving the particle forward slightly
732

733
    r() += TINY_BIT * u();
255,606✔
734
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
255,606✔
735
  }
736

737
  // Score to global leakage tally
738
  keff_tally_leakage() += wgt();
10,102,999✔
739

740
  // Kill the particle
741
  wgt() = 0.0;
10,102,999✔
742

743
  // Display message
744
  if (settings::verbosity >= 10 || trace()) {
10,102,999!
745
    write_message(1, "    Leaked out of surface {}", surf.id_);
6✔
746
  }
747
}
10,102,999✔
748

749
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
264,619,800✔
750
{
751
  // Do not handle reflective boundary conditions on lower universes
752
  if (n_coord() != 1) {
264,619,800!
UNCOV
753
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
754
                 " off surface in a lower universe.");
UNCOV
755
    return;
×
756
  }
757

758
  // Score surface currents since reflection causes the direction of the
759
  // particle to change. For surface filters, we need to score the tallies
760
  // twice, once before the particle's surface attribute has changed and
761
  // once after. For mesh surface filters, we need to artificially move
762
  // the particle slightly back in case the surface crossing is coincident
763
  // with a mesh boundary
764

765
  if (!model::active_surface_tallies.empty()) {
264,619,800✔
766
    Direction normal = surf.normal(r());
77,733✔
767
    normal /= normal.norm();
77,733✔
768
    score_surface_tally(*this, model::active_surface_tallies, normal);
77,733✔
769
  }
770

771
  if (!model::active_meshsurf_tallies.empty()) {
264,619,800✔
772
    Position r {this->r()};
12,786,951✔
773
    this->r() -= TINY_BIT * u();
12,786,951✔
774
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
12,786,951✔
775
    this->r() = r;
12,786,951✔
776
  }
777

778
  // Set the new particle direction
779
  u() = new_u;
264,619,800✔
780

781
  // Reassign particle's cell and surface
782
  coord(0).cell() = cell_last(0);
264,619,800✔
783
  surface() = -surface();
264,619,800✔
784

785
  // If a reflective surface is coincident with a lattice or universe
786
  // boundary, it is necessary to redetermine the particle's coordinates in
787
  // the lower universes.
788
  // (unless we're using a dagmc model, which has exactly one universe)
789
  n_coord() = 1;
264,619,800✔
790
  if (surf.geom_type() != GeometryType::DAG &&
529,239,600!
791
      !neighbor_list_find_cell(*this)) {
264,619,800✔
UNCOV
792
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
793
                 std::to_string(surf.id_) + ".");
×
UNCOV
794
    return;
×
795
  }
796

797
  // Set previous coordinate going slightly past surface crossing
798
  r_last_current() = r() + TINY_BIT * u();
264,619,800✔
799

800
  // Diagnostic message
801
  if (settings::verbosity >= 10 || trace()) {
264,619,800!
UNCOV
802
    write_message(1, "    Reflected from surface {}", surf.id_);
×
803
  }
804
}
805

806
void Particle::cross_periodic_bc(
613,077✔
807
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
808
{
809
  // Do not handle periodic boundary conditions on lower universes
810
  if (n_coord() != 1) {
613,077!
UNCOV
811
    mark_as_lost(
×
UNCOV
812
      "Cannot transfer particle " + std::to_string(id()) +
×
813
      " across surface in a lower universe. Boundary conditions must be "
814
      "applied to root universe.");
UNCOV
815
    return;
×
816
  }
817

818
  // Score surface currents since reflection causes the direction of the
819
  // particle to change -- artificially move the particle slightly back in
820
  // case the surface crossing is coincident with a mesh boundary
821
  if (!model::active_meshsurf_tallies.empty()) {
613,077!
UNCOV
822
    Position r {this->r()};
×
UNCOV
823
    this->r() -= TINY_BIT * u();
×
824
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
825
    this->r() = r;
×
826
  }
827

828
  // Adjust the particle's location and direction.
829
  r() = new_r;
613,077✔
830
  u() = new_u;
613,077✔
831

832
  // Reassign particle's surface
833
  surface() = new_surface;
613,077✔
834

835
  // Figure out what cell particle is in now
836
  n_coord() = 1;
613,077✔
837

838
  if (!neighbor_list_find_cell(*this)) {
613,077!
UNCOV
839
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
840
                 "boundary on surface " +
×
UNCOV
841
                 std::to_string(surf.id_) + ".");
×
UNCOV
842
    return;
×
843
  }
844

845
  // Set previous coordinate going slightly past surface crossing
846
  r_last_current() = r() + TINY_BIT * u();
613,077✔
847

848
  // Diagnostic message
849
  if (settings::verbosity >= 10 || trace()) {
613,077!
UNCOV
850
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
851
  }
852
}
853

854
void Particle::mark_as_lost(const char* message)
1,605✔
855
{
856
  // Print warning and write lost particle file
857
  warning(message);
1,605✔
858
  if (settings::max_write_lost_particles < 0 ||
1,605✔
859
      simulation::n_lost_particles < settings::max_write_lost_particles) {
1,500✔
860
    write_restart();
120✔
861
  }
862
  // Increment number of lost particles
863
  wgt() = 0.0;
1,605✔
864
#pragma omp atomic
865
  simulation::n_lost_particles += 1;
1,605✔
866

867
  // Count the total number of simulated particles (on this processor)
868
  auto n = simulation::current_batch * settings::gen_per_batch *
1,605✔
869
           simulation::work_per_rank;
870

871
  // Abort the simulation if the maximum number of lost particles has been
872
  // reached
873
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
1,605✔
874
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
3!
875
    fatal_error("Maximum number of lost particles has been reached.");
3✔
876
  }
877
}
1,602✔
878

879
void Particle::write_restart() const
120✔
880
{
881
  // Dont write another restart file if in particle restart mode
882
  if (settings::run_mode == RunMode::PARTICLE)
120✔
883
    return;
9✔
884

885
  // Set up file name
886
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
111✔
887
    simulation::current_batch, id());
111✔
888

889
#pragma omp critical(WriteParticleRestart)
890
  {
111✔
891
    // Create file
892
    hid_t file_id = file_open(filename, 'w');
111✔
893

894
    // Write filetype and version info
895
    write_attribute(file_id, "filetype", "particle restart");
111✔
896
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
111✔
897
    write_attribute(file_id, "openmc_version", VERSION);
111✔
898
#ifdef GIT_SHA1
899
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
900
#endif
901

902
    // Write data to file
903
    write_dataset(file_id, "current_batch", simulation::current_batch);
111✔
904
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
111✔
905
    write_dataset(file_id, "current_generation", simulation::current_gen);
111✔
906
    write_dataset(file_id, "n_particles", settings::n_particles);
111✔
907
    switch (settings::run_mode) {
111!
908
    case RunMode::FIXED_SOURCE:
75✔
909
      write_dataset(file_id, "run_mode", "fixed source");
75✔
910
      break;
911
    case RunMode::EIGENVALUE:
36✔
912
      write_dataset(file_id, "run_mode", "eigenvalue");
36✔
913
      break;
UNCOV
914
    case RunMode::PARTICLE:
×
UNCOV
915
      write_dataset(file_id, "run_mode", "particle restart");
×
916
      break;
917
    default:
918
      break;
919
    }
920
    write_dataset(file_id, "id", id());
111✔
921
    write_dataset(file_id, "type", type().pdg_number());
111✔
922

923
    // Get source site data for the particle that got lost
924
    int64_t i = current_work();
111✔
925
    SourceSite site;
111✔
926
    if (settings::run_mode == RunMode::EIGENVALUE) {
111✔
927
      site = simulation::source_bank[i];
36✔
928
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
75✔
929
               settings::use_shared_secondary_bank &&
75!
930
               i < simulation::shared_secondary_bank_read.size()) {
15!
UNCOV
931
      site = simulation::shared_secondary_bank_read[i];
×
932
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
75!
933
      // Re-sample using the same seed used to generate the source particle.
934
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
935
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
75✔
936
      uint64_t seed = init_seed(id, STREAM_SOURCE);
75✔
937
      site = sample_external_source(&seed);
75✔
938
    }
939
    write_dataset(file_id, "weight", site.wgt);
111✔
940
    write_dataset(file_id, "energy", site.E);
111✔
941
    write_dataset(file_id, "xyz", site.r);
111✔
942
    write_dataset(file_id, "uvw", site.u);
111✔
943
    write_dataset(file_id, "time", site.time);
111✔
944

945
    // Close file
946
    file_close(file_id);
111✔
947
  } // #pragma omp critical
948
}
111✔
949

950
void Particle::update_neutron_xs(
2,147,483,647✔
951
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
952
{
953
  // Get microscopic cross section cache
954
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
955

956
  // If the cache doesn't match, recalculate micro xs
957
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
1,405,382,417✔
958
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
959
      ncrystal_xs != micro.ncrystal_xs) {
1,374,678,641!
960
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
961

962
    // If NCrystal is being used, update micro cross section cache
963
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
964
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
965
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
3,005,169✔
966
      ncrystal_update_micro(ncrystal_xs, micro);
3,005,169✔
967
    }
968
  }
969
}
2,147,483,647✔
970

971
//==============================================================================
972
// Non-method functions
973
//==============================================================================
974
void add_surf_source_to_bank(Particle& p, const Surface& surf)
780,143,119✔
975
{
976
  if (simulation::current_batch <= settings::n_inactive ||
780,143,119✔
977
      simulation::surf_source_bank.full()) {
601,364,926✔
978
    return;
780,107,434✔
979
  }
980

981
  // If a cell/cellfrom/cellto parameter is defined
982
  if (settings::ssw_cell_id != C_NONE) {
95,634✔
983

984
    // Retrieve cell index and storage type
985
    int cell_idx = model::cell_map[settings::ssw_cell_id];
72,708✔
986

987
    if (surf.bc_) {
72,708✔
988
      // Leave if cellto with vacuum boundary condition
989
      if (surf.bc_->type() == "vacuum" &&
88,266✔
990
          settings::ssw_cell_type == SSWCellType::To) {
9,225✔
991
        return;
992
      }
993

994
      // Leave if other boundary condition than vacuum
995
      if (surf.bc_->type() != "vacuum") {
81,510✔
996
        return;
997
      }
998
    }
999

1000
    // Check if the cell of interest has been exited
1001
    bool exited = false;
1002
    for (int i = 0; i < p.n_coord_last(); ++i) {
92,682✔
1003
      if (p.cell_last(i) == cell_idx) {
58,260✔
1004
        exited = true;
20,664✔
1005
      }
1006
    }
1007

1008
    // Check if the cell of interest has been entered
1009
    bool entered = false;
1010
    for (int i = 0; i < p.n_coord(); ++i) {
82,404✔
1011
      if (p.coord(i).cell() == cell_idx) {
47,982✔
1012
        entered = true;
16,356✔
1013
      }
1014
    }
1015

1016
    // Vacuum boundary conditions: return if cell is not exited
1017
    if (surf.bc_) {
34,422✔
1018
      if (surf.bc_->type() == "vacuum" && !exited) {
11,694!
1019
        return;
1020
      }
1021
    } else {
1022

1023
      // If we both enter and exit the cell of interest
1024
      if (entered && exited) {
28,575✔
1025
        return;
1026
      }
1027

1028
      // If we did not enter nor exit the cell of interest
1029
      if (!entered && !exited) {
20,607✔
1030
        return;
1031
      }
1032

1033
      // If cellfrom and the cell before crossing is not the cell of
1034
      // interest
1035
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
17,484✔
1036
        return;
1037
      }
1038

1039
      // If cellto and the cell after crossing is not the cell of interest
1040
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
14,193✔
1041
        return;
1042
      }
1043
    }
1044
  }
1045

1046
  SourceSite site;
35,685✔
1047
  site.r = p.r();
35,685✔
1048
  site.u = p.u();
35,685✔
1049
  site.E = p.E();
35,685✔
1050
  site.time = p.time();
35,685✔
1051
  site.wgt = p.wgt();
35,685✔
1052
  site.delayed_group = p.delayed_group();
35,685✔
1053
  site.surf_id = surf.id_;
35,685✔
1054
  site.particle = p.type();
35,685✔
1055
  site.parent_id = p.id();
35,685✔
1056
  site.progeny_id = p.n_progeny();
35,685✔
1057
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
35,685✔
1058
}
1059

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