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

openmc-dev / openmc / 13591584831

28 Feb 2025 03:46PM UTC coverage: 85.051% (+0.3%) from 84.722%
13591584831

Pull #3067

github

web-flow
Merge 08055e996 into c26fde666
Pull Request #3067: Implement user-configurable random number stride

36 of 44 new or added lines in 8 files covered. (81.82%)

3588 existing lines in 111 files now uncovered.

51062 of 60037 relevant lines covered (85.05%)

32650986.73 hits per line

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

92.68
/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,894,898✔
54
    mass = 0.0;
15,894,898✔
55
    break;
15,894,898✔
56
  case ParticleType::electron:
53,263,141✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
53,263,141✔
59
    break;
53,263,141✔
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);
891,740,804✔
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(
111,492,748✔
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)]) {
111,492,748✔
84
    return false;
53,179,926✔
85
  }
86

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

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

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

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

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

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

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

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

171
    // Set birth cell attribute
172
    if (cell_born() == C_NONE)
224,707,300✔
173
      cell_born() = lowest_coord().cell;
224,707,300✔
174

175
    // Initialize last cells from current cell
176
    for (int j = 0; j < n_coord(); ++j) {
473,005,714✔
177
      cell_last(j) = coord(j).cell;
248,298,414✔
178
    }
179
    n_coord_last() = n_coord();
224,707,300✔
180
  }
181

182
  // Write particle track.
183
  if (write_track())
2,147,483,647✔
184
    write_particle_track(*this);
11,587✔
185

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

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

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

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

220
  // Sample a distance to collision
221
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
222
    collision_distance() = 0.0;
53,263,141✔
223
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
224
    collision_distance() = INFINITY;
50,524,905✔
225
  } else {
226
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
227
  }
228

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

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

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

247
    double push_back_distance = speed() * dt;
12,000✔
248
    this->move_distance(-push_back_distance);
12,000✔
249
    hit_time_boundary = true;
12,000✔
250
  }
251

252
  // Score track-length tallies
253
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
254
    score_tracklength_tally(*this, distance);
1,327,985,460✔
255
  }
256

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

263
  // Score flux derivative accumulators for differential tallies.
264
  if (!model::active_tallies.empty()) {
2,147,483,647✔
265
    score_track_derivative(*this, distance);
1,469,652,622✔
266
  }
267

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

274
void Particle::event_cross_surface()
1,704,973,820✔
275
{
276
  // Saving previous cell data
277
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
278
    cell_last(j) = coord(j).cell;
2,147,483,647✔
279
  }
280
  n_coord_last() = n_coord();
1,704,973,820✔
281

282
  // Set surface that particle is on and adjust coordinate levels
283
  surface() = boundary().surface;
1,704,973,820✔
284
  n_coord() = boundary().coord_level;
1,704,973,820✔
285

286
  if (boundary().lattice_translation[0] != 0 ||
1,704,973,820✔
287
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
288
      boundary().lattice_translation[2] != 0) {
1,430,915,294✔
289
    // Particle crosses lattice boundary
290

291
    bool verbose = settings::verbosity >= 10 || trace();
351,819,179✔
292
    cross_lattice(*this, boundary(), verbose);
351,819,179✔
293
    event() = TallyEvent::LATTICE;
351,819,179✔
294
  } else {
295
    // Particle crosses surface
296
    const auto& surf {model::surfaces[surface_index()].get()};
1,353,154,641✔
297
    // If BC, add particle to surface source before crossing surface
298
    if (surf->surf_source_ && surf->bc_) {
1,353,154,641✔
299
      add_surf_source_to_bank(*this, *surf);
630,014,470✔
300
    }
301
    this->cross_surface(*surf);
1,353,154,641✔
302
    // If no BC, add particle to surface source after crossing surface
303
    if (surf->surf_source_ && !surf->bc_) {
1,353,154,631✔
304
      add_surf_source_to_bank(*this, *surf);
722,150,371✔
305
    }
306
    if (settings::weight_window_checkpoint_surface) {
1,353,154,631✔
UNCOV
307
      apply_weight_windows(*this);
×
308
    }
309
    event() = TallyEvent::SURFACE;
1,353,154,631✔
310
  }
