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

openmc-dev / openmc / 12366050163

17 Dec 2024 03:55AM UTC coverage: 84.846% (+0.02%) from 84.827%
12366050163

Pull #3227

github

web-flow
Merge 06ec3f40d into 775c41512
Pull Request #3227: Adjust for secondary particle energy directly in heating scores

23 of 23 new or added lines in 6 files covered. (100.0%)

54 existing lines in 3 files now uncovered.

49874 of 58782 relevant lines covered (84.85%)

34219165.88 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:
15,653,146✔
54
    mass = 0.0;
15,653,146✔
55
    break;
15,653,146✔
56
  case ParticleType::electron:
52,787,368✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,787,368✔
59
    break;
52,787,368✔
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);
910,076,131✔
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(
110,485,983✔
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)]) {
110,485,983✔
91
    return;
52,699,503✔
92
  }
93

94
  secondary_bank().emplace_back();
57,786,480✔
95

96
  auto& bank {secondary_bank().back()};
57,786,480✔
97
  bank.particle = type;
57,786,480✔
98
  bank.wgt = wgt;
57,786,480✔
99
  bank.r = r();
57,786,480✔
100
  bank.u = u;
57,786,480✔
101
  bank.E = settings::run_CE ? E : g();
57,786,480✔
102
  bank.time = time();
57,786,480✔
103
  bank_second_E() += bank.E;
57,786,480✔
104
}
105

106
void Particle::split(double wgt)
2,188,426✔
107
{
108
  secondary_bank().emplace_back();
2,188,426✔
109
  auto& bank {secondary_bank().back()};
2,188,426✔
110
  bank.particle = type();
2,188,426✔
111
  bank.wgt = wgt;
2,188,426✔
112
  bank.r = r();
2,188,426✔
113
  bank.u = u();
2,188,426✔
114
  bank.E = settings::run_CE ? E() : g();
2,188,426✔
115
  bank.time = time();
2,188,426✔
116
}
2,188,426✔
117

118
void Particle::from_source(const SourceSite* src)
221,598,953✔
119
{
120
  // Reset some attributes
121
  clear();
221,598,953✔
122
  surface() = 0;
221,598,953✔
123
  cell_born() = C_NONE;
221,598,953✔
124
  material() = C_NONE;
221,598,953✔
125
  n_collision() = 0;
221,598,953✔
126
  fission() = false;
221,598,953✔
127
  zero_flux_derivs();
221,598,953✔
128

129
  // Copy attributes from source bank site
130
  type() = src->particle;
221,598,953✔
131
  wgt() = src->wgt;
221,598,953✔
132
  wgt_last() = src->wgt;
221,598,953✔
133
  r() = src->r;
221,598,953✔
134
  u() = src->u;
221,598,953✔
135
  r_born() = src->r;
221,598,953✔
136
  r_last_current() = src->r;
221,598,953✔
137
  r_last() = src->r;
221,598,953✔
138
  u_last() = src->u;
221,598,953✔
139
  if (settings::run_CE) {
221,598,953✔
140
    E() = src->E;
100,032,953✔
141
    g() = 0;
100,032,953✔
142
  } else {
143
    g() = static_cast<int>(src->E);
121,566,000✔
144
    g_last() = static_cast<int>(src->E);
121,566,000✔
145
    E() = data::mg.energy_bin_avg_[g()];
121,566,000✔
146
  }
147
  E_last() = E();
221,598,953✔
148
  time() = src->time;
221,598,953✔
149
  time_last() = src->time;
221,598,953✔
150
}
221,598,953✔
151

