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

openmc-dev / openmc / 15371300071

01 Jun 2025 05:04AM UTC coverage: 85.143% (+0.3%) from 84.827%
15371300071

Pull #3176

github

web-flow
Merge 4f739184a into cb95c784b
Pull Request #3176: MeshFilter rotation - solution to issue #3166

86 of 99 new or added lines in 4 files covered. (86.87%)

3707 existing lines in 117 files now uncovered.

52212 of 61323 relevant lines covered (85.14%)

42831974.38 hits per line

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

92.74
/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/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef DAGMC
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  // Determine mass in eV/c^2
48
  double mass;
49
  switch (this->type()) {
2,147,483,647✔
50
  case ParticleType::neutron:
2,147,483,647✔
51
    mass = MASS_NEUTRON_EV;
2,147,483,647✔
52
    break;
2,147,483,647✔
53
  case ParticleType::photon:
19,617,776✔
54
    mass = 0.0;
19,617,776✔
55
    break;
19,617,776✔
56
  case ParticleType::electron:
65,518,140✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
65,518,140✔
59
    break;
65,518,140✔
60
  }
61

62
  if (this->E() < 1.0e-9 * mass) {
2,147,483,647✔
63
    // If the energy is much smaller than the mass, revert to non-relativistic
64
    // formula. The 1e-9 criterion is specifically chosen as the point below
65
    // which the error from using the non-relativistic formula is less than the
66
    // round-off eror when using the relativistic formula (see analysis at
67
    // https://gist.github.com/paulromano/da3b473fe3df33de94b265bdff0c7817)
68
    return C_LIGHT * std::sqrt(2 * this->E() / mass);
1,167,590,391✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

73
    // Calculate speed via v = c * sqrt(1 - γ^-2)
74
    return C_LIGHT * std::sqrt(1 - inv_gamma * inv_gamma);
2,147,483,647✔
75
  }
76
}
77

78
bool Particle::create_secondary(
137,195,004✔
79
  double wgt, Direction u, double E, ParticleType type)
80
{
81
  // If energy is below cutoff for this particle, don't create secondary
82
  // particle
83
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
137,195,004✔
84
    return false;
65,415,140✔
85
  }
86

87
  auto& bank = secondary_bank().emplace_back();
71,779,864✔
88
  bank.particle = type;
71,779,864✔
89
  bank.wgt = wgt;
71,779,864✔
90
  bank.r = r();
71,779,864✔
91
  bank.u = u;
71,779,864✔
92
  bank.E = settings::run_CE ? E : g();
71,779,864✔
93
  bank.time = time();
71,779,864✔
94
  bank_second_E() += bank.E;
71,779,864✔
95
  return true;
71,779,864✔
96
}
97

98
void Particle::split(double wgt)
9,238,216✔
99
{
100
  auto& bank = secondary_bank().emplace_back();
9,238,216✔
101
  bank.particle = type();
9,238,216✔
102
  bank.wgt = wgt;
9,238,216✔
103
  bank.r = r();
9,238,216✔
104
  bank.u = u();
9,238,216✔
105
  bank.E = settings::run_CE ? E() : g();
9,238,216✔
106
  bank.time = time();
9,238,216✔
107
}
9,238,216✔
108

109
void Particle::from_source(const SourceSite* src)
298,430,011✔
110
{
111
  // Reset some attributes
112
  clear();
298,430,011✔
113
  surface() = SURFACE_NONE;
298,430,011✔
114
  cell_born() = C_NONE;
298,430,011✔
115
  material() = C_NONE;
298,430,011✔
116
  n_collision() = 0;
298,430,011✔
117
  fission() = false;
298,430,011✔
118
  zero_flux_derivs();
298,430,011✔
119
  lifetime() = 0.0;
298,430,011✔
120

121
  // Copy attributes from source bank site
122
  type() = src->particle;
298,430,011✔
123
  wgt() = src->wgt;
298,430,011✔
124
  wgt_last() = src->wgt;
298,430,011✔
125
  r() = src->r;
298,430,011✔
126
  u() = src->u;
298,430,011✔
127
  r_born() = src->r;
298,430,011✔
128
  r_last_current() = src->r;
298,430,011✔
129
  r_last() = src->r;
298,430,011✔
130
  u_last() = src->u;
298,430,011✔
131
  if (settings::run_CE) {
298,430,011✔
132
    E() = src->E;
136,657,066✔
133
    g() = 0;
136,657,066✔
134
  } else {
135
    g() = static_cast<int>(src->E);
161,772,945✔
136
    g_last() = static_cast<int>(src->E);
161,772,945✔
137
    E() = data::mg.energy_bin_avg_[g()];
161,772,945✔
138
  }
139
  E_last() = E();
298,430,011✔
140
  time() = src->time;
298,430,011✔
141
  time_last() = src->time;
298,430,011✔
142
  parent_nuclide() = src->parent_nuclide;
298,430,011✔
143
}
298,430,011✔
144

