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

openmc-dev / openmc / 12366039146

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

Pull #3227

github

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

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

19 existing lines in 1 file now uncovered.

49874 of 58782 relevant lines covered (84.85%)

33813403.41 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,656,992✔
54
    mass = 0.0;
15,656,992✔
55
    break;
15,656,992✔
56
  case ParticleType::electron:
52,792,192✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,792,192✔
59
    break;
52,792,192✔
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);
905,562,676✔
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,493,174✔
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,493,174✔
91
    return;
52,704,372✔
92
  }
93

94
  secondary_bank().emplace_back();
57,788,802✔
95

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

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

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

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

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

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

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

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

178
    // Set birth cell attribute
179
    if (cell_born() == C_NONE)
220,195,948✔
180
      cell_born() = lowest_coord().cell;
220,195,948✔
181

182
    // Initialize last cells from current cell
183
    for (int j = 0; j < n_coord(); ++j) {
451,809,481✔
184
      cell_last(j) = coord(j).cell;
231,613,533✔
185
    }
186
    n_coord_last() = n_coord();
220,195,948✔
187
  }
188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

289
  // Set surface that particle is on and adjust coordinate levels
290
  surface() = boundary().surface_index;
1,663,819,817✔
291
  n_coord() = boundary().coord_level;
1,663,819,817✔
292

293
  if (boundary().lattice_translation[0] != 0 ||
1,663,819,817✔
294
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
295
      boundary().lattice_translation[2] != 0) {
1,462,737,455✔
296
    // Particle crosses lattice boundary
297

298
    bool verbose = settings::verbosity >= 10 || trace();
240,567,571✔
299
    cross_lattice(*this, boundary(), verbose);
240,567,571✔
300
    event() = TallyEvent::LATTICE;
240,567,571✔
301
  } else {
302
    // Particle crosses surface
303
    // TODO: off-by-one
304
    const auto& surf {model::surfaces[std::abs(surface()) - 1].get()};
1,423,252,246✔
305
    // If BC, add particle to surface source before crossing surface
306
    if (surf->surf_source_ && surf->bc_) {
1,423,252,246✔
307
      add_surf_source_to_bank(*this, *surf);
663,174,483✔
308
    }
309
    this->cross_surface(*surf);
1,423,252,246✔
310
    // If no BC, add particle to surface source after crossing surface
311
    if (surf->surf_source_ && !surf->bc_) {
1,423,252,236✔
312
      add_surf_source_to_bank(*this, *surf);
759,087,963✔
313
    }
314
    if (settings::weight_window_checkpoint_surface) {
1,423,252,236✔
UNCOV
315
      apply_weight_windows(*this);
×
316
    }
317
    event() = TallyEvent::SURFACE;
1,423,252,236✔
318
  }
319
  // Score cell to cell partial currents
320
  if (!model::active_surface_tallies.empty()) {
1,663,819,807✔
321
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
322
  }
323
}
1,663,819,807✔
324

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

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

337
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
338
    score_surface_tally(*this, model::active_meshsurf_tallies);
125,142,418✔
339

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

343
  if (settings::run_CE) {
2,147,483,647✔
344
    collision(*this);
796,762,562✔
345
  } else {
346
    collision_mg(*this);
1,939,604,940✔
347
  }
348

349
  // Score collision estimator tallies -- this is done after a collision
350
  // has occurred rather than before because we need information on the
351
  // outgoing energy for any tallies with an outgoing energy filter
352
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
353
    score_collision_tally(*this);
98,858,492✔
354
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
355
    if (settings::run_CE) {
151,963,474✔
356
      score_analog_tally_ce(*this);
150,653,062✔
357
    } else {
358
      score_analog_tally_mg(*this);
1,310,412✔
359
    }
360
  }
361

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

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

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

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

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

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

397
  // Score flux derivative accumulators for differential tallies.
398
  if (!model::active_tallies.empty())
2,147,483,647✔
399
    score_collision_derivative(*this);
686,925,927✔
400

401
#ifdef DAGMC
402
  history().reset();
242,577,443✔
403
#endif
404
}
2,147,483,647✔
405

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

416
  // Check for secondary particles if this particle is dead
