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

openmc-dev / openmc / 18328199177

07 Oct 2025 10:43PM UTC coverage: 81.919% (-0.001%) from 81.92%
18328199177

Pull #3601

github

web-flow
Merge 5c38b1552 into 3dfa34d2c
Pull Request #3601: Reset DAGMC history when reviving from source.

16585 of 23090 branches covered (71.83%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

18 existing lines in 1 file now uncovered.

53704 of 62713 relevant lines covered (85.63%)

43393023.98 hits per line

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

85.42
/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 OPENMC_DAGMC_ENABLED
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
  if (settings::run_CE) {
2,147,483,647✔
48
    // Determine mass in eV/c^2
49
    double mass;
50
    switch (this->type()) {
1,894,030,947!
51
    case ParticleType::neutron:
1,824,605,747✔
52
      mass = MASS_NEUTRON_EV;
1,824,605,747✔
53
      break;
1,824,605,747✔
54
    case ParticleType::photon:
17,502,934✔
55
      mass = 0.0;
17,502,934✔
56
      break;
17,502,934✔
57
    case ParticleType::electron:
51,922,266✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
51,922,266✔
60
      break;
51,922,266✔
61
    }
62
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
63
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,894,030,947✔
64
           (this->E() + mass);
1,894,030,947✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
67
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
71
  }
72
}
73

74
bool Particle::create_secondary(
108,461,617✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
108,461,617✔
80
    return false;
51,872,920✔
81
  }
82

83
  auto& bank = secondary_bank().emplace_back();
56,588,697✔
84
  bank.particle = type;
56,588,697✔
85
  bank.wgt = wgt;
56,588,697✔
86
  bank.r = r();
56,588,697✔
87
  bank.u = u;
56,588,697✔
88
  bank.E = settings::run_CE ? E : g();
56,588,697!
89
  bank.time = time();
56,588,697✔
90
  bank_second_E() += bank.E;
56,588,697✔
91
  return true;
56,588,697✔
92
}
93

94
void Particle::split(double wgt)
4,243,912✔
95
{
96
  auto& bank = secondary_bank().emplace_back();
4,243,912✔
97
  bank.particle = type();
4,243,912✔
98
  bank.wgt = wgt;
4,243,912✔
99
  bank.r = r();
4,243,912✔
100
  bank.u = u();
4,243,912✔
101
  bank.E = settings::run_CE ? E() : g();
4,243,912✔
102
  bank.time = time();
4,243,912✔
103

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,243,912✔
106
    bank.surf_id = SURFACE_NONE;
4,243,892✔
107
  } else {
108
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
109
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20!
110
  }
111
}
4,243,912✔
112

113
void Particle::from_source(const SourceSite* src)
226,300,080✔
114
{
115
  // Reset some attributes
116
  clear();
226,300,080✔
117
  surface() = SURFACE_NONE;
226,300,080✔
118
  cell_born() = C_NONE;
226,300,080✔
119
  material() = C_NONE;
226,300,080✔
120
  n_collision() = 0;
226,300,080✔
121
  fission() = false;
226,300,080✔
122
  zero_flux_derivs();
226,300,080✔
123
  lifetime() = 0.0;
226,300,080✔
124

125
  // Copy attributes from source bank site
126
  type() = src->particle;
226,300,080✔
127
  wgt() = src->wgt;
226,300,080✔
128
  wgt_last() = src->wgt;
226,300,080✔
129
  r() = src->r;
226,300,080✔
130
  u() = src->u;
226,300,080✔
131
  r_born() = src->r;
226,300,080✔
132
  r_last_current() = src->r;
226,300,080✔
133
  r_last() = src->r;
226,300,080✔
134
  u_last() = src->u;
226,300,080✔
135
  if (settings::run_CE) {
226,300,080✔
136
    E() = src->E;
110,659,363✔
137
    g() = 0;
110,659,363✔
138
  } else {
139
    g() = static_cast<int>(src->E);
115,640,717✔
140
    g_last() = static_cast<int>(src->E);
115,640,717✔
141
    E() = data::mg.energy_bin_avg_[g()];
115,640,717✔
142
  }
143
  E_last() = E();
226,300,080✔
144
  time() = src->time;
226,300,080✔
145
  time_last() = src->time;
226,300,080✔
146
  parent_nuclide() = src->parent_nuclide;
226,300,080✔
147
  delayed_group() = src->delayed_group;
226,300,080✔
148

149
  // Convert signed surface ID to signed index
150
  if (src->surf_id != SURFACE_NONE) {
226,300,080✔
151
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
152
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020!
153
  }
154

155
#ifdef OPENMC_DAGMC_ENABLED
156
  history().reset();
22,211,257✔
157
#endif
158
}
226,300,080✔
159

