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

openmc-dev / openmc / 14983111830

12 May 2025 09:35PM UTC coverage: 85.165% (-0.04%) from 85.2%
14983111830

Pull #3402

github

web-flow
Merge 2fc68aee2 into 7382b5d1c
Pull Request #3402: Add transformation boundary condition

67 of 116 new or added lines in 5 files covered. (57.76%)

95 existing lines in 6 files now uncovered.

52397 of 61524 relevant lines covered (85.17%)

36950707.46 hits per line

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

90.91
/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,387,691✔
54
    mass = 0.0;
14,387,691✔
55
    break;
14,387,691✔
56
  case ParticleType::electron:
48,048,370✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,048,370✔
59
    break;
48,048,370✔
60
  }
61

62
  if (this->E() < 1.0e-9 * mass) {
2,147,483,647✔
63
    // If the energy is much smaller than the mass, revert to non-relativistic
64
    // formula. The 1e-9 criterion is specifically chosen as the point below
65
    // which the error from using the non-relativistic formula is less than the
66
    // round-off eror when using the relativistic formula (see analysis at
67
    // https://gist.github.com/paulromano/da3b473fe3df33de94b265bdff0c7817)
68
    return C_LIGHT * std::sqrt(2 * this->E() / mass);
856,079,147✔
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(
100,617,217✔
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)]) {
100,617,217✔
84
    return false;
47,972,856✔
85
  }
86

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

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

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

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

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

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

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

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

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

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
453,904,405✔
178
      cell_last(j) = coord(j).cell;
237,799,374✔
179
    }
180
    n_coord_last() = n_coord();
216,105,031✔
181
  }
182

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

290
  if (boundary().lattice_translation[0] != 0 ||
2,035,532,077✔
291
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
292
      boundary().lattice_translation[2] != 0) {
1,542,196,919✔
293
    // Particle crosses lattice boundary
294

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

321
void Particle::event_collide()
2,147,483,647✔
322
{
323
  // Score collision estimate of keff
324
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
325
      type() == ParticleType::neutron) {
2,136,469,803✔
326
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,097,144,352✔
327
  }
328

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

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

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

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

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

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

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

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

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

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

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

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

397
#ifdef DAGMC
398
  history().reset();
233,688,162✔
399
#endif
400
}
2,147,483,647✔
401

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

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

419
    // If no secondary particles, break out of event loop
420
    if (secondary_bank().empty())
216,104,627✔
421
      return;
156,346,911✔
422

423
    from_source(&secondary_bank().back());
59,757,716✔
424
    secondary_bank().pop_back();
59,757,716✔
425
    n_event() = 0;
59,757,716✔
426
    bank_second_E() = 0.0;
59,757,716✔
427

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

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

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

