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

openmc-dev / openmc / 12673179585

08 Jan 2025 03:00PM UTC coverage: 84.869% (+0.04%) from 84.827%
12673179585

Pull #3242

github

web-flow
Merge 650f2c09e into 8c7200fad
Pull Request #3242: Fix for erroneously non-zero tally results of photon threshold reactions

6 of 6 new or added lines in 1 file covered. (100.0%)

312 existing lines in 5 files now uncovered.

50088 of 59018 relevant lines covered (84.87%)

33959169.36 hits per line

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

92.58
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/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:
12,380,640✔
54
    mass = 0.0;
12,380,640✔
55
    break;
12,380,640✔
56
  case ParticleType::electron:
48,812,844✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,812,844✔
59
    break;
48,812,844✔
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);
908,633,547✔
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
void Particle::move_distance(double length)
12,000✔
79
{
80
  for (int j = 0; j < n_coord(); ++j) {
24,000✔
81
    coord(j).r += length * coord(j).u;
12,000✔
82
  }
83
}
12,000✔
84

85
void Particle::create_secondary(
104,284,479✔
86
  double wgt, Direction u, double E, ParticleType type)
87
{
88
  // If energy is below cutoff for this particle, don't create secondary
89
  // particle
90
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
104,284,479✔
91
    return;
48,693,348✔
92
  }
93

94
  secondary_bank().emplace_back();
55,591,131✔
95

96
  auto& bank {secondary_bank().back()};
55,591,131✔
97
  bank.particle = type;
55,591,131✔
98
  bank.wgt = wgt;
55,591,131✔
99
  bank.r = r();
55,591,131✔
100
  bank.u = u;
55,591,131✔
101
  bank.E = settings::run_CE ? E : g();
55,591,131✔
102
  bank.time = time();
55,591,131✔
103

104
  n_bank_second() += 1;
55,591,131✔
105
}
106

107
void Particle::from_source(const SourceSite* src)
216,933,178✔
108
{
109
  // Reset some attributes
110
  clear();
216,933,178✔
111
  surface() = 0;
216,933,178✔
112
  cell_born() = C_NONE;
216,933,178✔
113
  material() = C_NONE;
216,933,178✔
114
  n_collision() = 0;
216,933,178✔
115
  fission() = false;
216,933,178✔
116
  zero_flux_derivs();
216,933,178✔
117

118
  // Copy attributes from source bank site
119
  type() = src->particle;
216,933,178✔
120
  wgt() = src->wgt;
216,933,178✔
121
  wgt_last() = src->wgt;
216,933,178✔
122
  r() = src->r;
216,933,178✔
123
  u() = src->u;
216,933,178✔
124
  r_born() = src->r;
216,933,178✔
125
  r_last_current() = src->r;
216,933,178✔
126
  r_last() = src->r;
216,933,178✔
127
  u_last() = src->u;
216,933,178✔
128
  if (settings::run_CE) {
216,933,178✔
129
    E() = src->E;
95,367,178✔
130
    g() = 0;
95,367,178✔
131
  } else {
132
    g() = static_cast<int>(src->E);
121,566,000✔
133
    g_last() = static_cast<int>(src->E);
121,566,000✔
134
    E() = data::mg.energy_bin_avg_[g()];
121,566,000✔
135
  }
136
  E_last() = E();
216,933,178✔
137
  time() = src->time;
216,933,178✔
138
  time_last() = src->time;
216,933,178✔
139
}
216,933,178✔
140

141
void Particle::event_calculate_xs()
2,147,483,647✔
142
{
143
  // Set the random number stream
144
  stream() = STREAM_TRACKING;
2,147,483,647✔
145

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

153
  // Reset event variables
154
  event() = TallyEvent::KILL;
2,147,483,647✔
155
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
156
  event_mt() = REACTION_NONE;
2,147,483,647✔
157

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

168
    // Set birth cell attribute
169
    if (cell_born() == C_NONE)
216,374,554✔
170
      cell_born() = lowest_coord().cell;
216,374,554✔
171

172
    // Initialize last cells from current cell
173
    for (int j = 0; j < n_coord(); ++j) {
444,298,911✔
174
      cell_last(j) = coord(j).cell;
227,924,357✔
175
    }
176
    n_coord_last() = n_coord();
216,374,554✔
177
  }