160
void Particle::event_calculate_xs()
2,147,483,647✔
161
{
162
  // Set the random number stream
163
  stream() = STREAM_TRACKING;
2,147,483,647✔
164

165
  // Store pre-collision particle properties
166
  wgt_last() = wgt();
2,147,483,647✔
167
  E_last() = E();
2,147,483,647✔
168
  u_last() = u();
2,147,483,647✔
169
  r_last() = r();
2,147,483,647✔
170
  time_last() = time();
2,147,483,647✔
171

172
  // Reset event variables
173
  event() = TallyEvent::KILL;
2,147,483,647✔
174
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
175
  event_mt() = REACTION_NONE;
2,147,483,647✔
176

177
  // If the cell hasn't been determined based on the particle's location,
178
  // initiate a search for the current cell. This generally happens at the
179
  // beginning of the history and again for any secondary particles
180
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
181
    if (!exhaustive_find_cell(*this)) {
223,040,062!
182
      mark_as_lost(
×
183
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
184
      return;
×
185
    }
186

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
223,040,062!
189
      cell_born() = lowest_coord().cell();
223,040,062✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
462,822,349✔
193
      cell_last(j) = coord(j).cell();
239,782,287✔
194
    }
195
    n_coord_last() = n_coord();
223,040,062✔
196
  }
197

198
  // Write particle track.
199
  if (write_track())
2,147,483,647✔
200
    write_particle_track(*this);
10,818✔
201

202
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
203
    check_cell_overlap(*this);
×
204

205
  // Calculate microscopic and macroscopic cross sections
206
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
207
    if (settings::run_CE) {
2,147,483,647✔
208
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
209
          density_mult() != density_mult_last()) {
365,944,483✔
210
        // If the material is the same as the last material and the
211
        // temperature hasn't changed, we don't need to lookup cross
212
        // sections again.
213
        model::materials[material()]->calculate_xs(*this);
1,433,117,614✔
214
      }
215
    } else {
216
      // Get the MG data; unlike the CE case above, we have to re-calculate
217
      // cross sections for every collision since the cross sections may
218
      // be angle-dependent
219
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
220

221
      // Update the particle's group while we know we are multi-group
222
      g_last() = g();
2,063,937,414✔
223
    }
224
  } else {
225
    macro_xs().total = 0.0;
67,531,781✔
226
    macro_xs().absorption = 0.0;
67,531,781✔
227
    macro_xs().fission = 0.0;
67,531,781✔
228
    macro_xs().nu_fission = 0.0;
67,531,781✔
229
  }
230
}
231

232
void Particle::event_advance()
2,147,483,647✔
233
{
234
  // Find the distance to the nearest boundary
235
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
236

237
  // Sample a distance to collision
238
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
239
    collision_distance() = 0.0;
51,922,266✔
240
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
241
    collision_distance() = INFINITY;
67,531,781✔
242
  } else {
243
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
244
  }
245

246
  double speed = this->speed();
2,147,483,647✔
247
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
248
  double distance_cutoff =
249
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
250

251
  // Select smaller of the three distances
252
  double distance =
253
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
254

255
  // Advance particle in space and time
256
  this->move_distance(distance);
2,147,483,647✔
257
  double dt = distance / speed;
2,147,483,647✔
258
  this->time() += dt;
2,147,483,647✔
259
  this->lifetime() += dt;
2,147,483,647✔
260

261
  // Score timed track-length tallies
262
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
264
  }
265

266
  // Score track-length tallies
267
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
268
    score_tracklength_tally(*this, distance);
1,368,001,045✔
269
  }
270

271
  // Score track-length estimate of k-eff
272
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
273
      type() == ParticleType::neutron) {
2,147,483,647✔
274
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
275
  }
276

277
  // Score flux derivative accumulators for differential tallies.
278
  if (!model::active_tallies.empty()) {
2,147,483,647✔
279
    score_track_derivative(*this, distance);
1,546,090,698✔
280
  }
281

282
  // Set particle weight to zero if it hit the time boundary
