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

openmc-dev / openmc / 17846342348

19 Sep 2025 02:05AM UTC coverage: 85.2% (-0.006%) from 85.206%
17846342348

Pull #3546

github

web-flow
Merge 8f9d03c5f into afd9d0607
Pull Request #3546: Add distributed cell densities

155 of 194 new or added lines in 13 files covered. (79.9%)

164 existing lines in 4 files now uncovered.

53154 of 62387 relevant lines covered (85.2%)

38279262.9 hits per line

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

93.09
/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,779,895,285✔
51
    case ParticleType::neutron:
1,711,031,269✔
52
      mass = MASS_NEUTRON_EV;
1,711,031,269✔
53
      break;
1,711,031,269✔
54
    case ParticleType::photon:
17,445,127✔
55
      mass = 0.0;
17,445,127✔
56
      break;
17,445,127✔
57
    case ParticleType::electron:
51,418,889✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
51,418,889✔
60
      break;
51,418,889✔
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,779,895,285✔
64
           (this->E() + mass);
1,779,895,285✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,062,680,774✔
67
    int macro_t = this->mg_xs_cache().t;
2,062,680,774✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,062,680,774✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,062,680,774✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,062,680,774✔
71
  }
72
}
73

74
bool Particle::create_secondary(
107,394,360✔
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)]) {
107,394,360✔
80
    return false;
51,369,114✔
81
  }
82

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

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

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,082,180✔
106
    bank.surf_id = SURFACE_NONE;
4,082,160✔
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,082,180✔
112

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

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

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

155
void Particle::event_calculate_xs()
2,147,483,647✔
156
{
157
  // Set the random number stream
158
  stream() = STREAM_TRACKING;
2,147,483,647✔
159

160
  // Store pre-collision particle properties
161
  wgt_last() = wgt();
2,147,483,647✔
162
  E_last() = E();
2,147,483,647✔
163
  u_last() = u();
2,147,483,647✔
164
  r_last() = r();
2,147,483,647✔
165
  time_last() = time();
2,147,483,647✔
166

167
  // Reset event variables
168
  event() = TallyEvent::KILL;
2,147,483,647✔
169
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
170
  event_mt() = REACTION_NONE;
2,147,483,647✔
171

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

182
    // Set birth cell attribute
183
    if (cell_born() == C_NONE)
219,567,383✔
184
      cell_born() = lowest_coord().cell();
219,567,383✔
185

186
    // Initialize last cells from current cell
187
    for (int j = 0; j < n_coord(); ++j) {
455,131,111✔
188
      cell_last(j) = coord(j).cell();
235,563,728✔
189
    }
190
    n_coord_last() = n_coord();
219,567,383✔
191
  }
192

193
  // Write particle track.
194
  if (write_track())
2,147,483,647✔
195
    write_particle_track(*this);
10,833✔
196

197
  if (settings::check_overlaps)
2,147,483,647✔
198
    check_cell_overlap(*this);
×
199

200
  // Calculate microscopic and macroscopic cross sections
201
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
202
    if (settings::run_CE) {
2,147,483,647✔
203
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,025,674,668✔
204
          density_mult() != density_mult_last()) {
340,146,031✔
205
        // If the material is the same as the last material and the
206
        // temperature hasn't changed, we don't need to lookup cross
207
        // sections again.
208
        model::materials[material()]->calculate_xs(*this);
1,345,391,417✔
209
      }
210
    } else {
211
      // Get the MG data; unlike the CE case above, we have to re-calculate
212
      // cross sections for every collision since the cross sections may
213
      // be angle-dependent
214
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,680,774✔
215

216
      // Update the particle's group while we know we are multi-group
217
      g_last() = g();
2,062,680,774✔
218
    }
219
  } else {
220
    macro_xs().total = 0.0;
67,283,691✔
221
    macro_xs().absorption = 0.0;
67,283,691✔
222
    macro_xs().fission = 0.0;
67,283,691✔
223
    macro_xs().nu_fission = 0.0;
67,283,691✔
224
  }
225
}
226

227
void Particle::event_advance()
2,147,483,647✔
228
{
229
  // Find the distance to the nearest boundary
230
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
231

232
  // Sample a distance to collision
233
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
234
    collision_distance() = 0.0;
51,418,889✔
235
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
236
    collision_distance() = INFINITY;
67,283,691✔
237
  } else {
238
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
239
  }
240

241
  double speed = this->speed();
2,147,483,647✔
242
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
243
  double distance_cutoff =
