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

openmc-dev / openmc / 23096528802

14 Mar 2026 09:16PM UTC coverage: 80.856% (-0.7%) from 81.567%
23096528802

Pull #3766

github

web-flow
Merge 874fcac7a into bc9c31e0f
Pull Request #3766: Approximate multigroup velocity

16305 of 23410 branches covered (69.65%)

Branch coverage included in aggregate %.

25 of 26 new or added lines in 4 files covered. (96.15%)

1011 existing lines in 51 files now uncovered.

56234 of 66304 relevant lines covered (84.81%)

24044958.69 hits per line

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

86.17
/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
1,583,473,540✔
47
{
48
  if (settings::run_CE) {
1,583,473,540✔
49
    // Determine mass in eV/c^2
50
    double mass = this->mass();
832,950,724✔
51

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

67
double Particle::mass() const
832,950,724✔
68
{
69
  switch (type().pdg_number()) {
832,950,724✔
70
  case PDG_NEUTRON:
71
    return MASS_NEUTRON_EV;
72
  case PDG_ELECTRON:
19,699,567✔
73
  case PDG_POSITRON:
19,699,567✔
74
    return MASS_ELECTRON_EV;
19,699,567✔
75
  default:
8,112,619✔
76
    return this->type().mass() * AMU_EV;
8,112,619✔
77
  }
78
}
79

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

93
  // Increment number of secondaries created (for ParticleProductionFilter)
94
  n_secondaries()++;
21,422,504✔
95

96
  auto& bank = secondary_bank().emplace_back();
21,422,504✔
97
  bank.particle = type;
21,422,504✔
98
  bank.wgt = wgt;
21,422,504✔
99
  bank.r = r();
21,422,504!
100
  bank.u = u;
21,422,504✔
101
  bank.E = settings::run_CE ? E : g();
21,422,504!
102
  bank.time = time();
21,422,504✔
103
  bank_second_E() += bank.E;
21,422,504✔
104
  return true;
21,422,504✔
105
}
106

107
void Particle::split(double wgt)
1,544,860✔
108
{
109
  auto& bank = secondary_bank().emplace_back();
1,544,860✔
110
  bank.particle = type();
1,544,860✔
111
  bank.wgt = wgt;
1,544,860✔
112
  bank.r = r();
1,544,860✔
113
  bank.u = u();
1,544,860✔
114
  bank.E = settings::run_CE ? E() : g();
1,544,860✔
115
  bank.time = time();
1,544,860✔
116

117
  // Convert signed index to a signed surface ID
118
  if (surface() == SURFACE_NONE) {
1,544,860✔
119
    bank.surf_id = SURFACE_NONE;
1,544,784✔
120
  } else {
121
    int surf_id = model::surfaces[surface_index()]->id_;
76!
122
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
76!
123
  }
124
}
1,544,860✔
125

126
void Particle::from_source(const SourceSite* src)
87,482,292✔
127
{
128
  // Reset some attributes
129
  clear();
87,482,292✔
130
  surface() = SURFACE_NONE;
87,482,292✔
131
  cell_born() = C_NONE;
87,482,292✔
132
  material() = C_NONE;
87,482,292✔
133
  n_collision() = 0;
87,482,292✔
134
  fission() = false;
87,482,292✔
135
  zero_flux_derivs();
87,482,292✔
136
  lifetime() = 0.0;
87,482,292✔
137
#ifdef OPENMC_DAGMC_ENABLED
138
  history().reset();
139
#endif
140

141
  // Copy attributes from source bank site
142
  type() = src->particle;
87,482,292✔
143
  wgt() = src->wgt;
87,482,292✔
144
  wgt_last() = src->wgt;
87,482,292✔
145
  r() = src->r;
87,482,292✔
146
  u() = src->u;
87,482,292✔
147
  r_born() = src->r;
87,482,292✔
148
  r_last_current() = src->r;
87,482,292✔
149
  r_last() = src->r;
87,482,292✔
150
  u_last() = src->u;
87,482,292✔
151
  if (settings::run_CE) {
87,482,292✔
152
    E() = src->E;
45,327,664✔
153
    g() = 0;
45,327,664✔
154
  } else {
155
    g() = static_cast<int>(src->E);
42,154,628✔
156
    g_last() = static_cast<int>(src->E);
42,154,628✔
157
    E() = data::mg.energy_bin_avg_[g()];
42,154,628✔
158
  }
159
  E_last() = E();
87,482,292✔
160
  time() = src->time;
87,482,292✔
161
  time_last() = src->time;
87,482,292✔
162
  parent_nuclide() = src->parent_nuclide;
87,482,292✔
163
  delayed_group() = src->delayed_group;
87,482,292✔
164

165
  // Convert signed surface ID to signed index
166
  if (src->surf_id != SURFACE_NONE) {
87,482,292✔
167
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
40,076✔
168
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
40,076✔
169
  }
170
}
87,482,292✔
171

172
void Particle::event_calculate_xs()
1,573,492,936✔
173
{
174
  // Set the random number stream
175
  stream() = STREAM_TRACKING;
1,573,492,936✔
176

177
  // Store pre-collision particle properties
178
  wgt_last() = wgt();
1,573,492,936✔
179
  E_last() = E();
1,573,492,936✔
180
  u_last() = u();
1,573,492,936✔
181
  r_last() = r();
1,573,492,936✔
182
  time_last() = time();
1,573,492,936✔
183

184
  // Reset event variables
185
  event() = TallyEvent::KILL;
1,573,492,936✔
186
  event_nuclide() = NUCLIDE_NONE;
1,573,492,936✔
187
  event_mt() = REACTION_NONE;
1,573,492,936✔
188

189
  // If the cell hasn't been determined based on the particle's location,
190
  // initiate a search for the current cell. This generally happens at the
191
  // beginning of the history and again for any secondary particles
192
  if (lowest_coord().cell() == C_NONE) {
1,573,492,936✔
193
    if (!exhaustive_find_cell(*this)) {
84,329,496!
194
      mark_as_lost(
×
195
        "Could not find the cell containing particle " + std::to_string(id()));
×
196
      return;
×
197
    }
198

199
    // Set birth cell attribute
200
    if (cell_born() == C_NONE)
84,329,496!
201
      cell_born() = lowest_coord().cell();
84,329,496✔
202

203
    // Initialize last cells from current cell
204
    for (int j = 0; j < n_coord(); ++j) {
175,019,160✔
205
      cell_last(j) = coord(j).cell();
90,689,664✔
206
    }
207
    n_coord_last() = n_coord();
84,329,496✔
208
  }
209

210
  // Write particle track.
211
  if (write_track())
1,573,492,936✔
212
    write_particle_track(*this);
3,012✔
213

214
  if (settings::check_overlaps)
1,573,492,936!
215
    check_cell_overlap(*this);
×
216

217
  // Calculate microscopic and macroscopic cross sections
218
  if (material() != MATERIAL_VOID) {
1,573,492,936✔
219
    if (settings::run_CE) {
1,532,828,004✔
220
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
782,305,188✔
221
          density_mult() != density_mult_last()) {
135,564,821✔
222
        // If the material is the same as the last material and the
223
        // temperature hasn't changed, we don't need to lookup cross
224
        // sections again.
225
        model::materials[material()]->calculate_xs(*this);
646,743,855✔
226
      }
227
    } else {
228
      // Get the MG data; unlike the CE case above, we have to re-calculate
229
      // cross sections for every collision since the cross sections may
230
      // be angle-dependent
231
      data::mg.macro_xs_[material()].calculate_xs(*this);
750,522,816✔
232

233
      // Update the particle's group while we know we are multi-group
234
      g_last() = g();
750,522,816✔
235
    }
236
  } else {
237
    macro_xs().total = 0.0;
40,664,932✔
238
    macro_xs().absorption = 0.0;
40,664,932✔
239
    macro_xs().fission = 0.0;
40,664,932✔
240
    macro_xs().nu_fission = 0.0;
40,664,932✔
241
  }
242
}
243