178

179
  // Write particle track.
180
  if (write_track())
2,147,483,647✔
181
    write_particle_track(*this);
11,611✔
182

183
  if (settings::check_overlaps)
2,147,483,647✔
184
    check_cell_overlap(*this);
×
185

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

201
      // Update the particle's group while we know we are multi-group
202
      g_last() = g();
2,147,483,647✔
203
    }
204
  } else {
205
    macro_xs().total = 0.0;
50,524,846✔
206
    macro_xs().absorption = 0.0;
50,524,846✔
207
    macro_xs().fission = 0.0;
50,524,846✔
208
    macro_xs().nu_fission = 0.0;
50,524,846✔
209
  }
210
}
211

212
void Particle::event_advance()
2,147,483,647✔
213
{
214
  // Find the distance to the nearest boundary
215
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
216

217
  // Sample a distance to collision
218
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
219
    collision_distance() = 0.0;
48,812,844✔
220
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
221
    collision_distance() = INFINITY;
50,524,846✔
222
  } else {
223
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
224
  }
225

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

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

237
  // Kill particle if its time exceeds the cutoff
238
  bool hit_time_boundary = false;
2,147,483,647✔
239
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
240
  if (time() > time_cutoff) {
2,147,483,647✔
241
    double dt = time() - time_cutoff;
12,000✔
242
    time() = time_cutoff;
12,000✔
243

244
    double push_back_distance = speed() * dt;
12,000✔
245
    this->move_distance(-push_back_distance);
12,000✔
246
    hit_time_boundary = true;
12,000✔
247
  }
248

249
  // Score track-length tallies
250
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
251
    score_tracklength_tally(*this, distance);
1,364,344,030✔
252
  }
253

254
  // Score track-length estimate of k-eff
255
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
256
      type() == ParticleType::neutron) {
2,147,483,647✔
257
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
258
  }
259

260
  // Score flux derivative accumulators for differential tallies.
261
  if (!model::active_tallies.empty()) {
2,147,483,647✔
262
    score_track_derivative(*this, distance);
1,582,065,554✔
263
  }
264

265
  // Set particle weight to zero if it hit the time boundary
266
  if (hit_time_boundary) {
2,147,483,647✔
267
    wgt() = 0.0;
12,000✔
268
  }
269
}
2,147,483,647✔
270

271
void Particle::event_cross_surface()
1,684,349,859✔
272
{
273
  // Saving previous cell data
274
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
275
    cell_last(j) = coord(j).cell;
2,147,483,647✔
276
  }
277
  n_coord_last() = n_coord();
1,684,349,859✔
278

279
  // Set surface that particle is on and adjust coordinate levels
280
  surface() = boundary().surface_index;
1,684,349,859✔
281
  n_coord() = boundary().coord_level;
1,684,349,859✔
282

283
  if (boundary().lattice_translation[0] != 0 ||
1,684,349,859✔
284
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
285
      boundary().lattice_translation[2] != 0) {
1,482,005,942✔
286
    // Particle crosses lattice boundary
287

288
    bool verbose = settings::verbosity >= 10 || trace();
241,829,122✔
289
    cross_lattice(*this, boundary(), verbose);
241,829,122✔
290
    event() = TallyEvent::LATTICE;
241,829,122✔
291
  } else {
292
    // Particle crosses surface
293
    // TODO: off-by-one
294
    const auto& surf {model::surfaces[std::abs(surface()) - 1].get()};
1,442,520,737✔
295
    // If BC, add particle to surface source before crossing surface
296
    if (surf->surf_source_ && surf->bc_) {
1,442,520,737✔
297
      add_surf_source_to_bank(*this, *surf);
672,737,999✔
298
    }
299
    this->cross_surface(*surf);
1,442,520,737✔
300
    // If no BC, add particle to surface source after crossing surface
301
    if (surf->surf_source_ && !surf->bc_) {
1,442,520,727✔
302
      add_surf_source_to_bank(*this, *surf);
768,792,938✔
303
    }
304
    if (settings::weight_window_checkpoint_surface) {
1,442,520,727✔
305
      apply_weight_windows(*this);
×
306
    }
307
    event() = TallyEvent::SURFACE;
1,442,520,727✔
308
  }