244
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
245

246
  // Select smaller of the three distances
247
  double distance =
248
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
249

250
  // Advance particle in space and time
251
  this->move_distance(distance);
2,147,483,647✔
252
  double dt = distance / speed;
2,147,483,647✔
253
  this->time() += dt;
2,147,483,647✔
254
  this->lifetime() += dt;
2,147,483,647✔
255

256
  // Score timed track-length tallies
257
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
258
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
259
  }
260

261
  // Score track-length tallies
262
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_tracklength_tally(*this, distance);
1,275,472,961✔
264
  }
265

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

272
  // Score flux derivative accumulators for differential tallies.
273
  if (!model::active_tallies.empty()) {
2,147,483,647✔
274
    score_track_derivative(*this, distance);
1,435,359,313✔
275
  }
276

277
  // Set particle weight to zero if it hit the time boundary
278
  if (distance == distance_cutoff) {
2,147,483,647✔
279
    wgt() = 0.0;
224,928✔
280
  }
281
}
2,147,483,647✔
282

283
void Particle::event_cross_surface()
2,071,982,573✔
284
{
285
  // Saving previous cell data
286
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
287
    cell_last(j) = coord(j).cell();
2,147,483,647✔
288
  }
289
  n_coord_last() = n_coord();
2,071,982,573✔
290

291
  // Set surface that particle is on and adjust coordinate levels
292
  surface() = boundary().surface();
2,071,982,573✔
293
  n_coord() = boundary().coord_level();
2,071,982,573✔
294

295
  if (boundary().lattice_translation()[0] != 0 ||
2,071,982,573✔
296
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
297
      boundary().lattice_translation()[2] != 0) {
1,578,094,771✔
298
    // Particle crosses lattice boundary
299

300
    bool verbose = settings::verbosity >= 10 || trace();
680,269,955✔
301
    cross_lattice(*this, boundary(), verbose);
680,269,955✔
302
    event() = TallyEvent::LATTICE;
680,269,955✔
303
  } else {
304
    // Particle crosses surface
305
    const auto& surf {model::surfaces[surface_index()].get()};
1,391,712,618✔
306
    // If BC, add particle to surface source before crossing surface
307
    if (surf->surf_source_ && surf->bc_) {
1,391,712,618✔
308
      add_surf_source_to_bank(*this, *surf);
645,367,195✔
309
    }
310
    this->cross_surface(*surf);
1,391,712,618✔
311
    // If no BC, add particle to surface source after crossing surface
312
    if (surf->surf_source_ && !surf->bc_) {
1,391,712,609✔
313
      add_surf_source_to_bank(*this, *surf);
745,112,005✔
314
    }
315
    if (settings::weight_window_checkpoint_surface) {
1,391,712,609✔
316
      apply_weight_windows(*this);
396✔
317
    }
318
    event() = TallyEvent::SURFACE;
1,391,712,609✔
319
  }
320
  // Score cell to cell partial currents
321
  if (!model::active_surface_tallies.empty()) {
2,071,982,564✔
322
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
323
  }
324
}
2,071,982,564✔
325

326
void Particle::event_collide()
2,147,483,647✔
327
{
328
  // Score collision estimate of keff
329
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
330
      type() == ParticleType::neutron) {
2,130,647,129✔
331
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,091,324,945✔
332
  }
333

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

338
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
339
    score_surface_tally(*this, model::active_meshsurf_tallies);
62,915,094✔
340

341
  // Clear surface component
342
  surface() = SURFACE_NONE;
2,147,483,647✔
343

344
  if (settings::run_CE) {
2,147,483,647✔
345
    collision(*this);
726,472,272✔
346
  } else {
347
    collision_mg(*this);
1,781,763,302✔
348
  }
349

350
  // Score collision estimator tallies -- this is done after a collision
351
  // has occurred rather than before because we need information on the
352
  // outgoing energy for any tallies with an outgoing energy filter
353
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
354
    score_collision_tally(*this);
100,643,882✔
355
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
356
    if (settings::run_CE) {
107,867,287✔
357
      score_analog_tally_ce(*this);
106,666,076✔
358
    } else {
359
      score_analog_tally_mg(*this);
1,201,211✔
360
    }
361
  }
362

363
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
364
      type() == ParticleType::photon) {
16,918✔
365
    pht_collision_energy();
2,024✔
366
  }
367

368
  // Reset banked weight during collision
369
  n_bank() = 0;
2,147,483,647✔
370
  bank_second_E() = 0.0;