244
void Particle::event_advance()
1,573,492,936✔
245
{
246
  // Find the distance to the nearest boundary
247
  boundary() = distance_to_boundary(*this);
1,573,492,936✔
248

249
  // Sample a distance to collision
250
  if (type() == ParticleType::electron() ||
1,573,492,936✔
251
      type() == ParticleType::positron()) {
1,553,825,273✔
252
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
39,399,134!
253
  } else if (macro_xs().total == 0.0) {
1,553,793,369✔
254
    collision_distance() = INFINITY;
40,664,932✔
255
  } else {
256
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
1,513,128,437✔
257
  }
258

259
  double speed = this->speed();
1,573,492,936✔
260
  double time_cutoff = settings::time_cutoff[type().transport_index()];
1,573,492,936✔
261
  double distance_cutoff =
1,573,492,936✔
262
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
1,573,492,936✔
263

264
  // Select smaller of the three distances
265
  double distance =
1,573,492,936✔
266
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
1,573,492,936✔
267

268
  // Advance particle in space and time
269
  this->move_distance(distance);
1,573,492,936✔
270
  double dt = distance / speed;
1,573,492,936✔
271
  this->time() += dt;
1,573,492,936✔
272
  this->lifetime() += dt;
1,573,492,936✔
273

274
  // Score timed track-length tallies
275
  if (!model::active_timed_tracklength_tallies.empty()) {
1,573,492,936✔
276
    score_timed_tracklength_tally(*this, distance);
1,319,388✔
277
  }
278

279
  // Score track-length tallies
280
  if (!model::active_tracklength_tallies.empty()) {
1,573,492,936✔
281
    score_tracklength_tally(*this, distance);
622,621,832✔
282
  }
283

284
  // Score track-length estimate of k-eff
285
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
1,573,492,936✔
286
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
1,266,965,452✔
287
  }
