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

openmc-dev / openmc / 23893767470

02 Apr 2026 09:28AM UTC coverage: 81.134% (-0.3%) from 81.447%
23893767470

Pull #3877

github

web-flow
Merge 014dcc0e0 into 8223099ed
Pull Request #3877: Add VTKHDF output support for all structured mesh types (#3620)

17085 of 24531 branches covered (69.65%)

Branch coverage included in aggregate %.

110 of 128 new or added lines in 1 file covered. (85.94%)

473 existing lines in 25 files now uncovered.

57312 of 67165 relevant lines covered (85.33%)

40096836.11 hits per line

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

85.58
/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
2,147,483,647✔
48
{
49
  if (settings::run_CE) {
2,147,483,647✔
50
    // Determine mass in eV/c^2
51
    double mass;
1,872,943,563✔
52
    switch (type().pdg_number()) {
1,872,943,563✔
53
    case PDG_NEUTRON:
54
      mass = MASS_NEUTRON_EV;
55
    case PDG_ELECTRON:
56
    case PDG_POSITRON:
57
      mass = MASS_ELECTRON_EV;
1,872,943,563✔
58
    default:
1,872,943,563✔
59
      mass = this->type().mass() * AMU_EV;
1,872,943,563✔
60
    }
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,872,943,563✔
64
           (this->E() + mass);
1,872,943,563✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,688,676,066✔
67
    int macro_t = this->mg_xs_cache().t;
1,688,676,066✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
1,688,676,066✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,688,676,066✔
70
                   nullptr, nullptr, macro_t, macro_a);
1,688,676,066✔
71
  }
72
}
73

74
bool Particle::create_secondary(
92,182,019✔
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
  int idx = type.transport_index();
92,182,019✔
80
  if (idx == C_NONE) {
92,182,019!
81
    return false;
82
  }
83
  if (E < settings::energy_cutoff[idx]) {
92,182,019✔
84
    return false;
85
  }
86

87
  // Increment number of secondaries created (for ParticleProductionFilter)
88
  n_secondaries()++;
48,191,985✔
89

90
  auto& bank = secondary_bank().emplace_back();
48,191,985✔
91
  bank.particle = type;
48,191,985✔
92
  bank.wgt = wgt;
48,191,985✔
93
  bank.r = r();
48,191,985!
94
  bank.u = u;
48,191,985✔
95
  bank.E = settings::run_CE ? E : g();
48,191,985!
96
  bank.time = time();
48,191,985✔
97
  bank_second_E() += bank.E;
48,191,985✔
98
  return true;
48,191,985✔
99
}
100

101
void Particle::split(double wgt)
3,474,261✔
102
{
103
  auto& bank = secondary_bank().emplace_back();
3,474,261✔
104
  bank.particle = type();
3,474,261✔
105
  bank.wgt = wgt;
3,474,261✔
106
  bank.r = r();
3,474,261✔
107
  bank.u = u();
3,474,261✔
108
  bank.E = settings::run_CE ? E() : g();
3,474,261✔
109
  bank.time = time();
3,474,261✔
110

111
  // Convert signed index to a signed surface ID
112
  if (surface() == SURFACE_NONE) {
3,474,261✔
113
    bank.surf_id = SURFACE_NONE;
3,474,090✔
114
  } else {
115
    int surf_id = model::surfaces[surface_index()]->id_;
171!
116
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
171!
117
  }
118
}
3,474,261✔
119

