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

openmc-dev / openmc / 21621876490

03 Feb 2026 07:57AM UTC coverage: 81.649% (-0.1%) from 81.763%
21621876490

Pull #3742

github

web-flow
Merge 43429dda7 into b41e22f68
Pull Request #3742: Implement surface flux tallies

17340 of 24301 branches covered (71.36%)

Branch coverage included in aggregate %.

88 of 112 new or added lines in 5 files covered. (78.57%)

120 existing lines in 2 files now uncovered.

55994 of 65515 relevant lines covered (85.47%)

44167731.02 hits per line

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

85.28
/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/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

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

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (this->type().pdg_number()) {
2,113,859,850!
52
    case PDG_NEUTRON:
2,038,597,000✔
53
      mass = MASS_NEUTRON_EV;
2,038,597,000✔
54
      break;
2,038,597,000✔
55
    case PDG_PHOTON:
21,805,147✔
56
      mass = 0.0;
21,805,147✔
57
      break;
21,805,147✔
58
    case PDG_ELECTRON:
53,457,703✔
59
    case PDG_POSITRON:
60
      mass = MASS_ELECTRON_EV;
53,457,703✔
61
      break;
53,457,703✔
62
    default:
×
63
      fatal_error("Unsupported particle for speed calculation.");
×
64
    }
65
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
66
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,113,859,850✔
67
           (this->E() + mass);
2,113,859,850✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
70
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
73
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
74
  }
75
}
76

77
bool Particle::create_secondary(
111,514,376✔
78
  double wgt, Direction u, double E, ParticleType type)
79
{
80
  // If energy is below cutoff for this particle, don't create secondary
81
  // particle
82
  int idx = type.transport_index();
111,514,376✔
83
  if (idx == C_NONE) {
111,514,376!
84
    return false;
×
85
  }
86
  if (E < settings::energy_cutoff[idx]) {
111,514,376✔
87
    return false;
53,304,396✔
88
  }
89

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

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

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

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

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

159
  // Convert signed surface ID to signed index
160
  if (src->surf_id != SURFACE_NONE) {
238,061,654✔
161
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
162
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
163
  }
164
}
238,061,654✔
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)) {
229,577,745!
188
      mark_as_lost(
×
189
        "Could not find the cell containing particle " + std::to_string(id()));
×
190
      return;
×
191
    }
192

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
229,577,745!
195
      cell_born() = lowest_coord().cell();
229,577,745✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
476,180,170✔
199
      cell_last(j) = coord(j).cell();
246,602,425✔
200
    }
201
    n_coord_last() = n_coord();
229,577,745✔
202
  }
203

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

208
  if (settings::check_overlaps)
2,147,483,647!
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() ||
2,147,483,647✔
215
          density_mult() != density_mult_last()) {
365,032,184✔
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,609,565,539✔
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);
2,063,937,414✔
226

227
      // Update the particle's group while we know we are multi-group
228
      g_last() = g();
2,063,937,414✔
229
    }
230
  } else {
231
    macro_xs().total = 0.0;
111,825,058✔
232
    macro_xs().absorption = 0.0;
111,825,058✔
233
    macro_xs().fission = 0.0;
111,825,058✔
234
    macro_xs().nu_fission = 0.0;
111,825,058✔
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;
53,457,703!
247
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
248
    collision_distance() = INFINITY;
111,825,058✔
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 =
256
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
257

258
  // Select smaller of the three distances
259
  double distance =
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);
3,628,317✔
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,562,373,027✔
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,731,815,650✔
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;
224,928✔
291
  }
292
}
2,147,483,647✔
293

294
void Particle::event_cross_surface()
2,147,483,647✔
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();
2,147,483,647✔
301

302
  // Set surface that particle is on and adjust coordinate levels
303
  surface() = boundary().surface();
2,147,483,647✔
304
  n_coord() = boundary().coord_level();
2,147,483,647✔
305

306
  const auto& surf {*model::surfaces[surface_index()].get()};
2,147,483,647✔
307

