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

openmc-dev / openmc / 12776996362

14 Jan 2025 09:49PM UTC coverage: 84.938% (+0.2%) from 84.729%
12776996362

Pull #3133

github

web-flow
Merge 0495246d9 into 549cc0973
Pull Request #3133: Kinetics parameters using Iterated Fission Probability

318 of 330 new or added lines in 10 files covered. (96.36%)

1658 existing lines in 66 files now uncovered.

50402 of 59340 relevant lines covered (84.94%)

33987813.96 hits per line

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

92.63
/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:
24,761,280✔
54
    mass = 0.0;
24,761,280✔
55
    break;
24,761,280✔
56
  case ParticleType::electron:
97,625,688✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
97,625,688✔
59
    break;
97,625,688✔
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);
1,814,754,950✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

73
    // Calculate speed via v = c * sqrt(1 - γ^-2)
74
    return C_LIGHT * std::sqrt(1 - inv_gamma * inv_gamma);
2,147,483,647✔
75
  }
76
}
77

78
void Particle::move_distance(double length)
12,000✔
79
{
80
  for (int j = 0; j < n_coord(); ++j) {
24,000✔
81
    coord(j).r += length * coord(j).u;
12,000✔
82
  }
83
}
12,000✔
84

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

94
  secondary_bank().emplace_back();
55,592,743✔
95

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

104
  n_bank_second() += 1;
55,592,743✔
105
}
106

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

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

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

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

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

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

169
    // Set birth cell attribute
170
    if (cell_born() == C_NONE)
216,901,166✔
171
      cell_born() = lowest_coord().cell;
216,901,166✔
172

173
    // Initialize last cells from current cell
174
    for (int j = 0; j < n_coord(); ++j) {
445,418,244✔
175
      cell_last(j) = coord(j).cell;
228,517,078✔
176
    }
177
    n_coord_last() = n_coord();
216,901,166✔
178
  }
179

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

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

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

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

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

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

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

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

239
  // Kill particle if its time exceeds the cutoff
240
  bool hit_time_boundary = false;
2,147,483,647✔
241
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
242
  if (time() > time_cutoff) {
2,147,483,647✔
243
    double dt = time() - time_cutoff;
12,000✔
244
    time() = time_cutoff;
12,000✔
245
    lifetime() = 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,373,540,472✔
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,598,739,669✔
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,694,750,423✔
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,694,750,423✔
281

282
  // Set surface that particle is on and adjust coordinate levels
283
  surface() = boundary().surface_index;
1,694,750,423✔
284
  n_coord() = boundary().coord_level;
1,694,750,423✔
285

286
  if (boundary().lattice_translation[0] != 0 ||
1,694,750,423✔
287
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
288
      boundary().lattice_translation[2] != 0) {
1,491,775,777✔
289
    // Particle crosses lattice boundary
290

291
    bool verbose = settings::verbosity >= 10 || trace();
242,459,839✔
292
    cross_lattice(*this, boundary(), verbose);
242,459,839✔
293
    event() = TallyEvent::LATTICE;
242,459,839✔
294
  } else {
295
    // Particle crosses surface
296
    // TODO: off-by-one
297
    const auto& surf {model::surfaces[std::abs(surface()) - 1].get()};
1,452,290,584✔
298
    // If BC, add particle to surface source before crossing surface
299
    if (surf->surf_source_ && surf->bc_) {
1,452,290,584✔
300
      add_surf_source_to_bank(*this, *surf);
677,657,198✔
301
    }
302
    this->cross_surface(*surf);
1,452,290,584✔
303
    // If no BC, add particle to surface source after crossing surface
304
    if (surf->surf_source_ && !surf->bc_) {
1,452,290,574✔
305
      add_surf_source_to_bank(*this, *surf);
773,643,586✔
306
    }
307
    if (settings::weight_window_checkpoint_surface) {
1,452,290,574✔
UNCOV
308
      apply_weight_windows(*this);
×
309
    }
310
    event() = TallyEvent::SURFACE;
1,452,290,574✔
311
  }
312
  // Score cell to cell partial currents
313
  if (!model::active_surface_tallies.empty()) {
1,694,750,413✔
314
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
315
  }
316
}
1,694,750,413✔
317

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

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