120
void Particle::from_source(const SourceSite* src)
196,910,162✔
121
{
122
  // Reset some attributes
123
  clear();
196,910,162✔
124
  surface() = SURFACE_NONE;
196,910,162✔
125
  cell_born() = C_NONE;
196,910,162✔
126
  material() = C_NONE;
196,910,162✔
127
  n_collision() = 0;
196,910,162✔
128
  fission() = false;
196,910,162✔
129
  zero_flux_derivs();
196,910,162✔
130
  lifetime() = 0.0;
196,910,162✔
131
#ifdef OPENMC_DAGMC_ENABLED
132
  history().reset();
133
#endif
134

135
  // Copy attributes from source bank site
136
  type() = src->particle;
196,910,162✔
137
  wgt() = src->wgt;
196,910,162✔
138
  wgt_last() = src->wgt;
196,910,162✔
139
  r() = src->r;
196,910,162✔
140
  u() = src->u;
196,910,162✔
141
  r_born() = src->r;
196,910,162✔
142
  r_last_current() = src->r;
196,910,162✔
143
  r_last() = src->r;
196,910,162✔
144
  u_last() = src->u;
196,910,162✔
145
  if (settings::run_CE) {
196,910,162✔
146
    E() = src->E;
102,062,519✔
147
    g() = 0;
102,062,519✔
148
  } else {
149
    g() = static_cast<int>(src->E);
94,847,643✔
150
    g_last() = static_cast<int>(src->E);
94,847,643✔
151
    E() = data::mg.energy_bin_avg_[g()];
94,847,643✔
152
  }
153
  E_last() = E();
196,910,162✔
154
  time() = src->time;
196,910,162✔
155
  time_last() = src->time;
196,910,162✔
156
  parent_nuclide() = src->parent_nuclide;
196,910,162✔
157
  delayed_group() = src->delayed_group;
196,910,162✔
158

159
  // Convert signed surface ID to signed index
160
  if (src->surf_id != SURFACE_NONE) {
196,910,162✔
161
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
90,171✔
162
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
90,171✔
163
  }
164
}
196,910,162✔
165

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

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

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

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

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
189,816,371!
195
      cell_born() = lowest_coord().cell();
189,816,371✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
393,925,504✔
199
      cell_last(j) = coord(j).cell();
204,109,133✔
200
    }
201
    n_coord_last() = n_coord();
189,816,371✔
202
  }
203

204
  // Write particle track.
205
  if (write_track())
2,147,483,647✔
206
    write_particle_track(*this);
7,745✔
207

208
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
209
    check_cell_overlap(*this);
×
210

211
  // Calculate microscopic and macroscopic cross sections
212
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
213
    if (settings::run_CE) {
2,147,483,647✔
214
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,758,994,605✔
215
          density_mult() != density_mult_last()) {
304,852,851✔
216
        // If the material is the same as the last material and the
217
        // temperature hasn't changed, we don't need to lookup cross
218
        // sections again.
219
        model::materials[material()]->calculate_xs(*this);
1,454,149,602✔
220
      }
221
    } else {
222
      // Get the MG data; unlike the CE case above, we have to re-calculate
223
      // cross sections for every collision since the cross sections may
224
      // be angle-dependent
225
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,688,676,066✔
226

227
      // Update the particle's group while we know we are multi-group
228
      g_last() = g();
1,688,676,066✔
229
    }
230
  } else {
231
    macro_xs().total = 0.0;
91,492,599✔
232
    macro_xs().absorption = 0.0;
91,492,599✔
233
    macro_xs().fission = 0.0;
91,492,599✔
234
    macro_xs().nu_fission = 0.0;
91,492,599✔
235
  }
236
}
237

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

243
  // Sample a distance to collision
244
  if (type() == ParticleType::electron() ||
2,147,483,647✔
245
      type() == ParticleType::positron()) {
2,147,483,647✔
246
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
88,623,562!
247
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
248
    collision_distance() = INFINITY;
91,492,599✔
249
  } else {
250
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
251
  }
252

253
  double speed = this->speed();
2,147,483,647✔
254
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
255
  double distance_cutoff =
2,147,483,647✔
256
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
257

258
  // Select smaller of the three distances
259
  double distance =
2,147,483,647✔
260
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
261

262
  // Advance particle in space and time
263
  this->move_distance(distance);
2,147,483,647✔
264
  double dt = distance / speed;
2,147,483,647✔
265
  this->time() += dt;
2,147,483,647✔
266
  this->lifetime() += dt;
2,147,483,647✔
267

268
  // Score timed track-length tallies
269
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
270
    score_timed_tracklength_tally(*this, distance);
2,968,623✔
271
  }
272

273
  // Score track-length tallies
274
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
275
    score_tracklength_tally(*this, distance);
1,398,254,683✔
276
  }
277

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

283
  // Score flux derivative accumulators for differential tallies.
284
  if (!model::active_tallies.empty()) {
2,147,483,647✔
285
    score_track_derivative(*this, distance);
1,535,259,134✔
286
  }
287

288
  // Set particle weight to zero if it hit the time boundary
289
  if (distance == distance_cutoff) {
2,147,483,647✔
290
    wgt() = 0.0;
184,032✔
291
  }
292
}
2,147,483,647✔
293

294
void Particle::event_cross_surface()
1,971,102,615✔
295
{
296
  // Saving previous cell data
297
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
298
    cell_last(j) = coord(j).cell();
2,147,483,647✔
299
  }