308
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
309
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
310
      boundary().lattice_translation()[2] != 0) {
1,695,548,804✔
311
    // Particle crosses lattice boundary
312

313
    bool verbose = settings::verbosity >= 10 || trace();
732,435,527!
314
    cross_lattice(*this, boundary(), verbose);
732,435,527✔
315
    event() = TallyEvent::LATTICE;
732,435,527✔
316
  } else {
317
    // Particle crosses surface
318
    // If BC, add particle to surface source before crossing surface
319
    if (surf.surf_source_ && surf.bc_) {
1,507,006,915✔
320
      add_surf_source_to_bank(*this, surf);
688,547,979✔
321
    }
322
    this->cross_surface(surf);
1,507,006,915✔
323
    // If no BC, add particle to surface source after crossing surface
324
    if (surf.surf_source_ && !surf.bc_) {
1,507,006,906✔
325
      add_surf_source_to_bank(*this, surf);
817,221,100✔
326
    }
327
    if (settings::weight_window_checkpoint_surface) {
1,507,006,906✔
328
      apply_weight_windows(*this);
10,738✔
329
    }
330
    event() = TallyEvent::SURFACE;
1,507,006,906✔
331
  }
332
  // Score cell to cell partial currents
333
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
334
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,922,767✔
335
  }
336
}
2,147,483,647✔
337

338
void Particle::event_collide()
2,147,483,647✔
339
{
340
  // Score collision estimate of keff
341
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
342
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,051,295✔
343
  }
344

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

349
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
350
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
351

352
  // Clear surface component
353
  surface() = SURFACE_NONE;
2,147,483,647✔
354

355
  if (settings::run_CE) {
2,147,483,647✔
356
    collision(*this);
943,618,570✔
357
  } else {
358
    collision_mg(*this);
1,783,060,477✔
359
  }
360

361
  // Collision track feature to recording particle interaction
362
  if (settings::collision_track) {
2,147,483,647✔
363
    collision_track_record(*this);
150,087✔
364
  }
365

366
  // Score collision estimator tallies -- this is done after a collision
367
  // has occurred rather than before because we need information on the
368
  // outgoing energy for any tallies with an outgoing energy filter
369
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
370
    score_collision_tally(*this);
107,048,574✔
371
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
372
    if (settings::run_CE) {
291,821,708✔
373
      score_analog_tally_ce(*this);
290,613,446✔
374
    } else {
375
      score_analog_tally_mg(*this);
1,208,262✔
376
    }
377
  }
378

379
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
380
    pht_collision_energy();
2,024✔
381
  }
382

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

389
  // Reset fission logical
390
  fission() = false;
2,147,483,647✔
391

392
  // Save coordinates for tallying purposes
393
  r_last_current() = r();
2,147,483,647✔
394

395
  // Set last material to none since cross sections will need to be
396
  // re-evaluated
397
  material_last() = C_NONE;
2,147,483,647✔
398

399
  // Set all directions to base level -- right now, after a collision, only
400
  // the base level directions are changed
401
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
402
    if (coord(j + 1).rotated()) {
143,189,203✔
403
      // If next level is rotated, apply rotation matrix
404
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
405
      const auto& u {coord(j).u()};
10,426,614✔
406
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
407
    } else {
408
      // Otherwise, copy this level's direction
409
      coord(j + 1).u() = coord(j).u();
132,762,589✔
410
    }
411
  }
412

413
  // Score flux derivative accumulators for differential tallies.
414
  if (!model::active_tallies.empty())
2,147,483,647✔
415
    score_collision_derivative(*this);
815,983,007✔
416

417
#ifdef OPENMC_DAGMC_ENABLED
418
  history().reset();
249,914,780✔
419
#endif
420
}
2,147,483,647✔
421

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

432
  // Check for secondary particles if this particle is dead
433
  if (!alive()) {
2,147,483,647✔
434
    // Write final position for this particle
435
    if (write_track()) {
229,577,341✔
436
      write_particle_track(*this);
6,676✔
437
    }
438

439
    // If no secondary particles, break out of event loop
440
    if (secondary_bank().empty())
229,577,341✔
441
      return;
167,076,081✔
442

443
    from_source(&secondary_bank().back());
62,501,260✔
444
    secondary_bank().pop_back();
62,501,260✔
445
    n_event() = 0;
62,501,260✔
446
    bank_second_E() = 0.0;
62,501,260✔
447

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

465
        // Initialize last cells from current cell
466
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
467
          cell_last(j) = coord(j).cell();
605✔
468
        }
469
        n_coord_last() = n_coord();
605✔
470
      }
471
      pht_secondary_particles();
605✔
472
    }
473

474
    // Enter new particle in particle track file
475
    if (write_track())
62,501,260✔
476
      add_particle_track(*this);
5,606✔
477
  }
478
}
479