311
  // Score cell to cell partial currents
312
  if (!model::active_surface_tallies.empty()) {
1,704,973,810✔
313
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
314
  }
315
}
1,704,973,810✔
316

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

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

329
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
330
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,285,425✔
331

332
  // Clear surface component
333
  surface() = SURFACE_NONE;
2,147,483,647✔
334

335
  if (settings::run_CE) {
2,147,483,647✔
336
    collision(*this);
744,898,699✔
337
  } else {
338
    collision_mg(*this);
1,948,075,116✔
339
  }
340

341
  // Score collision estimator tallies -- this is done after a collision
342
  // has occurred rather than before because we need information on the
343
  // outgoing energy for any tallies with an outgoing energy filter
344
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
345
    score_collision_tally(*this);
99,216,227✔
346
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
347
    if (settings::run_CE) {
101,106,481✔
348
      score_analog_tally_ce(*this);
99,796,069✔
349
    } else {
350
      score_analog_tally_mg(*this);
1,310,412✔
351
    }
352
  }
353

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

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

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

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

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

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

389
  // Score flux derivative accumulators for differential tallies.
390
  if (!model::active_tallies.empty())
2,147,483,647✔
391
    score_collision_derivative(*this);
643,443,620✔
392

393
#ifdef DAGMC
394
  history().reset();
225,797,273✔
395
#endif
396
}
2,147,483,647✔
397

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

408
  // Check for secondary particles if this particle is dead
409
  if (!alive()) {
2,147,483,647✔
410
    // Write final position for this particle
411
    if (write_track()) {
224,706,950✔
412
      write_particle_track(*this);
7,082✔
413
    }
414

415
    // If no secondary particles, break out of event loop
416
    if (secondary_bank().empty())
224,706,950✔
417
      return;
158,794,496✔
418

419
    from_source(&secondary_bank().back());
65,912,454✔
420
    secondary_bank().pop_back();
65,912,454✔
421
    n_event() = 0;
65,912,454✔
422
    bank_second_E() = 0.0;
65,912,454✔
423

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

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

450
    // Enter new particle in particle track file
451
    if (write_track())
65,912,454✔
452
      add_particle_track(*this);
5,942✔
453
  }
454
}
455

456
void Particle::event_death()
158,795,496✔
457
{
458
#ifdef DAGMC
459
  history().reset();
13,202,385✔
460
#endif
461

462
  // Finish particle track output.
463
  if (write_track()) {
158,795,496✔
464
    finalize_particle_track(*this);
1,140✔
465
  }
466

467
// Contribute tally reduction variables to global accumulator
468
#pragma omp atomic
80,204,936✔
469
  global_tally_absorption += keff_tally_absorption();
158,795,496✔
470
#pragma omp atomic
79,982,193✔
471
  global_tally_collision += keff_tally_collision();
158,795,496✔
472
#pragma omp atomic
79,641,840✔
473
  global_tally_tracklength += keff_tally_tracklength();
158,795,496✔
474
#pragma omp atomic
79,159,889✔
475
  global_tally_leakage += keff_tally_leakage();
158,795,496✔
476

477
  // Reset particle tallies once accumulated
478
  keff_tally_absorption() = 0.0;
158,795,496✔
479
  keff_tally_collision() = 0.0;
158,795,496✔
480
  keff_tally_tracklength() = 0.0;
158,795,496✔
481
  keff_tally_leakage() = 0.0;
158,795,496✔
482

483
  if (!model::active_pulse_height_tallies.empty()) {
158,795,496✔
484
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
485
  }
486

487
  // Record the number of progeny created by this particle.
488
  // This data will be used to efficiently sort the fission bank.
489
  if (settings::run_mode == RunMode::EIGENVALUE) {
158,795,496✔
490
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
145,027,600✔
491
    simulation::progeny_per_particle[offset] = n_progeny();
145,027,600✔
492
  }
493
}
158,795,496✔
494

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

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

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

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