288

289
  // Score flux derivative accumulators for differential tallies.
290
  if (!model::active_tallies.empty()) {
1,573,492,936✔
291
    score_track_derivative(*this, distance);
682,764,396✔
292
  }
293

294
  // Set particle weight to zero if it hit the time boundary
295
  if (distance == distance_cutoff) {
1,573,492,936✔
296
    wgt() = 0.0;
81,792✔
297
  }
298
}
1,573,492,936✔
299

300
void Particle::event_cross_surface()
876,542,446✔
301
{
302
  // Saving previous cell data
303
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
304
    cell_last(j) = coord(j).cell();
1,694,346,918✔
305
  }
306
  n_coord_last() = n_coord();
876,542,446✔
307

308
  // Set surface that particle is on and adjust coordinate levels
309
  surface() = boundary().surface();
876,542,446✔
310
  n_coord() = boundary().coord_level();
876,542,446✔
311

312
  const auto& surf {*model::surfaces[surface_index()].get()};
876,542,446✔
313

314
  if (boundary().lattice_translation()[0] != 0 ||
876,542,446✔
315
      boundary().lattice_translation()[1] != 0 ||
876,542,446✔
316
      boundary().lattice_translation()[2] != 0) {
676,565,854✔
317
    // Particle crosses lattice boundary
318

319
    bool verbose = settings::verbosity >= 10 || trace();
268,536,428!
320
    cross_lattice(*this, boundary(), verbose);
268,536,428✔
321
    event() = TallyEvent::LATTICE;
268,536,428✔
322
  } else {
323
    // Particle crosses surface
324
    // If BC, add particle to surface source before crossing surface
325
    if (surf.surf_source_ && surf.bc_) {
608,006,018✔
326
      add_surf_source_to_bank(*this, surf);
261,756,958✔
327
    }
328
    this->cross_surface(surf);
608,006,018✔
329
    // If no BC, add particle to surface source after crossing surface
330
    if (surf.surf_source_ && !surf.bc_) {
608,006,014✔
331
      add_surf_source_to_bank(*this, surf);
345,781,816✔
332
    }
333
    if (settings::weight_window_checkpoint_surface) {
608,006,014✔
334
      apply_weight_windows(*this);
23,336✔
335
    }
336
    event() = TallyEvent::SURFACE;
608,006,014✔
337
  }
338
  // Score cell to cell partial currents
339
  if (!model::active_surface_tallies.empty()) {
876,542,442✔
340
    score_surface_tally(*this, model::active_surface_tallies, surf);
12,702,388✔
341
  }
342
}
876,542,442✔
343

344
void Particle::event_collide()
1,036,737,234✔
345
{
346

347
  // Score collision estimate of keff
348
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
1,036,737,234✔
349
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
778,133,479✔
350
  }
351

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

356
  if (!model::active_meshsurf_tallies.empty())
1,036,737,234✔
357
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
22,945,064✔
358

359
  // Clear surface component
360
  surface() = SURFACE_NONE;
1,036,737,234✔
361

362
  if (settings::run_CE) {
1,036,737,234✔
363
    collision(*this);
388,351,606✔
364
  } else {
365
    collision_mg(*this);
648,385,628✔
366
  }
367

368
  // Collision track feature to recording particle interaction
369
  if (settings::collision_track) {
1,036,737,234✔
370
    collision_track_record(*this);
55,196✔
371
  }
372

373
  // Score collision estimator tallies -- this is done after a collision