145
void Particle::event_calculate_xs()
2,147,483,647✔
146
{
147
  // Set the random number stream
148
  stream() = STREAM_TRACKING;
2,147,483,647✔
149

150
  // Store pre-collision particle properties
151
  wgt_last() = wgt();
2,147,483,647✔
152
  E_last() = E();
2,147,483,647✔
153
  u_last() = u();
2,147,483,647✔
154
  r_last() = r();
2,147,483,647✔
155
  time_last() = time();
2,147,483,647✔
156

157
  // Reset event variables
158
  event() = TallyEvent::KILL;
2,147,483,647✔
159
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
160
  event_mt() = REACTION_NONE;
2,147,483,647✔
161

162
  // If the cell hasn't been determined based on the particle's location,
163
  // initiate a search for the current cell. This generally happens at the
164
  // beginning of the history and again for any secondary particles
165
  if (lowest_coord().cell == C_NONE) {
2,147,483,647✔
166
    if (!exhaustive_find_cell(*this)) {
294,661,546✔
UNCOV
167
      mark_as_lost(
×
UNCOV
168
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
169
      return;
×
170
    }
171

172
    // Set birth cell attribute
173
    if (cell_born() == C_NONE)
294,661,546✔
174
      cell_born() = lowest_coord().cell;
294,661,546✔
175

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
618,953,381✔
178
      cell_last(j) = coord(j).cell;
324,291,835✔
179
    }
180
    n_coord_last() = n_coord();
294,661,546✔
181
  }
182

183
  // Write particle track.
184
  if (write_track())
2,147,483,647✔
185
    write_particle_track(*this);
14,911✔
186

187
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
188
    check_cell_overlap(*this);
×
189

190
  // Calculate microscopic and macroscopic cross sections
191
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
192
    if (settings::run_CE) {
2,147,483,647✔
193
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
2,147,483,647✔
194
        // If the material is the same as the last material and the
195
        // temperature hasn't changed, we don't need to lookup cross
196
        // sections again.
197
        model::materials[material()]->calculate_xs(*this);
1,775,026,157✔
198
      }
199
    } else {
200
      // Get the MG data; unlike the CE case above, we have to re-calculate
201
      // cross sections for every collision since the cross sections may
202
      // be angle-dependent
203
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,147,483,647✔
204

205
      // Update the particle's group while we know we are multi-group
206
      g_last() = g();
2,147,483,647✔
207
    }
208
  } else {
209
    macro_xs().total = 0.0;
90,595,140✔
210
    macro_xs().absorption = 0.0;
90,595,140✔
211
    macro_xs().fission = 0.0;
90,595,140✔
212
    macro_xs().nu_fission = 0.0;
90,595,140✔
213
  }
214
}
215

216
void Particle::event_advance()
2,147,483,647✔
217
{
218
  // Find the distance to the nearest boundary
219
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
220

221
  // Sample a distance to collision
222
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
223
    collision_distance() = 0.0;
65,518,140✔
224
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
225
    collision_distance() = INFINITY;
90,595,140✔
226
  } else {
227
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
228
  }
229

230
  // Select smaller of the two distances
231
  double distance = std::min(boundary().distance, collision_distance());
2,147,483,647✔
232

233
  // Advance particle in space and time
234
  // Short-term solution until the surface source is revised and we can use
235
  // this->move_distance(distance)
236
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
237
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
238
  }
239
  double dt = distance / this->speed();
2,147,483,647✔
240
  this->time() += dt;
2,147,483,647✔
241
  this->lifetime() += dt;
2,147,483,647✔
242

243
  // Kill particle if its time exceeds the cutoff
244
  bool hit_time_boundary = false;
2,147,483,647✔
245
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
246
  if (time() > time_cutoff) {
2,147,483,647✔
247
    double dt = time() - time_cutoff;
15,000✔
248
    time() = time_cutoff;
15,000✔
249
    lifetime() = time_cutoff;
15,000✔
250

251
    double push_back_distance = speed() * dt;
15,000✔
252
    this->move_distance(-push_back_distance);
15,000✔
253
    hit_time_boundary = true;
15,000✔
254
  }
255

256
  // Score track-length tallies
257
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
258
    score_tracklength_tally(*this, distance);