2,147,483,647✔
371
  wgt_bank() = 0.0;
2,147,483,647✔
372
  zero_delayed_bank();
2,147,483,647✔
373

374
  // Reset fission logical
375
  fission() = false;
2,147,483,647✔
376

377
  // Save coordinates for tallying purposes
378
  r_last_current() = r();
2,147,483,647✔
379

380
  // Set last material to none since cross sections will need to be
381
  // re-evaluated
382
  material_last() = C_NONE;
2,147,483,647✔
383

384
  // Set all directions to base level -- right now, after a collision, only
385
  // the base level directions are changed
386
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
387
    if (coord(j + 1).rotated()) {
112,740,601✔
388
      // If next level is rotated, apply rotation matrix
389
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,394,285✔
390
      const auto& u {coord(j).u()};
10,394,285✔
391
      coord(j + 1).u() = u.rotate(m);
10,394,285✔
392
    } else {
393
      // Otherwise, copy this level's direction
394
      coord(j + 1).u() = coord(j).u();
102,346,316✔
395
    }
396
  }
397

398
  // Score flux derivative accumulators for differential tallies.
399
  if (!model::active_tallies.empty())
2,147,483,647✔
400
    score_collision_derivative(*this);
623,042,358✔
401

402
#ifdef OPENMC_DAGMC_ENABLED
403
  history().reset();
230,584,045✔
404
#endif
405
}
2,147,483,647✔
406

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

417
  // Check for secondary particles if this particle is dead
418
  if (!alive()) {
2,147,483,647✔
419
    // Write final position for this particle
420
    if (write_track()) {
219,566,979✔
421
      write_particle_track(*this);
6,674✔
422
    }
423

424
    // If no secondary particles, break out of event loop
425
    if (secondary_bank().empty())
219,566,979✔
426
      return;
159,120,798✔
427

428
    from_source(&secondary_bank().back());
60,446,181✔
429
    secondary_bank().pop_back();
60,446,181✔
430
    n_event() = 0;
60,446,181✔
431
    bank_second_E() = 0.0;
60,446,181✔
432

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

450
        // Initialize last cells from current cell
451
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
452
          cell_last(j) = coord(j).cell();
605✔
453
        }
454
        n_coord_last() = n_coord();
605✔
455
      }
456
      pht_secondary_particles();
605✔
457
    }
458

459
    // Enter new particle in particle track file
460
    if (write_track())
60,446,181✔
461
      add_particle_track(*this);
5,604✔
462
  }
463
}
464

465
void Particle::event_death()
159,121,798✔
466
{
467
#ifdef OPENMC_DAGMC_ENABLED
468
  history().reset();
14,764,682✔
469
#endif
470

471
  // Finish particle track output.
472
  if (write_track()) {
159,121,798✔
473
    finalize_particle_track(*this);
1,070✔
474
  }
475

476
// Contribute tally reduction variables to global accumulator
477
#pragma omp atomic
87,385,542✔
478
  global_tally_absorption += keff_tally_absorption();
159,121,798✔
479
#pragma omp atomic
87,779,659✔
480
  global_tally_collision += keff_tally_collision();
159,121,798✔
481
#pragma omp atomic
87,249,921✔
482
  global_tally_tracklength += keff_tally_tracklength();
159,121,798✔
483
#pragma omp atomic
86,966,257✔
484
  global_tally_leakage += keff_tally_leakage();
159,121,798✔
485

486
  // Reset particle tallies once accumulated
487
  keff_tally_absorption() = 0.0;
159,121,798✔
488
  keff_tally_collision() = 0.0;
159,121,798✔
489
  keff_tally_tracklength() = 0.0;
159,121,798✔
490
  keff_tally_leakage() = 0.0;
159,121,798✔
491

492
  if (!model::active_pulse_height_tallies.empty()) {
159,121,798✔
493
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
494
  }
495

496
  // Record the number of progeny created by this particle.
497
  // This data will be used to efficiently sort the fission bank.
498
  if (settings::run_mode == RunMode::EIGENVALUE) {
159,121,798✔
499
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,765,800✔
500
    simulation::progeny_per_particle[offset] = n_progeny();
133,765,800✔
501
  }
502
}
159,121,798✔
503