374
  // has occurred rather than before because we need information on the
375
  // outgoing energy for any tallies with an outgoing energy filter
376
  if (!model::active_collision_tallies.empty())
1,036,737,234✔
377
    score_collision_tally(*this);
37,997,542✔
378
  if (!model::active_analog_tallies.empty()) {
1,036,737,234✔
379
    if (settings::run_CE) {
147,563,412✔
380
      score_analog_tally_ce(*this);
147,124,044✔
381
    } else {
382
      score_analog_tally_mg(*this);
439,368✔
383
    }
384
  }
385

386
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
1,036,737,234✔
387
    pht_collision_energy();
736✔
388
  }
389

390
  // Reset banked weight during collision
391
  n_bank() = 0;
1,036,737,234✔
392
  bank_second_E() = 0.0;
1,036,737,234✔
393
  wgt_bank() = 0.0;
1,036,737,234✔
394

395
  // Clear number of secondaries in this collision. This is
396
  // distinct from the number of created neutrons n_bank() above!
397
  n_secondaries() = 0;
1,036,737,234✔
398

399
  zero_delayed_bank();
1,036,737,234✔
400

401
  // Reset fission logical
402
  fission() = false;
1,036,737,234✔
403

404
  // Save coordinates for tallying purposes
405
  r_last_current() = r();
1,036,737,234✔
406

407
  // Set last material to none since cross sections will need to be
408
  // re-evaluated
409
  material_last() = C_NONE;
1,036,737,234✔
410

411
  // Set all directions to base level -- right now, after a collision, only
412
  // the base level directions are changed
413
  for (int j = 0; j < n_coord() - 1; ++j) {
1,095,472,966✔
414
    if (coord(j + 1).rotated()) {
58,735,732✔
415
      // If next level is rotated, apply rotation matrix
416
      const auto& m {model::cells[coord(j).cell()]->rotation_};
3,791,496✔
417
      const auto& u {coord(j).u()};
3,791,496✔
418
      coord(j + 1).u() = u.rotate(m);
3,791,496✔
419
    } else {
420
      // Otherwise, copy this level's direction
421
      coord(j + 1).u() = coord(j).u();
54,944,236✔
422
    }
423
  }
424

425
  // Score flux derivative accumulators for differential tallies.
426
  if (!model::active_tallies.empty())
1,036,737,234✔
427
    score_collision_derivative(*this);
339,444,679✔
428

429
#ifdef OPENMC_DAGMC_ENABLED
430
  history().reset();
431
#endif
432
}
1,036,737,234✔
433

434
void Particle::event_revive_from_secondary()
1,573,492,932✔
435
{
436
  // If particle has too many events, display warning and kill it
437
  ++n_event();
1,573,492,932✔
438
  if (n_event() == settings::max_particle_events) {
1,573,492,932!
439
    warning("Particle " + std::to_string(id()) +
×
440
            " underwent maximum number of events.");
441
    wgt() = 0.0;
×
442
  }
443

444
  // Check for secondary particles if this particle is dead
445
  if (!alive()) {
1,573,492,932✔
446
    // Write final position for this particle
447
    if (write_track()) {
84,329,712✔
448
      write_particle_track(*this);
1,632✔
449
    }
450

451
    // If no secondary particles, break out of event loop
452
    if (secondary_bank().empty())
84,329,712✔
453
      return;
454

455
    from_source(&secondary_bank().back());
22,967,492✔
456
    secondary_bank().pop_back();
22,967,492✔
457
    n_event() = 0;
22,967,492✔
458
    bank_second_E() = 0.0;
22,967,492✔
459

460
    // Subtract secondary particle energy from interim pulse-height results
461
    if (!model::active_pulse_height_tallies.empty() &&
22,967,492✔
462
        this->type().is_photon()) {
5,636✔
463
      // Since the birth cell of the particle has not been set we
464
      // have to determine it before the energy of the secondary particle can be
465
      // removed from the pulse-height of this cell.
466
      if (lowest_coord().cell() == C_NONE) {
220!
467
        bool verbose = settings::verbosity >= 10 || trace();
220!
468
        if (!exhaustive_find_cell(*this, verbose)) {
220!
469
          mark_as_lost("Could not find the cell containing particle " +
×
470
                       std::to_string(id()));
×
471
          return;
×
472
        }
473
        // Set birth cell attribute
474
        if (cell_born() == C_NONE)
220!
475
          cell_born() = lowest_coord().cell();
220✔
476

477
        // Initialize last cells from current cell
478
        for (int j = 0; j < n_coord(); ++j) {
440✔
479
          cell_last(j) = coord(j).cell();
220✔
480
        }
481
        n_coord_last() = n_coord();
220✔
482
      }
483
      pht_secondary_particles();
220✔
484
    }
485

486
    // Enter new particle in particle track file
487
    if (write_track())
22,967,492✔
488
      add_particle_track(*this);
1,352✔
489
  }
490
}
491