417
  if (!alive()) {
2,147,483,647✔
418
    // Write final position for this particle
419
    if (write_track()) {
220,195,598✔
420
      write_particle_track(*this);
7,082✔
421
    }
422

423
    // If no secondary particles, break out of event loop
424
    if (secondary_bank().empty())
220,195,598✔
425
      return;
160,014,816✔
426

427
    from_source(&secondary_bank().back());
60,180,782✔
428
    secondary_bank().pop_back();
60,180,782✔
429
    n_event() = 0;
60,180,782✔
430
    bank_second_E() = 0.0;
60,180,782✔
431

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

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

458
    // Enter new particle in particle track file
459
    if (write_track())
60,180,782✔
460
      add_particle_track(*this);
5,942✔
461
  }
462
}
463

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

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

475
// Contribute tally reduction variables to global accumulator
476
#pragma omp atomic
80,492,400✔
477
  global_tally_absorption += keff_tally_absorption();
160,015,816✔
478
#pragma omp atomic
80,275,845✔
479
  global_tally_collision += keff_tally_collision();
160,015,816✔
480
#pragma omp atomic
80,226,912✔
481
  global_tally_tracklength += keff_tally_tracklength();
160,015,816✔
482
#pragma omp atomic
79,901,781✔
483
  global_tally_leakage += keff_tally_leakage();
160,015,816✔
484

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

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

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

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

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

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

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

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

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

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

538
void Particle::cross_surface(const Surface& surf)
1,423,252,246✔
539
{
540

541
  if (settings::verbosity >= 10 || trace()) {
1,423,252,246✔
542
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
543
  }
544

545
// if we're crossing a CSG surface, make sure the DAG history is reset
546
#ifdef DAGMC
547
  if (surf.geom_type_ == GeometryType::CSG)
139,963,902✔
548
    history().reset();
139,935,117✔
549
#endif
550

551
  // Handle any applicable boundary conditions.
552
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,423,252,246✔
553
    surf.bc_->handle_particle(*this, surf);
663,434,454✔
554
    return;
663,434,454✔
555
  }
556

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

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

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

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

583
  bool verbose = settings::verbosity >= 10 || trace();
759,793,250✔
584
  if (neighbor_list_find_cell(*this, verbose)) {
759,793,250✔
585
    return;
759,762,682✔
586
  }
587

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

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

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

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

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

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

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

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

627
    r() += TINY_BIT * u();
1,789,430✔
628
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,789,430✔
629
  }
630

631
  // Score to global leakage tally
632
  keff_tally_leakage() += wgt();
22,570,703✔
633

634
  // Kill the particle
635
  wgt() = 0.0;
22,570,703✔
636

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

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

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

659
  if (!model::active_surface_tallies.empty()) {
641,257,339✔
660
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
661
  }
662

663
  if (!model::active_meshsurf_tallies.empty()) {
641,257,339✔
664
    Position r {this->r()};
92,728,136✔
665
    this->r() -= TINY_BIT * u();
92,728,136✔
666
    score_surface_tally(*this, model::active_meshsurf_tallies);
92,728,136✔
667
    this->r() = r;
92,728,136✔
668
  }
669

670
  // Set the new particle direction
671
  u() = new_u;
641,257,339✔
672

673
  // Reassign particle's cell and surface
674
  coord(0).cell = cell_last(0);
641,257,339✔
675
  surface() = -surface();
641,257,339✔
676

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

688
  // Set previous coordinate going slightly past surface crossing
689
  r_last_current() = r() + TINY_BIT * u();
641,257,339✔
690

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

882
ParticleType str_to_particle_type(std::string str)
3,299,940✔
883
{
884
  if (str == "neutron") {
3,299,940✔
885
    return ParticleType::neutron;
756,419✔
886
  } else if (str == "photon") {
2,543,521✔
887
    return ParticleType::photon;
2,543,453✔
888
  } else if (str == "electron") {
68✔
889
    return ParticleType::electron;
34✔
890
  } else if (str == "positron") {
34✔
891
    return ParticleType::positron;
34✔
892
  } else {
UNCOV
893
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
894
  }
895
}
896

897
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,422,262,446✔
898
{
899
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
900
      simulation::surf_source_bank.full()) {
1,128,490,535✔
901
    return;
1,422,145,848✔
902
  }
903

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

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

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

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

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

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

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

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

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

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

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

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

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