516
void Particle::pht_secondary_particles()
660✔
517
{
518
  // Removes the energy of secondary produced particles from the pulse-height
519

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

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

530
void Particle::cross_surface(const Surface& surf)
1,354,209,873✔
531
{
532

533
  if (settings::verbosity >= 10 || trace()) {
1,354,209,873✔
534
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
535
  }
536

537
// if we're crossing a CSG surface, make sure the DAG history is reset
538
#ifdef DAGMC
539
  if (surf.geom_type() == GeometryType::CSG)
112,558,515✔
540
    history().reset();
112,523,199✔
541
#endif
542

543
  // Handle any applicable boundary conditions.
544
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,354,209,873✔
545
    surf.bc_->handle_particle(*this, surf);
630,274,441✔
546
    return;
630,274,441✔
547
  }
548

549
  // ==========================================================================
550
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
551

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

565
    cell_instance() = 0;
28,265✔
566
    if (cell->distribcell_index_ >= 0)
28,265✔
567
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
568

569
    material() = cell->material(cell_instance());
28,265✔
570
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
571
    return;
28,265✔
572
  }
573
#endif
574

575
  bool verbose = settings::verbosity >= 10 || trace();
723,907,167✔
576
  if (neighbor_list_find_cell(*this, verbose)) {
723,907,167✔
577
    return;
723,876,599✔
578
  }
579

580
  // ==========================================================================
581
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
582

583
  // Remove lower coordinate levels
584
  n_coord() = 1;
30,568✔
585
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
586

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

593
    surface() = SURFACE_NONE;
6,268✔
594
    n_coord() = 1;
6,268✔
595
    r() += TINY_BIT * u();
6,268✔
596

597
    // Couldn't find next cell anywhere! This probably means there is an actual
598
    // undefined region in the geometry.
599

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

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

615
  if (!model::active_meshsurf_tallies.empty()) {
22,060,969✔
616
    // TODO: Find a better solution to score surface currents than
617
    // physically moving the particle forward slightly
618

619
    r() += TINY_BIT * u();
1,107,095✔
620
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,107,095✔
621
  }
622

623
  // Score to global leakage tally
624
  keff_tally_leakage() += wgt();
22,060,969✔
625

626
  // Kill the particle
627
  wgt() = 0.0;
22,060,969✔
628

629
  // Display message
630
  if (settings::verbosity >= 10 || trace()) {
22,060,969✔
631
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
632
  }
633
}
22,060,969✔
634

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

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

651
  if (!model::active_surface_tallies.empty()) {
608,607,060✔
652
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
653
  }
654

655
  if (!model::active_meshsurf_tallies.empty()) {
608,607,060✔
656
    Position r {this->r()};
55,050,482✔
657
    this->r() -= TINY_BIT * u();
55,050,482✔
658
    score_surface_tally(*this, model::active_meshsurf_tallies);
55,050,482✔
659
    this->r() = r;
55,050,482✔
660
  }
661

662
  // Set the new particle direction
663
  u() = new_u;
608,607,060✔
664

665
  // Reassign particle's cell and surface
666
  coord(0).cell = cell_last(0);
608,607,060✔
667
  surface() = -surface();
608,607,060✔
668

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

681
  // Set previous coordinate going slightly past surface crossing
682
  r_last_current() = r() + TINY_BIT * u();
608,607,060✔
683

684
  // Diagnostic message
685
  if (settings::verbosity >= 10 || trace()) {
608,607,060✔
UNCOV
686
    write_message(1, "    Reflected from surface {}", surf.id_);
×
687
  }
688
}
689

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

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

712
  // Adjust the particle's location and direction.
713
  r() = new_r;
727,164✔
714
  u() = new_u;