330
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
331
    score_surface_tally(*this, model::active_meshsurf_tallies);
142,094,749✔
332

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

336
  if (settings::run_CE) {
2,147,483,647✔
337
    collision(*this);
807,689,228✔
338
  } else {
339
    collision_mg(*this);
1,939,604,940✔
340
  }
341

342
  // Score collision estimator tallies -- this is done after a collision
343
  // has occurred rather than before because we need information on the
344
  // outgoing energy for any tallies with an outgoing energy filter
345
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
346
    score_collision_tally(*this);
92,062,488✔
347
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
348
    if (settings::run_CE) {
168,915,805✔
349
      score_analog_tally_ce(*this);
167,605,393✔
350
    } else {
351
      score_analog_tally_mg(*this);
1,310,412✔
352
    }
353
  }
354

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

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

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

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

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

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

390
  // Score flux derivative accumulators for differential tallies.
391
  if (!model::active_tallies.empty())
2,147,483,647✔
392
    score_collision_derivative(*this);
697,707,141✔
393

394
#ifdef DAGMC
395
  history().reset();
236,165,151✔
396
#endif
397
}
2,147,483,647✔
398

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

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

416
    // If no secondary particles, break out of event loop
417
    if (secondary_bank().empty())
216,900,816✔
418
      return;
161,104,816✔
419

420
    from_source(&secondary_bank().back());
55,796,000✔
421
    secondary_bank().pop_back();
55,796,000✔
422
    n_event() = 0;
55,796,000✔
423

424
    // Subtract secondary particle energy from interim pulse-height results
425
    if (!model::active_pulse_height_tallies.empty() &&
55,812,908✔
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 " +
×
434
                       std::to_string(id()));
×
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())
55,796,000✔
452
      add_particle_track(*this);
5,942✔
453
  }
454
}
455