283
  if (distance == distance_cutoff) {
2,147,483,647✔
284
    wgt() = 0.0;
224,928✔
285
  }
286
}
2,147,483,647✔
287

288
void Particle::event_cross_surface()
2,142,275,559✔
289
{
290
  // Saving previous cell data
291
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
292
    cell_last(j) = coord(j).cell();
2,147,483,647✔
293
  }
294
  n_coord_last() = n_coord();
2,142,275,559✔
295

296
  // Set surface that particle is on and adjust coordinate levels
297
  surface() = boundary().surface();
2,142,275,559✔
298
  n_coord() = boundary().coord_level();
2,142,275,559✔
299

300
  if (boundary().lattice_translation()[0] != 0 ||
2,142,275,559✔
301
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
302
      boundary().lattice_translation()[2] != 0) {
1,644,888,357✔
303
    // Particle crosses lattice boundary
304

305
    bool verbose = settings::verbosity >= 10 || trace();
684,845,586!
306
    cross_lattice(*this, boundary(), verbose);
684,845,586✔
307
    event() = TallyEvent::LATTICE;
684,845,586✔
308
  } else {
309
    // Particle crosses surface
310
    const auto& surf {model::surfaces[surface_index()].get()};
1,457,429,973✔
311
    // If BC, add particle to surface source before crossing surface
312
    if (surf->surf_source_ && surf->bc_) {
1,457,429,973✔
313
      add_surf_source_to_bank(*this, *surf);
671,370,874✔
314
    }
315
    this->cross_surface(*surf);
1,457,429,973✔
316
    // If no BC, add particle to surface source after crossing surface
317
    if (surf->surf_source_ && !surf->bc_) {
1,457,429,964✔
318
      add_surf_source_to_bank(*this, *surf);
784,821,263✔
319
    }
320
    if (settings::weight_window_checkpoint_surface) {
1,457,429,964✔
321
      apply_weight_windows(*this);
396!
322
    }
323
    event() = TallyEvent::SURFACE;
1,457,429,964✔
324
  }
325
  // Score cell to cell partial currents
326
  if (!model::active_surface_tallies.empty()) {
2,142,275,550✔
327
    score_surface_tally(*this, model::active_surface_tallies);
34,900,767✔
328
  }
329
}
2,142,275,550✔
330

331
void Particle::event_collide()
2,147,483,647✔
332
{
333
  // Score collision estimate of keff
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
335
      type() == ParticleType::neutron) {
2,147,483,647✔
336
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,130,429,655✔
337
  }
338

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

343
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
344
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,432,944✔
345

346
  // Clear surface component
347
  surface() = SURFACE_NONE;
2,147,483,647✔
348

349
  if (settings::run_CE) {
2,147,483,647✔
350
    collision(*this);
773,466,877✔
351
  } else {
352
    collision_mg(*this);
1,783,060,477✔
353
  }
354

355
  // Score collision estimator tallies -- this is done after a collision
356
  // has occurred rather than before because we need information on the
357
  // outgoing energy for any tallies with an outgoing energy filter
358
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
359
    score_collision_tally(*this);
105,704,280✔
360
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
361
    if (settings::run_CE) {
119,644,176✔
362
      score_analog_tally_ce(*this);
118,435,914✔
363
    } else {
364
      score_analog_tally_mg(*this);
1,208,262✔
365
    }
366
  }
367

368
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
369
      type() == ParticleType::photon) {
16,918✔
370
    pht_collision_energy();
2,024✔
371
  }
372

373
  // Reset banked weight during collision
374
  n_bank() = 0;
2,147,483,647✔
375
  bank_second_E() = 0.0;
2,147,483,647✔
376
  wgt_bank() = 0.0;
2,147,483,647✔
377
  zero_delayed_bank();
2,147,483,647✔
378

379
  // Reset fission logical
380
  fission() = false;
2,147,483,647✔
381

382
  // Save coordinates for tallying purposes
383
  r_last_current() = r();
2,147,483,647✔
384

385
  // Set last material to none since cross sections will need to be
386
  // re-evaluated
387
  material_last() = C_NONE;
2,147,483,647✔
388

389
  // Set all directions to base level -- right now, after a collision, only
390
  // the base level directions are changed
