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

openmc-dev / openmc / 22806159669

07 Mar 2026 07:59PM UTC coverage: 80.829% (-0.7%) from 81.556%
22806159669

Pull #3766

github

web-flow
Merge f7b0fd4d3 into 908e63115
Pull Request #3766: Approximate multigroup velocity

16271 of 23381 branches covered (69.59%)

Branch coverage included in aggregate %.

26 of 27 new or added lines in 4 files covered. (96.3%)

913 existing lines in 49 files now uncovered.

56170 of 66241 relevant lines covered (84.8%)

24033244.39 hits per line

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

86.07
/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,279,550✔
47
{
48
  if (settings::run_CE) {
1,583,279,550✔
49
    // Determine mass in eV/c^2
50
    double mass = this->mass();
832,756,734✔
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,756,734✔
54
           (this->E() + mass);
832,756,734✔
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,756,734✔
68
{
69
  switch (type().pdg_number()) {
832,756,734✔
70
  case PDG_NEUTRON:
71
    return MASS_NEUTRON_EV;
72
  case PDG_ELECTRON:
19,611,216✔
73
  case PDG_POSITRON:
19,611,216✔
74
    return MASS_ELECTRON_EV;
19,611,216✔
75
  default:
8,019,985✔
76
    return this->type().mass() * AMU_EV;
8,019,985✔
77
  }
78
}
79

80
bool Particle::create_secondary(
40,889,956✔
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,889,956✔
86
  if (idx == C_NONE) {
40,889,956!
87
    return false;
88
  }
89
  if (E < settings::energy_cutoff[idx]) {
40,889,956✔
90
    return false;
91
  }
92

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

96
  auto& bank = secondary_bank().emplace_back();
21,334,154✔
97
  bank.particle = type;
21,334,154✔
98
  bank.wgt = wgt;
21,334,154✔
99
  bank.r = r();
21,334,154!
100
  bank.u = u;
21,334,154✔
101
  bank.E = settings::run_CE ? E : g();
21,334,154!
102
  bank.time = time();
21,334,154✔
103
  bank_second_E() += bank.E;
21,334,154✔
104
  return true;
21,334,154✔
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,353,942✔
127
{
128
  // Reset some attributes
129
  clear();
87,353,942✔
130
  surface() = SURFACE_NONE;
87,353,942✔
131
  cell_born() = C_NONE;
87,353,942✔
132
  material() = C_NONE;
87,353,942✔
133
  n_collision() = 0;
87,353,942✔
134
  fission() = false;
87,353,942✔
135
  zero_flux_derivs();
87,353,942✔
136
  lifetime() = 0.0;
87,353,942✔
137
#ifdef OPENMC_DAGMC_ENABLED
138
  history().reset();
139
#endif
140

141
  // Copy attributes from source bank site
142
  type() = src->particle;
87,353,942✔
143
  wgt() = src->wgt;
87,353,942✔
144
  wgt_last() = src->wgt;
87,353,942✔
145
  r() = src->r;
87,353,942✔
146
  u() = src->u;
87,353,942✔
147
  r_born() = src->r;
87,353,942✔
148
  r_last_current() = src->r;
87,353,942✔
149
  r_last() = src->r;
87,353,942✔
150
  u_last() = src->u;
87,353,942✔
151
  if (settings::run_CE) {
87,353,942✔
152
    E() = src->E;
45,199,314✔
153
    g() = 0;
45,199,314✔
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,353,942✔
160
  time() = src->time;
87,353,942✔
161
  time_last() = src->time;
87,353,942✔
162
  parent_nuclide() = src->parent_nuclide;
87,353,942✔
163
  delayed_group() = src->delayed_group;
87,353,942✔
164

165
  // Convert signed surface ID to signed index
166
  if (src->surf_id != SURFACE_NONE) {
87,353,942✔
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,353,942✔
171

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

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

184
  // Reset event variables
185
  event() = TallyEvent::KILL;
1,573,298,946✔
186
  event_nuclide() = NUCLIDE_NONE;
1,573,298,946✔
187
  event_mt() = REACTION_NONE;
1,573,298,946✔
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,298,946✔
193
    if (!exhaustive_find_cell(*this)) {
84,201,146!
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,201,146!
201
      cell_born() = lowest_coord().cell();
84,201,146✔
202

203
    // Initialize last cells from current cell
204
    for (int j = 0; j < n_coord(); ++j) {
174,762,460✔
205
      cell_last(j) = coord(j).cell();
90,561,314✔
206
    }
207
    n_coord_last() = n_coord();
84,201,146✔
208
  }
209

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

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

217
  // Calculate microscopic and macroscopic cross sections
218
  if (material() != MATERIAL_VOID) {
1,573,298,946✔
219
    if (settings::run_CE) {
1,532,634,014✔
220
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
782,111,198✔
221
          density_mult() != density_mult_last()) {
135,564,511✔
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,550,175✔
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,298,946✔
245
{
246
  // Find the distance to the nearest boundary
247
  boundary() = distance_to_boundary(*this);
1,573,298,946✔
248

249
  // Sample a distance to collision
250
  if (type() == ParticleType::electron() ||
1,573,298,946✔
251
      type() == ParticleType::positron()) {
1,553,719,634✔
252
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
39,222,432!
253
  } else if (macro_xs().total == 0.0) {
1,553,687,730✔
254
    collision_distance() = INFINITY;
40,664,932✔
255
  } else {
256
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
1,513,022,798✔
257
  }
258

259
  double speed = this->speed();
1,573,298,946✔
260
  double time_cutoff = settings::time_cutoff[type().transport_index()];
1,573,298,946✔
261
  double distance_cutoff = (time_cutoff - time()) * speed;
1,573,298,946✔
262

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

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

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

278
  // Score track-length tallies
279
  if (!model::active_tracklength_tallies.empty()) {
1,573,298,946✔
280
    score_tracklength_tally(*this, distance);
622,608,510✔
281
  }
282

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

288
  // Score flux derivative accumulators for differential tallies.
289
  if (!model::active_tallies.empty()) {
1,573,298,946✔
290
    score_track_derivative(*this, distance);
682,571,078✔
291
  }
292

293
  // Set particle weight to zero if it hit the time boundary
294
  if (distance == distance_cutoff) {
1,573,298,946✔
295
    wgt() = 0.0;
453,532✔
296
  }
297
}
1,573,298,946✔
298

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

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

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

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

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

343
void Particle::event_collide()
1,036,171,783✔
344
{
345

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

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

355
  if (!model::active_meshsurf_tallies.empty())
1,036,171,783✔
356
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
22,945,064✔
357

358
  // Clear surface component
359
  surface() = SURFACE_NONE;
1,036,171,783✔
360

361
  if (settings::run_CE) {
1,036,171,783✔
362
    collision(*this);
387,786,155✔
363
  } else {
364
    collision_mg(*this);
648,385,628✔
365
  }
366

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

372
  // Score collision estimator tallies -- this is done after a collision
373
  // has occurred rather than before because we need information on the
374
  // outgoing energy for any tallies with an outgoing energy filter
375
  if (!model::active_collision_tallies.empty())
1,036,171,783✔
376
    score_collision_tally(*this);
37,575,033✔
377
  if (!model::active_analog_tallies.empty()) {
1,036,171,783✔
378
    if (settings::run_CE) {
147,371,052✔
379
      score_analog_tally_ce(*this);
146,931,684✔
380
    } else {
381
      score_analog_tally_mg(*this);
439,368✔
382
    }
383
  }
384

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

389
  // Reset banked weight during collision
390
  n_bank() = 0;
1,036,171,783✔
391
  bank_second_E() = 0.0;
1,036,171,783✔
392
  wgt_bank() = 0.0;
1,036,171,783✔
393

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

398
  zero_delayed_bank();
1,036,171,783✔
399

400
  // Reset fission logical
401
  fission() = false;
1,036,171,783✔
402

403
  // Save coordinates for tallying purposes
404
  r_last_current() = r();
1,036,171,783✔
405

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

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

424
  // Score flux derivative accumulators for differential tallies.
425
  if (!model::active_tallies.empty())
1,036,171,783✔
426
    score_collision_derivative(*this);
339,009,585✔
427

428
#ifdef OPENMC_DAGMC_ENABLED
429
  history().reset();
430
#endif
431
}
1,036,171,783✔
432

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

443
  // Check for secondary particles if this particle is dead
444
  if (!alive()) {
1,573,298,942✔
445
    // Write final position for this particle
446
    if (write_track()) {
84,201,362✔
447
      write_particle_track(*this);
1,632✔
448
    }
449

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

454
    from_source(&secondary_bank().back());
22,879,142✔
455
    secondary_bank().pop_back();
22,879,142✔
456
    n_event() = 0;
22,879,142✔
457
    bank_second_E() = 0.0;
22,879,142✔
458

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

565
void Particle::cross_surface(const Surface& surf)
608,699,395✔
566
{
567

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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