300
  n_coord_last() = n_coord();
1,971,102,615✔
301

302
  // Set surface that particle is on and adjust coordinate levels
303
  surface() = boundary().surface();
1,971,102,615✔
304
  n_coord() = boundary().coord_level();
1,971,102,615✔
305

306
  if (boundary().lattice_translation()[0] != 0 ||
1,971,102,615✔
307
      boundary().lattice_translation()[1] != 0 ||
1,971,102,615✔
308
      boundary().lattice_translation()[2] != 0) {
1,521,336,613✔
309
    // Particle crosses lattice boundary
310

311
    bool verbose = settings::verbosity >= 10 || trace();
604,026,403!
312
    cross_lattice(*this, boundary(), verbose);
604,026,403✔
313
    event() = TallyEvent::LATTICE;
604,026,403✔
314

315
    // Score cell to cell partial currents
316
    if (!model::active_surface_tallies.empty()) {
604,026,403!
UNCOV
317
      auto& lat {*model::lattices[lowest_coord().lattice()]};
×
UNCOV
318
      bool is_valid;
×
UNCOV
319
      Direction normal =
×
UNCOV
320
        lat.get_normal(boundary().lattice_translation(), is_valid);
×
UNCOV
321
      if (is_valid) {
×
UNCOV
322
        normal /= normal.norm();
×
UNCOV
323
        score_surface_tally(*this, model::active_surface_tallies, normal);
×
324
      }
325
    }
326

327
  } else {
328

329
    const auto& surf {*model::surfaces[surface_index()].get()};
1,367,076,212✔
330

331
    // Particle crosses surface
332
    // If BC, add particle to surface source before crossing surface
333
    if (surf.surf_source_ && surf.bc_) {
1,367,076,212✔
334
      add_surf_source_to_bank(*this, surf);
588,914,822✔
335
    }
336
    this->cross_surface(surf);
1,367,076,212✔
337
    // If no BC, add particle to surface source after crossing surface
338
    if (surf.surf_source_ && !surf.bc_) {
1,367,076,204✔
339
      add_surf_source_to_bank(*this, surf);
777,162,569✔
340
    }
341
    if (settings::weight_window_checkpoint_surface) {
1,367,076,204✔
342
      apply_weight_windows(*this);
52,506✔
343
    }
344
    event() = TallyEvent::SURFACE;
1,367,076,204✔
345

346
    // Score cell to cell partial currents
347
    if (!model::active_surface_tallies.empty()) {
1,367,076,204✔
348
      Direction normal = surf.normal(r());
28,580,373✔
349
      normal /= normal.norm();
28,580,373✔
350
      score_surface_tally(*this, model::active_surface_tallies, normal);
28,580,373✔
351
    }
352
  }
353
}
1,971,102,607✔
354

355
void Particle::event_collide()
2,147,483,647✔
356
{
357

358
  // Score collision estimate of keff
359
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
360
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,750,451,720✔
361
  }
362

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

367
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
368
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
51,626,394✔
369

370
  // Clear surface component
371
  surface() = SURFACE_NONE;
2,147,483,647✔
372

373
  if (settings::run_CE) {
2,147,483,647✔
374
    collision(*this);
873,713,166✔
375
  } else {
376
    collision_mg(*this);
1,458,867,663✔
377
  }
378

379
  // Collision track feature to recording particle interaction
380
  if (settings::collision_track) {
2,147,483,647✔
381
    collision_track_record(*this);
122,489✔
382
  }
383

384
  // Score collision estimator tallies -- this is done after a collision
385
  // has occurred rather than before because we need information on the
386
  // outgoing energy for any tallies with an outgoing energy filter
387
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
388
    score_collision_tally(*this);
86,639,525✔
389
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
390
    if (settings::run_CE) {
332,017,677✔
391
      score_analog_tally_ce(*this);
331,029,099✔
392
    } else {
393
      score_analog_tally_mg(*this);
988,578✔
394
    }
395
  }
396

397
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
398
    pht_collision_energy();
1,656✔
399
  }
400

401
  // Reset banked weight during collision
402
  n_bank() = 0;
2,147,483,647✔
403
  bank_second_E() = 0.0;
2,147,483,647✔
404
  wgt_bank() = 0.0;
2,147,483,647✔
405

406
  // Clear number of secondaries in this collision. This is
407
  // distinct from the number of created neutrons n_bank() above!
