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

openmc-dev / openmc / 13167860103

05 Feb 2025 10:35PM UTC coverage: 84.937% (+0.2%) from 84.729%
13167860103

Pull #3133

github

web-flow
Merge 715eed13d into 6e0f156d3
Pull Request #3133: Kinetics parameters using Iterated Fission Probability

312 of 322 new or added lines in 11 files covered. (96.89%)

2420 existing lines in 79 files now uncovered.

50463 of 59412 relevant lines covered (84.94%)

35029259.52 hits per line

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

92.78
/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,819,020✔
54
    mass = 0.0;
15,819,020✔
55
    break;
15,819,020✔
56
  case ParticleType::electron:
52,989,443✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,989,443✔
59
    break;
52,989,443✔
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,114,376✔
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,892,879✔
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,892,879✔
91
    return;
52,903,629✔
92
  }
93

94
  auto& bank = secondary_bank().emplace_back();
57,989,250✔
95
  bank.particle = type;
57,989,250✔
96
  bank.wgt = wgt;
57,989,250✔
97
  bank.r = r();
57,989,250✔
98
  bank.u = u;
57,989,250✔
99
  bank.E = settings::run_CE ? E : g();
57,989,250✔
100
  bank.time = time();
57,989,250✔
101
  bank_second_E() += bank.E;
57,989,250✔
102
}
103

104
void Particle::split(double wgt)
7,395,933✔
105
{
106
  auto& bank = secondary_bank().emplace_back();
7,395,933✔
107
  bank.particle = type();
7,395,933✔
108
  bank.wgt = wgt;
7,395,933✔
109
  bank.r = r();
7,395,933✔
110
  bank.u = u();
7,395,933✔
111
  bank.E = settings::run_CE ? E() : g();
7,395,933✔
112
  bank.time = time();
7,395,933✔
113
}
7,395,933✔
114

115
void Particle::from_source(const SourceSite* src)
228,489,926✔
116
{
117
  // Reset some attributes
118
  clear();
228,489,926✔
119
  surface() = SURFACE_NONE;
228,489,926✔
120
  cell_born() = C_NONE;
228,489,926✔
121
  material() = C_NONE;
228,489,926✔
122
  n_collision() = 0;
228,489,926✔
123
  fission() = false;
228,489,926✔
124
  zero_flux_derivs();
228,489,926✔
125
  lifetime() = 0.0;
228,489,926✔
126

127
  // Copy attributes from source bank site
128
  type() = src->particle;
228,489,926✔
129
  wgt() = src->wgt;
228,489,926✔
130
  wgt_last() = src->wgt;
228,489,926✔
131
  r() = src->r;
228,489,926✔
132
  u() = src->u;
228,489,926✔
133
  r_born() = src->r;
228,489,926✔
134
  r_last_current() = src->r;
228,489,926✔
135
  r_last() = src->r;
228,489,926✔
136
  u_last() = src->u;
228,489,926✔
137
  if (settings::run_CE) {
228,489,926✔
138
    E() = src->E;
100,517,570✔
139
    g() = 0;
100,517,570✔
140
  } else {
141
    g() = static_cast<int>(src->E);
127,972,356✔
142
    g_last() = static_cast<int>(src->E);
127,972,356✔
143
    E() = data::mg.energy_bin_avg_[g()];
127,972,356✔
144
  }
145
  E_last() = E();
228,489,926✔
146
  time() = src->time;
228,489,926✔
147
  time_last() = src->time;
228,489,926✔
148
}
228,489,926✔
149

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

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

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

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

177
    // Set birth cell attribute
178
    if (cell_born() == C_NONE)
227,909,702✔
179
      cell_born() = lowest_coord().cell;
227,909,702✔
180

181
    // Initialize last cells from current cell
182
    for (int j = 0; j < n_coord(); ++j) {
480,202,824✔
183
      cell_last(j) = coord(j).cell;
252,293,122✔
184
    }
185
    n_coord_last() = n_coord();
227,909,702✔
186
  }
187

188
  // Write particle track.
189
  if (write_track())
2,147,483,647✔
190
    write_particle_track(*this);
11,599✔
191

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

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

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

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

226
  // Sample a distance to collision
227
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
228
    collision_distance() = 0.0;
52,989,443✔
229
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
230
    collision_distance() = INFINITY;
50,524,743✔
231
  } else {
232
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
233
  }
234

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

238
  // Advance particle in space and time
