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

openmc-dev / openmc / 14260484407

04 Apr 2025 07:41AM UTC coverage: 84.589% (-0.3%) from 84.851%
14260484407

Pull #3279

github

web-flow
Merge 33e03305e into 07f533461
Pull Request #3279: Hexagonal mesh model

2 of 332 new or added lines in 3 files covered. (0.6%)

2798 existing lines in 84 files now uncovered.

51799 of 61236 relevant lines covered (84.59%)

38650400.15 hits per line

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

92.68
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef DAGMC
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  // Determine mass in eV/c^2
48
  double mass;
49
  switch (this->type()) {
2,147,483,647✔
50
  case ParticleType::neutron:
2,147,483,647✔
51
    mass = MASS_NEUTRON_EV;
2,147,483,647✔
52
    break;
2,147,483,647✔
53
  case ParticleType::photon:
14,568,200✔
54
    mass = 0.0;
14,568,200✔
55
    break;
14,568,200✔
56
  case ParticleType::electron:
48,822,143✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,822,143✔
59
    break;
48,822,143✔
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);
857,763,090✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

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

78
bool Particle::create_secondary(
102,208,686✔
79
  double wgt, Direction u, double E, ParticleType type)
80
{
81
  // If energy is below cutoff for this particle, don't create secondary
82
  // particle
83
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
102,208,686✔
84
    return false;
48,745,828✔
85
  }
86

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

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

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

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

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

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

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

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

171
    // Set birth cell attribute
172
    if (cell_born() == C_NONE)
216,839,099✔
173
      cell_born() = lowest_coord().cell;
216,839,099✔
174

175
    // Initialize last cells from current cell
176
    for (int j = 0; j < n_coord(); ++j) {
455,438,650✔
177
      cell_last(j) = coord(j).cell;
238,599,551✔
178
    }
179
    n_coord_last() = n_coord();
216,839,099✔
180
  }
181

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

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

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

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

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

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

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

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

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

247
    double push_back_distance = speed() * dt;
11,000✔
248
    this->move_distance(-push_back_distance);
11,000✔
249
    hit_time_boundary = true;
11,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,253,598,161✔
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,421,709,839✔
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;
11,000✔
271
  }
272
}
2,147,483,647✔
273

274
void Particle::event_cross_surface()
2,042,113,257✔
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();
2,042,113,257✔
281

282
  // Set surface that particle is on and adjust coordinate levels
283
  surface() = boundary().surface;
2,042,113,257✔
284
  n_coord() = boundary().coord_level;
2,042,113,257✔
285

286
  if (boundary().lattice_translation[0] != 0 ||
2,042,113,257✔
287
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
288
      boundary().lattice_translation[2] != 0) {
1,548,147,286✔
289
    // Particle crosses lattice boundary
290

291
    bool verbose = settings::verbosity >= 10 || trace();
684,510,054✔
292
    cross_lattice(*this, boundary(), verbose);
684,510,054✔
293
    event() = TallyEvent::LATTICE;
684,510,054✔
294
  } else {
295
    // Particle crosses surface
296
    const auto& surf {model::surfaces[surface_index()].get()};
1,357,603,203✔
297
    // If BC, add particle to surface source before crossing surface
298
    if (surf->surf_source_ && surf->bc_) {
1,357,603,203✔
299
      add_surf_source_to_bank(*this, *surf);
637,664,559✔
300
    }
301
    this->cross_surface(*surf);
1,357,603,203✔
302
    // If no BC, add particle to surface source after crossing surface
303
    if (surf->surf_source_ && !surf->bc_) {
1,357,603,194✔
304
      add_surf_source_to_bank(*this, *surf);
719,035,226✔
305
    }
306
    if (settings::weight_window_checkpoint_surface) {
1,357,603,194✔
UNCOV
307
      apply_weight_windows(*this);
×
308
    }
309
    event() = TallyEvent::SURFACE;
1,357,603,194✔
310
  }
311
  // Score cell to cell partial currents
312
  if (!model::active_surface_tallies.empty()) {
2,042,113,248✔
313
    score_surface_tally(*this, model::active_surface_tallies);
34,896,037✔
314
  }
315
}
2,042,113,248✔
316

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

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

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

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

335
  if (settings::run_CE) {
2,147,483,647✔
336
    collision(*this);
712,700,581✔
337
  } else {
338
    collision_mg(*this);
1,785,735,523✔
339
  }
340

341
  // Score collision estimator tallies -- this is done after a collision
342
  // has occurred rather than before because we need information on the
343
  // outgoing energy for any tallies with an outgoing energy filter
344
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
345
    score_collision_tally(*this);
91,226,071✔
346
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
347
    if (settings::run_CE) {
118,665,448✔
348
      score_analog_tally_ce(*this);
117,464,237✔
349
    } else {
350
      score_analog_tally_mg(*this);
1,201,211✔
351
    }
352
  }
353

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

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

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

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

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

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

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

393
#ifdef DAGMC
394
  history().reset();