152
void Particle::event_calculate_xs()
2,147,483,647✔
153
{
154
  // Set the random number stream
155
  stream() = STREAM_TRACKING;
2,147,483,647✔
156

157
  // Store pre-collision particle properties
158
  wgt_last() = wgt();
2,147,483,647✔
159
  E_last() = E();
2,147,483,647✔
160
  u_last() = u();
2,147,483,647✔
161
  r_last() = r();
2,147,483,647✔
162
  time_last() = time();
2,147,483,647✔
163

164
  // Reset event variables
165
  event() = TallyEvent::KILL;
2,147,483,647✔
166
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
167
  event_mt() = REACTION_NONE;
2,147,483,647✔
168

169
  // If the cell hasn't been determined based on the particle's location,
170
  // initiate a search for the current cell. This generally happens at the
171
  // beginning of the history and again for any secondary particles
172
  if (lowest_coord().cell == C_NONE) {
2,147,483,647✔
173
    if (!exhaustive_find_cell(*this)) {
221,040,329✔
UNCOV
174
      mark_as_lost(
×
UNCOV
175
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
176
      return;
×
177
    }
178

179
    // Set birth cell attribute
180
    if (cell_born() == C_NONE)
221,040,329✔
181
      cell_born() = lowest_coord().cell;
221,040,329✔
182

183
    // Initialize last cells from current cell
184
    for (int j = 0; j < n_coord(); ++j) {
453,694,565✔
185
      cell_last(j) = coord(j).cell;
232,654,236✔
186
    }
187
    n_coord_last() = n_coord();
221,040,329✔
188
  }
189

190
  // Write particle track.
191
  if (write_track())
2,147,483,647✔
192
    write_particle_track(*this);
11,616✔
193

194
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
195
    check_cell_overlap(*this);
×
196

197
  // Calculate microscopic and macroscopic cross sections
198
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
199
    if (settings::run_CE) {
2,147,483,647✔
200
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,896,077,014✔
201
        // If the material is the same as the last material and the
202
        // temperature hasn't changed, we don't need to lookup cross
203
        // sections again.
204
        model::materials[material()]->calculate_xs(*this);
1,489,761,505✔
205
      }
206
    } else {
207
      // Get the MG data; unlike the CE case above, we have to re-calculate
208
      // cross sections for every collision since the cross sections may
209
      // be angle-dependent
210
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,147,483,647✔
211

212
      // Update the particle's group while we know we are multi-group
213
      g_last() = g();
2,147,483,647✔
214
    }
215
  } else {
216
    macro_xs().total = 0.0;
50,521,309✔
217
    macro_xs().absorption = 0.0;
50,521,309✔
218
    macro_xs().fission = 0.0;
50,521,309✔
219
    macro_xs().nu_fission = 0.0;
50,521,309✔
220
  }
221
}
222

223
void Particle::event_advance()
2,147,483,647✔
224
{
225
  // Find the distance to the nearest boundary
226
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
227

228
  // Sample a distance to collision
229
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
230
    collision_distance() = 0.0;
52,787,368✔
231
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
232
    collision_distance() = INFINITY;
50,521,309✔
233
  } else {
234
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
235
  }
236

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

240
  // Advance particle in space and time
241
  // Short-term solution until the surface source is revised and we can use
242
  // this->move_distance(distance)
243
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
244
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
245
  }
246
  this->time() += distance / this->speed();
2,147,483,647✔
247

248
  // Kill particle if its time exceeds the cutoff
249
  bool hit_time_boundary = false;
2,147,483,647✔
250
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
251
  if (time() > time_cutoff) {
2,147,483,647✔
252
    double dt = time() - time_cutoff;
12,000✔
253
    time() = time_cutoff;
12,000✔
254

255
    double push_back_distance = speed() * dt;
12,000✔
256
    this->move_distance(-push_back_distance);
12,000✔
257
    hit_time_boundary = true;
12,000✔
258
  }
259

260
  // Score track-length tallies
261
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
262
    score_tracklength_tally(*this, distance);
1,378,797,173✔
263
  }
264

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

271
  // Score flux derivative accumulators for differential tallies.
272
  if (!model::active_tallies.empty()) {
2,147,483,647✔
273
    score_track_derivative(*this, distance);
1,603,432,730✔
274
  }
275