492
void Particle::event_death()
61,362,220✔
493
{
494
#ifdef OPENMC_DAGMC_ENABLED
495
  history().reset();
496
#endif
497

498
  // Finish particle track output.
499
  if (write_track()) {
61,362,220✔
500
    finalize_particle_track(*this);
280✔
501
  }
502

503
// Contribute tally reduction variables to global accumulator
504
#pragma omp atomic
505
  global_tally_absorption += keff_tally_absorption();
61,362,220✔
506
#pragma omp atomic
507
  global_tally_collision += keff_tally_collision();
61,362,220✔
508
#pragma omp atomic
509
  global_tally_tracklength += keff_tally_tracklength();
61,362,220✔
510
#pragma omp atomic
511
  global_tally_leakage += keff_tally_leakage();
61,362,220✔
512

513
  // Reset particle tallies once accumulated
514
  keff_tally_absorption() = 0.0;
61,362,220✔
515
  keff_tally_collision() = 0.0;
61,362,220✔
516
  keff_tally_tracklength() = 0.0;
61,362,220✔
517
  keff_tally_leakage() = 0.0;
61,362,220✔
518

519
  if (!model::active_pulse_height_tallies.empty()) {
61,362,220✔
520
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
2,000✔
521
  }
522

523
  // Record the number of progeny created by this particle.
524
  // This data will be used to efficiently sort the fission bank.
525
  if (settings::run_mode == RunMode::EIGENVALUE) {
61,362,220✔
526
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
51,472,800✔
527
    simulation::progeny_per_particle[offset] = n_progeny();
51,472,800✔
528
  }
529
}
61,362,220✔
530

531
void Particle::pht_collision_energy()
736✔
532
{
533
  // Adds the energy particles lose in a collision to the pulse-height
534

535
  // determine index of cell in pulse_height_cells
536
  auto it = std::find(model::pulse_height_cells.begin(),
736✔
537
    model::pulse_height_cells.end(), lowest_coord().cell());
736!
538

539
  if (it != model::pulse_height_cells.end()) {
736!
540
    int index = std::distance(model::pulse_height_cells.begin(), it);
736✔
541
    pht_storage()[index] += E_last() - E();
736✔
542

543
    // If the energy of the particle is below the cutoff, it will not be sampled
544
    // so its energy is added to the pulse-height in the cell
545
    int photon = ParticleType::photon().transport_index();
736✔
546
    if (E() < settings::energy_cutoff[photon]) {
736✔
547
      pht_storage()[index] += E();
300✔
548
    }
549
  }
550
}
736✔
551

552
void Particle::pht_secondary_particles()
220✔
553
{
554
  // Removes the energy of secondary produced particles from the pulse-height
555

556
  // determine index of cell in pulse_height_cells
557
  auto it = std::find(model::pulse_height_cells.begin(),
220✔
558
    model::pulse_height_cells.end(), cell_born());
220!
559

560
  if (it != model::pulse_height_cells.end()) {
220!
561
    int index = std::distance(model::pulse_height_cells.begin(), it);
220✔
562
    pht_storage()[index] -= E();
220✔
563
  }
564
}
220✔
565

566
void Particle::cross_surface(const Surface& surf)
608,698,234✔
567
{
568

569
  if (settings::verbosity >= 10 || trace()) {
608,698,234✔
570
    write_message(1, "    Crossing surface {}", surf.id_);
24✔
571
  }
572

573
// if we're crossing a CSG surface, make sure the DAG history is reset
574
#ifdef OPENMC_DAGMC_ENABLED
575
  if (surf.geom_type() == GeometryType::CSG)
576
    history().reset();
577
#endif
578

579
  // Handle any applicable boundary conditions.
580
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
608,698,234!
581
      settings::run_mode != RunMode::VOLUME) {
582
    surf.bc_->handle_particle(*this, surf);
261,888,158✔
583
    return;
261,888,158✔
584
  }
585

586
  // ==========================================================================