727,164✔
715

716
  // Reassign particle's surface
717
  surface() = new_surface;
727,164✔
718

719
  // Figure out what cell particle is in now
720
  n_coord() = 1;
727,164✔
721

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

731
  // Set previous coordinate going slightly past surface crossing
732
  r_last_current() = r() + TINY_BIT * u();
727,164✔
733

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

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

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

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

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

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

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

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

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

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

832
    // Close file
833
    file_close(file_id);
329✔
834
  } // #pragma omp critical
835
}
329✔
836

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

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

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

856
//==============================================================================
857
// Non-method functions
858
//==============================================================================
859

860
std::string particle_type_to_str(ParticleType type)
3,252,576✔
861
{
862
  switch (type) {
3,252,576✔
863
  case ParticleType::neutron:
2,456,004✔
864
    return "neutron";
2,456,004✔
865
  case ParticleType::photon:
796,332✔
866
    return "photon";
796,332✔
867
  case ParticleType::electron:
120✔
868
    return "electron";
120✔
869
  case ParticleType::positron:
120✔
870
    return "positron";
120✔
871
  }
UNCOV
872
  UNREACHABLE();
×
873
}
874

875
ParticleType str_to_particle_type(std::string str)
3,033,142✔
876
{
877
  if (str == "neutron") {
3,033,142✔
878
    return ParticleType::neutron;
695,569✔
879
  } else if (str == "photon") {
2,337,573✔
880
    return ParticleType::photon;
2,337,505✔
881
  } else if (str == "electron") {
68✔
882
    return ParticleType::electron;
34✔
883
  } else if (str == "positron") {
34✔
884
    return ParticleType::positron;
34✔
885
  } else {
UNCOV
886
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
887
  }
888
}
889

890
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,352,164,841✔
891
{
892
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
893
      simulation::surf_source_bank.full()) {
1,086,499,930✔
894
    return;
1,352,048,242✔
895
  }
896

897
  // If a cell/cellfrom/cellto parameter is defined
898
  if (settings::ssw_cell_id != C_NONE) {
349,640✔
899

900
    // Retrieve cell index and storage type
901
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,444✔
902

903
    if (surf.bc_) {
283,444✔
904
      // Leave if cellto with vacuum boundary condition
905
      if (surf.bc_->type() == "vacuum" &&
202,458✔
906
          settings::ssw_cell_type == SSWCellType::To) {
35,218✔
907
        return;
13,071✔
908
      }
909

910
      // Leave if other boundary condition than vacuum
911
      if (surf.bc_->type() != "vacuum") {
154,169✔
912
        return;
132,022✔
913
      }
914
    }
915

916
    // Check if the cell of interest has been exited
917
    bool exited = false;
138,351✔
918
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,549✔
919
      if (p.cell_last(i) == cell_idx) {
228,198✔
920
        exited = true;
81,191✔
921
      }
922
    }
923

924
    // Check if the cell of interest has been entered
925
    bool entered = false;
138,351✔
926
    for (int i = 0; i < p.n_coord(); ++i) {
328,948✔
927
      if (p.coord(i).cell == cell_idx) {
190,597✔
928
        entered = true;
64,719✔
929
      }
930
    }
931

932
    // Vacuum boundary conditions: return if cell is not exited
933
    if (surf.bc_) {
138,351✔
934
      if (surf.bc_->type() == "vacuum" && !exited) {
22,147✔
935
        return;
15,247✔
936
      }
937
    } else {
938

939
      // If we both enter and exit the cell of interest
940
      if (entered && exited) {
116,204✔
941
        return;
31,409✔
942
      }
943

944
      // If we did not enter nor exit the cell of interest
945
      if (!entered && !exited) {
84,795✔
946
        return;
15,503✔
947
      }
948

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

955
      // If cellto and the cell after crossing is not the cell of interest
956
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
56,625✔
957
        return;
13,122✔
958
      }
959
    }
960
  }
961

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

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