276
  // Set particle weight to zero if it hit the time boundary
277
  if (hit_time_boundary) {
2,147,483,647✔
278
    wgt() = 0.0;
12,000✔
279
  }
280
}
2,147,483,647✔
281

282
void Particle::event_cross_surface()
1,692,828,971✔
283
{
284
  // Saving previous cell data
285
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
286
    cell_last(j) = coord(j).cell;
2,147,483,647✔
287
  }
288
  n_coord_last() = n_coord();
1,692,828,971✔
289

290
  // Set surface that particle is on and adjust coordinate levels
291
  surface() = boundary().surface_index;
1,692,828,971✔
292
  n_coord() = boundary().coord_level;
1,692,828,971✔
293

294
  if (boundary().lattice_translation[0] != 0 ||
1,692,828,971✔
295
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
296
      boundary().lattice_translation[2] != 0) {
1,489,901,007✔
297
    // Particle crosses lattice boundary
298

299
    bool verbose = settings::verbosity >= 10 || trace();
242,413,143✔
300
    cross_lattice(*this, boundary(), verbose);
242,413,143✔
301
    event() = TallyEvent::LATTICE;
242,413,143✔
302
  } else {
303
    // Particle crosses surface
304
    // TODO: off-by-one
305
    const auto& surf {model::surfaces[std::abs(surface()) - 1].get()};
1,450,415,828✔
306
    // If BC, add particle to surface source before crossing surface
307
    if (surf->surf_source_ && surf->bc_) {
1,450,415,828✔
308
      add_surf_source_to_bank(*this, *surf);
676,996,971✔
309
    }
310
    this->cross_surface(*surf);
1,450,415,828✔
311
    // If no BC, add particle to surface source after crossing surface
312
    if (surf->surf_source_ && !surf->bc_) {
1,450,415,818✔
313
      add_surf_source_to_bank(*this, *surf);
772,429,057✔
314
    }
315
    if (settings::weight_window_checkpoint_surface) {
1,450,415,818✔
UNCOV
316
      apply_weight_windows(*this);
×
317
    }
318
    event() = TallyEvent::SURFACE;
1,450,415,818✔
319
  }
320
  // Score cell to cell partial currents
321
  if (!model::active_surface_tallies.empty()) {
1,692,828,961✔
322
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
323
  }
324
}
1,692,828,961✔
325

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

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

338
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
339
    score_surface_tally(*this, model::active_meshsurf_tallies);
142,094,749✔
340

341
  // Clear surface component
342
  surface() = 0;
2,147,483,647✔
343

344
  if (settings::run_CE) {
2,147,483,647✔
345
    collision(*this);
814,123,452✔
346
  } else {
347
    collision_mg(*this);
1,939,604,940✔
348
  }
349

350
  // Score collision estimator tallies -- this is done after a collision
351
  // has occurred rather than before because we need information on the
352
  // outgoing energy for any tallies with an outgoing energy filter
353
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
354
    score_collision_tally(*this);
98,849,822✔
355
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
356
    if (settings::run_CE) {
168,915,805✔
357
      score_analog_tally_ce(*this);
167,605,393✔
358
    } else {
359
      score_analog_tally_mg(*this);
1,310,412✔
360
    }
361
  }
362

363
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
364
      type() == ParticleType::photon) {
18,456✔
365
    pht_collision_energy();
2,208✔
366
  }
367

368
  // Reset banked weight during collision
369
  n_bank() = 0;
2,147,483,647✔
370
  bank_second_E() = 0.0;
2,147,483,647✔
371
  wgt_bank() = 0.0;
2,147,483,647✔
372
  zero_delayed_bank();
2,147,483,647✔
373

374
  // Reset fission logical
375
  fission() = false;
2,147,483,647✔
376

377
  // Save coordinates for tallying purposes
378
  r_last_current() = r();
2,147,483,647✔
379

380
  // Set last material to none since cross sections will need to be
381
  // re-evaluated