456
void Particle::event_death()
161,105,816✔
457
{
458
#ifdef DAGMC
459
  history().reset();
13,679,645✔
460
#endif
461

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

467
// Contribute tally reduction variables to global accumulator
468
#pragma omp atomic
81,384,736✔
469
  global_tally_absorption += keff_tally_absorption();
161,105,816✔
470
#pragma omp atomic
80,938,515✔
471
  global_tally_collision += keff_tally_collision();
161,105,816✔
472
#pragma omp atomic
80,942,608✔
473
  global_tally_tracklength += keff_tally_tracklength();
161,105,816✔
474
#pragma omp atomic
80,588,728✔
475
  global_tally_leakage += keff_tally_leakage();
161,105,816✔
476

477
  // Reset particle tallies once accumulated
478
  keff_tally_absorption() = 0.0;
161,105,816✔
479
  keff_tally_collision() = 0.0;
161,105,816✔
480
  keff_tally_tracklength() = 0.0;
161,105,816✔
481
  keff_tally_leakage() = 0.0;
161,105,816✔
482

483
  if (!model::active_pulse_height_tallies.empty()) {
161,105,816✔
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) {
161,105,816✔
490
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,568,600✔
491
    simulation::progeny_per_particle[offset] = n_progeny();
148,568,600✔
492
  }
493
}
161,105,816✔
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,452,290,584✔
531
{
532

533
  if (settings::verbosity >= 10 || trace()) {
1,452,290,584✔
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)
130,350,900✔
540
    history().reset();
130,315,584✔
541
#endif
542

543
  // Handle any applicable boundary conditions.
544
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,452,290,584✔
545
    surf.bc_->handle_particle(*this, surf);
677,917,169✔
546
    return;
677,917,169✔
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) {
69,437,676✔
555
    int32_t i_cell = next_cell(std::abs(surface()), 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();
774,345,150✔
576
  if (neighbor_list_find_cell(*this, verbose)) {
774,345,150✔
577
    return;
774,314,582✔
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() = 0;
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,937,244✔
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,937,244✔
616
    // TODO: Find a better solution to score surface currents than
617
    // physically moving the particle forward slightly
618

619
    r() += TINY_BIT * u();
2,016,875✔
620
    score_surface_tally(*this, model::active_meshsurf_tallies);
2,016,875✔
621
  }
622

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

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

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

635
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
655,373,513✔
636
{
637
  // Do not handle reflective boundary conditions on lower universes
638
  if (n_coord() != 1) {
655,373,513✔
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()) {
655,373,513✔
652
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
653
  }
654

655
  if (!model::active_meshsurf_tallies.empty()) {
655,373,513✔
656
    Position r {this->r()};
105,287,354✔
657
    this->r() -= TINY_BIT * u();
105,287,354✔
658
    score_surface_tally(*this, model::active_meshsurf_tallies);
105,287,354✔
659
    this->r() = r;
105,287,354✔
660
  }
661

662
  // Set the new particle direction
663
  u() = new_u;
655,373,513✔
664

665
  // Reassign particle's cell and surface
666
  coord(0).cell = cell_last(0);
655,373,513✔
667
  surface() = -surface();
655,373,513✔
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;
655,373,513✔
674
  if (surf.geom_type() != GeometryType::DAG &&
1,310,744,487✔
675
      !neighbor_list_find_cell(*this)) {
655,370,974✔
676
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
677
                 std::to_string(surf.id_) + ".");
×
678
    return;
×
679
  }
680

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

684
  // Diagnostic message
685
  if (settings::verbosity >= 10 || trace()) {
655,373,513✔
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(
×
696
      "Cannot transfer particle " + std::to_string(id()) +
×
697
      " across surface in a lower universe. Boundary conditions must be "
698
      "applied to root universe.");
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✔
706
    Position r {this->r()};
×
707
    this->r() -= TINY_BIT * u();
×
708
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
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✔
723
    mark_as_lost("Couldn't find particle after hitting periodic "
×
724
                 "boundary on surface " +
×
725
                 std::to_string(surf.id_) +
×
726
                 ". The normal vector "
727
                 "of one periodic surface may need to be reversed.");
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✔
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);
329✔
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:
×
801
      write_dataset(file_id, "run_mode", "particle restart");
×
802
      break;
×
803
    default:
×
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,722✔
851
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,722✔
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,245,772✔
861
{
862
  switch (type) {
3,245,772✔
863
  case ParticleType::neutron:
2,450,772✔
864
    return "neutron";
2,450,772✔
865
  case ParticleType::photon:
794,760✔
866
    return "photon";
794,760✔
867
  case ParticleType::electron:
120✔
868
    return "electron";
120✔
869
  case ParticleType::positron:
120✔
870
    return "positron";
120✔
871
  }
872
  UNREACHABLE();
×
873
}
874

875
ParticleType str_to_particle_type(std::string str)
3,392,964✔
876
{
877
  if (str == "neutron") {
3,392,964✔
878
    return ParticleType::neutron;
779,885✔
879
  } else if (str == "photon") {
2,613,079✔
880
    return ParticleType::photon;
2,613,011✔
881
  } else if (str == "electron") {
68✔
882
    return ParticleType::electron;
34✔
883
  } else if (str == "positron") {
34✔
884
    return ParticleType::positron;
34✔
885
  } else {
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,451,300,784✔
891
{
892
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
893
      simulation::surf_source_bank.full()) {
1,145,831,909✔
894
    return;
1,451,184,186✔
895
  }
896

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

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

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

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

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

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

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

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

944
      // If we did not enter nor exit the cell of interest
945
      if (!entered && !exited) {
84,791✔
946
        return;
15,499✔
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,666✔
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,626✔
957
        return;
13,123✔
958
      }
959
    }
960
  }
961

962
  SourceSite site;
116,598✔
963
  site.r = p.r();
116,598✔
964
  site.u = p.u();
116,598✔
965
  site.E = p.E();
116,598✔
966
  site.time = p.time();
116,598✔
967
  site.wgt = p.wgt();
116,598✔
968
  site.delayed_group = p.delayed_group();
116,598✔
969
  site.surf_id = surf.id_;
116,598✔
970
  site.particle = p.type();
116,598✔
971
  site.parent_id = p.id();
116,598✔
972
  site.progeny_id = p.n_progeny();
116,598✔
973
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
116,598✔
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

© 2026 Coveralls, Inc