309
  // Score cell to cell partial currents
310
  if (!model::active_surface_tallies.empty()) {
1,684,349,849✔
311
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
312
  }
313
}
1,684,349,849✔
314

315
void Particle::event_collide()
2,147,483,647✔
316
{
317
  // Score collision estimate of keff
318
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
319
      type() == ParticleType::neutron) {
2,147,483,647✔
320
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
321
  }
322

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

327
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
328
    score_surface_tally(*this, model::active_meshsurf_tallies);
136,443,972✔
329

330
  // Clear surface component
331
  surface() = 0;
2,147,483,647✔
332

333
  if (settings::run_CE) {
2,147,483,647✔
334
    collision(*this);
801,235,457✔
335
  } else {
336
    collision_mg(*this);
1,939,604,940✔
337
  }
338

339
  // Score collision estimator tallies -- this is done after a collision
340
  // has occurred rather than before because we need information on the
341
  // outgoing energy for any tallies with an outgoing energy filter
342
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
343
    score_collision_tally(*this);
91,602,840✔
344
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
345
    if (settings::run_CE) {
163,265,028✔
346
      score_analog_tally_ce(*this);
161,954,616✔
347
    } else {
348
      score_analog_tally_mg(*this);
1,310,412✔
349
    }
350
  }
351

352
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
353
      type() == ParticleType::photon) {
18,456✔
354
    pht_collision_energy();
2,208✔
355
  }
356

357
  // Reset banked weight during collision
358
  n_bank() = 0;
2,147,483,647✔
359
  n_bank_second() = 0;
2,147,483,647✔
360
  wgt_bank() = 0.0;
2,147,483,647✔
361
  zero_delayed_bank();
2,147,483,647✔
362

363
  // Reset fission logical
364
  fission() = false;
2,147,483,647✔
365

366
  // Save coordinates for tallying purposes
367
  r_last_current() = r();
2,147,483,647✔
368

369
  // Set last material to none since cross sections will need to be
370
  // re-evaluated
371
  material_last() = C_NONE;
2,147,483,647✔
372

373
  // Set all directions to base level -- right now, after a collision, only
374
  // the base level directions are changed
375
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
376
    if (coord(j + 1).rotated) {
127,272,021✔
377
      // If next level is rotated, apply rotation matrix
378
      const auto& m {model::cells[coord(j).cell]->rotation_};
11,339,220✔
379
      const auto& u {coord(j).u};
11,339,220✔
380
      coord(j + 1).u = u.rotate(m);
11,339,220✔
381
    } else {
382
      // Otherwise, copy this level's direction
383
      coord(j + 1).u = coord(j).u;
115,932,801✔
384
    }
385
  }
386

387
  // Score flux derivative accumulators for differential tallies.
388
  if (!model::active_tallies.empty())
2,147,483,647✔
389
    score_collision_derivative(*this);
691,398,822✔
390

391
#ifdef DAGMC
392
  history().reset();
241,998,620✔
393
#endif
394
}
2,147,483,647✔
395

396
void Particle::event_revive_from_secondary()
2,147,483,647✔
397
{
398
  // If particle has too many events, display warning and kill it
399
  ++n_event();
2,147,483,647✔
400
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
401
    warning("Particle " + std::to_string(id()) +
×
402
            " underwent maximum number of events.");
403
    wgt() = 0.0;
×
404
  }