408
  n_secondaries() = 0;
2,147,483,647✔
409

410
  zero_delayed_bank();
2,147,483,647✔
411

412
  // Reset fission logical
413
  fission() = false;
2,147,483,647✔
414

415
  // Save coordinates for tallying purposes
416
  r_last_current() = r();
2,147,483,647✔
417

418
  // Set last material to none since cross sections will need to be
419
  // re-evaluated
420
  material_last() = C_NONE;
2,147,483,647✔
421

422
  // Set all directions to base level -- right now, after a collision, only
423
  // the base level directions are changed
424
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
425
    if (coord(j + 1).rotated()) {
131,814,528✔
426
      // If next level is rotated, apply rotation matrix
427
      const auto& m {model::cells[coord(j).cell()]->rotation_};
8,530,866✔
428
      const auto& u {coord(j).u()};
8,530,866✔
429
      coord(j + 1).u() = u.rotate(m);
8,530,866✔
430
    } else {
431
      // Otherwise, copy this level's direction
432
      coord(j + 1).u() = coord(j).u();
123,283,662✔
433
    }
434
  }
435

436
  // Score flux derivative accumulators for differential tallies.
437
  if (!model::active_tallies.empty())
2,147,483,647✔
438
    score_collision_derivative(*this);
763,808,279✔
439

440
#ifdef OPENMC_DAGMC_ENABLED
441
  history().reset();
442
#endif
443
}
2,147,483,647✔
444

445
void Particle::event_revive_from_secondary()
2,147,483,647✔
446
{
447
  // If particle has too many events, display warning and kill it
448
  ++n_event();
2,147,483,647✔
449
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
UNCOV
450
    warning("Particle " + std::to_string(id()) +
×
451
            " underwent maximum number of events.");
UNCOV
452
    wgt() = 0.0;
×
453
  }
454

455
  // Check for secondary particles if this particle is dead
456
  if (!alive()) {
2,147,483,647✔
457
    // Write final position for this particle
458
    if (write_track()) {
189,815,858✔
459
      write_particle_track(*this);
4,544✔
460
    }
461

462
    // If no secondary particles, break out of event loop
463
    if (secondary_bank().empty())
189,815,858✔
464
      return;
465

466
    from_source(&secondary_bank().back());
51,722,245✔
467
    secondary_bank().pop_back();
51,722,245✔
468
    n_event() = 0;
51,722,245✔
469
    bank_second_E() = 0.0;
51,722,245✔
470

471
    // Subtract secondary particle energy from interim pulse-height results
472
    if (!model::active_pulse_height_tallies.empty() &&
51,722,245✔
473
        this->type().is_photon()) {
12,681✔
474
      // Since the birth cell of the particle has not been set we
475
      // have to determine it before the energy of the secondary particle can be
476
      // removed from the pulse-height of this cell.
477
      if (lowest_coord().cell() == C_NONE) {
495!
478
        bool verbose = settings::verbosity >= 10 || trace();
495!
479
        if (!exhaustive_find_cell(*this, verbose)) {
495!
UNCOV
480
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
481
                       std::to_string(id()));
×
UNCOV
482
          return;
×
483
        }
484
        // Set birth cell attribute
485
        if (cell_born() == C_NONE)
495!
486
          cell_born() = lowest_coord().cell();
495✔
487

488
        // Initialize last cells from current cell
489
        for (int j = 0; j < n_coord(); ++j) {
990✔
490
          cell_last(j) = coord(j).cell();
495✔
491
        }
492
        n_coord_last() = n_coord();
495✔
493
      }
494
      pht_secondary_particles();
495✔
495
    }
496

497
    // Enter new particle in particle track file
498
    if (write_track())
51,722,245✔
499
      add_particle_track(*this);
3,794✔
500
  }
501
}
502