460
void Particle::event_death()
156,347,911✔
461
{
462
#ifdef DAGMC
463
  history().reset();
14,540,385✔
464
#endif
465

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

471
// Contribute tally reduction variables to global accumulator
472
#pragma omp atomic
86,151,078✔
473
  global_tally_absorption += keff_tally_absorption();
156,347,911✔
474
#pragma omp atomic
85,773,003✔
475
  global_tally_collision += keff_tally_collision();
156,347,911✔
476
#pragma omp atomic
85,738,448✔
477
  global_tally_tracklength += keff_tally_tracklength();
156,347,911✔
478
#pragma omp atomic
85,652,665✔
479
  global_tally_leakage += keff_tally_leakage();
156,347,911✔
480

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

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

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

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

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

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

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

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

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

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

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

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

541
// if we're crossing a CSG surface, make sure the DAG history is reset
542
#ifdef DAGMC
543
  if (surf.geom_type() == GeometryType::CSG)
130,897,457✔
544
    history().reset();
130,862,141✔
545
#endif
546

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

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

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

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

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

579
  bool verbose = settings::verbosity >= 10 || trace();
717,412,347✔
580
  if (neighbor_list_find_cell(*this, verbose)) {
717,412,347✔
581
    return;
717,384,328✔
582
  }
583

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

744
void Particle::cross_transformation_bc(
1,004,542✔
745
  const Surface& surf, Position new_r, Direction new_u)
746
{
747
  // Do not handle transformation boundary conditions on lower universes
748
  if (n_coord() != 1) {
1,004,542✔
NEW
749
    mark_as_lost("Cannot transform particle " + std::to_string(id()) +
×
750
                 " off surface in a lower universe.");
NEW
751
    return;
×
752
  }
753

754
  // Score surface currents since transformation causes the direction of the
755
  // particle to change. For surface filters, we need to score the tallies
756
  // twice, once before the particle's surface attribute has changed and
757
  // once after. For mesh surface filters, we need to artificially move
758
  // the particle slightly back in case the surface crossing is coincident
759
  // with a mesh boundary
760

761
  if (!model::active_surface_tallies.empty()) {
1,004,542✔
NEW
762
    score_surface_tally(*this, model::active_surface_tallies);
×
763
  }
764

765
  if (!model::active_meshsurf_tallies.empty()) {
1,004,542✔
NEW
766
    Position r {this->r()};
×
NEW
767
    this->r() -= TINY_BIT * u();
×
NEW
768
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
NEW
769
    this->r() = r;
×
770
  }
771

772
  // Adjust the particle's location and direction.
773
  r() = new_r;
1,004,542✔
774
  u() = new_u;
1,004,542✔
775

776
  // Reassign particle's cell and surface
777
  coord(0).cell = cell_last(0);
1,004,542✔
778
  surface() = -surface();
1,004,542✔
779

780
  // If a transformation surface is coincident with a lattice or universe
781
  // boundary, it is necessary to redetermine the particle's coordinates in
782
  // the lower universes.
783
  // (unless we're using a dagmc model, which has exactly one universe)
784
  n_coord() = 1;
1,004,542✔
785
  if (surf.geom_type() != GeometryType::DAG &&
2,009,084✔
786
      !neighbor_list_find_cell(*this)) {
1,004,542✔
NEW
787
    mark_as_lost("Couldn't find particle after transforming from surface " +
×
NEW
788
                 std::to_string(surf.id_) + ".");
×
NEW
789
    return;
×
790
  }
791

792
  // Set previous coordinate going slightly past surface crossing
793
  r_last_current() = r() + TINY_BIT * u();
1,004,542✔
794

795
  // Diagnostic message
796
  if (settings::verbosity >= 10 || trace()) {
1,004,542✔
NEW
797
    write_message(1, "    Transformed from surface {}", surf.id_);
×
798
  }
799
}
800

801
void Particle::mark_as_lost(const char* message)
5,744✔
802
{
803
  // Print warning and write lost particle file
804
  warning(message);
5,744✔
805
  if (settings::max_write_lost_particles < 0 ||
5,744✔
806
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
807
    write_restart();
324✔
808
  }
809
  // Increment number of lost particles
810
  wgt() = 0.0;
5,744✔
811
#pragma omp atomic
3,124✔
812
  simulation::n_lost_particles += 1;
2,620✔
813

814
  // Count the total number of simulated particles (on this processor)
815
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
816
           simulation::work_per_rank;
817

818
  // Abort the simulation if the maximum number of lost particles has been
819
  // reached
820
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
821
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
822
    fatal_error("Maximum number of lost particles has been reached.");
9✔
823
  }
824
}
5,735✔
825

826
void Particle::write_restart() const
324✔
827
{
828
  // Dont write another restart file if in particle restart mode
829
  if (settings::run_mode == RunMode::PARTICLE)
324✔
830
    return;
22✔
831

832
  // Set up file name
833
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
834
    simulation::current_batch, id());
565✔
835

836
#pragma omp critical(WriteParticleRestart)
314✔
837
  {
838
    // Create file
839
    hid_t file_id = file_open(filename, 'w');
302✔
840

841
    // Write filetype and version info
842
    write_attribute(file_id, "filetype", "particle restart");
302✔
843
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
844
    write_attribute(file_id, "openmc_version", VERSION);
302✔
845
#ifdef GIT_SHA1
846
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
847
#endif
848

849
    // Write data to file
850
    write_dataset(file_id, "current_batch", simulation::current_batch);
302✔
851
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
302✔
852
    write_dataset(file_id, "current_generation", simulation::current_gen);
302✔
853
    write_dataset(file_id, "n_particles", settings::n_particles);
302✔
854
    switch (settings::run_mode) {
302✔
855
    case RunMode::FIXED_SOURCE:
225✔
856
      write_dataset(file_id, "run_mode", "fixed source");
225✔
857
      break;
225✔
858
    case RunMode::EIGENVALUE:
77✔
859
      write_dataset(file_id, "run_mode", "eigenvalue");
77✔
860
      break;
77✔
861
    case RunMode::PARTICLE:
×
862
      write_dataset(file_id, "run_mode", "particle restart");
×
863
      break;
×
864
    default:
×
865
      break;
×
866
    }
867
    write_dataset(file_id, "id", id());
302✔
868
    write_dataset(file_id, "type", static_cast<int>(type()));
302✔
869

870
    int64_t i = current_work();
302✔
871
    if (settings::run_mode == RunMode::EIGENVALUE) {
302✔
872
      // take source data from primary bank for eigenvalue simulation
873
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
77✔
874
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
77✔
875
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
77✔
876
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
77✔
877
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
77✔
878
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225✔
879
      // re-sample using rng random number seed used to generate source particle
880
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
881
                     settings::n_particles +
225✔
882
                   simulation::work_index[mpi::rank] + i;
225✔
883
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
884
      // re-sample source site
885
      auto site = sample_external_source(&seed);
225✔
886
      write_dataset(file_id, "weight", site.wgt);
225✔
887
      write_dataset(file_id, "energy", site.E);
225✔
888
      write_dataset(file_id, "xyz", site.r);
225✔
889
      write_dataset(file_id, "uvw", site.u);
225✔
890
      write_dataset(file_id, "time", site.time);
225✔
891
    }
892

893
    // Close file
894
    file_close(file_id);
302✔
895
  } // #pragma omp critical