391
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
392
    if (coord(j + 1).rotated()) {
118,808,190✔
393
      // If next level is rotated, apply rotation matrix
394
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
395
      const auto& u {coord(j).u()};
10,426,614✔
396
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
397
    } else {
398
      // Otherwise, copy this level's direction
399
      coord(j + 1).u() = coord(j).u();
108,381,576✔
400
    }
401
  }
402

403
  // Score flux derivative accumulators for differential tallies.
404
  if (!model::active_tallies.empty())
2,147,483,647✔
405
    score_collision_derivative(*this);
666,499,860✔
406

407
#ifdef OPENMC_DAGMC_ENABLED
408
  history().reset();
268,644,782✔
409
#endif
410
}
2,147,483,647✔
411

412
void Particle::event_revive_from_secondary()
2,147,483,647✔
413
{
414
  // If particle has too many events, display warning and kill it
415
  ++n_event();
2,147,483,647✔
416
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
UNCOV
417
    warning("Particle " + std::to_string(id()) +
×
418
            " underwent maximum number of events.");
UNCOV
419
    wgt() = 0.0;
×
420
  }
421

422
  // Check for secondary particles if this particle is dead
423
  if (!alive()) {
2,147,483,647✔
424
    // Write final position for this particle
425
    if (write_track()) {
223,039,658✔
426
      write_particle_track(*this);
6,676✔
427
    }
428

429
    // If no secondary particles, break out of event loop
430
    if (secondary_bank().empty())
223,039,658✔
431
      return;
161,868,318✔
432

433
    from_source(&secondary_bank().back());
61,171,340✔
434
    secondary_bank().pop_back();
61,171,340✔
435
    n_event() = 0;
61,171,340✔
436
    bank_second_E() = 0.0;
61,171,340✔
437

438
    // Subtract secondary particle energy from interim pulse-height results
439
    if (!model::active_pulse_height_tallies.empty() &&
61,186,839✔
440
        this->type() == ParticleType::photon) {
15,499✔
441
      // Since the birth cell of the particle has not been set we
442
      // have to determine it before the energy of the secondary particle can be
443
      // removed from the pulse-height of this cell.
444
      if (lowest_coord().cell() == C_NONE) {
605!
445
        bool verbose = settings::verbosity >= 10 || trace();
605!
446
        if (!exhaustive_find_cell(*this, verbose)) {
605!
447
          mark_as_lost("Could not find the cell containing particle " +
×
448
                       std::to_string(id()));
×
UNCOV
449
          return;
×
450
        }
451
        // Set birth cell attribute
452
        if (cell_born() == C_NONE)
605!
453
          cell_born() = lowest_coord().cell();
605✔
454

455
        // Initialize last cells from current cell
456
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
457
          cell_last(j) = coord(j).cell();
605✔
458
        }
459
        n_coord_last() = n_coord();
605✔
460
      }
461
      pht_secondary_particles();
605✔
462
    }
463

464
    // Enter new particle in particle track file
465
    if (write_track())
61,171,340✔
466
      add_particle_track(*this);
5,606✔
467
  }
468
}
469

470
void Particle::event_death()
161,869,318✔
471
{
472
#ifdef OPENMC_DAGMC_ENABLED
473
  history().reset();
15,944,102✔
474
#endif
475

476
  // Finish particle track output.
477
  if (write_track()) {
161,869,318✔
478
    finalize_particle_track(*this);
1,070✔
479
  }
480

481
// Contribute tally reduction variables to global accumulator
482
#pragma omp atomic
89,667,915✔
483
  global_tally_absorption += keff_tally_absorption();
161,869,318✔
484
#pragma omp atomic
89,446,704✔
485
  global_tally_collision += keff_tally_collision();
161,869,318✔
486
#pragma omp atomic
89,285,082✔
487
  global_tally_tracklength += keff_tally_tracklength();
161,869,318✔
488
#pragma omp atomic
89,006,902✔
489
  global_tally_leakage += keff_tally_leakage();
161,869,318✔
490

491
  // Reset particle tallies once accumulated
492
  keff_tally_absorption() = 0.0;
161,869,318✔
493
  keff_tally_collision() = 0.0;
161,869,318✔
494
  keff_tally_tracklength() = 0.0;
161,869,318✔
495
  keff_tally_leakage() = 0.0;
161,869,318✔
496

497
  if (!model::active_pulse_height_tallies.empty()) {
161,869,318✔
498
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
499
  }
500

501
  // Record the number of progeny created by this particle.
502
  // This data will be used to efficiently sort the fission bank.
503
  if (settings::run_mode == RunMode::EIGENVALUE) {
161,869,318✔
504
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
135,880,300✔
505
    simulation::progeny_per_particle[offset] = n_progeny();
135,880,300✔
506
  }
507
}
161,869,318✔
508