503
void Particle::event_death()
138,094,613✔
504
{
505
#ifdef OPENMC_DAGMC_ENABLED
506
  history().reset();
507
#endif
508

509
  // Finish particle track output.
510
  if (write_track()) {
138,094,613✔
511
    finalize_particle_track(*this);
750✔
512
  }
513

514
// Contribute tally reduction variables to global accumulator
515
#pragma omp atomic
62,162,571✔
516
  global_tally_absorption += keff_tally_absorption();
138,094,613✔
517
#pragma omp atomic
62,553,718✔
518
  global_tally_collision += keff_tally_collision();
138,094,613✔
519
#pragma omp atomic
62,145,486✔
520
  global_tally_tracklength += keff_tally_tracklength();
138,094,613✔
521
#pragma omp atomic
61,608,722✔
522
  global_tally_leakage += keff_tally_leakage();
138,094,613✔
523

524
  // Reset particle tallies once accumulated
525
  keff_tally_absorption() = 0.0;
138,094,613✔
526
  keff_tally_collision() = 0.0;
138,094,613✔
527
  keff_tally_tracklength() = 0.0;
138,094,613✔
528
  keff_tally_leakage() = 0.0;
138,094,613✔
529

530
  if (!model::active_pulse_height_tallies.empty()) {
138,094,613✔
531
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
4,500✔
532
  }
533

534
  // Record the number of progeny created by this particle.
535
  // This data will be used to efficiently sort the fission bank.
536
  if (settings::run_mode == RunMode::EIGENVALUE) {
138,094,613✔
537
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
115,795,800✔
538
    simulation::progeny_per_particle[offset] = n_progeny();
115,795,800✔
539
  }
540
}
138,094,613✔
541

542
void Particle::pht_collision_energy()
1,656✔
543
{
544
  // Adds the energy particles lose in a collision to the pulse-height
545

546
  // determine index of cell in pulse_height_cells
547
  auto it = std::find(model::pulse_height_cells.begin(),
1,656✔
548
    model::pulse_height_cells.end(), lowest_coord().cell());
1,656!
549

550
  if (it != model::pulse_height_cells.end()) {
1,656!
551
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,656✔
552
    pht_storage()[index] += E_last() - E();
1,656✔
553

554
    // If the energy of the particle is below the cutoff, it will not be sampled
555
    // so its energy is added to the pulse-height in the cell
556
    int photon = ParticleType::photon().transport_index();
1,656✔
557
    if (E() < settings::energy_cutoff[photon]) {
1,656✔
558
      pht_storage()[index] += E();
675✔
559
    }
560
  }
561
}
1,656✔
562

563
void Particle::pht_secondary_particles()
495✔
564
{
565
  // Removes the energy of secondary produced particles from the pulse-height
566

567
  // determine index of cell in pulse_height_cells
568
  auto it = std::find(model::pulse_height_cells.begin(),
495✔
569
    model::pulse_height_cells.end(), cell_born());
495!
570

571
  if (it != model::pulse_height_cells.end()) {
495!
572
    int index = std::distance(model::pulse_height_cells.begin(), it);
495✔
573
    pht_storage()[index] -= E();
495✔
574
  }
575
}
495✔
576

577
void Particle::cross_surface(const Surface& surf)
1,368,659,690✔
578
{
579

580
  if (settings::verbosity >= 10 || trace()) {
1,368,659,690✔
581
    write_message(1, "    Crossing surface {}", surf.id_);
54✔
582
  }
583

584
// if we're crossing a CSG surface, make sure the DAG history is reset
585
#ifdef OPENMC_DAGMC_ENABLED
586
  if (surf.geom_type() == GeometryType::CSG)
587
    history().reset();
588
#endif
589

590
  // Handle any applicable boundary conditions.
591
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,368,659,690!
592
      settings::run_mode != RunMode::VOLUME) {
593
    surf.bc_->handle_particle(*this, surf);
589,199,968✔
594
    return;
589,199,968✔
595
  }
596

597
  // ==========================================================================
598
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
599

600
#ifdef OPENMC_DAGMC_ENABLED
601
  // in DAGMC, we know what the next cell should be
602
  if (surf.geom_type() == GeometryType::DAG) {
603
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
604
                       lowest_coord().universe()) -
605
                     1;
606
    // save material, temperature, and density multiplier
607
    material_last() = material();
608
    sqrtkT_last() = sqrtkT();
609
    density_mult_last() = density_mult();
610
    // set new cell value
611
    lowest_coord().cell() = i_cell;
612
    auto& cell = model::cells[i_cell];
613

614
    cell_instance() = 0;
615
    if (cell->distribcell_index_ >= 0)
616
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
617

618
    material() = cell->material(cell_instance());
619
    sqrtkT() = cell->sqrtkT(cell_instance());
620
    density_mult() = cell->density_mult(cell_instance());
621
    return;
622
  }
623
#endif
624

625
  bool verbose = settings::verbosity >= 10 || trace();
779,459,722!
626
  if (neighbor_list_find_cell(*this, verbose)) {
779,459,722✔
627
    return;
628
  }