587
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
588

589
#ifdef OPENMC_DAGMC_ENABLED
590
  // in DAGMC, we know what the next cell should be
591
  if (surf.geom_type() == GeometryType::DAG) {
592
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
593
                       lowest_coord().universe()) -
594
                     1;
595
    // save material, temperature, and density multiplier
596
    material_last() = material();
597
    sqrtkT_last() = sqrtkT();
598
    density_mult_last() = density_mult();
599
    // set new cell value
600
    lowest_coord().cell() = i_cell;
601
    auto& cell = model::cells[i_cell];
602

603
    cell_instance() = 0;
604
    if (cell->distribcell_index_ >= 0)
605
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
606

607
    material() = cell->material(cell_instance());
608
    sqrtkT() = cell->sqrtkT(cell_instance());
609
    density_mult() = cell->density_mult(cell_instance());
610
    return;
611
  }
612
#endif
613

614
  bool verbose = settings::verbosity >= 10 || trace();
346,810,076!
615
  if (neighbor_list_find_cell(*this, verbose)) {
346,810,076✔
616
    return;
617
  }
618

619
  // ==========================================================================
620
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
621

622
  // Remove lower coordinate levels
623
  n_coord() = 1;
10,884✔
624
  bool found = exhaustive_find_cell(*this, verbose);
10,884✔
625

626
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
10,884!
627
    // If a cell is still not found, there are two possible causes: 1) there is
628
    // a void in the model, and 2) the particle hit a surface at a tangent. If
629
    // the particle is really traveling tangent to a surface, if we move it
630
    // forward a tiny bit it should fix the problem.
631

632
    surface() = SURFACE_NONE;
2,116✔
633
    n_coord() = 1;
2,116✔
634
    r() += TINY_BIT * u();
2,116✔
635

636
    // Couldn't find next cell anywhere! This probably means there is an actual
637
    // undefined region in the geometry.
638

639
    if (!exhaustive_find_cell(*this, verbose)) {
2,116!
640
      mark_as_lost("After particle " + std::to_string(id()) +
6,344✔
641
                   " crossed surface " + std::to_string(surf.id_) +
6,344✔
642
                   " it could not be located in any cell and it did not leak.");
643
      return;
2,112✔
644
    }
645
  }
646
}
647

648
void Particle::cross_vacuum_bc(const Surface& surf)
12,651,281✔
649
{
650
  // Score any surface current tallies -- note that the particle is moved
651
  // forward slightly so that if the mesh boundary is on the surface, it is
652
  // still processed
653

654
  if (!model::active_meshsurf_tallies.empty()) {
12,651,281✔
655
    // TODO: Find a better solution to score surface currents than
656
    // physically moving the particle forward slightly
657

658
    r() += TINY_BIT * u();
340,808✔
659
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
340,808✔
660
  }
661

662
  // Score to global leakage tally
663
  keff_tally_leakage() += wgt();
12,651,281✔
664

665
  // Kill the particle
666
  wgt() = 0.0;
12,651,281✔
667

668
  // Display message
669
  if (settings::verbosity >= 10 || trace()) {
12,651,281!
670
    write_message(1, "    Leaked out of surface {}", surf.id_);
8✔
671
  }
672
}
12,651,281✔
673

674
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
248,783,968✔
675
{
676
  // Do not handle reflective boundary conditions on lower universes
677
  if (n_coord() != 1) {
248,783,968!
678
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
679
                 " off surface in a lower universe.");
680
    return;
×
681
  }
682

683
  // Score surface currents since reflection causes the direction of the
684
  // particle to change. For surface filters, we need to score the tallies
685
  // twice, once before the particle's surface attribute has changed and
686
  // once after. For mesh surface filters, we need to artificially move
687
  // the particle slightly back in case the surface crossing is coincident
688
  // with a mesh boundary
689

690
  if (!model::active_surface_tallies.empty()) {
248,783,968✔
691
    score_surface_tally(*this, model::active_surface_tallies, surf);
103,644✔
692
  }
693

694
  if (!model::active_meshsurf_tallies.empty()) {
248,783,968✔
695
    Position r {this->r()};
17,049,268✔
696
    this->r() -= TINY_BIT * u();
17,049,268✔
697
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
17,049,268✔
698
    this->r() = r;
17,049,268✔
699
  }
700

701
  // Set the new particle direction
702
  u() = new_u;
248,783,968✔
703

704
  // Reassign particle's cell and surface