239
  // Short-term solution until the surface source is revised and we can use
240
  // this->move_distance(distance)
241
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
242
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
243
  }
244
  double dt = distance / this->speed();
2,147,483,647✔
245
  this->time() += dt;
2,147,483,647✔
246
  this->lifetime() += dt;
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
    lifetime() = time_cutoff;
12,000✔
255

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

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

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

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

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

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

291
  // Set surface that particle is on and adjust coordinate levels
292
  surface() = boundary().surface;
1,750,743,481✔
293
  n_coord() = boundary().coord_level;
1,750,743,481✔
294

295
  if (boundary().lattice_translation[0] != 0 ||
1,750,743,481✔
296
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
297
      boundary().lattice_translation[2] != 0) {
1,512,623,598✔
298
    // Particle crosses lattice boundary
299

300
    bool verbose = settings::verbosity >= 10 || trace();
295,162,031✔
301
    cross_lattice(*this, boundary(), verbose);
295,162,031✔
302
    event() = TallyEvent::LATTICE;
295,162,031✔
303
  } else {
304
    // Particle crosses surface
305
    // TODO: off-by-one
306
    const auto& surf {model::surfaces[surface_index()].get()};
1,455,581,450✔
307
    // If BC, add particle to surface source before crossing surface
308
    if (surf->surf_source_ && surf->bc_) {
1,455,581,450✔
309
      add_surf_source_to_bank(*this, *surf);
681,267,432✔
310
    }
311
    this->cross_surface(*surf);
1,455,581,450✔
312
    // If no BC, add particle to surface source after crossing surface
313
    if (surf->surf_source_ && !surf->bc_) {
1,455,581,440✔
314
      add_surf_source_to_bank(*this, *surf);
773,324,218✔
315
    }
316
    if (settings::weight_window_checkpoint_surface) {
1,455,581,440✔
UNCOV
317
      apply_weight_windows(*this);
×
318
    }
319
    event() = TallyEvent::SURFACE;
1,455,581,440✔
320
  }
321
  // Score cell to cell partial currents
322
  if (!model::active_surface_tallies.empty()) {
1,750,743,471✔
323
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
324
  }
325
}
1,750,743,471✔
326

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

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

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

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

345
  if (settings::run_CE) {
2,147,483,647✔
346
    collision(*this);
815,258,586✔
347
  } else {
348
    collision_mg(*this);
1,948,075,116✔
349
  }
350

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

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

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

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

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

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

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

399
  // Score flux derivative accumulators for differential tallies.
400
  if (!model::active_tallies.empty())
2,147,483,647✔
401
    score_collision_derivative(*this);
713,746,687✔
402

403
#ifdef DAGMC
404
  history().reset();
249,223,935✔
405
#endif
406
}
2,147,483,647✔
407

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

418
  // Check for secondary particles if this particle is dead
419
  if (!alive()) {
2,147,483,647✔
420
    // Write final position for this particle
421
    if (write_track()) {
227,909,352✔
422
      write_particle_track(*this);
7,086✔
423
    }
424

425
    // If no secondary particles, break out of event loop
426
    if (secondary_bank().empty())
227,909,352✔
427
      return;
162,320,816✔
428

429
    from_source(&secondary_bank().back());
65,588,536✔
430
    secondary_bank().pop_back();
65,588,536✔
431
    n_event() = 0;
65,588,536✔
432
    bank_second_E() = 0.0;
65,588,536✔
433

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

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

460
    // Enter new particle in particle track file
461
    if (write_track())
65,588,536✔
462
      add_particle_track(*this);
5,946✔
463
  }
464
}
465