629

630
  // ==========================================================================
631
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
632

633
  // Remove lower coordinate levels
634
  n_coord() = 1;
24,479✔
635
  bool found = exhaustive_find_cell(*this, verbose);
24,479✔
636

637
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
24,479!
638
    // If a cell is still not found, there are two possible causes: 1) there is
639
    // a void in the model, and 2) the particle hit a surface at a tangent. If
640
    // the particle is really traveling tangent to a surface, if we move it
641
    // forward a tiny bit it should fix the problem.
642

643
    surface() = SURFACE_NONE;
4,751✔
644
    n_coord() = 1;
4,751✔
645
    r() += TINY_BIT * u();
4,751✔
646

647
    // Couldn't find next cell anywhere! This probably means there is an actual
648
    // undefined region in the geometry.
649

650
    if (!exhaustive_find_cell(*this, verbose)) {
4,751!
651
      mark_as_lost("After particle " + std::to_string(id()) +
14,245✔
652
                   " crossed surface " + std::to_string(surf.id_) +
14,245✔
653
                   " it could not be located in any cell and it did not leak.");
654
      return;
4,743✔
655
    }
656
  }
657
}
658

659
void Particle::cross_vacuum_bc(const Surface& surf)
28,547,946✔
660
{
661
  // Score any surface current tallies -- note that the particle is moved
662
  // forward slightly so that if the mesh boundary is on the surface, it is
663
  // still processed
664

665
  if (!model::active_meshsurf_tallies.empty()) {
28,547,946✔
666
    // TODO: Find a better solution to score surface currents than
667
    // physically moving the particle forward slightly
668

669
    r() += TINY_BIT * u();
766,818✔
670
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
766,818✔
671
  }
672

673
  // Score to global leakage tally
674
  keff_tally_leakage() += wgt();
28,547,946✔
675

676
  // Kill the particle
677
  wgt() = 0.0;
28,547,946✔
678

679
  // Display message
680
  if (settings::verbosity >= 10 || trace()) {
28,547,946!
681
    write_message(1, "    Leaked out of surface {}", surf.id_);
18✔
682
  }
683
}
28,547,946✔
684

685
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
559,638,070✔
686
{
687
  // Do not handle reflective boundary conditions on lower universes
688
  if (n_coord() != 1) {
559,638,070!
UNCOV
689
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
690
                 " off surface in a lower universe.");
UNCOV
691
    return;
×
692
  }
693

694
  // Score surface currents since reflection causes the direction of the
695
  // particle to change. For surface filters, we need to score the tallies
696
  // twice, once before the particle's surface attribute has changed and
697
  // once after. For mesh surface filters, we need to artificially move
698
  // the particle slightly back in case the surface crossing is coincident
699
  // with a mesh boundary
700

701
  if (!model::active_surface_tallies.empty()) {
559,638,070✔
702
    Direction normal = surf.normal(r());
233,199✔
703
    normal /= normal.norm();
233,199✔
704
    score_surface_tally(*this, model::active_surface_tallies, normal);
233,199✔
705
  }
706

707
  if (!model::active_meshsurf_tallies.empty()) {
559,638,070✔
708
    Position r {this->r()};
38,360,853✔
709
    this->r() -= TINY_BIT * u();
38,360,853✔
710
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
38,360,853✔
711
    this->r() = r;
38,360,853✔
712
  }
713

714
  // Set the new particle direction
715
  u() = new_u;
559,638,070✔
716

717
  // Reassign particle's cell and surface
718
  coord(0).cell() = cell_last(0);
559,638,070✔
719
  surface() = -surface();
559,638,070✔
720

721
  // If a reflective surface is coincident with a lattice or universe
722
  // boundary, it is necessary to redetermine the particle's coordinates in
723
  // the lower universes.
724
  // (unless we're using a dagmc model, which has exactly one universe)
725
  n_coord() = 1;
559,638,070✔
726
  if (surf.geom_type() != GeometryType::DAG &&
1,119,276,140!
727
      !neighbor_list_find_cell(*this)) {
559,638,070✔
728
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
729
                 std::to_string(surf.id_) + ".");
×
UNCOV
730
    return;
×
731
  }
732

733
  // Set previous coordinate going slightly past surface crossing
734
  r_last_current() = r() + TINY_BIT * u();
559,638,070✔
735

736
  // Diagnostic message