382
  material_last() = C_NONE;
2,147,483,647✔
383

384
  // Set all directions to base level -- right now, after a collision, only
385
  // the base level directions are changed
386
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
387
    if (coord(j + 1).rotated) {
128,581,272✔
388
      // If next level is rotated, apply rotation matrix
389
      const auto& m {model::cells[coord(j).cell]->rotation_};
11,339,220✔
390
      const auto& u {coord(j).u};
11,339,220✔
391
      coord(j + 1).u = u.rotate(m);
11,339,220✔
392
    } else {
393
      // Otherwise, copy this level's direction
394
      coord(j + 1).u = coord(j).u;
117,242,052✔
395
    }
396
  }
397

398
  // Score flux derivative accumulators for differential tallies.
399
  if (!model::active_tallies.empty())
2,147,483,647✔
400
    score_collision_derivative(*this);
704,286,817✔
401

402
#ifdef DAGMC
403
  history().reset();
236,734,919✔
404
#endif
405
}
2,147,483,647✔
406

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

417
  // Check for secondary particles if this particle is dead
418
  if (!alive()) {
2,147,483,647✔
419
    // Write final position for this particle
420
    if (write_track()) {
221,039,979✔
421
      write_particle_track(*this);
7,090✔
422
    }
423

424
    // If no secondary particles, break out of event loop
425
    if (secondary_bank().empty())
221,039,979✔
426
      return;
160,861,816✔
427

428
    from_source(&secondary_bank().back());
60,178,163✔
429
    secondary_bank().pop_back();
60,178,163✔
430
    n_event() = 0;
60,178,163✔
431
    bank_second_E() = 0.0;
60,178,163✔
432

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

450
        // Initialize last cells from current cell
451
        for (int j = 0; j < n_coord(); ++j) {
1,320✔
452
          cell_last(j) = coord(j).cell;
660✔
453
        }
454
        n_coord_last() = n_coord();
660✔
455
      }
456
      pht_secondary_particles();
660✔
457
    }
458

459
    // Enter new particle in particle track file
460
    if (write_track())
60,178,163✔
461
      add_particle_track(*this);
5,950✔
462
  }
463
}
464

465
void Particle::event_death()
160,862,816✔
466
{
467
#ifdef DAGMC
468
  history().reset();
13,660,145✔
469
#endif
470

471
  // Finish particle track output.
472
  if (write_track()) {
160,862,816✔
473
    finalize_particle_track(*this);
1,140✔
474
  }
475

476
// Contribute tally reduction variables to global accumulator
477
#pragma omp atomic
81,162,876✔
478
  global_tally_absorption += keff_tally_absorption();
160,862,816✔
479
#pragma omp atomic
80,915,599✔
480
  global_tally_collision += keff_tally_collision();
160,862,816✔
481
#pragma omp atomic
80,794,419✔
482
  global_tally_tracklength += keff_tally_tracklength();
160,862,816✔
483
#pragma omp atomic
80,466,721✔
484
  global_tally_leakage += keff_tally_leakage();
160,862,816✔
485

486
  // Reset particle tallies once accumulated
487
  keff_tally_absorption() = 0.0;
160,862,816✔
488
  keff_tally_collision() = 0.0;
160,862,816✔
489
  keff_tally_tracklength() = 0.0;
160,862,816✔
490
  keff_tally_leakage() = 0.0;
160,862,816✔
491

492
  if (!model::active_pulse_height_tallies.empty()) {
160,862,816✔
493
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
494
  }
495

496
  // Record the number of progeny created by this particle.
497
  // This data will be used to efficiently sort the fission bank.
498
  if (settings::run_mode == RunMode::EIGENVALUE) {
160,862,816✔
499
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,319,600✔
500
    simulation::progeny_per_particle[offset] = n_progeny();
148,319,600✔
501
  }
502
}
160,862,816✔
503