227,928,488✔
395
#endif
396
}
2,147,483,647✔
397

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

408
  // Check for secondary particles if this particle is dead
409
  if (!alive()) {
2,147,483,647✔
410
    // Write final position for this particle
411
    if (write_track()) {
216,838,695✔
412
      write_particle_track(*this);
6,674✔
413
    }
414

415
    // If no secondary particles, break out of event loop
416
    if (secondary_bank().empty())
216,838,695✔
417
      return;
156,257,911✔
418

419
    from_source(&secondary_bank().back());
60,580,784✔
420
    secondary_bank().pop_back();
60,580,784✔
421
    n_event() = 0;
60,580,784✔
422
    bank_second_E() = 0.0;
60,580,784✔
423

424
    // Subtract secondary particle energy from interim pulse-height results
425
    if (!model::active_pulse_height_tallies.empty() &&
60,596,283✔
426
        this->type() == ParticleType::photon) {
15,499✔
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) {
605✔
431
        bool verbose = settings::verbosity >= 10 || trace();
605✔
432
        if (!exhaustive_find_cell(*this, verbose)) {
605✔
UNCOV
433
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
434
                       std::to_string(id()));
×
UNCOV
435
          return;
×
436
        }
437
        // Set birth cell attribute
438
        if (cell_born() == C_NONE)
605✔
439
          cell_born() = lowest_coord().cell;
605✔
440

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

450
    // Enter new particle in particle track file
451
    if (write_track())
60,580,784✔
452
      add_particle_track(*this);
5,604✔
453
  }
454
}
455

456
void Particle::event_death()
156,258,911✔
457
{
458
#ifdef DAGMC
459
  history().reset();
14,229,385✔
460
#endif
461

462
  // Finish particle track output.
463
  if (write_track()) {
156,258,911✔
464
    finalize_particle_track(*this);
1,070✔
465
  }
466

467
// Contribute tally reduction variables to global accumulator
468
#pragma omp atomic
86,313,620✔
469
  global_tally_absorption += keff_tally_absorption();
156,258,911✔
470
#pragma omp atomic
85,941,972✔
471
  global_tally_collision += keff_tally_collision();
156,258,911✔
472
#pragma omp atomic
85,903,614✔
473
  global_tally_tracklength += keff_tally_tracklength();
156,258,911✔
474
#pragma omp atomic
85,705,102✔
475
  global_tally_leakage += keff_tally_leakage();
156,258,911✔
476

477
  // Reset particle tallies once accumulated
478
  keff_tally_absorption() = 0.0;
156,258,911✔
479
  keff_tally_collision() = 0.0;
156,258,911✔
480
  keff_tally_tracklength() = 0.0;
156,258,911✔
481
  keff_tally_leakage() = 0.0;
156,258,911✔
482

483
  if (!model::active_pulse_height_tallies.empty()) {
156,258,911✔
484
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
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) {
156,258,911✔
490
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,440,800✔
491
    simulation::progeny_per_particle[offset] = n_progeny();
133,440,800✔
492
  }
493
}
156,258,911✔
494

495
void Particle::pht_collision_energy()
2,024✔
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,024✔
501
    model::pulse_height_cells.end(), lowest_coord().cell);
2,024✔
502

503
  if (it != model::pulse_height_cells.end()) {
2,024✔
504
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
505
    pht_storage()[index] += E_last() - E();
2,024✔
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,024✔
510
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
511
      pht_storage()[index] += E();
825✔
512
    }
513
  }
514
}
2,024✔
515

516
void Particle::pht_secondary_particles()
605✔
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(),
605✔
522
    model::pulse_height_cells.end(), cell_born());
605✔
523

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

530
void Particle::cross_surface(const Surface& surf)
1,358,570,499✔
531
{
532

533
  if (settings::verbosity >= 10 || trace()) {
1,358,570,499✔
534
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
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)
122,657,611✔
540
    history().reset();
122,622,295✔
541
#endif
542

543
  // Handle any applicable boundary conditions.
544
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,358,570,499✔
545
    surf.bc_->handle_particle(*this, surf);
637,902,176✔
546
    return;
637,902,176✔
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) {
65,368,821✔
555
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
556
                       lowest_coord().universe) -
28,265✔
557
                     1;
28,265✔
558
    // save material and temp
559
    material_last() = material();
28,265✔
560
    sqrtkT_last() = sqrtkT();
28,265✔
561
    // set new cell value
562
    lowest_coord().cell = i_cell;
28,265✔
563
    auto& cell = model::cells[i_cell];
28,265✔
564

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

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

575
  bool verbose = settings::verbosity >= 10 || trace();
720,640,058✔
576
  if (neighbor_list_find_cell(*this, verbose)) {
720,640,058✔
577
    return;
720,612,039✔
578
  }
579

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

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

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

593
    surface() = SURFACE_NONE;
5,744✔
594
    n_coord() = 1;
5,744✔
595
    r() += TINY_BIT * u();
