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

openmc-dev / openmc / 15477449824

05 Jun 2025 09:15PM UTC coverage: 85.105% (-0.1%) from 85.2%
15477449824

Pull #3402

github

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

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

705 existing lines in 34 files now uncovered.

52222 of 61362 relevant lines covered (85.1%)

36944745.1 hits per line

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

90.87
/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,035,877✔
54
    mass = 0.0;
15,035,877✔
55
    break;
15,035,877✔
56
  case ParticleType::electron:
48,518,070✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,518,070✔
59
    break;
48,518,070✔
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);
859,390,448✔
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,570,709✔
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,570,709✔
84
    return false;
48,443,931✔
85
  }
86

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

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

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

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

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
456,196,246✔
178
      cell_last(j) = coord(j).cell;
239,012,455✔
179
    }
180
    n_coord_last() = n_coord();
217,183,791✔
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,654,588,435✔
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,321,583,028✔
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,441,035✔
210
    macro_xs().absorption = 0.0;
66,441,035✔
211
    macro_xs().fission = 0.0;
66,441,035✔
212
    macro_xs().nu_fission = 0.0;
66,441,035✔
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,518,070✔
224
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
225
    collision_distance() = INFINITY;
66,441,035✔
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,268,377,320✔
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,445,377,344✔
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,058,660,709✔
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,058,660,709✔
285

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

290
  if (boundary().lattice_translation[0] != 0 ||
2,058,660,709✔
291
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
292
      boundary().lattice_translation[2] != 0) {
1,564,016,903✔
293
    // Particle crosses lattice boundary
294

295
    bool verbose = settings::verbosity >= 10 || trace();
685,187,950✔
296
    cross_lattice(*this, boundary(), verbose);
685,187,950✔
297
    event() = TallyEvent::LATTICE;
685,187,950✔
298
  } else {
299
    // Particle crosses surface
300
    const auto& surf {model::surfaces[surface_index()].get()};
1,373,472,759✔
301
    // If BC, add particle to surface source before crossing surface
302
    if (surf->surf_source_ && surf->bc_) {
1,373,472,759✔
303
      add_surf_source_to_bank(*this, *surf);
645,404,802✔
304
    }
305
    this->cross_surface(*surf);
1,373,472,759✔
306
    // If no BC, add particle to surface source after crossing surface
307
    if (surf->surf_source_ && !surf->bc_) {
1,373,472,750✔
308
      add_surf_source_to_bank(*this, *surf);
727,164,539✔
309
    }
310
    if (settings::weight_window_checkpoint_surface) {
1,373,472,750✔
311
      apply_weight_windows(*this);
×
312
    }
313
    event() = TallyEvent::SURFACE;
1,373,472,750✔
314
  }
315
  // Score cell to cell partial currents
316
  if (!model::active_surface_tallies.empty()) {
2,058,660,700✔
317
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
318
  }
319
}
2,058,660,700✔
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,147,483,647✔
326
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,109,308,232✔
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);
79,867,425✔
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);
721,315,651✔
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,450,856✔
350
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
351
    if (settings::run_CE) {
124,607,505✔
352
      score_analog_tally_ce(*this);
123,406,294✔
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) {
123,762,882✔
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;
113,368,597✔
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);
624,544,255✔
396

397
#ifdef DAGMC
398
  history().reset();
234,081,346✔
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()) {
217,183,386✔
416
      write_particle_track(*this);
6,674✔
417
    }
418

419
    // If no secondary particles, break out of event loop
420
    if (secondary_bank().empty())
217,183,386✔
421
      return;
156,943,185✔
422

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

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

460
void Particle::event_death()
156,944,185✔
461
{
462
#ifdef DAGMC
463
  history().reset();
14,551,589✔
464
#endif
465

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

471
// Contribute tally reduction variables to global accumulator
472
#pragma omp atomic
86,415,592✔
473
  global_tally_absorption += keff_tally_absorption();
156,944,185✔
474
#pragma omp atomic
86,882,926✔
475
  global_tally_collision += keff_tally_collision();
156,944,185✔
476
#pragma omp atomic
86,302,535✔
477
  global_tally_tracklength += keff_tally_tracklength();
156,944,185✔
478
#pragma omp atomic
85,965,316✔
479
  global_tally_leakage += keff_tally_leakage();
156,944,185✔
480

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

487
  if (!model::active_pulse_height_tallies.empty()) {
156,944,185✔
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,944,185✔
494
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
134,091,897✔
495
    simulation::progeny_per_particle[offset] = n_progeny();
134,091,897✔
496
  }
497
}
156,944,185✔
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,374,440,055✔
535
{
536

537
  if (settings::verbosity >= 10 || trace()) {
1,374,440,055✔
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)
132,865,601✔
544
    history().reset();
132,830,285✔
545
#endif
546

547
  // Handle any applicable boundary conditions.
548
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,374,440,055✔
549
    surf.bc_->handle_particle(*this, surf);
645,642,419✔
550
    return;
645,642,419✔
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) {
70,514,805✔
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();
728,769,371✔
580
  if (neighbor_list_find_cell(*this, verbose)) {
728,769,371✔
581
    return;
728,741,352✔
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,598,125✔
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,598,125✔
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,172,785✔
624
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,172,785✔
625
  }
626

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

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

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

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

659
  if (!model::active_meshsurf_tallies.empty()) {
614,400,790✔
660
    Position r {this->r()};
59,184,621✔
661
    this->r() -= TINY_BIT * u();
59,184,621✔
662
    score_surface_tally(*this, model::active_meshsurf_tallies);
59,184,621✔
663
    this->r() = r;
59,184,621✔
664
  }
665

666
  // Set the new particle direction
667
  u() = new_u;
614,400,790✔
668

669
  // Reassign particle's cell and surface
670
  coord(0).cell = cell_last(0);
614,400,790✔
671
  surface() = -surface();
614,400,790✔
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;
614,400,790✔
678
  if (surf.geom_type() != GeometryType::DAG &&
1,228,799,041✔
679
      !neighbor_list_find_cell(*this)) {
614,398,251✔
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();
614,400,790✔
687

688
  // Diagnostic message
689
  if (settings::verbosity >= 10 || trace()) {
614,400,790✔
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 && !exhaustive_find_cell(*this)) {
1,004,542✔
NEW
785
    mark_as_lost("Couldn't find particle after transforming from surface " +
×
NEW
786
                 std::to_string(surf.id_) + ".");
×
NEW
787
    return;
×
788
  }
789

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

934
ParticleType str_to_particle_type(std::string str)
3,040,226✔
935
{
936
  if (str == "neutron") {
3,040,226✔
937
    return ParticleType::neutron;
697,185✔
938
  } else if (str == "photon") {
2,343,041✔
939
    return ParticleType::photon;
2,342,955✔
940
  } else if (str == "electron") {
86✔
941
    return ParticleType::electron;
43✔
942
  } else if (str == "positron") {
43✔
943
    return ParticleType::positron;
43✔
944
  } else {
UNCOV
945
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
946
  }
947
}
948

949
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,372,569,341✔
950
{
951
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
952
      simulation::surf_source_bank.full()) {
1,073,943,620✔
953
    return;
1,372,462,576✔
954
  }
955

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

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

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

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

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

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

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

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

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

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

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

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

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