480
void Particle::event_death()
167,077,081✔
481
{
482
#ifdef OPENMC_DAGMC_ENABLED
483
  history().reset();
15,264,135✔
484
#endif
485

486
  // Finish particle track output.
487
  if (write_track()) {
167,077,081✔
488
    finalize_particle_track(*this);
1,070✔
489
  }
490

491
// Contribute tally reduction variables to global accumulator
492
#pragma omp atomic
91,787,540✔
493
  global_tally_absorption += keff_tally_absorption();
167,077,081✔
494
#pragma omp atomic
92,119,188✔
495
  global_tally_collision += keff_tally_collision();
167,077,081✔
496
#pragma omp atomic
91,424,210✔
497
  global_tally_tracklength += keff_tally_tracklength();
167,077,081✔
498
#pragma omp atomic
91,297,964✔
499
  global_tally_leakage += keff_tally_leakage();
167,077,081✔
500

501
  // Reset particle tallies once accumulated
502
  keff_tally_absorption() = 0.0;
167,077,081✔
503
  keff_tally_collision() = 0.0;
167,077,081✔
504
  keff_tally_tracklength() = 0.0;
167,077,081✔
505
  keff_tally_leakage() = 0.0;
167,077,081✔
506

507
  if (!model::active_pulse_height_tallies.empty()) {
167,077,081✔
508
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
509
  }
510

511
  // Record the number of progeny created by this particle.
512
  // This data will be used to efficiently sort the fission bank.
513
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,077,081✔
514
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,925,700✔
515
    simulation::progeny_per_particle[offset] = n_progeny();
140,925,700✔
516
  }
517
}
167,077,081✔
518

519
void Particle::pht_collision_energy()
2,024✔
520
{
521
  // Adds the energy particles lose in a collision to the pulse-height
522

523
  // determine index of cell in pulse_height_cells
524
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
525
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
526

527
  if (it != model::pulse_height_cells.end()) {
2,024!
528
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
529
    pht_storage()[index] += E_last() - E();
2,024✔
530

531
    // If the energy of the particle is below the cutoff, it will not be sampled
532
    // so its energy is added to the pulse-height in the cell
533
    int photon = ParticleType::photon().transport_index();
2,024✔
534
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
535
      pht_storage()[index] += E();
825✔
536
    }
537
  }
538
}
2,024✔
539

540
void Particle::pht_secondary_particles()
605✔
541
{
542
  // Removes the energy of secondary produced particles from the pulse-height
543

544
  // determine index of cell in pulse_height_cells
545
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
546
    model::pulse_height_cells.end(), cell_born());
605✔
547

548
  if (it != model::pulse_height_cells.end()) {
605!
549
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
550
    pht_storage()[index] -= E();
605✔
551
  }
552
}
605✔
553

554
void Particle::cross_surface(const Surface& surf)
1,508,810,261✔
555
{
556

557
  if (settings::verbosity >= 10 || trace()) {
1,508,810,261✔
558
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
559
  }
560

561
// if we're crossing a CSG surface, make sure the DAG history is reset
562
#ifdef OPENMC_DAGMC_ENABLED
563
  if (surf.geom_type() == GeometryType::CSG)
137,894,985✔
564
    history().reset();
137,839,866✔
565
#endif
566

567
  // Handle any applicable boundary conditions.
568
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
569
      settings::run_mode != RunMode::VOLUME) {
689,020,031✔
570
    surf.bc_->handle_particle(*this, surf);
688,900,087✔
571
    return;
688,900,087✔
572
  }
573

574
  // ==========================================================================
575
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
576

577
#ifdef OPENMC_DAGMC_ENABLED
578
  // in DAGMC, we know what the next cell should be
579
  if (surf.geom_type() == GeometryType::DAG) {
74,820,960✔
580
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
581
                       lowest_coord().universe()) -
44,310✔
582
                     1;
44,310✔
583
    // save material, temperature, and density multiplier
584
    material_last() = material();
44,310✔
585
    sqrtkT_last() = sqrtkT();
44,310✔
586
    density_mult_last() = density_mult();
44,310✔
587
    // set new cell value
588
    lowest_coord().cell() = i_cell;
44,310✔
589
    auto& cell = model::cells[i_cell];
44,310✔
590

591
    cell_instance() = 0;
44,310✔
592
    if (cell->distribcell_index_ >= 0)
44,310✔
593
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
594

595
    material() = cell->material(cell_instance());
44,310✔
596
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
597
    density_mult() = cell->density_mult(cell_instance());
44,310✔
598
    return;
44,310✔
599
  }
600
#endif
601

602
  bool verbose = settings::verbosity >= 10 || trace();
819,865,864!
603
  if (neighbor_list_find_cell(*this, verbose)) {
819,865,864✔
604
    return;
819,835,953✔
605
  }
606

