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

openmc-dev / openmc / 15648508499

14 Jun 2025 04:41AM UTC coverage: 85.162% (+0.04%) from 85.126%
15648508499

Pull #3346

github

web-flow
Merge 95507c5a3 into b11eb0265
Pull Request #3346: Allow specifying number of equiprobable angles for thermal scattering data generation

52373 of 61498 relevant lines covered (85.16%)

36636961.06 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,034,962✔
54
    mass = 0.0;
15,034,962✔
55
    break;
15,034,962✔
56
  case ParticleType::electron:
48,516,872✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,516,872✔
59
    break;
48,516,872✔
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);
856,246,322✔
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(
101,566,074✔
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)]) {
101,566,074✔
84
    return false;
48,442,727✔
85
  }
86

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

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

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

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

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

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

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

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

172
    // Set birth cell attribute
173
    if (cell_born() == C_NONE)
216,547,594✔
174
      cell_born() = lowest_coord().cell;
216,547,594✔
175

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
454,789,531✔
178
      cell_last(j) = coord(j).cell;
238,241,937✔
179
    }
180
    n_coord_last() = n_coord();
216,547,594✔
181
  }
182

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

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

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

205
      // Update the particle's group while we know we are multi-group
206
      g_last() = g();
2,079,768,108✔
207
    }
208
  } else {
209
    macro_xs().total = 0.0;
66,455,937✔
210
    macro_xs().absorption = 0.0;
66,455,937✔
211
    macro_xs().fission = 0.0;
66,455,937✔
212
    macro_xs().nu_fission = 0.0;
66,455,937✔
213
  }
214
}
215

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

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

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

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

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

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

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

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

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

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

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

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

290
  if (boundary().lattice_translation[0] != 0 ||
2,034,997,326✔
291
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
292
      boundary().lattice_translation[2] != 0) {
1,541,662,116✔
293
    // Particle crosses lattice boundary
294

295
    bool verbose = settings::verbosity >= 10 || trace();
683,879,339✔
296
    cross_lattice(*this, boundary(), verbose);
683,879,339✔
297
    event() = TallyEvent::LATTICE;
683,879,339✔
298
  } else {
299
    // Particle crosses surface
300
    const auto& surf {model::surfaces[surface_index()].get()};
1,351,117,987✔
301
    // If BC, add particle to surface source before crossing surface
302
    if (surf->surf_source_ && surf->bc_) {
1,351,117,987✔
303
      add_surf_source_to_bank(*this, *surf);
634,118,770✔
304
    }
305
    this->cross_surface(*surf);
1,351,117,987✔
306
    // If no BC, add particle to surface source after crossing surface
307
    if (surf->surf_source_ && !surf->bc_) {
1,351,117,978✔
308
      add_surf_source_to_bank(*this, *surf);
716,095,799✔
309
    }
310
    if (settings::weight_window_checkpoint_surface) {
1,351,117,978✔
311
      apply_weight_windows(*this);
×
312
    }
313
    event() = TallyEvent::SURFACE;
1,351,117,978✔
314
  }
315
  // Score cell to cell partial currents
316
  if (!model::active_surface_tallies.empty()) {
2,034,997,317✔
317
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
318
  }
319
}
2,034,997,317✔
320

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

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

333
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
334
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
335

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

339
  if (settings::run_CE) {
2,147,483,647✔
340
    collision(*this);
713,570,518✔
341
  } else {
342
    collision_mg(*this);
1,785,735,523✔
343
  }
344

345
  // Score collision estimator tallies -- this is done after a collision
346
  // has occurred rather than before because we need information on the
347
  // outgoing energy for any tallies with an outgoing energy filter
348
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
349
    score_collision_tally(*this);
92,448,743✔
350
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
351
    if (settings::run_CE) {
113,305,951✔
352
      score_analog_tally_ce(*this);
112,104,740✔
353
    } else {
354
      score_analog_tally_mg(*this);
1,201,211✔
355
    }
356
  }
357

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

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

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

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

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

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

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

397
#ifdef DAGMC
398
  history().reset();
228,541,480✔
399
#endif
400
}
2,147,483,647✔
401

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

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

419
    // If no secondary particles, break out of event loop
420
    if (secondary_bank().empty())
216,547,190✔
421
      return;
156,310,618✔
422

423
    from_source(&secondary_bank().back());
60,236,572✔
424
    secondary_bank().pop_back();
60,236,572✔
425
    n_event() = 0;
60,236,572✔
426
    bank_second_E() = 0.0;
60,236,572✔
427

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

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

454
    // Enter new particle in particle track file
455
    if (write_track())
60,236,572✔
456
      add_particle_track(*this);
5,604✔
457
  }
458
}
459