504
void Particle::pht_collision_energy()
2,208✔
505
{
506
  // Adds the energy particles lose in a collision to the pulse-height
507

508
  // determine index of cell in pulse_height_cells
509
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
510
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
511

512
  if (it != model::pulse_height_cells.end()) {
2,208✔
513
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
514
    pht_storage()[index] += E_last() - E();
2,208✔
515

516
    // If the energy of the particle is below the cutoff, it will not be sampled
517
    // so its energy is added to the pulse-height in the cell
518
    int photon = static_cast<int>(ParticleType::photon);
2,208✔
519
    if (E() < settings::energy_cutoff[photon]) {
2,208✔
520
      pht_storage()[index] += E();
900✔
521
    }
522
  }
523
}
2,208✔
524

525
void Particle::pht_secondary_particles()
660✔
526
{
527
  // Removes the energy of secondary produced particles from the pulse-height
528

529
  // determine index of cell in pulse_height_cells
530
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
531
    model::pulse_height_cells.end(), cell_born());
660✔
532

533
  if (it != model::pulse_height_cells.end()) {
660✔
534
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
535
    pht_storage()[index] -= E();
660✔
536
  }
537
}
660✔
538

539
void Particle::cross_surface(const Surface& surf)
1,450,415,828✔
540
{
541

542
  if (settings::verbosity >= 10 || trace()) {
1,450,415,828✔
543
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
544
  }
545

546
// if we're crossing a CSG surface, make sure the DAG history is reset
547
#ifdef DAGMC
548
  if (surf.geom_type_ == GeometryType::CSG)
130,503,363✔
549
    history().reset();
130,474,578✔
550
#endif
551

552
  // Handle any applicable boundary conditions.
553
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,450,415,828✔
554
    surf.bc_->handle_particle(*this, surf);
677,256,942✔
555
    return;
677,256,942✔
556
  }
557

558
  // ==========================================================================
559
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
560

561
#ifdef DAGMC
562
  // in DAGMC, we know what the next cell should be
563
  if (surf.geom_type_ == GeometryType::DAG) {
69,592,069✔
564
    int32_t i_cell = next_cell(std::abs(surface()), cell_last(n_coord() - 1),
24,542✔
565
                       lowest_coord().universe) -
24,542✔
566
                     1;
24,542✔
567
    // save material and temp
568
    material_last() = material();
24,542✔
569
    sqrtkT_last() = sqrtkT();
24,542✔
570
    // set new cell value
571
    lowest_coord().cell = i_cell;
24,542✔
572
    auto& cell = model::cells[i_cell];
24,542✔
573

574
    cell_instance() = 0;
24,542✔
575
    if (cell->distribcell_index_ >= 0)
24,542✔
576
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
23,541✔
577

578
    material() = cell->material(cell_instance());
24,542✔
579
    sqrtkT() = cell->sqrtkT(cell_instance());
24,542✔
580
    return;
24,542✔
581
  }
582
#endif
583

584
  bool verbose = settings::verbosity >= 10 || trace();
773,134,344✔
585
  if (neighbor_list_find_cell(*this, verbose)) {
773,134,344✔
586
    return;
773,103,776✔
587
  }
588

589
  // ==========================================================================
590
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
591

592
  // Remove lower coordinate levels
593
  n_coord() = 1;
30,568✔
594
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
595

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

602
    surface() = 0;
6,268✔
603
    n_coord() = 1;
6,268✔
604
    r() += TINY_BIT * u();
6,268✔
605

606
    // Couldn't find next cell anywhere! This probably means there is an actual
607
    // undefined region in the geometry.
608

609
    if (!exhaustive_find_cell(*this, verbose)) {
6,268✔
610
      mark_as_lost("After particle " + std::to_string(id()) +
18,794✔
611
                   " crossed surface " + std::to_string(surf.id_) +
25,052✔
612
                   " it could not be located in any cell and it did not leak.");
613
      return;
6,258✔
614
    }
615
  }
616
}
617