1,709,652,982✔
259
  }
260

261
  // Score track-length estimate of k-eff
262
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
263
      type() == ParticleType::neutron) {
2,147,483,647✔
264
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
265
  }
266

267
  // Score flux derivative accumulators for differential tallies.
268
  if (!model::active_tallies.empty()) {
2,147,483,647✔
269
    score_track_derivative(*this, distance);
1,933,262,204✔
270
  }
271

272
  // Set particle weight to zero if it hit the time boundary
273
  if (hit_time_boundary) {
2,147,483,647✔
274
    wgt() = 0.0;
15,000✔
275
  }
276
}
2,147,483,647✔
277

278
void Particle::event_cross_surface()
2,147,483,647✔
279
{
280
  // Saving previous cell data
281
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
282
    cell_last(j) = coord(j).cell;
2,147,483,647✔
283
  }
284
  n_coord_last() = n_coord();
2,147,483,647✔
285

286
  // Set surface that particle is on and adjust coordinate levels
287
  surface() = boundary().surface;
2,147,483,647✔
288
  n_coord() = boundary().coord_level;
2,147,483,647✔
289

290
  if (boundary().lattice_translation[0] != 0 ||
2,147,483,647✔
291
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
292
      boundary().lattice_translation[2] != 0) {
2,110,216,342✔
293
    // Particle crosses lattice boundary
294

295
    bool verbose = settings::verbosity >= 10 || trace();
933,024,459✔
296
    cross_lattice(*this, boundary(), verbose);
933,024,459✔
297
    event() = TallyEvent::LATTICE;
933,024,459✔
298
  } else {
299
    // Particle crosses surface
300
    const auto& surf {model::surfaces[surface_index()].get()};
1,850,384,327✔
301
    // If BC, add particle to surface source before crossing surface
302
    if (surf->surf_source_ && surf->bc_) {
1,850,384,327✔
303
      add_surf_source_to_bank(*this, *surf);
868,406,186✔
304
    }
305
    this->cross_surface(*surf);
1,850,384,327✔
306
    // If no BC, add particle to surface source after crossing surface
307
    if (surf->surf_source_ && !surf->bc_) {
1,850,384,314✔
308
      add_surf_source_to_bank(*this, *surf);
980,729,195✔
309
    }
310
    if (settings::weight_window_checkpoint_surface) {
1,850,384,314✔
UNCOV
311
      apply_weight_windows(*this);
×
312
    }
313
    event() = TallyEvent::SURFACE;
1,850,384,314✔
314
  }
315
  // Score cell to cell partial currents
316
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
317
    score_surface_tally(*this, model::active_surface_tallies);
47,585,475✔
318
  }
319
}
2,147,483,647✔
320

321
void Particle::event_collide()
2,147,483,647✔
322
{
323
  // Score collision estimate of keff
324
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
325
      type() == ParticleType::neutron) {
2,147,483,647✔
326
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
327
  }
328

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

333
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
334
    score_surface_tally(*this, model::active_meshsurf_tallies);
97,094,864✔
335

336
  // Clear surface component
337
  surface() = SURFACE_NONE;
2,147,483,647✔
338

339
  if (settings::run_CE) {
2,147,483,647✔
340
    collision(*this);
967,388,103✔
341
  } else {
342
    collision_mg(*this);
2,147,483,647✔
343
  }
344

345
  // Score collision estimator tallies -- this is done after a collision
346
  // has occurred rather than before because we need information on the
347
  // outgoing energy for any tallies with an outgoing energy filter
348
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
349
    score_collision_tally(*this);
123,492,584✔
350
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
351
    if (settings::run_CE) {
158,103,284✔
352
      score_analog_tally_ce(*this);
156,465,269✔
353
    } else {
354
      score_analog_tally_mg(*this);
1,638,015✔
355
    }
356
  }
357

358
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
359
      type() == ParticleType::photon) {
23,070✔
360
    pht_collision_energy();
2,760✔
361
  }
362

363
  // Reset banked weight during collision
364
  n_bank() = 0;
2,147,483,647✔
365
  bank_second_E() = 0.0;
2,147,483,647✔
366
  wgt_bank() = 0.0;
2,147,483,647✔
367
  zero_delayed_bank();
2,147,483,647✔
368

369
  // Reset fission logical
370
  fission() = false;
2,147,483,647✔
371

372
  // Save coordinates for tallying purposes
373
  r_last_current() = r();
2,147,483,647✔
374

375
  // Set last material to none since cross sections will need to be
376
  // re-evaluated
377
  material_last() = C_NONE;