504
void Particle::pht_collision_energy()
2,024✔
505
{
506
  // Adds the energy particles lose in a collision to the pulse-height
507

508
  // determine index of cell in pulse_height_cells
509
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
510
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
511

512
  if (it != model::pulse_height_cells.end()) {
2,024✔
513
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
514
    pht_storage()[index] += E_last() - E();
2,024✔
515

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

525
void Particle::pht_secondary_particles()
605✔
526
{
527
  // Removes the energy of secondary produced particles from the pulse-height
528

529
  // determine index of cell in pulse_height_cells
530
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
531
    model::pulse_height_cells.end(), cell_born());
605✔
532

533
  if (it != model::pulse_height_cells.end()) {
605✔
534
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
535
    pht_storage()[index] -= E();
605✔
536
  }
537
}
605✔
538

539
void Particle::cross_surface(const Surface& surf)
1,392,845,816✔
540
{
541

542
  if (settings::verbosity >= 10 || trace()) {
1,392,845,816✔
543
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
544
  }
545

546
// if we're crossing a CSG surface, make sure the DAG history is reset
547
#ifdef OPENMC_DAGMC_ENABLED
548
  if (surf.geom_type() == GeometryType::CSG)
127,915,108✔
549
    history().reset();
127,871,060✔
550
#endif
551

552
  // Handle any applicable boundary conditions.
553
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,038,680,572✔
554
      settings::run_mode != RunMode::VOLUME) {
645,834,756✔
555
    surf.bc_->handle_particle(*this, surf);
645,714,812✔
556
    return;
645,714,812✔
557
  }
558

559
  // ==========================================================================
560
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
561

562
#ifdef OPENMC_DAGMC_ENABLED
563
  // in DAGMC, we know what the next cell should be
564
  if (surf.geom_type() == GeometryType::DAG) {
68,616,832✔
565
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
36,997✔
566
                       lowest_coord().universe()) -
36,997✔
567
                     1;
36,997✔
568
    // save material, temperature, and density multiplier
569
    material_last() = material();
36,997✔
570
    sqrtkT_last() = sqrtkT();
36,997✔
571
    density_mult_last() = density_mult();
36,997✔
572
    // set new cell value
573
    lowest_coord().cell() = i_cell;
36,997✔
574
    auto& cell = model::cells[i_cell];
36,997✔
575

576
    cell_instance() = 0;
36,997✔
577
    if (cell->distribcell_index_ >= 0)
36,997✔
578
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
579

580
    material() = cell->material(cell_instance());
36,997✔
581
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
582
    density_mult() = cell->density_mult(cell_instance());
36,997✔
583
    return;
36,997✔
584
  }
585
#endif
586

587
  bool verbose = settings::verbosity >= 10 || trace();
747,094,007✔
588
  if (neighbor_list_find_cell(*this, verbose)) {
747,094,007✔
589
    return;
747,065,988✔
590
  }
591

592
  // ==========================================================================
593
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
594

595
  // Remove lower coordinate levels
596
  n_coord() = 1;
28,019✔
597
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
598

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

605
    surface() = SURFACE_NONE;
5,744✔
606
    n_coord() = 1;
5,744✔
607
    r() += TINY_BIT * u();
5,744✔
608

609
    // Couldn't find next cell anywhere! This probably means there is an actual
610
    // undefined region in the geometry.
611

612
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
613
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
614
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
615
                   " it could not be located in any cell and it did not leak.");
616
      return;
5,735✔
617
    }
618
  }
619
}
620

621
void Particle::cross_vacuum_bc(const Surface& surf)
32,896,424✔
622
{
623
  // Score any surface current tallies -- note that the particle is moved
624
  // forward slightly so that if the mesh boundary is on the surface, it is
625
  // still processed
626

627
  if (!model::active_meshsurf_tallies.empty()) {
32,896,424✔
628
    // TODO: Find a better solution to score surface currents than
629
    // physically moving the particle forward slightly
630

631
    r() += TINY_BIT * u();
945,450✔
632
    score_surface_tally(*this, model::active_meshsurf_tallies);
945,450✔
633
  }
634

635
  // Score to global leakage tally
636
  keff_tally_leakage() += wgt();
32,896,424✔
637

638
  // Kill the particle
639
  wgt() = 0.0;
32,896,424✔
640

641
  // Display message
642
  if (settings::verbosity >= 10 || trace()) {
32,896,424✔
643
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
644
  }
645
}
32,896,424✔
646

647
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
613,179,426✔
648
{
649
  // Do not handle reflective boundary conditions on lower universes
650
  if (n_coord() != 1) {
613,179,426✔
UNCOV
651
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
652
                 " off surface in a lower universe.");
UNCOV
653
    return;
×
654
  }
655

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