509
void Particle::pht_collision_energy()
2,024✔
510
{
511
  // Adds the energy particles lose in a collision to the pulse-height
512

513
  // determine index of cell in pulse_height_cells
514
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
515
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
516

517
  if (it != model::pulse_height_cells.end()) {
2,024!
518
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
519
    pht_storage()[index] += E_last() - E();
2,024✔
520

521
    // If the energy of the particle is below the cutoff, it will not be sampled
522
    // so its energy is added to the pulse-height in the cell
523
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
524
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
525
      pht_storage()[index] += E();
825✔
526
    }
527
  }
528
}
2,024✔
529

530
void Particle::pht_secondary_particles()
605✔
531
{
532
  // Removes the energy of secondary produced particles from the pulse-height
533

534
  // determine index of cell in pulse_height_cells
535
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
536
    model::pulse_height_cells.end(), cell_born());
605✔
537

538
  if (it != model::pulse_height_cells.end()) {
605!
539
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
540
    pht_storage()[index] -= E();
605✔
541
  }
542
}
605✔
543

544
void Particle::cross_surface(const Surface& surf)
1,458,849,203✔
545
{
546

547
  if (settings::verbosity >= 10 || trace()) {
1,458,849,203✔
548
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
549
  }
550

551
// if we're crossing a CSG surface, make sure the DAG history is reset
552
#ifdef OPENMC_DAGMC_ENABLED
553
  if (surf.geom_type() == GeometryType::CSG)
219,717,899✔
554
    history().reset();
219,673,122✔
555
#endif
556

557
  // Handle any applicable boundary conditions.
558
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,130,713,937!
559
      settings::run_mode != RunMode::VOLUME) {
671,864,734✔
560
    surf.bc_->handle_particle(*this, surf);
671,722,982✔
561
    return;
671,722,982✔
562
  }
563

564
  // ==========================================================================
565
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
566

567
#ifdef OPENMC_DAGMC_ENABLED
568
  // in DAGMC, we know what the next cell should be
569
  if (surf.geom_type() == GeometryType::DAG) {
127,589,010✔
570
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
37,445✔
571
                       lowest_coord().universe()) -
37,445✔
572
                     1;
37,445✔
573
    // save material, temperature, and density multiplier
574
    material_last() = material();
37,445✔
575
    sqrtkT_last() = sqrtkT();
37,445✔
576
    density_mult_last() = density_mult();
37,445✔
577
    // set new cell value
578
    lowest_coord().cell() = i_cell;
37,445✔
579
    auto& cell = model::cells[i_cell];
37,445✔
580

581
    cell_instance() = 0;
37,445✔
582
    if (cell->distribcell_index_ >= 0)
37,445✔
583
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
36,421✔
584

585
    material() = cell->material(cell_instance());
37,445✔
586
    sqrtkT() = cell->sqrtkT(cell_instance());
37,445✔
587
    density_mult() = cell->density_mult(cell_instance());
37,445✔
588
    return;
37,445✔
589
  }
590
#endif
591

592
  bool verbose = settings::verbosity >= 10 || trace();
787,088,776!
593
  if (neighbor_list_find_cell(*this, verbose)) {
787,088,776✔
594
    return;
787,058,865✔
595
  }
596

597
  // ==========================================================================
598
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
599

600
  // Remove lower coordinate levels
601
  n_coord() = 1;
29,911✔
602
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
603

604
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,911!
605
    // If a cell is still not found, there are two possible causes: 1) there is
606
    // a void in the model, and 2) the particle hit a surface at a tangent. If
607
    // the particle is really traveling tangent to a surface, if we move it
608
    // forward a tiny bit it should fix the problem.
609

610
    surface() = SURFACE_NONE;
5,799✔
611
    n_coord() = 1;
5,799✔
612
    r() += TINY_BIT * u();
5,799✔
613

614
    // Couldn't find next cell anywhere! This probably means there is an actual
615
    // undefined region in the geometry.
616

617
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
618
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
619
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
620
                   " it could not be located in any cell and it did not leak.");