2,147,483,647✔
378

379
  // Set all directions to base level -- right now, after a collision, only
380
  // the base level directions are changed
381
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
382
    if (coord(j + 1).rotated) {
165,944,376✔
383
      // If next level is rotated, apply rotation matrix
384
      const auto& m {model::cells[coord(j).cell]->rotation_};
14,174,025✔
385
      const auto& u {coord(j).u};
14,174,025✔
386
      coord(j + 1).u = u.rotate(m);
14,174,025✔
387
    } else {
388
      // Otherwise, copy this level's direction
389
      coord(j + 1).u = coord(j).u;
151,770,351✔
390
    }
391
  }
392

393
  // Score flux derivative accumulators for differential tallies.
394
  if (!model::active_tallies.empty())
2,147,483,647✔
395
    score_collision_derivative(*this);
836,447,452✔
396

397
#ifdef DAGMC
398
  history().reset();
227,991,337✔
399
#endif
400
}
2,147,483,647✔
401

402
void Particle::event_revive_from_secondary()
2,147,483,647✔
403
{
404
  // If particle has too many events, display warning and kill it
405
  ++n_event();
2,147,483,647✔
406
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
UNCOV
407
    warning("Particle " + std::to_string(id()) +
×
408
            " underwent maximum number of events.");
UNCOV
409
    wgt() = 0.0;
×
410
  }
411

412
  // Check for secondary particles if this particle is dead
413
  if (!alive()) {
2,147,483,647✔
414
    // Write final position for this particle
415
    if (write_track()) {
294,661,358✔
416
      write_particle_track(*this);
9,190✔
417
    }
418

419
    // If no secondary particles, break out of event loop
420
    if (secondary_bank().empty())
294,661,358✔
421
      return;
213,255,251✔
422

423
    from_source(&secondary_bank().back());
81,406,107✔
424
    secondary_bank().pop_back();
81,406,107✔
425
    n_event() = 0;
81,406,107✔
426
    bank_second_E() = 0.0;
81,406,107✔
427

428
    // Subtract secondary particle energy from interim pulse-height results
429
    if (!model::active_pulse_height_tallies.empty() &&
81,427,242✔
430
        this->type() == ParticleType::photon) {
21,135✔
431
      // Since the birth cell of the particle has not been set we
432
      // have to determine it before the energy of the secondary particle can be
433
      // removed from the pulse-height of this cell.
434
      if (lowest_coord().cell == C_NONE) {
825✔
435
        bool verbose = settings::verbosity >= 10 || trace();
825✔
436
        if (!exhaustive_find_cell(*this, verbose)) {
825✔
UNCOV
437
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
438
                       std::to_string(id()));
×
UNCOV
439
          return;
×
440
        }
441
        // Set birth cell attribute
442
        if (cell_born() == C_NONE)
825✔
443
          cell_born() = lowest_coord().cell;
825✔
444

445
        // Initialize last cells from current cell
446
        for (int j = 0; j < n_coord(); ++j) {
1,650✔
447
          cell_last(j) = coord(j).cell;
825✔
448
        }
449
        n_coord_last() = n_coord();
825✔
450
      }
451
      pht_secondary_particles();
825✔
452
    }
453

454
    // Enter new particle in particle track file
455
    if (write_track())
81,406,107✔
456
      add_particle_track(*this);
7,720✔
457
  }
458
}
459

460
void Particle::event_death()
213,256,251✔
461
{
462
#ifdef DAGMC
463
  history().reset();
14,258,385✔
464
#endif
465

466
  // Finish particle track output.
467
  if (write_track()) {
213,256,251✔
468
    finalize_particle_track(*this);
1,470✔
469
  }
470

471
// Contribute tally reduction variables to global accumulator
472
#pragma omp atomic
86,017,723✔
473
  global_tally_absorption += keff_tally_absorption();
213,256,251✔
474
#pragma omp atomic
85,964,971✔
475
  global_tally_collision += keff_tally_collision();
213,256,251✔
476
#pragma omp atomic
85,781,720✔
477
  global_tally_tracklength += keff_tally_tracklength();
213,256,251✔
478
#pragma omp atomic
85,586,567✔
479
  global_tally_leakage += keff_tally_leakage();
213,256,251✔
480

481
  // Reset particle tallies once accumulated
482
  keff_tally_absorption() = 0.0;
213,256,251✔
483
  keff_tally_collision() = 0.0;
213,256,251✔
484
  keff_tally_tracklength() = 0.0;
213,256,251✔
485
  keff_tally_leakage() = 0.0;
213,256,251✔
486

487
  if (!model::active_pulse_height_tallies.empty()) {
213,256,251✔
488
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
7,500✔
489
  }
490

491
  // Record the number of progeny created by this particle.
492
  // This data will be used to efficiently sort the fission bank.
493
  if (settings::run_mode == RunMode::EIGENVALUE) {
213,256,251✔
494
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
182,177,000✔
495
    simulation::progeny_per_particle[offset] = n_progeny();
182,177,000✔
496
  }
497
}
213,256,251✔
498