405

406
  // Check for secondary particles if this particle is dead
407
  if (!alive()) {
2,147,483,647✔
408
    // Write final position for this particle
409
    if (write_track()) {
216,374,204✔
410
      write_particle_track(*this);
7,086✔
411
    }
412

413
    // If no secondary particles, break out of event loop
414
    if (secondary_bank().empty())
216,374,204✔
415
      return;
160,579,816✔
416

417
    from_source(&secondary_bank().back());
55,794,388✔
418
    secondary_bank().pop_back();
55,794,388✔
419
    n_event() = 0;
55,794,388✔
420

421
    // Subtract secondary particle energy from interim pulse-height results
422
    if (!model::active_pulse_height_tallies.empty() &&
55,811,296✔
423
        this->type() == ParticleType::photon) {
16,908✔
424
      // Since the birth cell of the particle has not been set we
425
      // have to determine it before the energy of the secondary particle can be
426
      // removed from the pulse-height of this cell.
427
      if (lowest_coord().cell == C_NONE) {
660✔
428
        bool verbose = settings::verbosity >= 10 || trace();
660✔
429
        if (!exhaustive_find_cell(*this, verbose)) {
660✔
430
          mark_as_lost("Could not find the cell containing particle " +
×
431
                       std::to_string(id()));
×
432
          return;
×
433
        }
434
        // Set birth cell attribute
435
        if (cell_born() == C_NONE)
660✔
436
          cell_born() = lowest_coord().cell;
660✔
437

438
        // Initialize last cells from current cell
439
        for (int j = 0; j < n_coord(); ++j) {
1,320✔
440
          cell_last(j) = coord(j).cell;
660✔
441
        }
442
        n_coord_last() = n_coord();
660✔
443
      }
444
      pht_secondary_particles();
660✔
445
    }
446

447
    // Enter new particle in particle track file
448
    if (write_track())
55,794,388✔
449
      add_particle_track(*this);
5,946✔
450
  }
451
}
452

453
void Particle::event_death()
160,580,816✔
454
{
455
#ifdef DAGMC
456
  history().reset();
13,945,645✔
457
#endif
458

459
  // Finish particle track output.
460
  if (write_track()) {
160,580,816✔
461
    finalize_particle_track(*this);
1,140✔
462
  }
463

464
// Contribute tally reduction variables to global accumulator
465
#pragma omp atomic
81,377,262✔
466
  global_tally_absorption += keff_tally_absorption();
160,580,816✔
467
#pragma omp atomic
81,908,611✔
468
  global_tally_collision += keff_tally_collision();
160,580,816✔
469
#pragma omp atomic
81,254,648✔
470
  global_tally_tracklength += keff_tally_tracklength();
160,580,816✔
471
#pragma omp atomic
80,759,495✔
472
  global_tally_leakage += keff_tally_leakage();
160,580,816✔
473

474
  // Reset particle tallies once accumulated
475
  keff_tally_absorption() = 0.0;
160,580,816✔
476
  keff_tally_collision() = 0.0;
160,580,816✔
477
  keff_tally_tracklength() = 0.0;
160,580,816✔
478
  keff_tally_leakage() = 0.0;
160,580,816✔
479

480
  if (!model::active_pulse_height_tallies.empty()) {
160,580,816✔
481
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
482
  }
483

484
  // Record the number of progeny created by this particle.
485
  // This data will be used to efficiently sort the fission bank.
486
  if (settings::run_mode == RunMode::EIGENVALUE) {
160,580,816✔
487
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,043,600✔
488
    simulation::progeny_per_particle[offset] = n_progeny();
148,043,600✔
489
  }
490
}
160,580,816✔
491