705
  coord(0).cell() = cell_last(0);
248,783,968✔
706
  surface() = -surface();
248,783,968✔
707

708
  // If a reflective surface is coincident with a lattice or universe
709
  // boundary, it is necessary to redetermine the particle's coordinates in
710
  // the lower universes.
711
  // (unless we're using a dagmc model, which has exactly one universe)
712
  n_coord() = 1;
248,783,968✔
713
  if (surf.geom_type() != GeometryType::DAG &&
497,567,936!
714
      !neighbor_list_find_cell(*this)) {
248,783,968✔
715
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
716
                 std::to_string(surf.id_) + ".");
×
717
    return;
×
718
  }
719

720
  // Set previous coordinate going slightly past surface crossing
721
  r_last_current() = r() + TINY_BIT * u();
248,783,968✔
722

723
  // Diagnostic message
724
  if (settings::verbosity >= 10 || trace()) {
248,783,968!
725
    write_message(1, "    Reflected from surface {}", surf.id_);
×
726
  }
727
}
728

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

741
  // Score surface currents since reflection causes the direction of the
742
  // particle to change -- artificially move the particle slightly back in
743
  // case the surface crossing is coincident with a mesh boundary
744
  if (!model::active_meshsurf_tallies.empty()) {
818,533!
745
    Position r {this->r()};
×
746
    this->r() -= TINY_BIT * u();
×
747
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
748
    this->r() = r;
×
749
  }
750

751
  // Adjust the particle's location and direction.
752
  r() = new_r;
818,533✔
753
  u() = new_u;
818,533✔
754

755
  // Reassign particle's surface
756
  surface() = new_surface;
818,533✔
757

758
  // Figure out what cell particle is in now
759
  n_coord() = 1;
818,533✔
760

761
  if (!neighbor_list_find_cell(*this)) {
818,533!
762
    mark_as_lost("Couldn't find particle after hitting periodic "
×
763
                 "boundary on surface " +
×
764
                 std::to_string(surf.id_) + ".");
×
765
    return;
×
766
  }
767

768
  // Set previous coordinate going slightly past surface crossing
769
  r_last_current() = r() + TINY_BIT * u();
818,533✔
770

771
  // Diagnostic message
772
  if (settings::verbosity >= 10 || trace()) {
818,533!
773
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
774
  }
775
}
776

777
void Particle::mark_as_lost(const char* message)
2,116✔
778
{
779
  // Print warning and write lost particle file
780
  warning(message);
2,116✔
781
  if (settings::max_write_lost_particles < 0 ||
2,116✔
782
      simulation::n_lost_particles < settings::max_write_lost_particles) {
2,000✔
783
    write_restart();
136✔
784
  }
785
  // Increment number of lost particles
786
  wgt() = 0.0;
2,116✔
787
#pragma omp atomic
788
  simulation::n_lost_particles += 1;
2,116✔
789

790
  // Count the total number of simulated particles (on this processor)
791
  auto n = simulation::current_batch * settings::gen_per_batch *
2,116✔
792
           simulation::work_per_rank;
793

794
  // Abort the simulation if the maximum number of lost particles has been
795
  // reached
796
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
2,116✔
797
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
4!
798
    fatal_error("Maximum number of lost particles has been reached.");
4✔
799
  }
800
}
2,112✔
801

802
void Particle::write_restart() const
136✔
803
{
804
  // Dont write another restart file if in particle restart mode
805
  if (settings::run_mode == RunMode::PARTICLE)
136✔
806
    return;
8✔
807

808
  // Set up file name
809
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
128✔
810
    simulation::current_batch, id());
128✔
811

812
#pragma omp critical(WriteParticleRestart)
813
  {
128✔
814
    // Create file
815
    hid_t file_id = file_open(filename, 'w');
128✔
816

817
    // Write filetype and version info
818
    write_attribute(file_id, "filetype", "particle restart");
128✔
819
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
128✔
820
    write_attribute(file_id, "openmc_version", VERSION);
128✔
821
#ifdef GIT_SHA1
822
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
823
#endif
824

825
    // Write data to file
826
    write_dataset(file_id, "current_batch", simulation::current_batch);
128✔
827
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
128✔
828
    write_dataset(file_id, "current_generation", simulation::current_gen);
128✔
829
    write_dataset(file_id, "n_particles", settings::n_particles);
128✔
830
    switch (settings::run_mode) {
128!
831
    case RunMode::FIXED_SOURCE:
80✔
832
      write_dataset(file_id, "run_mode", "fixed source");
80✔
833
      break;
834
    case RunMode::EIGENVALUE:
48✔
835
      write_dataset(file_id, "run_mode", "eigenvalue");
48✔
836
      break;
837
    case RunMode::PARTICLE:
×
838
      write_dataset(file_id, "run_mode", "particle restart");
×
839
      break;
840
    default:
841
      break;
842
    }
843
    write_dataset(file_id, "id", id());
128✔
844
    write_dataset(file_id, "type", type().pdg_number());
128✔
845

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

869
    // Close file
870
    file_close(file_id);
128✔
871
  } // #pragma omp critical