499
void Particle::pht_collision_energy()
2,760✔
500
{
501
  // Adds the energy particles lose in a collision to the pulse-height
502

503
  // determine index of cell in pulse_height_cells
504
  auto it = std::find(model::pulse_height_cells.begin(),
2,760✔
505
    model::pulse_height_cells.end(), lowest_coord().cell);
2,760✔
506

507
  if (it != model::pulse_height_cells.end()) {
2,760✔
508
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,760✔
509
    pht_storage()[index] += E_last() - E();
2,760✔
510

511
    // If the energy of the particle is below the cutoff, it will not be sampled
512
    // so its energy is added to the pulse-height in the cell
513
    int photon = static_cast<int>(ParticleType::photon);
2,760✔
514
    if (E() < settings::energy_cutoff[photon]) {
2,760✔
515
      pht_storage()[index] += E();
1,125✔
516
    }
517
  }
518
}
2,760✔
519

520
void Particle::pht_secondary_particles()
825✔
521
{
522
  // Removes the energy of secondary produced particles from the pulse-height
523

524
  // determine index of cell in pulse_height_cells
525
  auto it = std::find(model::pulse_height_cells.begin(),
825✔
526
    model::pulse_height_cells.end(), cell_born());
825✔
527

528
  if (it != model::pulse_height_cells.end()) {
825✔
529
    int index = std::distance(model::pulse_height_cells.begin(), it);
825✔
530
    pht_storage()[index] -= E();
825✔
531
  }
532
}
825✔
533

534
void Particle::cross_surface(const Surface& surf)
1,851,703,367✔
535
{
536

537
  if (settings::verbosity >= 10 || trace()) {
1,851,703,367✔
538
    write_message(1, "    Crossing surface {}", surf.id_);
45✔
539
  }
540

541
// if we're crossing a CSG surface, make sure the DAG history is reset
542
#ifdef DAGMC
543
  if (surf.geom_type() == GeometryType::CSG)
122,922,686✔
544
    history().reset();
122,887,370✔
545
#endif
546

547
  // Handle any applicable boundary conditions.
548
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,851,703,367✔
549
    surf.bc_->handle_particle(*this, surf);
868,733,219✔
550
    return;
868,733,219✔
551
  }
552

553
  // ==========================================================================
554
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
555

556
#ifdef DAGMC
557
  // in DAGMC, we know what the next cell should be
558
  if (surf.geom_type() == GeometryType::DAG) {
65,528,971✔
559
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
560
                       lowest_coord().universe) -
28,265✔
561
                     1;
28,265✔
562
    // save material and temp
563
    material_last() = material();
28,265✔
564
    sqrtkT_last() = sqrtkT();
28,265✔
565
    // set new cell value
566
    lowest_coord().cell = i_cell;
28,265✔
567
    auto& cell = model::cells[i_cell];
28,265✔
568

569
    cell_instance() = 0;
28,265✔
570
    if (cell->distribcell_index_ >= 0)
28,265✔
571
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
572

573
    material() = cell->material(cell_instance());
28,265✔
574
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
575
    return;
28,265✔
576
  }
577
#endif
578

579
  bool verbose = settings::verbosity >= 10 || trace();
982,941,883✔
580
  if (neighbor_list_find_cell(*this, verbose)) {
982,941,883✔
581
    return;
982,903,668✔
582
  }
583

584
  // ==========================================================================
585
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
586

587
  // Remove lower coordinate levels
588
  n_coord() = 1;
38,215✔
589
  bool found = exhaustive_find_cell(*this, verbose);
38,215✔
590

591
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
38,215✔
592
    // If a cell is still not found, there are two possible causes: 1) there is
593
    // a void in the model, and 2) the particle hit a surface at a tangent. If
594
    // the particle is really traveling tangent to a surface, if we move it
595
    // forward a tiny bit it should fix the problem.
596

597
    surface() = SURFACE_NONE;
7,840✔
598
    n_coord() = 1;
7,840✔
599
    r() += TINY_BIT * u();
7,840✔
600

601
    // Couldn't find next cell anywhere! This probably means there is an actual