607
  // ==========================================================================
608
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
609

610
  // Remove lower coordinate levels
611
  n_coord() = 1;
29,911✔
612
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
613

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

620
    surface() = SURFACE_NONE;
5,799✔
621
    n_coord() = 1;
5,799✔
622
    r() += TINY_BIT * u();
5,799✔
623

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

627
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
628
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
629
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
630
                   " it could not be located in any cell and it did not leak.");
631
      return;
5,790✔
632
    }
633
  }
634
}
635

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

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

646
    r() += TINY_BIT * u();
937,222✔
647
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
648
  }
649

650
  // Score to global leakage tally
651
  keff_tally_leakage() += wgt();
35,022,064✔
652

653
  // Kill the particle
654
  wgt() = 0.0;
35,022,064✔
655

656
  // Display message
657
  if (settings::verbosity >= 10 || trace()) {
35,022,064!
658
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
659
  }
660
}
35,022,064✔
661

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

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

678
  if (!model::active_surface_tallies.empty()) {
652,640,003✔
679
    score_surface_tally(*this, model::active_surface_tallies, surf);
285,021✔
680
  }
681

682
  if (!model::active_meshsurf_tallies.empty()) {
652,640,003✔
683
    Position r {this->r()};
46,885,487✔
684
    this->r() -= TINY_BIT * u();
46,885,487✔
685
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
686
    this->r() = r;
46,885,487✔
687
  }
688

689
  // Set the new particle direction
690
  u() = new_u;
652,640,003✔
691

692
  // Reassign particle's cell and surface
693
  coord(0).cell() = cell_last(0);
652,640,003✔
694
  surface() = -surface();
652,640,003✔
695

696
  // If a reflective surface is coincident with a lattice or universe
697
  // boundary, it is necessary to redetermine the particle's coordinates in
698
  // the lower universes.
699
  // (unless we're using a dagmc model, which has exactly one universe)
700
  n_coord() = 1;
652,640,003✔
701
  if (surf.geom_type() != GeometryType::DAG &&
1,305,277,248!
702
      !neighbor_list_find_cell(*this)) {
652,637,245!
703
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
704
                 std::to_string(surf.id_) + ".");
×
705
    return;
×
706
  }
707

708
  // Set previous coordinate going slightly past surface crossing
709
  r_last_current() = r() + TINY_BIT * u();
652,640,003✔
710

711
  // Diagnostic message
712
  if (settings::verbosity >= 10 || trace()) {
652,640,003!
713
    write_message(1, "    Reflected from surface {}", surf.id_);
×
714
  }
715
}
716

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

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

739
  // Adjust the particle's location and direction.
740
  r() = new_r;
2,243,486✔
741
  u() = new_u;
2,243,486✔
742

743
  // Reassign particle's surface
744
  surface() = new_surface;
2,243,486✔
745

746
  // Figure out what cell particle is in now
747
  n_coord() = 1;
2,243,486✔
748

749
  if (!neighbor_list_find_cell(*this)) {
2,243,486!
750
    mark_as_lost("Couldn't find particle after hitting periodic "
×
751
                 "boundary on surface " +
×
752
                 std::to_string(surf.id_) + ".");
×
753
    return;
×
754
  }
755

756
  // Set previous coordinate going slightly past surface crossing
757
  r_last_current() = r() + TINY_BIT * u();
2,243,486✔
758

759
  // Diagnostic message
760
  if (settings::verbosity >= 10 || trace()) {
2,243,486!
761
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
762
  }
763
}
764

765
void Particle::mark_as_lost(const char* message)
5,799✔
766
{
767
  // Print warning and write lost particle file
768
  warning(message);
5,799✔
769
  if (settings::max_write_lost_particles < 0 ||
5,799✔
770
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
771
    write_restart();
379✔
772
  }
773
  // Increment number of lost particles
774
  wgt() = 0.0;
5,799✔
775
#pragma omp atomic
3,154✔
776
  simulation::n_lost_particles += 1;
2,645✔
777

778
  // Count the total number of simulated particles (on this processor)
779
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
780
           simulation::work_per_rank;
781

782
  // Abort the simulation if the maximum number of lost particles has been
783
  // reached
784
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
785
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
786
    fatal_error("Maximum number of lost particles has been reached.");
9✔
787
  }
788
}
5,790✔
789

790
void Particle::write_restart() const
379✔
791
{
792
  // Dont write another restart file if in particle restart mode
793
  if (settings::run_mode == RunMode::PARTICLE)
379✔
794
    return;
22✔
795

796
  // Set up file name
797
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
798
    simulation::current_batch, id());