621
      return;
5,790✔
622
    }
623
  }
624
}
625

626
void Particle::cross_vacuum_bc(const Surface& surf)
33,719,401✔
627
{
628
  // Score any surface current tallies -- note that the particle is moved
629
  // forward slightly so that if the mesh boundary is on the surface, it is
630
  // still processed
631

632
  if (!model::active_meshsurf_tallies.empty()) {
33,719,401✔
633
    // TODO: Find a better solution to score surface currents than
634
    // physically moving the particle forward slightly
635

636
    r() += TINY_BIT * u();
1,087,206✔
637
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,087,206✔
638
  }
639

640
  // Score to global leakage tally
641
  keff_tally_leakage() += wgt();
33,719,401✔
642

643
  // Kill the particle
644
  wgt() = 0.0;
33,719,401✔
645

646
  // Display message
647
  if (settings::verbosity >= 10 || trace()) {
33,719,401!
648
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
649
  }
650
}
33,719,401✔
651

652
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
638,347,424✔
653
{
654
  // Do not handle reflective boundary conditions on lower universes
655
  if (n_coord() != 1) {
638,347,424!
UNCOV
656
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
657
                 " off surface in a lower universe.");
UNCOV
658
    return;
×
659
  }
660

661
  // Score surface currents since reflection causes the direction of the
662
  // particle to change. For surface filters, we need to score the tallies
663
  // twice, once before the particle's surface attribute has changed and
664
  // once after. For mesh surface filters, we need to artificially move
665
  // the particle slightly back in case the surface crossing is coincident
666
  // with a mesh boundary
667

668
  if (!model::active_surface_tallies.empty()) {
638,347,424✔
669
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
670
  }
671

672
  if (!model::active_meshsurf_tallies.empty()) {
638,347,424✔
673
    Position r {this->r()};
55,305,995✔
674
    this->r() -= TINY_BIT * u();
55,305,995✔
675
    score_surface_tally(*this, model::active_meshsurf_tallies);
55,305,995✔
676
    this->r() = r;
55,305,995✔
677
  }
678

679
  // Set the new particle direction
680
  u() = new_u;
638,347,424✔
681

682
  // Reassign particle's cell and surface
683
  coord(0).cell() = cell_last(0);
638,347,424✔
684
  surface() = -surface();
638,347,424✔
685

686
  // If a reflective surface is coincident with a lattice or universe
687
  // boundary, it is necessary to redetermine the particle's coordinates in
688
  // the lower universes.
689
  // (unless we're using a dagmc model, which has exactly one universe)
690
  n_coord() = 1;
638,347,424✔
691
  if (surf.geom_type() != GeometryType::DAG &&
1,276,692,090!
692
      !neighbor_list_find_cell(*this)) {
638,344,666!
693
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
694
                 std::to_string(surf.id_) + ".");
×
UNCOV
695
    return;
×
696
  }
697

698
  // Set previous coordinate going slightly past surface crossing
699
  r_last_current() = r() + TINY_BIT * u();
638,347,424✔
700

701
  // Diagnostic message
702
  if (settings::verbosity >= 10 || trace()) {
638,347,424!
UNCOV
703
    write_message(1, "    Reflected from surface {}", surf.id_);
×
704
  }
705
}
706