602
    // undefined region in the geometry.
603

604
    if (!exhaustive_find_cell(*this, verbose)) {
7,840✔
605
      mark_as_lost("After particle " + std::to_string(id()) +
23,507✔
606
                   " crossed surface " + std::to_string(surf.id_) +
31,334✔
607
                   " it could not be located in any cell and it did not leak.");
608
      return;
7,827✔
609
    }
610
  }
611
}
612

613
void Particle::cross_vacuum_bc(const Surface& surf)
41,506,402✔
614
{
615
  // Score any surface current tallies -- note that the particle is moved
616
  // forward slightly so that if the mesh boundary is on the surface, it is
617
  // still processed
618

619
  if (!model::active_meshsurf_tallies.empty()) {
41,506,402✔
620
    // TODO: Find a better solution to score surface currents than
621
    // physically moving the particle forward slightly
622

623
    r() += TINY_BIT * u();
1,440,730✔
624
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,440,730✔
625
  }
626

627
  // Score to global leakage tally
628
  keff_tally_leakage() += wgt();
41,506,402✔
629

630
  // Kill the particle
631
  wgt() = 0.0;
41,506,402✔
632

633
  // Display message
634
  if (settings::verbosity >= 10 || trace()) {
41,506,402✔
635
    write_message(1, "    Leaked out of surface {}", surf.id_);
15✔
636
  }
637
}
41,506,402✔
638

639
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
827,718,055✔
640
{
641
  // Do not handle reflective boundary conditions on lower universes
642
  if (n_coord() != 1) {
827,718,055✔
UNCOV
643
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
644
                 " off surface in a lower universe.");
UNCOV
645
    return;
×
646
  }
647

648
  // Score surface currents since reflection causes the direction of the
649
  // particle to change. For surface filters, we need to score the tallies
650
  // twice, once before the particle's surface attribute has changed and
651
  // once after. For mesh surface filters, we need to artificially move
652
  // the particle slightly back in case the surface crossing is coincident
653
  // with a mesh boundary
654

655
  if (!model::active_surface_tallies.empty()) {
827,718,055✔
656
    score_surface_tally(*this, model::active_surface_tallies);
384,285✔
657
  }
658

659
  if (!model::active_meshsurf_tallies.empty()) {
827,718,055✔
660
    Position r {this->r()};
71,952,907✔
661
    this->r() -= TINY_BIT * u();
71,952,907✔
662
    score_surface_tally(*this, model::active_meshsurf_tallies);
71,952,907✔
663
    this->r() = r;
71,952,907✔
664
  }
665

666
  // Set the new particle direction
667
  u() = new_u;
827,718,055✔
668

669
  // Reassign particle's cell and surface
670
  coord(0).cell = cell_last(0);
827,718,055✔
671
  surface() = -surface();
827,718,055✔
672

673
  // If a reflective surface is coincident with a lattice or universe
674
  // boundary, it is necessary to redetermine the particle's coordinates in
675
  // the lower universes.
676
  // (unless we're using a dagmc model, which has exactly one universe)
677
  n_coord() = 1;
827,718,055✔
678
  if (surf.geom_type() != GeometryType::DAG &&
1,655,433,571✔
679
      !neighbor_list_find_cell(*this)) {
827,715,516✔
UNCOV
680
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
681
                 std::to_string(surf.id_) + ".");
×
682
    return;
×
683
  }
684

685
  // Set previous coordinate going slightly past surface crossing
686
  r_last_current() = r() + TINY_BIT * u();
827,718,055✔
687

688
  // Diagnostic message
689
  if (settings::verbosity >= 10 || trace()) {
827,718,055✔
UNCOV
690
    write_message(1, "    Reflected from surface {}", surf.id_);
×
691
  }
692
}
693