663
  if (!model::active_surface_tallies.empty()) {
613,179,426✔
664
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
665
  }
666

667
  if (!model::active_meshsurf_tallies.empty()) {
613,179,426✔
668
    Position r {this->r()};
46,625,403✔
669
    this->r() -= TINY_BIT * u();
46,625,403✔
670
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,625,403✔
671
    this->r() = r;
46,625,403✔
672
  }
673

674
  // Set the new particle direction
675
  u() = new_u;
613,179,426✔
676

677
  // Reassign particle's cell and surface
678
  coord(0).cell() = cell_last(0);
613,179,426✔
679
  surface() = -surface();
613,179,426✔
680

681
  // If a reflective surface is coincident with a lattice or universe
682
  // boundary, it is necessary to redetermine the particle's coordinates in
683
  // the lower universes.
684
  // (unless we're using a dagmc model, which has exactly one universe)
685
  n_coord() = 1;
613,179,426✔
686
  if (surf.geom_type() != GeometryType::DAG &&
1,226,356,313✔
687
      !neighbor_list_find_cell(*this)) {
613,176,887✔
UNCOV
688
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
689
                 std::to_string(surf.id_) + ".");
×
UNCOV
690
    return;
×
691
  }
692

693
  // Set previous coordinate going slightly past surface crossing
694
  r_last_current() = r() + TINY_BIT * u();
613,179,426✔
695

696
  // Diagnostic message
697
  if (settings::verbosity >= 10 || trace()) {
613,179,426✔
UNCOV
698
    write_message(1, "    Reflected from surface {}", surf.id_);
×
699
  }
700
}
701

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

714
  // Score surface currents since reflection causes the direction of the
715
  // particle to change -- artificially move the particle slightly back in
716
  // case the surface crossing is coincident with a mesh boundary
717
  if (!model::active_meshsurf_tallies.empty()) {
666,318✔
UNCOV
718
    Position r {this->r()};
×
UNCOV
719
    this->r() -= TINY_BIT * u();
×
UNCOV
720
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
721
    this->r() = r;
×
722
  }
723

724
  // Adjust the particle's location and direction.
725
  r() = new_r;
666,318✔
726
  u() = new_u;
666,318✔
727

728
  // Reassign particle's surface
729
  surface() = new_surface;
666,318✔
730

731
  // Figure out what cell particle is in now
732
  n_coord() = 1;
666,318✔
733

734
  if (!neighbor_list_find_cell(*this)) {
666,318✔
735
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
736
                 "boundary on surface " +
×
UNCOV
737
                 std::to_string(surf.id_) +
×
738
                 ". The normal vector "
739
                 "of one periodic surface may need to be reversed.");
UNCOV
740
    return;
×
741
  }
742

743
  // Set previous coordinate going slightly past surface crossing
744
  r_last_current() = r() + TINY_BIT * u();
666,318✔
745

746
  // Diagnostic message
747
  if (settings::verbosity >= 10 || trace()) {
666,318✔
UNCOV
748
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
749
  }
750
}
751

752
void Particle::mark_as_lost(const char* message)
5,744✔
753
{
754
  // Print warning and write lost particle file
755
  warning(message);
5,744✔
756
  if (settings::max_write_lost_particles < 0 ||
5,744✔
757
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
758
    write_restart();
324✔
759
  }
760
  // Increment number of lost particles
761
  wgt() = 0.0;
5,744✔
762
#pragma omp atomic
3,124✔
763
  simulation::n_lost_particles += 1;
2,620✔
764

765
  // Count the total number of simulated particles (on this processor)
766
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
767
           simulation::work_per_rank;
768

769
  // Abort the simulation if the maximum number of lost particles has been
770
  // reached
771
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
772
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
773
    fatal_error("Maximum number of lost particles has been reached.");
9✔
774
  }
775
}
5,735✔
776

777
void Particle::write_restart() const
324✔
778
{
779
  // Dont write another restart file if in particle restart mode
780
  if (settings::run_mode == RunMode::PARTICLE)
324✔
781
    return;
22✔
782

783
  // Set up file name
784
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
785
    simulation::current_batch, id());
565✔
786

787
#pragma omp critical(WriteParticleRestart)
314✔
788
  {
789
    // Create file
790
    hid_t file_id = file_open(filename, 'w');
302✔
791

792
    // Write filetype and version info
793
    write_attribute(file_id, "filetype", "particle restart");
302✔
794
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
795
    write_attribute(file_id, "openmc_version", VERSION);
302✔
796
#ifdef GIT_SHA1
797
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
798
#endif
799

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

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

844
    // Close file
845
    file_close(file_id);
302✔
846
  } // #pragma omp critical
