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

openmc-dev / openmc / 15477384531

05 Jun 2025 09:11PM UTC coverage: 85.103% (-0.1%) from 85.2%
15477384531

Pull #3402

github

web-flow
Merge 1880399c8 into 4943fa363
Pull Request #3402: Add transformation boundary condition

65 of 113 new or added lines in 4 files covered. (57.52%)

702 existing lines in 33 files now uncovered.

52214 of 61354 relevant lines covered (85.1%)

36677177.0 hits per line

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

90.89
/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,036,792✔
54
    mass = 0.0;
15,036,792✔
55
    break;
15,036,792✔
56
  case ParticleType::electron:
48,519,268✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,519,268✔
59
    break;
48,519,268✔
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,214,014✔
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(
101,571,360✔
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)]) {
101,571,360✔
84
    return false;
48,445,135✔
85
  }
86

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

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

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

121
  // Copy attributes from source bank site
122
  type() = src->particle;
219,362,617✔
123
  wgt() = src->wgt;
219,362,617✔
124
  wgt_last() = src->wgt;
219,362,617✔
125
  r() = src->r;
219,362,617✔
126
  u() = src->u;
219,362,617✔
127
  r_born() = src->r;
219,362,617✔
128
  r_last_current() = src->r;
219,362,617✔
129
  r_last() = src->r;
219,362,617✔
130
  u_last() = src->u;
219,362,617✔
131
  if (settings::run_CE) {
219,362,617✔
132
    E() = src->E;
100,729,124✔
133
    g() = 0;
100,729,124✔
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();
219,362,617✔
140
  time() = src->time;
219,362,617✔
141
  time_last() = src->time;
219,362,617✔
142
  parent_nuclide() = src->parent_nuclide;
219,362,617✔
143
}
219,362,617✔
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,599,076✔
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,599,076✔
174
      cell_born() = lowest_coord().cell;
216,599,076✔
175

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
454,892,495✔
178
      cell_last(j) = coord(j).cell;
238,293,419✔
179
    }
180
    n_coord_last() = n_coord();
216,599,076✔
181
  }
182

183
  // Write particle track.
184
  if (write_track())
2,147,483,647✔
185
    write_particle_track(*this);
10,836✔
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,619,444,102✔
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,297,921,234✔
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,947✔
210
    macro_xs().absorption = 0.0;
66,440,947✔
211
    macro_xs().fission = 0.0;
66,440,947✔
212
    macro_xs().nu_fission = 0.0;
66,440,947✔
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,519,268✔
224
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
225
    collision_distance() = INFINITY;
66,440,947✔
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,070,819✔
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,410,242,777✔
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,671,606✔
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,671,606✔
285

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

290
  if (boundary().lattice_translation[0] != 0 ||
2,035,671,606✔
291
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
292
      boundary().lattice_translation[2] != 0) {
1,542,336,412✔
293
    // Particle crosses lattice boundary
294

295
    bool verbose = settings::verbosity >= 10 || trace();
683,879,321✔
296
    cross_lattice(*this, boundary(), verbose);
683,879,321✔
297
    event() = TallyEvent::LATTICE;
683,879,321✔
298
  } else {
299
    // Particle crosses surface
300
    const auto& surf {model::surfaces[surface_index()].get()};
1,351,792,285✔
301
    // If BC, add particle to surface source before crossing surface
302
    if (surf->surf_source_ && surf->bc_) {
1,351,792,285✔
303
      add_surf_source_to_bank(*this, *surf);
635,079,165✔
304
    }
305
    this->cross_surface(*surf);
1,351,792,285✔
306
    // If no BC, add particle to surface source after crossing surface
307
    if (surf->surf_source_ && !surf->bc_) {
1,351,792,276✔
308
      add_surf_source_to_bank(*this, *surf);
715,809,702✔
309
    }
310
    if (settings::weight_window_checkpoint_surface) {
1,351,792,276✔
311
      apply_weight_windows(*this);
×
312
    }
313
    event() = TallyEvent::SURFACE;
1,351,792,276✔
314
  }
315
  // Score cell to cell partial currents
316
  if (!model::active_surface_tallies.empty()) {
2,035,671,597✔
317
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
318
  }