492
void Particle::pht_collision_energy()
2,208✔
493
{
494
  // Adds the energy particles lose in a collision to the pulse-height
495

496
  // determine index of cell in pulse_height_cells
497
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
498
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
499

500
  if (it != model::pulse_height_cells.end()) {
2,208✔
501
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
502
    pht_storage()[index] += E_last() - E();
2,208✔
503

504
    // If the energy of the particle is below the cutoff, it will not be sampled
505
    // so its energy is added to the pulse-height in the cell
506
    int photon = static_cast<int>(ParticleType::photon);
2,208✔
507
    if (E() < settings::energy_cutoff[photon]) {
2,208✔
508
      pht_storage()[index] += E();
900✔
509
    }
510
  }
511
}
2,208✔
512

513
void Particle::pht_secondary_particles()
660✔
514
{
515
  // Removes the energy of secondary produced particles from the pulse-height
516

517
  // determine index of cell in pulse_height_cells
518
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
519
    model::pulse_height_cells.end(), cell_born());
660✔
520

521
  if (it != model::pulse_height_cells.end()) {
660✔
522
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
523
    pht_storage()[index] -= E();
660✔
524
  }
525
}
660✔
526

527
void Particle::cross_surface(const Surface& surf)
1,442,520,737✔
528
{
529

530
  if (settings::verbosity >= 10 || trace()) {
1,442,520,737✔
531
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
532
  }
533

534
// if we're crossing a CSG surface, make sure the DAG history is reset
535
#ifdef DAGMC
536
  if (surf.geom_type() == GeometryType::CSG)
140,144,583✔
537
    history().reset();
140,109,267✔
538
#endif
539

540
  // Handle any applicable boundary conditions.
541
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,442,520,737✔
542
    surf.bc_->handle_particle(*this, surf);
672,997,970✔
543
    return;
672,997,970✔
544
  }
545

546
  // ==========================================================================
547
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
548

549
#ifdef DAGMC
550
  // in DAGMC, we know what the next cell should be
551
  if (surf.geom_type() == GeometryType::DAG) {
74,449,622✔
552
    int32_t i_cell = next_cell(std::abs(surface()), cell_last(n_coord() - 1),
28,265✔
553
                       lowest_coord().universe) -
28,265✔
554
                     1;
28,265✔
555
    // save material and temp
556
    material_last() = material();
28,265✔
557
    sqrtkT_last() = sqrtkT();
28,265✔
558
    // set new cell value
559
    lowest_coord().cell = i_cell;
28,265✔
560
    auto& cell = model::cells[i_cell];
28,265✔
561

562
    cell_instance() = 0;
28,265✔
563
    if (cell->distribcell_index_ >= 0)
28,265✔
564
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
565

566
    material() = cell->material(cell_instance());
28,265✔
567
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
568
    return;
28,265✔
569
  }
570
#endif
571

572
  bool verbose = settings::verbosity >= 10 || trace();
769,494,502✔
573
  if (neighbor_list_find_cell(*this, verbose)) {
769,494,502✔
574
    return;
769,463,934✔
575
  }
576

577
  // ==========================================================================
578
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
579

580
  // Remove lower coordinate levels
581
  n_coord() = 1;
30,568✔
582
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
583

584
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
30,568✔
585
    // If a cell is still not found, there are two possible causes: 1) there is
586
    // a void in the model, and 2) the particle hit a surface at a tangent. If
587
    // the particle is really traveling tangent to a surface, if we move it
588
    // forward a tiny bit it should fix the problem.
589

590
    surface() = 0;
6,268✔
591
    n_coord() = 1;
6,268✔
592
    r() += TINY_BIT * u();
6,268✔
593

594
    // Couldn't find next cell anywhere! This probably means there is an actual
595
    // undefined region in the geometry.
596

597
    if (!exhaustive_find_cell(*this, verbose)) {
6,268✔
598
      mark_as_lost("After particle " + std::to_string(id()) +
18,794✔
599
                   " crossed surface " + std::to_string(surf.id_) +
25,052✔
600
                   " it could not be located in any cell and it did not leak.");
601
      return;
6,258✔
602
    }
603
  }
604
}
605