466
void Particle::event_death()
162,321,816✔
467
{
468
#ifdef DAGMC
469
  history().reset();
14,351,145✔
470
#endif
471

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

477
// Contribute tally reduction variables to global accumulator
478
#pragma omp atomic
82,063,538✔
479
  global_tally_absorption += keff_tally_absorption();
162,321,816✔
480
#pragma omp atomic
81,822,524✔
481
  global_tally_collision += keff_tally_collision();
162,321,816✔
482
#pragma omp atomic
82,003,921✔
483
  global_tally_tracklength += keff_tally_tracklength();
162,321,816✔
484
#pragma omp atomic
81,497,592✔
485
  global_tally_leakage += keff_tally_leakage();
162,321,816✔
486

487
  // Reset particle tallies once accumulated
488
  keff_tally_absorption() = 0.0;
162,321,816✔
489
  keff_tally_collision() = 0.0;
162,321,816✔
490
  keff_tally_tracklength() = 0.0;
162,321,816✔
491
  keff_tally_leakage() = 0.0;
162,321,816✔
492

493
  if (!model::active_pulse_height_tallies.empty()) {
162,321,816✔
494
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
495
  }
496

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

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

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

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

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

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

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

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

540
void Particle::cross_surface(const Surface& surf)
1,455,581,450✔
541
{
542

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

547
// if we're crossing a CSG surface, make sure the DAG history is reset
548
#ifdef DAGMC
549
  if (surf.geom_type() == GeometryType::CSG)
149,915,982✔
550
    history().reset();
149,880,666✔
551
#endif
552

553
  // Handle any applicable boundary conditions.
554
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,455,581,450✔
555
    surf.bc_->handle_particle(*this, surf);
681,527,403✔
556
    return;
681,527,403✔
557
  }
558

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

562
#ifdef DAGMC
563
  // in DAGMC, we know what the next cell should be
564
  if (surf.geom_type() == GeometryType::DAG) {
79,139,038✔
565
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
566
                       lowest_coord().universe) -
28,265✔
567
                     1;
28,265✔
568
    // save material and temp
569
    material_last() = material();
28,265✔
570
    sqrtkT_last() = sqrtkT();
28,265✔
571
    // set new cell value
572
    lowest_coord().cell = i_cell;
28,265✔
573
    auto& cell = model::cells[i_cell];
28,265✔
574

575
    cell_instance() = 0;
28,265✔
576
    if (cell->distribcell_index_ >= 0)
28,265✔
577
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
578

579
    material() = cell->material(cell_instance());
28,265✔
580
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
581
    return;
28,265✔
582
  }
583
#endif
584

585
  bool verbose = settings::verbosity >= 10 || trace();
774,025,782✔
586
  if (neighbor_list_find_cell(*this, verbose)) {
774,025,782✔
587
    return;
773,995,214✔
588
  }
589

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

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

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

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

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

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

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

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

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

633
  // Score to global leakage tally
634
  keff_tally_leakage() += wgt();
22,993,046✔
635

636
  // Kill the particle
637
  wgt() = 0.0;
22,993,046✔
638

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

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

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

661
  if (!model::active_surface_tallies.empty()) {
658,927,945✔
662
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
663
  }
664

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

672
  // Set the new particle direction
673
  u() = new_u;
658,927,945✔
674

675
  // Reassign particle's cell and surface
676
  coord(0).cell = cell_last(0);
658,927,945✔
677
  surface() = -surface();
658,927,945✔
678

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

691
  // Set previous coordinate going slightly past surface crossing
692
  r_last_current() = r() + TINY_BIT * u();
658,927,945✔
693

694
  // Diagnostic message
695
  if (settings::verbosity >= 10 || trace()) {
658,927,945✔
696
    write_message(1, "    Reflected from surface {}", surf.id_);
×
697
  }
698
}
699

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

866
//==============================================================================
867
// Non-method functions
868
//==============================================================================
869

870
std::string particle_type_to_str(ParticleType type)
3,252,552✔
871
{
872
  switch (type) {
3,252,552✔
873
  case ParticleType::neutron:
2,456,004✔
874
    return "neutron";
2,456,004✔
875
  case ParticleType::photon:
796,308✔
876
    return "photon";
796,308✔
877
  case ParticleType::electron:
120✔
878
    return "electron";
120✔
879
  case ParticleType::positron:
120✔
880
    return "positron";
120✔
881
  }
UNCOV
882
  UNREACHABLE();
×
883
}
884

885
ParticleType str_to_particle_type(std::string str)
3,397,549✔
886
{
887
  if (str == "neutron") {
3,397,549✔
888
    return ParticleType::neutron;
781,806✔
889
  } else if (str == "photon") {
2,615,743✔
890
    return ParticleType::photon;
2,615,675✔
891
  } else if (str == "electron") {
68✔
892
    return ParticleType::electron;
34✔
893
  } else if (str == "positron") {
34✔
894
    return ParticleType::positron;
34✔
895
  } else {
UNCOV
896
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
897
  }
898
}
899

900
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,454,591,650✔
901
{
902
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
903
      simulation::surf_source_bank.full()) {
1,148,801,271✔
904
    return;
1,454,475,052✔
905
  }
906

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

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

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

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

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

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

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

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

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

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

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

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

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