5,744✔
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)) {
5,744✔
601
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
602
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
603
                   " it could not be located in any cell and it did not leak.");
604
      return;
5,735✔
605
    }
606
  }
607
}
608

609
void Particle::cross_vacuum_bc(const Surface& surf)
30,371,788✔
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()) {
30,371,788✔
616
    // TODO: Find a better solution to score surface currents than
617
    // physically moving the particle forward slightly
618

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

623
  // Score to global leakage tally
624
  keff_tally_leakage() += wgt();
30,371,788✔
625

626
  // Kill the particle
627
  wgt() = 0.0;
30,371,788✔
628

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

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

655
  if (!model::active_meshsurf_tallies.empty()) {
607,891,426✔
656
    Position r {this->r()};
54,998,215✔
657
    this->r() -= TINY_BIT * u();
54,998,215✔
658
    score_surface_tally(*this, model::active_meshsurf_tallies);
54,998,215✔
659
    this->r() = r;
54,998,215✔
660
  }
661

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

665
  // Reassign particle's cell and surface
666
  coord(0).cell = cell_last(0);
607,891,426✔
667
  surface() = -surface();
607,891,426✔
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;
607,891,426✔
674
  if (surf.geom_type() != GeometryType::DAG &&
1,215,780,313✔
675
      !neighbor_list_find_cell(*this)) {
607,888,887✔
UNCOV
676
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
677
                 std::to_string(surf.id_) + ".");
×
UNCOV
678
    return;
×
679
  }
680

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

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

690
void Particle::cross_periodic_bc(
666,318✔
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) {
666,318✔
UNCOV
695
    mark_as_lost(
×
UNCOV
696
      "Cannot transfer particle " + std::to_string(id()) +
×
697
      " across surface in a lower universe. Boundary conditions must be "
698
      "applied to root universe.");
UNCOV
699
    return;
×
700
  }
701

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

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

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

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

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

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

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

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

753
  // Count the total number of simulated particles (on this processor)
754
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
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 &&
5,744✔
760
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
761
    fatal_error("Maximum number of lost particles has been reached.");
9✔
762
  }
763
}
5,735✔
764

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

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

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

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

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

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

832
    // Close file
833
    file_close(file_id);
302✔
834
  } // #pragma omp critical
835
}
302✔
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);
11,018,953✔
851
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
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,130,116✔
861
{
862
  switch (type) {
3,130,116✔
863
  case ParticleType::neutron:
2,399,925✔
864
    return "neutron";
2,399,925✔
865
  case ParticleType::photon:
729,971✔
866
    return "photon";
729,971✔
867
  case ParticleType::electron:
110✔
868
    return "electron";
110✔
869
  case ParticleType::positron:
110✔
870
    return "positron";
110✔
871
  }
UNCOV
872
  UNREACHABLE();
×
873
}
874

875
ParticleType str_to_particle_type(std::string str)
2,908,450✔
876
{
877
  if (str == "neutron") {
2,908,450✔
878
    return ParticleType::neutron;
664,566✔
879
  } else if (str == "photon") {
2,243,884✔
880
    return ParticleType::photon;
2,243,820✔
881
  } else if (str == "electron") {
64✔
882
    return ParticleType::electron;
32✔
883
  } else if (str == "positron") {
32✔
884
    return ParticleType::positron;
32✔
885
  } else {
UNCOV
886
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
887
  }
888
}
889

890
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,356,699,785✔
891
{
892
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
893
      simulation::surf_source_bank.full()) {
1,062,496,355✔
894
    return;
1,356,593,020✔
895
  }
896

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

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

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

910
      // Leave if other boundary condition than vacuum
911
      if (surf.bc_->type() != "vacuum") {
140,281✔
912
        return;
120,020✔
913
      }
914
    }
915

916
    // Check if the cell of interest has been exited
917
    bool exited = false;
126,732✔
918
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,341✔
919
      if (p.cell_last(i) == cell_idx) {
208,609✔
920
        exited = true;
74,236✔
921
      }
922
    }
923

924
    // Check if the cell of interest has been entered
925
    bool entered = false;
126,732✔
926
    for (int i = 0; i < p.n_coord(); ++i) {
301,037✔
927
      if (p.coord(i).cell == cell_idx) {
174,305✔
928
        entered = true;
59,097✔
929
      }
930
    }
931

932
    // Vacuum boundary conditions: return if cell is not exited
933
    if (surf.bc_) {
126,732✔
934
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
935
        return;
13,961✔
936
      }
937
    } else {
938

939
      // If we both enter and exit the cell of interest
940
      if (entered && exited) {
106,471✔
941
        return;
28,613✔
942
      }
943

944
      // If we did not enter nor exit the cell of interest
945
      if (!entered && !exited) {
77,858✔
946
        return;
14,351✔
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) {
63,507✔
952
        return;
11,564✔
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) {
51,943✔
957
        return;
12,039✔
958
      }
959
    }
960
  }
961

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