694
void Particle::cross_periodic_bc(
909,702✔
695
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
696
{
697
  // Do not handle periodic boundary conditions on lower universes
698
  if (n_coord() != 1) {
909,702✔
UNCOV
699
    mark_as_lost(
×
UNCOV
700
      "Cannot transfer particle " + std::to_string(id()) +
×
701
      " across surface in a lower universe. Boundary conditions must be "
702
      "applied to root universe.");
703
    return;
×
704
  }
705

706
  // Score surface currents since reflection causes the direction of the
707
  // particle to change -- artificially move the particle slightly back in
708
  // case the surface crossing is coincident with a mesh boundary
709
  if (!model::active_meshsurf_tallies.empty()) {
909,702✔
UNCOV
710
    Position r {this->r()};
×
UNCOV
711
    this->r() -= TINY_BIT * u();
×
UNCOV
712
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
713
    this->r() = r;
×
714
  }
715

716
  // Adjust the particle's location and direction.
717
  r() = new_r;
909,702✔
718
  u() = new_u;
909,702✔
719

720
  // Reassign particle's surface
721
  surface() = new_surface;
909,702✔
722

723
  // Figure out what cell particle is in now
724
  n_coord() = 1;
909,702✔
725

726
  if (!neighbor_list_find_cell(*this)) {
909,702✔
UNCOV
727
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
728
                 "boundary on surface " +
×
UNCOV
729
                 std::to_string(surf.id_) +
×
730
                 ". The normal vector "
731
                 "of one periodic surface may need to be reversed.");
732
    return;
×
733
  }
734

735
  // Set previous coordinate going slightly past surface crossing
736
  r_last_current() = r() + TINY_BIT * u();
909,702✔
737

738
  // Diagnostic message
739
  if (settings::verbosity >= 10 || trace()) {
909,702✔
UNCOV
740
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
741
  }
742
}
743

744
void Particle::mark_as_lost(const char* message)
7,840✔
745
{
746
  // Print warning and write lost particle file
747
  warning(message);
7,840✔
748
  if (settings::max_write_lost_particles < 0 ||
7,840✔
749
      simulation::n_lost_particles < settings::max_write_lost_particles) {
7,500✔
750
    write_restart();
450✔
751
  }
752
  // Increment number of lost particles
753
  wgt() = 0.0;
7,840✔
754
#pragma omp atomic
3,124✔
755
  simulation::n_lost_particles += 1;
4,716✔
756

757
  // Count the total number of simulated particles (on this processor)
758
  auto n = simulation::current_batch * settings::gen_per_batch *
7,840✔
759
           simulation::work_per_rank;
760

761
  // Abort the simulation if the maximum number of lost particles has been
762
  // reached
763
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
7,840✔
764
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
13✔
765
    fatal_error("Maximum number of lost particles has been reached.");
13✔
766
  }
767
}
7,827✔
768

769
void Particle::write_restart() const
450✔
770
{
771
  // Dont write another restart file if in particle restart mode
772
  if (settings::run_mode == RunMode::PARTICLE)
450✔
773
    return;
30✔
774

775
  // Set up file name
776
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
777
    simulation::current_batch, id());
801✔
778

779
#pragma omp critical(WriteParticleRestart)
314✔
780
  {
781
    // Create file
782
    hid_t file_id = file_open(filename, 'w');
420✔
783

784
    // Write filetype and version info
785
    write_attribute(file_id, "filetype", "particle restart");
420✔
786
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
420✔
787
    write_attribute(file_id, "openmc_version", VERSION);
420✔
788
#ifdef GIT_SHA1
789
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
790
#endif
791

792
    // Write data to file
793
    write_dataset(file_id, "current_batch", simulation::current_batch);
420✔
794
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
420✔
795
    write_dataset(file_id, "current_generation", simulation::current_gen);
420✔
796
    write_dataset(file_id, "n_particles", settings::n_particles);
420✔
797
    switch (settings::run_mode) {
420✔
798
    case RunMode::FIXED_SOURCE:
315✔
799
      write_dataset(file_id, "run_mode", "fixed source");
315✔
800
      break;
315✔
801
    case RunMode::EIGENVALUE:
105✔
802
      write_dataset(file_id, "run_mode", "eigenvalue");
105✔
803
      break;
105✔
UNCOV
804
    case RunMode::PARTICLE:
×
UNCOV
805
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
806
      break;
×
UNCOV
807
    default:
×
UNCOV
808
      break;
×
809
    }
810
    write_dataset(file_id, "id", id());
420✔
811
    write_dataset(file_id, "type", static_cast<int>(type()));
420✔
812

813
    int64_t i = current_work();
420✔
814
    if (settings::run_mode == RunMode::EIGENVALUE) {
420✔
815
      // take source data from primary bank for eigenvalue simulation
816
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
105✔
817
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
105✔
818
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
105✔
819
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
105✔
820
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
105✔
821
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
315✔
822
      // re-sample using rng random number seed used to generate source particle
823
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
315✔
824
                     settings::n_particles +
315✔
825
                   simulation::work_index[mpi::rank] + i;
315✔
826
      uint64_t seed = init_seed(id, STREAM_SOURCE);
315✔
827
      // re-sample source site
828
      auto site = sample_external_source(&seed);
315✔
829
      write_dataset(file_id, "weight", site.wgt);
315✔
830
      write_dataset(file_id, "energy", site.E);
315✔
831
      write_dataset(file_id, "xyz", site.r);
315✔
832
      write_dataset(file_id, "uvw", site.u);
315✔
833
      write_dataset(file_id, "time", site.time);
315✔
834
    }
835

836
    // Close file
837
    file_close(file_id);
420✔
838
  } // #pragma omp critical