872
}
128✔
873

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

880
  // If the cache doesn't match, recalculate micro xs
881
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
1,023,036,322✔
882
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
883
      ncrystal_xs != micro.ncrystal_xs) {
982,141,342!
884
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
1,952,971,915✔
885

886
    // If NCrystal is being used, update micro cross section cache
887
    micro.ncrystal_xs = ncrystal_xs;
1,952,971,915✔
888
    if (ncrystal_xs >= 0.0) {
1,952,971,915✔
889
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
4,006,892✔
890
      ncrystal_update_micro(ncrystal_xs, micro);
4,006,892✔
891
    }
892
  }
893
}
2,147,483,647✔
894

895
//==============================================================================
896
// Non-method functions
897
//==============================================================================
898
void add_surf_source_to_bank(Particle& p, const Surface& surf)
607,538,774✔
899
{
900
  if (simulation::current_batch <= settings::n_inactive ||
607,538,774✔
901
      simulation::surf_source_bank.full()) {
467,371,005✔
902
    return;
607,491,194✔
903
  }
904

905
  // If a cell/cellfrom/cellto parameter is defined
906
  if (settings::ssw_cell_id != C_NONE) {
127,512✔
907

908
    // Retrieve cell index and storage type
909
    int cell_idx = model::cell_map[settings::ssw_cell_id];
96,944✔
910

911
    if (surf.bc_) {
96,944✔
912
      // Leave if cellto with vacuum boundary condition
913
      if (surf.bc_->type() == "vacuum" &&
117,688✔
914
          settings::ssw_cell_type == SSWCellType::To) {
12,300✔
915
        return;
916
      }
917

918
      // Leave if other boundary condition than vacuum
919
      if (surf.bc_->type() != "vacuum") {
108,680✔
920
        return;
921
      }
922
    }
923

924
    // Check if the cell of interest has been exited
925
    bool exited = false;
926
    for (int i = 0; i < p.n_coord_last(); ++i) {
123,576✔
927
      if (p.cell_last(i) == cell_idx) {
77,680✔
928
        exited = true;
27,552✔
929
      }
930
    }
931

932
    // Check if the cell of interest has been entered
933
    bool entered = false;
934
    for (int i = 0; i < p.n_coord(); ++i) {
109,872✔
935
      if (p.coord(i).cell() == cell_idx) {
63,976✔
936
        entered = true;
21,808✔
937
      }
938
    }
939

940
    // Vacuum boundary conditions: return if cell is not exited
941
    if (surf.bc_) {
45,896✔
942
      if (surf.bc_->type() == "vacuum" && !exited) {
15,592!
943
        return;
944
      }
945
    } else {
946

947
      // If we both enter and exit the cell of interest
948
      if (entered && exited) {
38,100✔
949
        return;
950
      }
951

952
      // If we did not enter nor exit the cell of interest
953
      if (!entered && !exited) {
27,476✔
954
        return;
955
      }
956

957
      // If cellfrom and the cell before crossing is not the cell of
958
      // interest
959
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
23,312✔
960
        return;
961
      }
962

963
      // If cellto and the cell after crossing is not the cell of interest
964
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
18,924✔
965
        return;
966
      }
967
    }
968
  }
969

970
  SourceSite site;
47,580✔
971
  site.r = p.r();
47,580✔
972
  site.u = p.u();
47,580✔
973
  site.E = p.E();
47,580✔
974
  site.time = p.time();
47,580✔
975
  site.wgt = p.wgt();
47,580✔
976
  site.delayed_group = p.delayed_group();
47,580✔
977
  site.surf_id = surf.id_;
47,580✔
978
  site.particle = p.type();
47,580✔
979
  site.parent_id = p.id();
47,580✔
980
  site.progeny_id = p.n_progeny();
47,580✔
981
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
47,580✔
982
}
983

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