707
void Particle::cross_periodic_bc(
661,623✔
708
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
709
{
710
  // Do not handle periodic boundary conditions on lower universes
711
  if (n_coord() != 1) {
661,623!
712
    mark_as_lost(
×
UNCOV
713
      "Cannot transfer particle " + std::to_string(id()) +
×
714
      " across surface in a lower universe. Boundary conditions must be "
715
      "applied to root universe.");
UNCOV
716
    return;
×
717
  }
718

719
  // Score surface currents since reflection causes the direction of the
720
  // particle to change -- artificially move the particle slightly back in
721
  // case the surface crossing is coincident with a mesh boundary
722
  if (!model::active_meshsurf_tallies.empty()) {
661,623!
723
    Position r {this->r()};
×
724
    this->r() -= TINY_BIT * u();
×
725
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
726
    this->r() = r;
×
727
  }
728

729
  // Adjust the particle's location and direction.
730
  r() = new_r;
661,623✔
731
  u() = new_u;
661,623✔
732

733
  // Reassign particle's surface
734
  surface() = new_surface;
661,623✔
735

736
  // Figure out what cell particle is in now
737
  n_coord() = 1;
661,623✔
738

739
  if (!neighbor_list_find_cell(*this)) {
661,623!
740
    mark_as_lost("Couldn't find particle after hitting periodic "
×
741
                 "boundary on surface " +
×
UNCOV
742
                 std::to_string(surf.id_) +
×
743
                 ". The normal vector "
744
                 "of one periodic surface may need to be reversed.");
UNCOV
745
    return;
×
746
  }
747

748
  // Set previous coordinate going slightly past surface crossing
749
  r_last_current() = r() + TINY_BIT * u();
661,623✔
750

751
  // Diagnostic message
752
  if (settings::verbosity >= 10 || trace()) {
661,623!
UNCOV
753
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
754
  }
755
}
756

757
void Particle::mark_as_lost(const char* message)
5,799✔
758
{
759
  // Print warning and write lost particle file
760
  warning(message);
5,799✔
761
  if (settings::max_write_lost_particles < 0 ||
5,799✔
762
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
763
    write_restart();
379✔
764
  }
765
  // Increment number of lost particles
766
  wgt() = 0.0;
5,799✔
767
#pragma omp atomic
3,154✔
768
  simulation::n_lost_particles += 1;
2,645✔
769

770
  // Count the total number of simulated particles (on this processor)
771
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
772
           simulation::work_per_rank;
773

774
  // Abort the simulation if the maximum number of lost particles has been
775
  // reached
776
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
777
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
778
    fatal_error("Maximum number of lost particles has been reached.");
9✔
779
  }
780
}
5,790✔
781

782
void Particle::write_restart() const
379✔
783
{
784
  // Dont write another restart file if in particle restart mode
785
  if (settings::run_mode == RunMode::PARTICLE)
379✔
786
    return;
22✔
787

788
  // Set up file name
789
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
790
    simulation::current_batch, id());
665✔
791

792
#pragma omp critical(WriteParticleRestart)
374✔
793
  {
794
    // Create file
795
    hid_t file_id = file_open(filename, 'w');
357✔
796

797
    // Write filetype and version info
798
    write_attribute(file_id, "filetype", "particle restart");
357✔
799
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
357✔
800
    write_attribute(file_id, "openmc_version", VERSION);
357✔
801
#ifdef GIT_SHA1
802
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
803
#endif
804

805
    // Write data to file
806
    write_dataset(file_id, "current_batch", simulation::current_batch);
357✔
807
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
357✔
808
    write_dataset(file_id, "current_generation", simulation::current_gen);
357✔
809
    write_dataset(file_id, "n_particles", settings::n_particles);
357✔
810
    switch (settings::run_mode) {
357!
811
    case RunMode::FIXED_SOURCE:
225✔
812
      write_dataset(file_id, "run_mode", "fixed source");
225✔
813
      break;
225✔
814
    case RunMode::EIGENVALUE:
132✔
815
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
816
      break;
132✔
817
    case RunMode::PARTICLE:
×
818
      write_dataset(file_id, "run_mode", "particle restart");
×
819
      break;
×
820
    default:
×
UNCOV
821
      break;
×
822
    }
823
    write_dataset(file_id, "id", id());
357✔
824
    write_dataset(file_id, "type", static_cast<int>(type()));
357✔
825

826
    int64_t i = current_work();
357✔
827
    if (settings::run_mode == RunMode::EIGENVALUE) {
357✔
828
      // take source data from primary bank for eigenvalue simulation
829
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
830
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
831
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
832
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
833
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
834
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
835
      // re-sample using rng random number seed used to generate source particle
836
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
837
                     settings::n_particles +
225✔
838
                   simulation::work_index[mpi::rank] + i;
225✔
839
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
840
      // re-sample source site
841
      auto site = sample_external_source(&seed);
225✔
842
      write_dataset(file_id, "weight", site.wgt);
225✔
843
      write_dataset(file_id, "energy", site.E);
225✔
844
      write_dataset(file_id, "xyz", site.r);
225✔
845
      write_dataset(file_id, "uvw", site.u);
225✔
846
      write_dataset(file_id, "time", site.time);
225✔
847
    }
848

849
    // Close file
850
    file_close(file_id);
357✔
851
  } // #pragma omp critical
852
}
357✔
853