847
}
302✔
848

849
void Particle::update_neutron_xs(
2,147,483,647✔
850
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
851
{
852
  // Get microscopic cross section cache
853
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
854

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

860
    // If NCrystal is being used, update micro cross section cache
861
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
862
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
863
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
864
    }
865
  }
866
}
2,147,483,647✔
867

868
//==============================================================================
869
// Non-method functions
870
//==============================================================================
871

872
std::string particle_type_to_str(ParticleType type)
3,130,197✔
873
{
874
  switch (type) {
3,130,197✔
875
  case ParticleType::neutron:
2,399,940✔
876
    return "neutron";
2,399,940✔
877
  case ParticleType::photon:
729,993✔
878
    return "photon";
729,993✔
879
  case ParticleType::electron:
132✔
880
    return "electron";
132✔
881
  case ParticleType::positron:
132✔
882
    return "positron";
132✔
883
  }
UNCOV
884
  UNREACHABLE();
×
885
}
886

887
ParticleType str_to_particle_type(std::string str)
3,169,865✔
888
{
889
  if (str == "neutron") {
3,169,865✔
890
    return ParticleType::neutron;
733,937✔
891
  } else if (str == "photon") {
2,435,928✔
892
    return ParticleType::photon;
2,435,842✔
893
  } else if (str == "electron") {
86✔
894
    return ParticleType::electron;
43✔
895
  } else if (str == "positron") {
43✔
896
    return ParticleType::positron;
43✔
897
  } else {
UNCOV
898
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
899
  }
900
}
901

902
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,390,479,200✔
903
{
904
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
905
      simulation::surf_source_bank.full()) {
1,090,805,973✔
906
    return;
1,390,350,434✔
907
  }
908

909
  // If a cell/cellfrom/cellto parameter is defined
910
  if (settings::ssw_cell_id != C_NONE) {
341,268✔
911

912
    // Retrieve cell index and storage type
913
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
914

915
    if (surf.bc_) {
258,706✔
916
      // Leave if cellto with vacuum boundary condition
917
      if (surf.bc_->type() == "vacuum" &&
184,448✔
918
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
919
        return;
11,953✔
920
      }
921

922
      // Leave if other boundary condition than vacuum
923
      if (surf.bc_->type() != "vacuum") {
140,281✔
924
        return;
120,020✔
925
      }
926
    }
927

928
    // Check if the cell of interest has been exited
929
    bool exited = false;
126,733✔
930
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,343✔
931
      if (p.cell_last(i) == cell_idx) {
208,610✔
932
        exited = true;
74,235✔
933
      }
934
    }
935

936
    // Check if the cell of interest has been entered
937
    bool entered = false;
126,733✔
938
    for (int i = 0; i < p.n_coord(); ++i) {
301,039✔
939
      if (p.coord(i).cell() == cell_idx) {
174,306✔
940
        entered = true;
59,099✔
941
      }
942
    }
943

944
    // Vacuum boundary conditions: return if cell is not exited
945
    if (surf.bc_) {
126,733✔
946
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
947
        return;
13,961✔
948
      }
949
    } else {
950

951
      // If we both enter and exit the cell of interest
952
      if (entered && exited) {
106,472✔
953
        return;
28,613✔
954
      }
955

956
      // If we did not enter nor exit the cell of interest
957
      if (!entered && !exited) {
77,859✔
958
        return;
14,351✔
959
      }
960

961
      // If cellfrom and the cell before crossing is not the cell of
962
      // interest
963
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,508✔
964
        return;
11,566✔
965
      }
966

967
      // If cellto and the cell after crossing is not the cell of interest
968
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
969
        return;
12,038✔
970
      }
971
    }
972
  }
973

974
  SourceSite site;
128,766✔
975
  site.r = p.r();
128,766✔
976
  site.u = p.u();
128,766✔
977
  site.E = p.E();
128,766✔
978
  site.time = p.time();
128,766✔
979
  site.wgt = p.wgt();
128,766✔
980
  site.delayed_group = p.delayed_group();
128,766✔
981
  site.surf_id = surf.id_;
128,766✔
982
  site.particle = p.type();
128,766✔
983
  site.parent_id = p.id();
128,766✔
984
  site.progeny_id = p.n_progeny();
128,766✔
985
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
128,766✔
986
}
987

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