839
}
420✔
840

841
void Particle::update_neutron_xs(
2,147,483,647✔
842
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
843
{
844
  // Get microscopic cross section cache
845
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
846

847
  // If the cache doesn't match, recalculate micro xs
848
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
849
      i_sab != micro.index_sab || sab_frac != micro.sab_frac) {
2,147,483,647✔
850
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
851

852
    // If NCrystal is being used, update micro cross section cache
853
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
854
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
15,025,845✔
855
      ncrystal_update_micro(ncrystal_xs, micro);
15,025,845✔
856
    }
857
  }
858
}
2,147,483,647✔
859

860
//==============================================================================
861
// Non-method functions
862
//==============================================================================
863

864
std::string particle_type_to_str(ParticleType type)
4,268,340✔
865
{
866
  switch (type) {
4,268,340✔
867
  case ParticleType::neutron:
3,272,625✔
868
    return "neutron";
3,272,625✔
869
  case ParticleType::photon:
995,415✔
870
    return "photon";
995,415✔
871
  case ParticleType::electron:
150✔
872
    return "electron";
150✔
873
  case ParticleType::positron:
150✔
874
    return "positron";
150✔
875
  }
UNCOV
876
  UNREACHABLE();
×
877
}
878

879
ParticleType str_to_particle_type(std::string str)
4,073,117✔
880
{
881
  if (str == "neutron") {
4,073,117✔
882
    return ParticleType::neutron;
933,870✔
883
  } else if (str == "photon") {
3,139,247✔
884
    return ParticleType::photon;
3,139,159✔
885
  } else if (str == "electron") {
88✔
886
    return ParticleType::electron;
44✔
887
  } else if (str == "positron") {
44✔
888
    return ParticleType::positron;
44✔
889
  } else {
UNCOV
890
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
891
  }
892
}
893

894
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,849,135,381✔
895
{
896
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
897
      simulation::surf_source_bank.full()) {
1,450,732,338✔
898
    return;
1,848,989,283✔
899
  }
900

901
  // If a cell/cellfrom/cellto parameter is defined
902
  if (settings::ssw_cell_id != C_NONE) {
440,716✔
903

904
    // Retrieve cell index and storage type
905
    int cell_idx = model::cell_map[settings::ssw_cell_id];
357,618✔
906

907
    if (surf.bc_) {
357,618✔
908
      // Leave if cellto with vacuum boundary condition
909
      if (surf.bc_->type() == "vacuum" &&
256,472✔
910
          settings::ssw_cell_type == SSWCellType::To) {
44,222✔
911
        return;
16,425✔
912
      }
913

914
      // Leave if other boundary condition than vacuum
915
      if (surf.bc_->type() != "vacuum") {
195,825✔
916
        return;
168,028✔
917
      }
918
    }
919

920
    // Check if the cell of interest has been exited
921
    bool exited = false;
173,165✔
922
    for (int i = 0; i < p.n_coord_last(); ++i) {
460,087✔
923
      if (p.cell_last(i) == cell_idx) {
286,922✔
924
        exited = true;
102,059✔
925
      }
926
    }
927

928
    // Check if the cell of interest has been entered
929
    bool entered = false;
173,165✔
930
    for (int i = 0; i < p.n_coord(); ++i) {
412,595✔
931
      if (p.coord(i).cell == cell_idx) {
239,430✔
932
        entered = true;
81,571✔
933
      }
934
    }
935

936
    // Vacuum boundary conditions: return if cell is not exited
937
    if (surf.bc_) {
173,165✔
938
      if (surf.bc_->type() == "vacuum" && !exited) {
27,797✔
939
        return;
19,097✔
940
      }
941
    } else {
942

943
      // If we both enter and exit the cell of interest
944
      if (entered && exited) {
145,368✔
945
        return;
39,797✔
946
      }
947

948
      // If we did not enter nor exit the cell of interest
949
      if (!entered && !exited) {
105,571✔
950
        return;
18,935✔
951
      }
952

953
      // If cellfrom and the cell before crossing is not the cell of
954
      // interest
955
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
86,636✔
956
        return;
15,962✔
957
      }
958

959
      // If cellto and the cell after crossing is not the cell of interest
960
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
70,674✔
961
        return;
16,374✔
962
      }
963
    }
964
  }
965

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

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