606
void Particle::cross_vacuum_bc(const Surface& surf)
22,722,606✔
607
{
608
  // Score any surface current tallies -- note that the particle is moved
609
  // forward slightly so that if the mesh boundary is on the surface, it is
610
  // still processed
611

612
  if (!model::active_meshsurf_tallies.empty()) {
22,722,606✔
613
    // TODO: Find a better solution to score surface currents than
614
    // physically moving the particle forward slightly
615

616
    r() += TINY_BIT * u();
1,941,060✔
617
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,941,060✔
618
  }
619

620
  // Score to global leakage tally
621
  keff_tally_leakage() += wgt();
22,722,606✔
622

623
  // Kill the particle
624
  wgt() = 0.0;
22,722,606✔
625

626
  // Display message
627
  if (settings::verbosity >= 10 || trace()) {
22,722,606✔
628
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
629
  }
630
}
22,722,606✔
631

632
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
650,668,952✔
633
{
634
  // Do not handle reflective boundary conditions on lower universes
635
  if (n_coord() != 1) {
650,668,952✔
636
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
637
                 " off surface in a lower universe.");
638
    return;
×
639
  }
640

641
  // Score surface currents since reflection causes the direction of the
642
  // particle to change. For surface filters, we need to score the tallies
643
  // twice, once before the particle's surface attribute has changed and
644
  // once after. For mesh surface filters, we need to artificially move
645
  // the particle slightly back in case the surface crossing is coincident
646
  // with a mesh boundary
647

648
  if (!model::active_surface_tallies.empty()) {
650,668,952✔
649
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
650
  }
651

652
  if (!model::active_meshsurf_tallies.empty()) {
650,668,952✔
653
    Position r {this->r()};
101,100,948✔
654
    this->r() -= TINY_BIT * u();
101,100,948✔
655
    score_surface_tally(*this, model::active_meshsurf_tallies);
101,100,948✔
656
    this->r() = r;
101,100,948✔
657
  }
658

659
  // Set the new particle direction
660
  u() = new_u;
650,668,952✔
661

662
  // Reassign particle's cell and surface
663
  coord(0).cell = cell_last(0);
650,668,952✔
664
  surface() = -surface();
650,668,952✔
665

666
  // If a reflective surface is coincident with a lattice or universe
667
  // boundary, it is necessary to redetermine the particle's coordinates in
668
  // the lower universes.
669
  // (unless we're using a dagmc model, which has exactly one universe)
670
  n_coord() = 1;
650,668,952✔
671
  if (surf.geom_type() != GeometryType::DAG &&
1,301,335,365✔
672
      !neighbor_list_find_cell(*this)) {
650,666,413✔
673
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
674
                 std::to_string(surf.id_) + ".");
×
UNCOV
675
    return;
×
676
  }
677

678
  // Set previous coordinate going slightly past surface crossing
679
  r_last_current() = r() + TINY_BIT * u();
650,668,952✔
680

681
  // Diagnostic message
682
  if (settings::verbosity >= 10 || trace()) {
650,668,952✔
UNCOV
683
    write_message(1, "    Reflected from surface {}", surf.id_);
×
684
  }
685
}
686