460
void Particle::event_death()
156,311,618✔
461
{
462
#ifdef DAGMC
463
  history().reset();
14,259,502✔
464
#endif
465

466
  // Finish particle track output.
467
  if (write_track()) {
156,311,618✔
468
    finalize_particle_track(*this);
1,070✔
469
  }
470

471
// Contribute tally reduction variables to global accumulator
472
#pragma omp atomic
85,898,561✔
473
  global_tally_absorption += keff_tally_absorption();
156,311,618✔
474
#pragma omp atomic
86,137,272✔
475
  global_tally_collision += keff_tally_collision();
156,311,618✔
476
#pragma omp atomic
85,794,412✔
477
  global_tally_tracklength += keff_tally_tracklength();
156,311,618✔
478
#pragma omp atomic
85,353,012✔
479
  global_tally_leakage += keff_tally_leakage();
156,311,618✔
480

481
  // Reset particle tallies once accumulated
482
  keff_tally_absorption() = 0.0;
156,311,618✔
483
  keff_tally_collision() = 0.0;
156,311,618✔
484
  keff_tally_tracklength() = 0.0;
156,311,618✔
485
  keff_tally_leakage() = 0.0;
156,311,618✔
486

487
  if (!model::active_pulse_height_tallies.empty()) {
156,311,618✔
488
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
489
  }
490

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

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

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

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

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

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

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

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

534
void Particle::cross_surface(const Surface& surf)
1,352,101,255✔
535
{
536

537
  if (settings::verbosity >= 10 || trace()) {
1,352,101,255✔
538
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
539
  }
540

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

547
  // Handle any applicable boundary conditions.
548
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,352,101,255✔
549
    surf.bc_->handle_particle(*this, surf);
634,356,387✔
550
    return;
634,356,387✔
551
  }
552

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

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

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

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

579
  bool verbose = settings::verbosity >= 10 || trace();
717,716,603✔
580
  if (neighbor_list_find_cell(*this, verbose)) {
717,716,603✔
581
    return;
717,688,584✔
582
  }
583

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

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

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

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

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

604
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
605
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
606
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
607
                   " it could not be located in any cell and it did not leak.");
608
      return;
5,735✔
609
    }
610
  }
611
}
612

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

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

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

627
  // Score to global leakage tally
628
  keff_tally_leakage() += wgt();
30,490,642✔
629

630
  // Kill the particle
631
  wgt() = 0.0;
30,490,642✔
632

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

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

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

655
  if (!model::active_surface_tallies.empty()) {
604,226,783✔
656
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
657
  }
658

659
  if (!model::active_meshsurf_tallies.empty()) {
604,226,783✔
660
    Position r {this->r()};
50,811,809✔
661
    this->r() -= TINY_BIT * u();
50,811,809✔
662
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
663
    this->r() = r;
50,811,809✔
664
  }
665

666
  // Set the new particle direction
667
  u() = new_u;
604,226,783✔
668

669
  // Reassign particle's cell and surface
670
  coord(0).cell = cell_last(0);
604,226,783✔
671
  surface() = -surface();
604,226,783✔
672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

864
std::string particle_type_to_str(ParticleType type)
3,130,182✔
865
{
866
  switch (type) {
3,130,182✔
867
  case ParticleType::neutron:
2,399,925✔
868
    return "neutron";
2,399,925✔
869
  case ParticleType::photon:
729,993✔
870
    return "photon";
729,993✔
871
  case ParticleType::electron:
132✔
872
    return "electron";
132✔
873
  case ParticleType::positron:
132✔
874
    return "positron";
132✔
875
  }
876
  UNREACHABLE();
×
877
}
878

879
ParticleType str_to_particle_type(std::string str)
2,955,559✔
880
{
881
  if (str == "neutron") {
2,955,559✔
882
    return ParticleType::neutron;
676,349✔
883
  } else if (str == "photon") {
2,279,210✔
884
    return ParticleType::photon;
2,279,124✔
885
  } else if (str == "electron") {
86✔
886
    return ParticleType::electron;
43✔
887
  } else if (str == "positron") {
43✔
888
    return ParticleType::positron;
43✔
889
  } else {
890
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
891
  }
892
}
893

894
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,350,214,569✔
895
{
896
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
897
      simulation::surf_source_bank.full()) {
1,059,866,582✔
898
    return;
1,350,107,804✔
899
  }
900

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

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

907
    if (surf.bc_) {
258,703✔
908
      // Leave if cellto with vacuum boundary condition
909
      if (surf.bc_->type() == "vacuum" &&
184,448✔
910
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
911
        return;
11,953✔
912
      }
913

914
      // Leave if other boundary condition than vacuum
915
      if (surf.bc_->type() != "vacuum") {
140,281✔
916
        return;
120,020✔
917
      }
918
    }
919

920
    // Check if the cell of interest has been exited
921
    bool exited = false;
126,730✔
922
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,337✔
923
      if (p.cell_last(i) == cell_idx) {
208,607✔
924
        exited = true;
74,235✔
925
      }
926
    }
927

928
    // Check if the cell of interest has been entered
929
    bool entered = false;
126,730✔
930
    for (int i = 0; i < p.n_coord(); ++i) {
301,033✔
931
      if (p.coord(i).cell == cell_idx) {
174,303✔
932
        entered = true;
59,096✔
933
      }
934
    }
935

936
    // Vacuum boundary conditions: return if cell is not exited
937
    if (surf.bc_) {
126,730✔
938
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
939
        return;
13,961✔
940
      }
941
    } else {
942

943
      // If we both enter and exit the cell of interest
944
      if (entered && exited) {
106,469✔
945
        return;
28,613✔
946
      }
947

948
      // If we did not enter nor exit the cell of interest
949
      if (!entered && !exited) {
77,856✔
950
        return;
14,351✔
951
      }
952

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

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

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

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

© 2026 Coveralls, Inc