618
void Particle::cross_vacuum_bc(const Surface& surf)
22,798,149✔
619
{
620
  // Score any surface current tallies -- note that the particle is moved
621
  // forward slightly so that if the mesh boundary is on the surface, it is
622
  // still processed
623

624
  if (!model::active_meshsurf_tallies.empty()) {
22,798,149✔
625
    // TODO: Find a better solution to score surface currents than
626
    // physically moving the particle forward slightly
627

628
    r() += TINY_BIT * u();
2,016,875✔
629
    score_surface_tally(*this, model::active_meshsurf_tallies);
2,016,875✔
630
  }
631

632
  // Score to global leakage tally
633
  keff_tally_leakage() += wgt();
22,798,149✔
634

635
  // Kill the particle
636
  wgt() = 0.0;
22,798,149✔
637

638
  // Display message
639
  if (settings::verbosity >= 10 || trace()) {
22,798,149✔
640
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
641
  }
642
}
22,798,149✔
643

644
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
654,852,381✔
645
{
646
  // Do not handle reflective boundary conditions on lower universes
647
  if (n_coord() != 1) {
654,852,381✔
UNCOV
648
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
649
                 " off surface in a lower universe.");
UNCOV
650
    return;
×
651
  }
652

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

660
  if (!model::active_surface_tallies.empty()) {
654,852,381✔
661
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
662
  }
663

664
  if (!model::active_meshsurf_tallies.empty()) {
654,852,381✔
665
    Position r {this->r()};
105,287,354✔
666
    this->r() -= TINY_BIT * u();
105,287,354✔
667
    score_surface_tally(*this, model::active_meshsurf_tallies);
105,287,354✔
668
    this->r() = r;
105,287,354✔
669
  }
670

671
  // Set the new particle direction
672
  u() = new_u;
654,852,381✔
673

674
  // Reassign particle's cell and surface
675
  coord(0).cell = cell_last(0);
654,852,381✔
676
  surface() = -surface();
654,852,381✔
677

678
  // If a reflective surface is coincident with a lattice or universe
679
  // boundary, it is necessary to redetermine the particle's coordinates in
680
  // the lower universes.
681
  // (unless we're using a dagmc model, which has exactly one universe)
682
  n_coord() = 1;
654,852,381✔
683
  if (surf.geom_type_ != GeometryType::DAG && !neighbor_list_find_cell(*this)) {
654,852,381✔
UNCOV
684
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
685
                 std::to_string(surf.id_) + ".");
×
UNCOV
686
    return;
×
687
  }
688

689
  // Set previous coordinate going slightly past surface crossing
690
  r_last_current() = r() + TINY_BIT * u();
654,852,381✔
691

692
  // Diagnostic message
693
  if (settings::verbosity >= 10 || trace()) {
654,852,381✔
UNCOV
694
    write_message(1, "    Reflected from surface {}", surf.id_);
×
695
  }
696
}
697

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

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

720
  // Adjust the particle's location and direction.
721
  r() = new_r;
727,164✔
722
  u() = new_u;
727,164✔
723

724
  // Reassign particle's surface
725
  surface() = new_surface;
727,164✔
726

727
  // Figure out what cell particle is in now
728
  n_coord() = 1;
727,164✔
729

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

739
  // Set previous coordinate going slightly past surface crossing
740
  r_last_current() = r() + TINY_BIT * u();
727,164✔
741

742
  // Diagnostic message
743
  if (settings::verbosity >= 10 || trace()) {
727,164✔
UNCOV
744
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
745
  }
746
}
747