687
void Particle::cross_periodic_bc(
727,164✔
688
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
689
{
690
  // Do not handle periodic boundary conditions on lower universes
691
  if (n_coord() != 1) {
727,164✔
692
    mark_as_lost(
×
UNCOV
693
      "Cannot transfer particle " + std::to_string(id()) +
×
694
      " across surface in a lower universe. Boundary conditions must be "
695
      "applied to root universe.");
UNCOV
696
    return;
×
697
  }
698

699
  // Score surface currents since reflection causes the direction of the
700
  // particle to change -- artificially move the particle slightly back in
701
  // case the surface crossing is coincident with a mesh boundary
702
  if (!model::active_meshsurf_tallies.empty()) {
727,164✔
703
    Position r {this->r()};
×
704
    this->r() -= TINY_BIT * u();
×
705
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
706
    this->r() = r;
×
707
  }
708

709
  // Adjust the particle's location and direction.
710
  r() = new_r;
727,164✔
711
  u() = new_u;
727,164✔
712

713
  // Reassign particle's surface
714
  surface() = new_surface;
727,164✔
715

716
  // Figure out what cell particle is in now
717
  n_coord() = 1;
727,164✔
718

719
  if (!neighbor_list_find_cell(*this)) {
727,164✔
720
    mark_as_lost("Couldn't find particle after hitting periodic "
×
721
                 "boundary on surface " +
×
UNCOV
722
                 std::to_string(surf.id_) +
×
723
                 ". The normal vector "
724
                 "of one periodic surface may need to be reversed.");
UNCOV
725
    return;
×
726
  }
727

728
  // Set previous coordinate going slightly past surface crossing
729
  r_last_current() = r() + TINY_BIT * u();
727,164✔
730

731
  // Diagnostic message
732
  if (settings::verbosity >= 10 || trace()) {
727,164✔
UNCOV
733
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
734
  }
735
}
736

737
void Particle::mark_as_lost(const char* message)
6,268✔
738
{
739
  // Print warning and write lost particle file
740
  warning(message);
6,268✔
741
  if (settings::max_write_lost_particles < 0 ||
6,268✔
742
      simulation::n_lost_particles < settings::max_write_lost_particles) {
6,000✔
743
    write_restart();
353✔
744
  }
745
  // Increment number of lost particles
746
  wgt() = 0.0;
6,268✔
747
#pragma omp atomic
3,124✔
748
  simulation::n_lost_particles += 1;
3,144✔
749

750
  // Count the total number of simulated particles (on this processor)
751
  auto n = simulation::current_batch * settings::gen_per_batch *
6,268✔
752
           simulation::work_per_rank;
753

754
  // Abort the simulation if the maximum number of lost particles has been
755
  // reached
756
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
6,268✔
757
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10✔
758
    fatal_error("Maximum number of lost particles has been reached.");
10✔
759
  }
760
}
6,258✔
761

762
void Particle::write_restart() const
353✔
763
{
764
  // Dont write another restart file if in particle restart mode
765
  if (settings::run_mode == RunMode::PARTICLE)
353✔
766
    return;
24✔
767

768
  // Set up file name
769
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
770
    simulation::current_batch, id());
619✔
771

772
#pragma omp critical(WriteParticleRestart)
314✔
773
  {
774
    // Create file
775
    hid_t file_id = file_open(filename, 'w');
329✔
776

777
    // Write filetype and version info
778
    write_attribute(file_id, "filetype", "particle restart");
329✔
779
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
329✔
780
    write_attribute(file_id, "openmc_version", VERSION);
329✔
781
#ifdef GIT_SHA1
782
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
329✔
783
#endif
784

785
    // Write data to file
786
    write_dataset(file_id, "current_batch", simulation::current_batch);
329✔
787
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
329✔
788
    write_dataset(file_id, "current_generation", simulation::current_gen);
329✔
789
    write_dataset(file_id, "n_particles", settings::n_particles);
329✔
790
    switch (settings::run_mode) {
329✔
791
    case RunMode::FIXED_SOURCE:
245✔
792
      write_dataset(file_id, "run_mode", "fixed source");
245✔
793
      break;
245✔
794
    case RunMode::EIGENVALUE:
84✔
795
      write_dataset(file_id, "run_mode", "eigenvalue");
84✔
796
      break;
84✔
797
    case RunMode::PARTICLE:
×
798
      write_dataset(file_id, "run_mode", "particle restart");
×
799
      break;
×
800
    default:
×
UNCOV
801
      break;
×
802
    }
803
    write_dataset(file_id, "id", id());
329✔
804
    write_dataset(file_id, "type", static_cast<int>(type()));
329✔
805

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

829
    // Close file
830
    file_close(file_id);
329✔
831
  } // #pragma omp critical