737
  if (settings::verbosity >= 10 || trace()) {
559,638,070!
738
    write_message(1, "    Reflected from surface {}", surf.id_);
×
739
  }
740
}
741

742
void Particle::cross_periodic_bc(
1,836,606✔
743
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
744
{
745
  // Do not handle periodic boundary conditions on lower universes
746
  if (n_coord() != 1) {
1,836,606!
UNCOV
747
    mark_as_lost(
×
UNCOV
748
      "Cannot transfer particle " + std::to_string(id()) +
×
749
      " across surface in a lower universe. Boundary conditions must be "
750
      "applied to root universe.");
UNCOV
751
    return;
×
752
  }
753

754
  // Score surface currents since reflection causes the direction of the
755
  // particle to change -- artificially move the particle slightly back in
756
  // case the surface crossing is coincident with a mesh boundary
757
  if (!model::active_meshsurf_tallies.empty()) {
1,836,606!
758
    Position r {this->r()};
×
UNCOV
759
    this->r() -= TINY_BIT * u();
×
UNCOV
760
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
761
    this->r() = r;
×
762
  }
763

764
  // Adjust the particle's location and direction.
765
  r() = new_r;
1,836,606✔
766
  u() = new_u;
1,836,606✔
767

768
  // Reassign particle's surface
769
  surface() = new_surface;
1,836,606✔
770

771
  // Figure out what cell particle is in now
772
  n_coord() = 1;
1,836,606✔
773

774
  if (!neighbor_list_find_cell(*this)) {
1,836,606!
UNCOV
775
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
776
                 "boundary on surface " +
×
UNCOV
777
                 std::to_string(surf.id_) + ".");
×
UNCOV
778
    return;
×
779
  }
780

781
  // Set previous coordinate going slightly past surface crossing
782
  r_last_current() = r() + TINY_BIT * u();
1,836,606✔
783

784
  // Diagnostic message
785
  if (settings::verbosity >= 10 || trace()) {
1,836,606!
UNCOV
786
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
787
  }
788
}
789

790
void Particle::mark_as_lost(const char* message)
4,751✔
791
{
792
  // Print warning and write lost particle file
793
  warning(message);
4,751✔
794
  if (settings::max_write_lost_particles < 0 ||
4,751✔
795
      simulation::n_lost_particles < settings::max_write_lost_particles) {
4,500✔
796
    write_restart();
306✔
797
  }
798
  // Increment number of lost particles
799
  wgt() = 0.0;
4,751✔
800
#pragma omp atomic
2,106✔
801
  simulation::n_lost_particles += 1;
2,645✔
802

803
  // Count the total number of simulated particles (on this processor)
804
  auto n = simulation::current_batch * settings::gen_per_batch *
4,751✔
805
           simulation::work_per_rank;
806

807
  // Abort the simulation if the maximum number of lost particles has been
808
  // reached
809
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
4,751✔
810
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
8!
811
    fatal_error("Maximum number of lost particles has been reached.");
8✔
812
  }
813
}
4,743✔
814

815
void Particle::write_restart() const
306✔
816
{
817
  // Dont write another restart file if in particle restart mode
818
  if (settings::run_mode == RunMode::PARTICLE)
306✔
819
    return;
18✔
820

821
  // Set up file name
822
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
288✔
823
    simulation::current_batch, id());
288✔
824