665✔
799

800
#pragma omp critical(WriteParticleRestart)
374✔
801
  {
802
    // Create file
803
    hid_t file_id = file_open(filename, 'w');
357✔
804

805
    // Write filetype and version info
806
    write_attribute(file_id, "filetype", "particle restart");
357✔
807
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
357✔
808
    write_attribute(file_id, "openmc_version", VERSION);
357✔
809
#ifdef GIT_SHA1
810
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
811
#endif
812

813
    // Write data to file
814
    write_dataset(file_id, "current_batch", simulation::current_batch);
357✔
815
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
357✔
816
    write_dataset(file_id, "current_generation", simulation::current_gen);
357✔
817
    write_dataset(file_id, "n_particles", settings::n_particles);
357✔
818
    switch (settings::run_mode) {
357!
819
    case RunMode::FIXED_SOURCE:
225✔
820
      write_dataset(file_id, "run_mode", "fixed source");
225✔
821
      break;
225✔
822
    case RunMode::EIGENVALUE:
132✔
823
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
824
      break;
132✔
825
    case RunMode::PARTICLE:
×
826
      write_dataset(file_id, "run_mode", "particle restart");
×
827
      break;
×
828
    default:
×
829
      break;
×
830
    }
831
    write_dataset(file_id, "id", id());
357✔
832
    write_dataset(file_id, "type", type().pdg_number());
357✔
833

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

857
    // Close file
858
    file_close(file_id);
357✔
859
  } // #pragma omp critical
860
}
357✔
861

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

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

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

883
//==============================================================================
884
// Non-method functions
885
//==============================================================================
886
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,505,769,079✔
887
{
888
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
889
      simulation::surf_source_bank.full()) {
1,178,698,275✔
890
    return;
1,505,639,426✔
891
  }
892

893
  // If a cell/cellfrom/cellto parameter is defined
894
  if (settings::ssw_cell_id != C_NONE) {
337,083✔
895

896
    // Retrieve cell index and storage type
897
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,438✔
898

899
    if (surf.bc_) {
254,438✔
900
      // Leave if cellto with vacuum boundary condition
901
      if (surf.bc_->type() == "vacuum" &&
182,556!
902
          settings::ssw_cell_type == SSWCellType::To) {
33,098✔
903
        return;
12,136✔
904
      }
905

906
      // Leave if other boundary condition than vacuum
907
      if (surf.bc_->type() != "vacuum") {
137,322✔
908
        return;
116,360✔
909
      }
910
    }
911

912
    // Check if the cell of interest has been exited
913
    bool exited = false;
125,942✔
914
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,673✔
915
      if (p.cell_last(i) == cell_idx) {
207,731✔
916
        exited = true;
73,765✔
917
      }
918
    }
919

920
    // Check if the cell of interest has been entered
921
    bool entered = false;
125,942✔
922
    for (int i = 0; i < p.n_coord(); ++i) {
297,975✔
923
      if (p.coord(i).cell() == cell_idx) {
172,033✔
924
        entered = true;
57,517✔
925
      }
926
    }
927

928
    // Vacuum boundary conditions: return if cell is not exited
929
    if (surf.bc_) {
125,942✔
930
      if (surf.bc_->type() == "vacuum" && !exited) {
20,962!
931
        return;
14,662✔
932
      }
933
    } else {
934

935
      // If we both enter and exit the cell of interest
936
      if (entered && exited) {
104,980✔
937
        return;
27,203✔
938
      }
939

940
      // If we did not enter nor exit the cell of interest
941
      if (!entered && !exited) {
77,777✔
942
        return;
13,501✔
943
      }
944

945
      // If cellfrom and the cell before crossing is not the cell of
946
      // interest
947
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,276✔
948
        return;
11,543✔
949
      }
950

951
      // If cellto and the cell after crossing is not the cell of interest
952
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
953
        return;
12,025✔
954
      }
955
    }
956
  }
957

958
  SourceSite site;
129,653✔
959
  site.r = p.r();
129,653✔
960
  site.u = p.u();
129,653✔
961
  site.E = p.E();
129,653✔
962
  site.time = p.time();
129,653✔
963
  site.wgt = p.wgt();
129,653✔
964
  site.delayed_group = p.delayed_group();
129,653✔
965
  site.surf_id = surf.id_;
129,653✔
966
  site.particle = p.type();
129,653✔
967
  site.parent_id = p.id();
129,653✔
968
  site.progeny_id = p.n_progeny();
129,653✔
969
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
970
}
971

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