319
}
2,035,671,597✔
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,466,536✔
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);
709,160,343✔
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);
92,452,969✔
350
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
351
    if (settings::run_CE) {
113,305,951✔
352
      score_analog_tally_ce(*this);
112,104,740✔
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);
612,398,420✔
396

397
#ifdef DAGMC
398
  history().reset();
228,138,496✔
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,598,672✔
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,598,672✔
421
      return;
156,359,088✔
422

423
    from_source(&secondary_bank().back());
60,239,584✔
424
    secondary_bank().pop_back();
60,239,584✔
425
    n_event() = 0;
60,239,584✔
426
    bank_second_E() = 0.0;
60,239,584✔
427

428
    // Subtract secondary particle energy from interim pulse-height results
429
    if (!model::active_pulse_height_tallies.empty() &&
60,255,083✔
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())
60,239,584✔
456
      add_particle_track(*this);
5,604✔
457
  }
458
}
459

460
void Particle::event_death()
156,360,088✔
461
{
462
#ifdef DAGMC
463
  history().reset();
14,264,492✔
464
#endif
465

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

471
// Contribute tally reduction variables to global accumulator
472
#pragma omp atomic
86,108,116✔
473
  global_tally_absorption += keff_tally_absorption();
156,360,088✔
474
#pragma omp atomic
86,830,012✔
475
  global_tally_collision += keff_tally_collision();
156,360,088✔
476
#pragma omp atomic
85,713,298✔
477
  global_tally_tracklength += keff_tally_tracklength();
156,360,088✔
478
#pragma omp atomic
85,585,010✔
479
  global_tally_leakage += keff_tally_leakage();
156,360,088✔
480

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

487
  if (!model::active_pulse_height_tallies.empty()) {
156,360,088✔
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,360,088✔
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,360,088✔
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,759,581✔
535
{
536

537
  if (settings::verbosity >= 10 || trace()) {
1,352,759,581✔
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)
123,004,918✔
544
    history().reset();
122,969,602✔
545
#endif
546

547
  // Handle any applicable boundary conditions.
548
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,352,759,581✔
549
    surf.bc_->handle_particle(*this, surf);
635,316,782✔
550
    return;
635,316,782✔
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) {
65,516,585✔
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,414,534✔
580
  if (neighbor_list_find_cell(*this, verbose)) {
717,414,534✔
581
    return;
717,386,515✔
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,495✔
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,495✔
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,495✔
629

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

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

639
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
604,226,783✔
640
{
641
  // Do not handle reflective boundary conditions on lower universes
642
  if (n_coord() != 1) {
604,226,783✔
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,226,783✔
656
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
657
  }
658

659
  if (!model::active_meshsurf_tallies.empty()) {
604,226,783✔
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,226,783✔
668

669
  // Reassign particle's cell and surface
670
  coord(0).cell = cell_last(0);
604,226,783✔
671
  surface() = -surface();
604,226,783✔
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,226,783✔
678
  if (surf.geom_type() != GeometryType::DAG &&
1,208,451,027✔
679
      !neighbor_list_find_cell(*this)) {
604,224,244✔
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,226,783✔
687

688
  // Diagnostic message
689
  if (settings::verbosity >= 10 || trace()) {
604,226,783✔
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
  if (!model::active_surface_tallies.empty()) {
1,004,542✔
NEW
761
    score_surface_tally(*this, model::active_surface_tallies);
×
762
  }
763

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

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

775
  // Clear the surface assignment after transformation so as not to confuse the
776
  // cell finding routine
777
  surface() = SURFACE_NONE;
1,004,542✔
778

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

935
ParticleType str_to_particle_type(std::string str)
2,952,276✔
936
{
937
  if (str == "neutron") {
2,952,276✔
938
    return ParticleType::neutron;
676,801✔
939
  } else if (str == "photon") {
2,275,475✔
940
    return ParticleType::photon;
2,275,389✔
941
  } else if (str == "electron") {
86✔
942
    return ParticleType::electron;
43✔
943
  } else if (str == "positron") {
43✔
944
    return ParticleType::positron;
43✔
945
  } else {
946
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
947
  }
948
}
949

950
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,350,888,867✔
951
{
952
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
953
      simulation::surf_source_bank.full()) {
1,060,037,905✔
954
    return;
1,350,782,102✔
955
  }
956

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

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

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

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

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

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

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

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

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

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

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

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

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