825
#pragma omp critical(WriteParticleRestart)
123✔
826
  {
288✔
827
    // Create file
828
    hid_t file_id = file_open(filename, 'w');
288✔
829

830
    // Write filetype and version info
831
    write_attribute(file_id, "filetype", "particle restart");
288✔
832
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
288✔
833
    write_attribute(file_id, "openmc_version", VERSION);
288✔
834
#ifdef GIT_SHA1
835
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
836
#endif
837

838
    // Write data to file
839
    write_dataset(file_id, "current_batch", simulation::current_batch);
288✔
840
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
288✔
841
    write_dataset(file_id, "current_generation", simulation::current_gen);
288✔
842
    write_dataset(file_id, "n_particles", settings::n_particles);
288✔
843
    switch (settings::run_mode) {
288!
844
    case RunMode::FIXED_SOURCE:
180✔
845
      write_dataset(file_id, "run_mode", "fixed source");
180✔
846
      break;
75✔
847
    case RunMode::EIGENVALUE:
108✔
848
      write_dataset(file_id, "run_mode", "eigenvalue");
108✔
849
      break;
48✔
UNCOV
850
    case RunMode::PARTICLE:
×
UNCOV
851
      write_dataset(file_id, "run_mode", "particle restart");
×
852
      break;
853
    default:
854
      break;
855
    }
856
    write_dataset(file_id, "id", id());
288✔
857
    write_dataset(file_id, "type", type().pdg_number());
288✔
858

859
    int64_t i = current_work();
288✔
860
    if (settings::run_mode == RunMode::EIGENVALUE) {
288✔
861
      // take source data from primary bank for eigenvalue simulation
862
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
108✔
863
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
108✔
864
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
108✔
865
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
108✔
866
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
108✔
867
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
180!
868
      // re-sample using rng random number seed used to generate source particle
869
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
180✔
870
                     settings::n_particles +
180✔
871
                   simulation::work_index[mpi::rank] + i;
180✔
872
      uint64_t seed = init_seed(id, STREAM_SOURCE);
180✔
873
      // re-sample source site
874
      auto site = sample_external_source(&seed);
180✔
875
      write_dataset(file_id, "weight", site.wgt);
180✔
876
      write_dataset(file_id, "energy", site.E);
180✔
877
      write_dataset(file_id, "xyz", site.r);
180✔
878
      write_dataset(file_id, "uvw", site.u);
180✔
879
      write_dataset(file_id, "time", site.time);
180✔
880
    }
881

882
    // Close file
883
    file_close(file_id);
288✔
884
  } // #pragma omp critical
885
}
288✔
886

887
void Particle::update_neutron_xs(
2,147,483,647✔
888
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
889
{
890
  // Get microscopic cross section cache
891
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
892

893
  // If the cache doesn't match, recalculate micro xs
894
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
895
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
896
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
897
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
898

899
    // If NCrystal is being used, update micro cross section cache
900
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
901
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
902
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
9,015,507✔
903
      ncrystal_update_micro(ncrystal_xs, micro);
9,015,507✔
904
    }
905
  }
906
}
2,147,483,647✔
907

908
//==============================================================================
909
// Non-method functions
910
//==============================================================================
911
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,366,077,391✔
912
{
913
  if (simulation::current_batch <= settings::n_inactive ||
1,366,077,391✔
914
      simulation::surf_source_bank.full()) {
1,050,710,836✔
915
    return;
1,365,975,632✔
916
  }
917

918
  // If a cell/cellfrom/cellto parameter is defined
919
  if (settings::ssw_cell_id != C_NONE) {
263,324✔
920

921
    // Retrieve cell index and storage type
922
    int cell_idx = model::cell_map[settings::ssw_cell_id];
197,196✔
923

924
    if (surf.bc_) {
197,196✔
925
      // Leave if cellto with vacuum boundary condition
926
      if (surf.bc_->type() == "vacuum" &&
236,676✔
927
          settings::ssw_cell_type == SSWCellType::To) {
25,250✔
928
        return;
929
      }
930

931
      // Leave if other boundary condition than vacuum
932
      if (surf.bc_->type() != "vacuum") {
218,660✔
933
        return;
934
      }
935
    }
936

937
    // Check if the cell of interest has been exited
938
    bool exited = false;
939
    for (int i = 0; i < p.n_coord_last(); ++i) {
255,499✔
940
      if (p.cell_last(i) == cell_idx) {
160,399✔
941
        exited = true;
57,278✔
942
      }
943
    }
944

945
    // Check if the cell of interest has been entered
946
    bool entered = false;
947
    for (int i = 0; i < p.n_coord(); ++i) {
227,053✔
948
      if (p.coord(i).cell() == cell_idx) {
131,953✔
949
        entered = true;
45,091✔
950
      }
951
    }
952

953
    // Vacuum boundary conditions: return if cell is not exited
954
    if (surf.bc_) {
95,100✔
955
      if (surf.bc_->type() == "vacuum" && !exited) {
32,484!
956
        return;
957
      }
958
    } else {
959

960
      // If we both enter and exit the cell of interest
961
      if (entered && exited) {
78,858✔
962
        return;
963
      }
964

965
      // If we did not enter nor exit the cell of interest
966
      if (!entered && !exited) {
56,967✔
967
        return;
968
      }
969

970
      // If cellfrom and the cell before crossing is not the cell of
971
      // interest
972
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
48,387✔
973
        return;
974
      }
975

976
      // If cellto and the cell after crossing is not the cell of interest
977
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
39,398✔
978
        return;
979
      }
980
    }
981
  }
982

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

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