832
}
329✔
833

834
void Particle::update_neutron_xs(
2,147,483,647✔
835
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
836
{
837
  // Get microscopic cross section cache
838
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
839

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

845
    // If NCrystal is being used, update micro cross section cache
846
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
847
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,722✔
848
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,722✔
849
    }
850
  }
851
}
2,147,483,647✔
852

853
//==============================================================================
854
// Non-method functions
855
//==============================================================================
856

857
std::string particle_type_to_str(ParticleType type)
3,245,772✔
858
{
859
  switch (type) {
3,245,772✔
860
  case ParticleType::neutron:
2,450,772✔
861
    return "neutron";
2,450,772✔
862
  case ParticleType::photon:
794,760✔
863
    return "photon";
794,760✔
864
  case ParticleType::electron:
120✔
865
    return "electron";
120✔
866
  case ParticleType::positron:
120✔
867
    return "positron";
120✔
868
  }
UNCOV
869
  UNREACHABLE();
×
870
}
871

872
ParticleType str_to_particle_type(std::string str)
3,361,652✔
873
{
874
  if (str == "neutron") {
3,361,652✔
875
    return ParticleType::neutron;
771,883✔
876
  } else if (str == "photon") {
2,589,769✔
877
    return ParticleType::photon;
2,589,701✔
878
  } else if (str == "electron") {
68✔
879
    return ParticleType::electron;
34✔
880
  } else if (str == "positron") {
34✔
881
    return ParticleType::positron;
34✔
882
  } else {
UNCOV
883
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
884
  }
885
}
886

887
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,441,530,937✔
888
{
889
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
890
      simulation::surf_source_bank.full()) {
1,139,984,274✔
891
    return;
1,441,414,339✔
892
  }
893

894
  // If a cell/cellfrom/cellto parameter is defined
895
  if (settings::ssw_cell_id != C_NONE) {
349,634✔
896

897
    // Retrieve cell index and storage type
898
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,439✔
899

900
    if (surf.bc_) {
283,439✔
901
      // Leave if cellto with vacuum boundary condition
902
      if (surf.bc_->type() == "vacuum" &&
202,456✔
903
          settings::ssw_cell_type == SSWCellType::To) {
35,217✔
904
        return;
13,071✔
905
      }
906

907
      // Leave if other boundary condition than vacuum
908
      if (surf.bc_->type() != "vacuum") {
154,168✔
909
        return;
132,022✔
910
      }
911
    }
912

913
    // Check if the cell of interest has been exited
914
    bool exited = false;
138,346✔
915
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,539✔
916
      if (p.cell_last(i) == cell_idx) {
228,193✔
917
        exited = true;
81,192✔
918
      }
919
    }
920

921
    // Check if the cell of interest has been entered
922
    bool entered = false;
138,346✔
923
    for (int i = 0; i < p.n_coord(); ++i) {
328,938✔
924
      if (p.coord(i).cell == cell_idx) {
190,592✔
925
        entered = true;
64,718✔
926
      }
927
    }
928

929
    // Vacuum boundary conditions: return if cell is not exited
930
    if (surf.bc_) {
138,346✔
931
      if (surf.bc_->type() == "vacuum" && !exited) {
22,146✔
932
        return;
15,246✔
933
      }
934
    } else {
935

936
      // If we both enter and exit the cell of interest
937
      if (entered && exited) {
116,200✔
938
        return;
31,409✔
939
      }
940

941
      // If we did not enter nor exit the cell of interest
942
      if (!entered && !exited) {
84,791✔
943
        return;
15,499✔
944
      }
945

946
      // If cellfrom and the cell before crossing is not the cell of
947
      // interest
948
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
69,292✔
949
        return;
12,666✔
950
      }
951

952
      // If cellto and the cell after crossing is not the cell of interest
953
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
56,626✔
954
        return;
13,123✔
955
      }
956
    }
957
  }
958

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

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

© 2025 Coveralls, Inc