854
void Particle::update_neutron_xs(
2,147,483,647✔
855
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
856
{
857
  // Get microscopic cross section cache
858
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
859

860
  // If the cache doesn't match, recalculate micro xs
861
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
862
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
863
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
864
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
865

866
    // If NCrystal is being used, update micro cross section cache
867
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
868
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
869
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
870
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
871
    }
872
  }
873
}
2,147,483,647✔
874

875
//==============================================================================
876
// Non-method functions
877
//==============================================================================
878

879
std::string particle_type_to_str(ParticleType type)
3,387,343✔
880
{
881
  switch (type) {
3,387,343!
882
  case ParticleType::neutron:
2,528,516✔
883
    return "neutron";
2,528,516✔
884
  case ParticleType::photon:
858,563✔
885
    return "photon";
858,563✔
886
  case ParticleType::electron:
132✔
887
    return "electron";
132✔
888
  case ParticleType::positron:
132✔
889
    return "positron";
132✔
890
  }
UNCOV
891
  UNREACHABLE();
×
892
}
893

894
ParticleType str_to_particle_type(std::string str)
3,384,074✔
895
{
896
  if (str == "neutron") {
3,384,074✔
897
    return ParticleType::neutron;
783,880✔
898
  } else if (str == "photon") {
2,600,194✔
899
    return ParticleType::photon;
2,600,108✔
900
  } else if (str == "electron") {
86✔
901
    return ParticleType::electron;
43✔
902
  } else if (str == "positron") {
43!
903
    return ParticleType::positron;
43✔
904
  } else {
UNCOV
905
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
906
  }
907
}
908

909
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,456,192,137✔
910
{
911
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
912
      simulation::surf_source_bank.full()) {
1,150,189,415✔
913
    return;
1,456,062,484✔
914
  }
915

916
  // If a cell/cellfrom/cellto parameter is defined
917
  if (settings::ssw_cell_id != C_NONE) {
337,083✔
918

919
    // Retrieve cell index and storage type
920
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,438✔
921

922
    if (surf.bc_) {
254,438✔
923
      // Leave if cellto with vacuum boundary condition
924
      if (surf.bc_->type() == "vacuum" &&
182,558!
925
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
926
        return;
12,136✔
927
      }
928

929
      // Leave if other boundary condition than vacuum
930
      if (surf.bc_->type() != "vacuum") {
137,323✔
931
        return;
116,360✔
932
      }
933
    }
934

935
    // Check if the cell of interest has been exited
936
    bool exited = false;
125,942✔
937
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,673✔
938
      if (p.cell_last(i) == cell_idx) {
207,731✔
939
        exited = true;
73,764✔
940
      }
941
    }
942

943
    // Check if the cell of interest has been entered
944
    bool entered = false;
125,942✔
945
    for (int i = 0; i < p.n_coord(); ++i) {
297,975✔
946
      if (p.coord(i).cell() == cell_idx) {
172,033✔
947
        entered = true;
57,517✔
948
      }
949
    }
950

951
    // Vacuum boundary conditions: return if cell is not exited
952
    if (surf.bc_) {
125,942✔
953
      if (surf.bc_->type() == "vacuum" && !exited) {
20,963!
954
        return;
14,663✔
955
      }
956
    } else {
957

958
      // If we both enter and exit the cell of interest
959
      if (entered && exited) {
104,979✔
960
        return;
27,203✔
961
      }
962

963
      // If we did not enter nor exit the cell of interest
964
      if (!entered && !exited) {
77,776✔
965
        return;
13,501✔
966
      }
967

968
      // If cellfrom and the cell before crossing is not the cell of
969
      // interest
970
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,275✔
971
        return;
11,543✔
972
      }
973

974
      // If cellto and the cell after crossing is not the cell of interest
975
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
976
        return;
12,024✔
977
      }
978
    }
979
  }
980

981
  SourceSite site;
129,653✔
982
  site.r = p.r();
129,653✔
983
  site.u = p.u();
129,653✔
984
  site.E = p.E();
129,653✔
985
  site.time = p.time();
129,653✔
986
  site.wgt = p.wgt();
129,653✔
987
  site.delayed_group = p.delayed_group();
129,653✔
988
  site.surf_id = surf.id_;
129,653✔
989
  site.particle = p.type();
129,653✔
990
  site.parent_id = p.id();
129,653✔
991
  site.progeny_id = p.n_progeny();
129,653✔
992
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
993
}
994

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

© 2025 Coveralls, Inc