896
}
302✔
897

898
void Particle::update_neutron_xs(
2,147,483,647✔
899
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
900
{
901
  // Get microscopic cross section cache
902
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
903

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

909
    // If NCrystal is being used, update micro cross section cache
910
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
911
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
912
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
913
    }
914
  }
915
}
2,147,483,647✔
916

917
//==============================================================================
918
// Non-method functions
919
//==============================================================================
920

921
std::string particle_type_to_str(ParticleType type)
3,130,116✔
922
{
923
  switch (type) {
3,130,116✔
924
  case ParticleType::neutron:
2,399,925✔
925
    return "neutron";
2,399,925✔
926
  case ParticleType::photon:
729,971✔
927
    return "photon";
729,971✔
928
  case ParticleType::electron:
110✔
929
    return "electron";
110✔
930
  case ParticleType::positron:
110✔
931
    return "positron";
110✔
932
  }
933
  UNREACHABLE();
×
934
}
935

936
ParticleType str_to_particle_type(std::string str)
2,950,527✔
937
{
938
  if (str == "neutron") {
2,950,527✔
939
    return ParticleType::neutron;
675,272✔
940
  } else if (str == "photon") {
2,275,255✔
941
    return ParticleType::photon;
2,275,191✔
942
  } else if (str == "electron") {
64✔
943
    return ParticleType::electron;
32✔
944
  } else if (str == "positron") {
32✔
945
    return ParticleType::positron;
32✔
946
  } else {
947
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
948
  }
949
}
950

951
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,350,749,387✔
952
{
953
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
954
      simulation::surf_source_bank.full()) {
1,059,898,425✔
955
    return;
1,350,642,622✔
956
  }
957

958
  // If a cell/cellfrom/cellto parameter is defined
959
  if (settings::ssw_cell_id != C_NONE) {
319,267✔
960

961
    // Retrieve cell index and storage type
962
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
963

964
    if (surf.bc_) {
258,706✔
965
      // Leave if cellto with vacuum boundary condition
966
      if (surf.bc_->type() == "vacuum" &&
184,450✔
967
          settings::ssw_cell_type == SSWCellType::To) {
32,215✔
968
        return;
11,953✔
969
      }
970

971
      // Leave if other boundary condition than vacuum
972
      if (surf.bc_->type() != "vacuum") {
140,282✔
973
        return;
120,020✔
974
      }
975
    }
976

977
    // Check if the cell of interest has been exited
978
    bool exited = false;
126,733✔
979
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,343✔
980
      if (p.cell_last(i) == cell_idx) {
208,610✔
981
        exited = true;
74,235✔
982
      }
983
    }
984

985
    // Check if the cell of interest has been entered
986
    bool entered = false;
126,733✔
987
    for (int i = 0; i < p.n_coord(); ++i) {
301,039✔
988
      if (p.coord(i).cell == cell_idx) {
174,306✔
989
        entered = true;
59,096✔
990
      }
991
    }
992

993
    // Vacuum boundary conditions: return if cell is not exited
994
    if (surf.bc_) {
126,733✔
995
      if (surf.bc_->type() == "vacuum" && !exited) {
20,262✔
996
        return;
13,962✔
997
      }
998
    } else {
999

1000
      // If we both enter and exit the cell of interest
1001
      if (entered && exited) {
106,471✔
1002
        return;
28,613✔
1003
      }
1004

1005
      // If we did not enter nor exit the cell of interest
1006
      if (!entered && !exited) {
77,858✔
1007
        return;
14,353✔
1008
      }
1009

1010
      // If cellfrom and the cell before crossing is not the cell of
1011
      // interest
1012
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,505✔
1013
        return;
11,563✔
1014
      }
1015

1016
      // If cellto and the cell after crossing is not the cell of interest
1017
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
1018
        return;
12,038✔
1019
      }
1020
    }
1021
  }
1022

1023
  SourceSite site;
106,765✔
1024
  site.r = p.r();
106,765✔
1025
  site.u = p.u();
106,765✔
1026
  site.E = p.E();
106,765✔
1027
  site.time = p.time();
106,765✔
1028
  site.wgt = p.wgt();
106,765✔
1029
  site.delayed_group = p.delayed_group();
106,765✔
1030
  site.surf_id = surf.id_;
106,765✔
1031
  site.particle = p.type();
106,765✔
1032
  site.parent_id = p.id();
106,765✔
1033
  site.progeny_id = p.n_progeny();
106,765✔
1034
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
106,765✔
1035
}
1036

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