748
void Particle::mark_as_lost(const char* message)
6,268✔
749
{
750
  // Print warning and write lost particle file
751
  warning(message);
6,268✔
752
  if (settings::max_write_lost_particles < 0 ||
6,268✔
753
      simulation::n_lost_particles < settings::max_write_lost_particles) {
6,000✔
754
    write_restart();
353✔
755
  }
756
  // Increment number of lost particles
757
  wgt() = 0.0;
6,268✔
758
#pragma omp atomic
3,124✔
759
  simulation::n_lost_particles += 1;
3,144✔
760

761
  // Count the total number of simulated particles (on this processor)
762
  auto n = simulation::current_batch * settings::gen_per_batch *
6,268✔
763
           simulation::work_per_rank;
764

765
  // Abort the simulation if the maximum number of lost particles has been
766
  // reached
767
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
6,268✔
768
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10✔
769
    fatal_error("Maximum number of lost particles has been reached.");
10✔
770
  }
771
}
6,258✔
772

773
void Particle::write_restart() const
353✔
774
{
775
  // Dont write another restart file if in particle restart mode
776
  if (settings::run_mode == RunMode::PARTICLE)
353✔
777
    return;
24✔
778

779
  // Set up file name
780
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
781
    simulation::current_batch, id());
619✔
782

783
#pragma omp critical(WriteParticleRestart)
314✔
784
  {
785
    // Create file
786
    hid_t file_id = file_open(filename, 'w');
329✔
787

788
    // Write filetype and version info
789
    write_attribute(file_id, "filetype", "particle restart");
329✔
790
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
329✔
791
    write_attribute(file_id, "openmc_version", VERSION);
329✔
792
#ifdef GIT_SHA1
793
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
329✔
794
#endif
795

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

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

840
    // Close file
841
    file_close(file_id);
329✔
842
  } // #pragma omp critical
843
}
329✔
844

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

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

856
    // If NCrystal is being used, update micro cross section cache
857
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
858
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,722✔
859
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,722✔
860
    }
861
  }
862
}
2,147,483,647✔
863

864
//==============================================================================
865
// Non-method functions
866
//==============================================================================
867

868
std::string particle_type_to_str(ParticleType type)
3,247,320✔
869
{
870
  switch (type) {
3,247,320✔
871
  case ParticleType::neutron:
2,450,772✔
872
    return "neutron";
2,450,772✔
873
  case ParticleType::photon:
796,308✔
874
    return "photon";
796,308✔
875
  case ParticleType::electron:
120✔
876
    return "electron";
120✔
877
  case ParticleType::positron:
120✔
878
    return "positron";
120✔
879
  }
UNCOV
880
  UNREACHABLE();
×
881
}
882

883
ParticleType str_to_particle_type(std::string str)
3,372,842✔
884
{
885
  if (str == "neutron") {
3,372,842✔
886
    return ParticleType::neutron;
774,289✔
887
  } else if (str == "photon") {
2,598,553✔
888
    return ParticleType::photon;
2,598,485✔
889
  } else if (str == "electron") {
68✔
890
    return ParticleType::electron;
34✔
891
  } else if (str == "positron") {
34✔
892
    return ParticleType::positron;
34✔
893
  } else {
UNCOV
894
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
895
  }
896
}
897

898
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,449,426,028✔
899
{
900
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
901
      simulation::surf_source_bank.full()) {
1,143,991,989✔
902
    return;
1,449,309,430✔
903
  }
904

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

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

911
    if (surf.bc_) {
283,443✔
912
      // Leave if cellto with vacuum boundary condition
913
      if (surf.bc_->type() == "vacuum" &&
202,458✔
914
          settings::ssw_cell_type == SSWCellType::To) {
35,218✔
915
        return;
13,071✔
916
      }
917

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

924
    // Check if the cell of interest has been exited
925
    bool exited = false;
138,350✔
926
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,547✔
927
      if (p.cell_last(i) == cell_idx) {
228,197✔
928
        exited = true;
81,192✔
929
      }
930
    }
931

932
    // Check if the cell of interest has been entered
933
    bool entered = false;
138,350✔
934
    for (int i = 0; i < p.n_coord(); ++i) {
328,946✔
935
      if (p.coord(i).cell == cell_idx) {
190,596✔
936
        entered = true;
64,717✔
937
      }
938
    }
939

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

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

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

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

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

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

984
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc