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

openmc-dev / openmc / 22669462911

04 Mar 2026 12:31PM UTC coverage: 81.555% (-0.003%) from 81.558%
22669462911

Pull #3849

github

web-flow
Merge ee90dabdc into 70be65000
Pull Request #3849: Fixed a bug in cell last update

17537 of 25247 branches covered (69.46%)

Branch coverage included in aggregate %.

43 of 47 new or added lines in 6 files covered. (91.49%)

1 existing line in 1 file now uncovered.

57927 of 67284 relevant lines covered (86.09%)

44986125.79 hits per line

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

87.12
/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/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

36
#ifdef OPENMC_DAGMC_ENABLED
37
#include "DagMC.hpp"
38
#endif
39

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
2,147,483,647✔
51
    switch (type().pdg_number()) {
2,147,483,647✔
52
    case PDG_NEUTRON:
53
      mass = MASS_NEUTRON_EV;
54
    case PDG_ELECTRON:
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
2,147,483,647✔
57
    default:
2,147,483,647✔
58
      mass = this->type().mass() * AMU_EV;
2,147,483,647✔
59
    }
60

61
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
62
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
63
           (this->E() + mass);
2,147,483,647✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
66
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
69
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
70
  }
71
}
72

73
bool Particle::create_secondary(
112,513,085✔
74
  double wgt, Direction u, double E, ParticleType type)
75
{
76
  // If energy is below cutoff for this particle, don't create secondary
77
  // particle
78
  int idx = type.transport_index();
112,513,085✔
79
  if (idx == C_NONE) {
112,513,085!
80
    return false;
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
112,513,085✔
83
    return false;
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
58,709,553✔
88

89
  auto& bank = secondary_bank().emplace_back();
58,709,553✔
90
  bank.particle = type;
58,709,553✔
91
  bank.wgt = wgt;
58,709,553✔
92
  bank.r = r();
58,709,553!
93
  bank.u = u;
58,709,553✔
94
  bank.E = settings::run_CE ? E : g();
58,709,553!
95
  bank.time = time();
58,709,553✔
96
  bank_second_E() += bank.E;
58,709,553✔
97
  return true;
58,709,553✔
98
}
99

100
void Particle::split(double wgt)
4,250,165✔
101
{
102
  auto& bank = secondary_bank().emplace_back();
4,250,165✔
103
  bank.particle = type();
4,250,165✔
104
  bank.wgt = wgt;
4,250,165✔
105
  bank.r = r();
4,250,165✔
106
  bank.u = u();
4,250,165✔
107
  bank.E = settings::run_CE ? E() : g();
4,250,165✔
108
  bank.time = time();
4,250,165✔
109

110
  // Convert signed index to a signed surface ID
111
  if (surface() == SURFACE_NONE) {
4,250,165✔
112
    bank.surf_id = SURFACE_NONE;
4,249,620✔
113
  } else {
114
    int surf_id = model::surfaces[surface_index()]->id_;
545✔
115
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
545✔
116
  }
117
}
4,250,165✔
118

119
void Particle::from_source(const SourceSite* src)
240,638,721✔
120
{
121
  // Reset some attributes
122
  clear();
240,638,721✔
123
  surface() = SURFACE_NONE;
240,638,721✔
124
  cell_born() = C_NONE;
240,638,721✔
125
  material() = C_NONE;
240,638,721✔
126
  n_collision() = 0;
240,638,721✔
127
  fission() = false;
240,638,721✔
128
  zero_flux_derivs();
240,638,721✔
129
  lifetime() = 0.0;
240,638,721✔
130
#ifdef OPENMC_DAGMC_ENABLED
131
  history().reset();
22,040,180✔
132
#endif
133

134
  // Copy attributes from source bank site
135
  type() = src->particle;
240,638,721✔
136
  wgt() = src->wgt;
240,638,721✔
137
  wgt_last() = src->wgt;
240,638,721✔
138
  r() = src->r;
240,638,721✔
139
  u() = src->u;
240,638,721✔
140
  r_born() = src->r;
240,638,721✔
141
  r_last_current() = src->r;
240,638,721✔
142
  r_last() = src->r;
240,638,721✔
143
  u_last() = src->u;
240,638,721✔
144
  if (settings::run_CE) {
240,638,721✔
145
    E() = src->E;
124,713,104✔
146
    g() = 0;
124,713,104✔
147
  } else {
148
    g() = static_cast<int>(src->E);
115,925,617✔
149
    g_last() = static_cast<int>(src->E);
115,925,617✔
150
    E() = data::mg.energy_bin_avg_[g()];
115,925,617✔
151
  }
152
  E_last() = E();
240,638,721✔
153
  time() = src->time;
240,638,721✔
154
  time_last() = src->time;
240,638,721✔
155
  parent_nuclide() = src->parent_nuclide;
240,638,721✔
156
  delayed_group() = src->delayed_group;
240,638,721✔
157

158
  // Convert signed surface ID to signed index
159
  if (src->surf_id != SURFACE_NONE) {
240,638,721✔
160
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,545✔
161
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,545✔
162
  }
163
}
240,638,721✔
164

165
void Particle::event_calculate_xs()
2,147,483,647✔
166
{
167
  // Set the random number stream
168
  stream() = STREAM_TRACKING;
2,147,483,647✔
169

170
  // Store pre-collision particle properties
171
  wgt_last() = wgt();
2,147,483,647✔
172
  E_last() = E();
2,147,483,647✔
173
  u_last() = u();
2,147,483,647✔
174
  r_last() = r();
2,147,483,647✔
175
  time_last() = time();
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)) {
231,967,812!
182
      mark_as_lost(
×
183
        "Could not find the cell containing particle " + std::to_string(id()));
×
184
      return;
×
185
    }
186

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
231,967,812!
189
      cell_born() = lowest_coord().cell();
231,967,812✔
190
  }
191

192
  // Initialize last cells from current cell
193
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
194
    cell_last(j) = coord(j).cell();
2,147,483,647✔
195
  }
196
  n_coord_last() = n_coord();
2,147,483,647✔
197

198
  // Reset event variables
199
  event() = TallyEvent::KILL;
2,147,483,647✔
200
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
201
  event_mt() = REACTION_NONE;
2,147,483,647✔
202

203
  // Write particle track.
204
  if (write_track())
2,147,483,647✔
205
    write_particle_track(*this);
10,309✔
206

207
  if (settings::check_overlaps)
2,147,483,647!
208
    check_cell_overlap(*this);
×
209

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

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
2,063,937,414✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
111,838,536✔
231
    macro_xs().absorption = 0.0;
111,838,536✔
232
    macro_xs().fission = 0.0;
111,838,536✔
233
    macro_xs().nu_fission = 0.0;
111,838,536✔
234
  }
235

236
  // Initialize last material from current material
237
  material_last() = material();
2,147,483,647✔
238
}
239

240
void Particle::event_advance()
2,147,483,647✔
241
{
242
  // Find the distance to the nearest boundary
243
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
244

245
  // Sample a distance to collision
246
  if (type() == ParticleType::electron() ||
2,147,483,647✔
247
      type() == ParticleType::positron()) {
2,147,483,647✔
248
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
107,912,018!
249
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
250
    collision_distance() = INFINITY;
111,838,536✔
251
  } else {
252
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
253
  }
254

255
  double speed = this->speed();
2,147,483,647✔
256
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
257
  double distance_cutoff =
2,147,483,647✔
258
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
259

260
  // Select smaller of the three distances
261
  double distance =
2,147,483,647✔
262
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
263

264
  // Advance particle in space and time
265
  this->move_distance(distance);
2,147,483,647✔
266
  double dt = distance / speed;
2,147,483,647✔
267
  this->time() += dt;
2,147,483,647✔
268
  this->lifetime() += dt;
2,147,483,647✔
269

270
  // Score timed track-length tallies
271
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
272
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
273
  }
274

275
  // Score track-length tallies
276
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
277
    score_tracklength_tally(*this, distance);
1,722,164,847✔
278
  }
279

280
  // Score track-length estimate of k-eff
281
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
282
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
283
  }
284

285
  // Score flux derivative accumulators for differential tallies.
286
  if (!model::active_tallies.empty()) {
2,147,483,647✔
287
    score_track_derivative(*this, distance);
1,892,038,505✔
288
  }
289

290
  // Set particle weight to zero if it hit the time boundary
291
  if (distance == distance_cutoff) {
2,147,483,647✔
292
    wgt() = 0.0;
224,928✔
293
  }
294
}
2,147,483,647✔
295

296
void Particle::event_cross_surface()
2,147,483,647✔
297
{
298
  // Saving previous cell data
299
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
300
    cell_last(j) = coord(j).cell();
2,147,483,647✔
301
  }
302
  n_coord_last() = n_coord();
2,147,483,647✔
303

304
  // Saving previous material data
305
  material_last() = material();
2,147,483,647✔
306

307
  // Set surface that particle is on and adjust coordinate levels
308
  surface() = boundary().surface();
2,147,483,647✔
309
  n_coord() = boundary().coord_level();
2,147,483,647✔
310

311
  const auto& surf {*model::surfaces[surface_index()].get()};
2,147,483,647✔
312

313
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
314
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
315
      boundary().lattice_translation()[2] != 0) {
1,860,115,562✔
316
    // Particle crosses lattice boundary
317

318
    bool verbose = settings::verbosity >= 10 || trace();
750,250,842!
319
    cross_lattice(*this, boundary(), verbose);
750,250,842✔
320
    event() = TallyEvent::LATTICE;
750,250,842✔
321
  } else {
322
    // Particle crosses surface
323
    // If BC, add particle to surface source before crossing surface
324
    if (surf.surf_source_ && surf.bc_) {
1,671,573,709✔
325
      add_surf_source_to_bank(*this, surf);
720,325,114✔
326
    }
327
    this->cross_surface(surf);
1,671,573,709✔
328
    // If no BC, add particle to surface source after crossing surface
329
    if (surf.surf_source_ && !surf.bc_) {
1,671,573,700✔
330
      add_surf_source_to_bank(*this, surf);
950,010,759✔
331
    }
332
    if (settings::weight_window_checkpoint_surface) {
1,671,573,700✔
333
      apply_weight_windows(*this);
74,912✔
334
    }
335
    event() = TallyEvent::SURFACE;
1,671,573,700✔
336
  }
337
  // Score cell to cell partial currents
338
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
339
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,954,711✔
340
  }
341
}
2,147,483,647✔
342

343
void Particle::event_collide()
2,147,483,647✔
344
{
345

346
  // Score collision estimate of keff
347
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
348
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,139,390,631✔
349
  }
350

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

355
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
356
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
357

358
  // Clear surface component
359
  surface() = SURFACE_NONE;
2,147,483,647✔
360

361
  if (settings::run_CE) {
2,147,483,647✔
362
    collision(*this);
1,071,147,019✔
363
  } else {
364
    collision_mg(*this);
1,783,060,477✔
365
  }
366

367
  // Collision track feature to recording particle interaction
368
  if (settings::collision_track) {
2,147,483,647✔
369
    collision_track_record(*this);
150,087✔
370
  }
371

372
  // Score collision estimator tallies -- this is done after a collision
373
  // has occurred rather than before because we need information on the
374
  // outgoing energy for any tallies with an outgoing energy filter
375
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
376
    score_collision_tally(*this);
107,395,546✔
377
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
378
    if (settings::run_CE) {
406,034,945✔
379
      score_analog_tally_ce(*this);
404,826,683✔
380
    } else {
381
      score_analog_tally_mg(*this);
1,208,262✔
382
    }
383
  }
384

385
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
386
    pht_collision_energy();
2,024✔
387
  }
388

389
  // Reset banked weight during collision
390
  n_bank() = 0;
2,147,483,647✔
391
  bank_second_E() = 0.0;
2,147,483,647✔
392
  wgt_bank() = 0.0;
2,147,483,647✔
393

394
  // Clear number of secondaries in this collision. This is
395
  // distinct from the number of created neutrons n_bank() above!
396
  n_secondaries() = 0;
2,147,483,647✔
397

398
  zero_delayed_bank();
2,147,483,647✔
399

400
  // Reset fission logical
401
  fission() = false;
2,147,483,647✔
402

403
  // Save coordinates for tallying purposes
404
  r_last_current() = r();
2,147,483,647✔
405

406
  // Set last material to none since cross sections will need to be
407
  // re-evaluated
408
  material_last() = C_NONE;
2,147,483,647✔
409

410
  // Set all directions to base level -- right now, after a collision, only
411
  // the base level directions are changed
412
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
413
    if (coord(j + 1).rotated()) {
161,247,365✔
414
      // If next level is rotated, apply rotation matrix
415
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
416
      const auto& u {coord(j).u()};
417
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
418
    } else {
419
      // Otherwise, copy this level's direction
420
      coord(j + 1).u() = coord(j).u();
150,820,751✔
421
    }
422
  }
423

424
  // Score flux derivative accumulators for differential tallies.
425
  if (!model::active_tallies.empty())
2,147,483,647✔
426
    score_collision_derivative(*this);
936,534,023✔
427

428
#ifdef OPENMC_DAGMC_ENABLED
429
  history().reset();
261,796,259✔
430
#endif
431
}
2,147,483,647✔
432

433
void Particle::event_revive_from_secondary()
2,147,483,647✔
434
{
435
  // If particle has too many events, display warning and kill it
436
  ++n_event();
2,147,483,647✔
437
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
438
    warning("Particle " + std::to_string(id()) +
×
439
            " underwent maximum number of events.");
440
    wgt() = 0.0;
×
441
  }
442

443
  // Check for secondary particles if this particle is dead
444
  if (!alive()) {
2,147,483,647✔
445
    // Write final position for this particle
446
    if (write_track()) {
231,967,408✔
447
      write_particle_track(*this);
6,244✔
448
    }
449

450
    // If no secondary particles, break out of event loop
451
    if (secondary_bank().empty())
231,967,408✔
452
      return;
453

454
    from_source(&secondary_bank().back());
63,163,237✔
455
    secondary_bank().pop_back();
63,163,237✔
456
    n_event() = 0;
63,163,237✔
457
    bank_second_E() = 0.0;
63,163,237✔
458

459
    // Subtract secondary particle energy from interim pulse-height results
460
    if (!model::active_pulse_height_tallies.empty() &&
63,163,237✔
461
        this->type().is_photon()) {
15,499✔
462
      // Since the birth cell of the particle has not been set we
463
      // have to determine it before the energy of the secondary particle can be
464
      // removed from the pulse-height of this cell.
465
      if (lowest_coord().cell() == C_NONE) {
605!
466
        bool verbose = settings::verbosity >= 10 || trace();
605!
467
        if (!exhaustive_find_cell(*this, verbose)) {
605!
468
          mark_as_lost("Could not find the cell containing particle " +
×
469
                       std::to_string(id()));
×
470
          return;
×
471
        }
472
        // Set birth cell attribute
473
        if (cell_born() == C_NONE)
605!
474
          cell_born() = lowest_coord().cell();
605✔
475

476
        // Initialize last cells from current cell
477
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
478
          cell_last(j) = coord(j).cell();
605✔
479
        }
480
        n_coord_last() = n_coord();
605✔
481
      }
482
      pht_secondary_particles();
605✔
483
    }
484

485
    // Enter new particle in particle track file
486
    if (write_track())
63,163,237✔
487
      add_particle_track(*this);
5,234✔
488
  }
489
}
490

491
void Particle::event_death()
168,805,171✔
492
{
493
#ifdef OPENMC_DAGMC_ENABLED
494
  history().reset();
15,422,585✔
495
#endif
496

497
  // Finish particle track output.
498
  if (write_track()) {
168,805,171✔
499
    finalize_particle_track(*this);
1,010✔
500
  }
501

502
// Contribute tally reduction variables to global accumulator
503
#pragma omp atomic
93,093,877✔
504
  global_tally_absorption += keff_tally_absorption();
168,805,171✔
505
#pragma omp atomic
93,187,364✔
506
  global_tally_collision += keff_tally_collision();
168,805,171✔
507
#pragma omp atomic
93,048,493✔
508
  global_tally_tracklength += keff_tally_tracklength();
168,805,171✔
509
#pragma omp atomic
92,499,237✔
510
  global_tally_leakage += keff_tally_leakage();
168,805,171✔
511

512
  // Reset particle tallies once accumulated
513
  keff_tally_absorption() = 0.0;
168,805,171✔
514
  keff_tally_collision() = 0.0;
168,805,171✔
515
  keff_tally_tracklength() = 0.0;
168,805,171✔
516
  keff_tally_leakage() = 0.0;
168,805,171✔
517

518
  if (!model::active_pulse_height_tallies.empty()) {
168,805,171✔
519
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
520
  }
521

522
  // Record the number of progeny created by this particle.
523
  // This data will be used to efficiently sort the fission bank.
524
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,805,171✔
525
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,534,700✔
526
    simulation::progeny_per_particle[offset] = n_progeny();
141,534,700✔
527
  }
528
}
168,805,171✔
529

530
void Particle::pht_collision_energy()
2,024✔
531
{
532
  // Adds the energy particles lose in a collision to the pulse-height
533

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

538
  if (it != model::pulse_height_cells.end()) {
2,024!
539
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
540
    pht_storage()[index] += E_last() - E();
2,024✔
541

542
    // If the energy of the particle is below the cutoff, it will not be sampled
543
    // so its energy is added to the pulse-height in the cell
544
    int photon = ParticleType::photon().transport_index();
2,024✔
545
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
546
      pht_storage()[index] += E();
825✔
547
    }
548
  }
549
}
2,024✔
550

551
void Particle::pht_secondary_particles()
605✔
552
{
553
  // Removes the energy of secondary produced particles from the pulse-height
554

555
  // determine index of cell in pulse_height_cells
556
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
557
    model::pulse_height_cells.end(), cell_born());
605!
558

559
  if (it != model::pulse_height_cells.end()) {
605!
560
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
561
    pht_storage()[index] -= E();
605✔
562
  }
563
}
605✔
564

565
void Particle::cross_surface(const Surface& surf)
1,673,478,383✔
566
{
567

568
  if (settings::verbosity >= 10 || trace()) {
1,673,478,383✔
569
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
570
  }
571

572
// if we're crossing a CSG surface, make sure the DAG history is reset
573
#ifdef OPENMC_DAGMC_ENABLED
574
  if (surf.geom_type() == GeometryType::CSG)
152,812,478✔
575
    history().reset();
152,755,319✔
576
#endif
577

578
  // Handle any applicable boundary conditions.
579
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,478,383!
580
      settings::run_mode != RunMode::VOLUME) {
581
    surf.bc_->handle_particle(*this, surf);
720,677,222✔
582
    return;
720,677,222✔
583
  }
584

585
  // ==========================================================================
586
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
587

588
#ifdef OPENMC_DAGMC_ENABLED
589
  // in DAGMC, we know what the next cell should be
590
  if (surf.geom_type() == GeometryType::DAG) {
86,855,098✔
591
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
592
                       lowest_coord().universe()) -
46,350✔
593
                     1;
46,350✔
594
    // save material, temperature, and density multiplier
595
    material_last() = material();
46,350✔
596
    sqrtkT_last() = sqrtkT();
46,350✔
597
    density_mult_last() = density_mult();
46,350✔
598
    // set new cell value
599
    lowest_coord().cell() = i_cell;
46,350✔
600
    auto& cell = model::cells[i_cell];
46,350✔
601

602
    cell_instance() = 0;
46,350✔
603
    if (cell->distribcell_index_ >= 0)
46,350✔
604
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
605

606
    material() = cell->material(cell_instance());
46,350!
607
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
608
    density_mult() = cell->density_mult(cell_instance());
46,350✔
609
    return;
46,350✔
610
  }
611
#endif
612

613
  bool verbose = settings::verbosity >= 10 || trace();
952,754,811!
614
  if (neighbor_list_find_cell(*this, verbose)) {
952,754,811✔
615
    return;
616
  }
617

618
  // ==========================================================================
619
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
620

621
  // Remove lower coordinate levels
622
  n_coord() = 1;
29,911✔
623
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
624

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

631
    surface() = SURFACE_NONE;
5,799✔
632
    n_coord() = 1;
5,799✔
633
    r() += TINY_BIT * u();
5,799✔
634

635
    // Couldn't find next cell anywhere! This probably means there is an actual
636
    // undefined region in the geometry.
637

638
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
639
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
640
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
641
                   " it could not be located in any cell and it did not leak.");
642
      return;
5,790✔
643
    }
644
  }
645
}
646

647
void Particle::cross_vacuum_bc(const Surface& surf)
35,102,044✔
648
{
649
  // Score any surface current tallies -- note that the particle is moved
650
  // forward slightly so that if the mesh boundary is on the surface, it is
651
  // still processed
652

653
  if (!model::active_meshsurf_tallies.empty()) {
35,102,044✔
654
    // TODO: Find a better solution to score surface currents than
655
    // physically moving the particle forward slightly
656

657
    r() += TINY_BIT * u();
937,222✔
658
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
659
  }
660

661
  // Score to global leakage tally
662
  keff_tally_leakage() += wgt();
35,102,044✔
663

664
  // Kill the particle
665
  wgt() = 0.0;
35,102,044✔
666

667
  // Display message
668
  if (settings::verbosity >= 10 || trace()) {
35,102,044!
669
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
670
  }
671
}
35,102,044✔
672

673
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,336,305✔
674
{
675
  // Do not handle reflective boundary conditions on lower universes
676
  if (n_coord() != 1) {
684,336,305!
677
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
678
                 " off surface in a lower universe.");
679
    return;
×
680
  }
681

682
  // Score surface currents since reflection causes the direction of the
683
  // particle to change. For surface filters, we need to score the tallies
684
  // twice, once before the particle's surface attribute has changed and
685
  // once after. For mesh surface filters, we need to artificially move
686
  // the particle slightly back in case the surface crossing is coincident
687
  // with a mesh boundary
688

689
  if (!model::active_surface_tallies.empty()) {
684,336,305✔
690
    score_surface_tally(*this, model::active_surface_tallies, surf);
302,423✔
691
  }
692

693
  if (!model::active_meshsurf_tallies.empty()) {
684,336,305✔
694
    Position r {this->r()};
46,885,487✔
695
    this->r() -= TINY_BIT * u();
46,885,487✔
696
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
697
    this->r() = r;
46,885,487✔
698
  }
699

700
  // Set the new particle direction
701
  u() = new_u;
684,336,305✔
702

703
  // Reassign particle's cell and surface
704
  coord(0).cell() = cell_last(0);
684,336,305✔
705
  surface() = -surface();
684,336,305✔
706

707
  // If a reflective surface is coincident with a lattice or universe
708
  // boundary, it is necessary to redetermine the particle's coordinates in
709
  // the lower universes.
710
  // (unless we're using a dagmc model, which has exactly one universe)
711
  n_coord() = 1;
684,336,305✔
712
  if (surf.geom_type() != GeometryType::DAG &&
1,368,669,852!
713
      !neighbor_list_find_cell(*this)) {
684,333,547✔
NEW
714
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
715
                 std::to_string(surf.id_) + ".");
×
NEW
716
    return;
×
717
  }
718

719
  // Set previous coordinate going slightly past surface crossing
720
  r_last_current() = r() + TINY_BIT * u();
684,336,305✔
721

722
  // Diagnostic message
723
  if (settings::verbosity >= 10 || trace()) {
684,336,305!
724
    write_message(1, "    Reflected from surface {}", surf.id_);
×
725
  }
726
}
727

728
void Particle::cross_periodic_bc(
2,244,339✔
729
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
730
{
731
  // Do not handle periodic boundary conditions on lower universes
732
  if (n_coord() != 1) {
2,244,339!
733
    mark_as_lost(
×
734
      "Cannot transfer particle " + std::to_string(id()) +
×
735
      " across surface in a lower universe. Boundary conditions must be "
736
      "applied to root universe.");
737
    return;
×
738
  }
739

740
  // Score surface currents since reflection causes the direction of the
741
  // particle to change -- artificially move the particle slightly back in
742
  // case the surface crossing is coincident with a mesh boundary
743
  if (!model::active_meshsurf_tallies.empty()) {
2,244,339!
744
    Position r {this->r()};
×
745
    this->r() -= TINY_BIT * u();
×
746
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
747
    this->r() = r;
×
748
  }
749

750
  // Adjust the particle's location and direction.
751
  r() = new_r;
2,244,339✔
752
  u() = new_u;
2,244,339✔
753

754
  // Reassign particle's surface
755
  surface() = new_surface;
2,244,339✔
756

757
  // Figure out what cell particle is in now
758
  n_coord() = 1;
2,244,339✔
759

760
  if (!neighbor_list_find_cell(*this)) {
2,244,339!
761
    mark_as_lost("Couldn't find particle after hitting periodic "
×
762
                 "boundary on surface " +
×
763
                 std::to_string(surf.id_) + ".");
×
764
    return;
×
765
  }
766

767
  // Set previous coordinate going slightly past surface crossing
768
  r_last_current() = r() + TINY_BIT * u();
2,244,339✔
769

770
  // Diagnostic message
771
  if (settings::verbosity >= 10 || trace()) {
2,244,339!
772
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
773
  }
774
}
775

776
void Particle::mark_as_lost(const char* message)
5,799✔
777
{
778
  // Print warning and write lost particle file
779
  warning(message);
5,799✔
780
  if (settings::max_write_lost_particles < 0 ||
5,799✔
781
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
782
    write_restart();
374✔
783
  }
784
  // Increment number of lost particles
785
  wgt() = 0.0;
5,799✔
786
#pragma omp atomic
3,154✔
787
  simulation::n_lost_particles += 1;
2,645✔
788

789
  // Count the total number of simulated particles (on this processor)
790
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
791
           simulation::work_per_rank;
792

793
  // Abort the simulation if the maximum number of lost particles has been
794
  // reached
795
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
796
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
797
    fatal_error("Maximum number of lost particles has been reached.");
9✔
798
  }
799
}
5,790✔
800

801
void Particle::write_restart() const
374✔
802
{
803
  // Dont write another restart file if in particle restart mode
804
  if (settings::run_mode == RunMode::PARTICLE)
374✔
805
    return;
22✔
806

807
  // Set up file name
808
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
809
    simulation::current_batch, id());
352✔
810

811
#pragma omp critical(WriteParticleRestart)
187✔
812
  {
352✔
813
    // Create file
814
    hid_t file_id = file_open(filename, 'w');
352✔
815

816
    // Write filetype and version info
817
    write_attribute(file_id, "filetype", "particle restart");
352✔
818
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
819
    write_attribute(file_id, "openmc_version", VERSION);
352✔
820
#ifdef GIT_SHA1
821
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
822
#endif
823

824
    // Write data to file
825
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
826
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
827
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
828
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
829
    switch (settings::run_mode) {
352!
830
    case RunMode::FIXED_SOURCE:
220✔
831
      write_dataset(file_id, "run_mode", "fixed source");
220✔
832
      break;
115✔
833
    case RunMode::EIGENVALUE:
132✔
834
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
835
      break;
72✔
836
    case RunMode::PARTICLE:
×
837
      write_dataset(file_id, "run_mode", "particle restart");
×
838
      break;
839
    default:
840
      break;
841
    }
842
    write_dataset(file_id, "id", id());
352✔
843
    write_dataset(file_id, "type", type().pdg_number());
352✔
844

845
    int64_t i = current_work();
352✔
846
    if (settings::run_mode == RunMode::EIGENVALUE) {
352✔
847
      // take source data from primary bank for eigenvalue simulation
848
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
849
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
850
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
851
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
852
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
853
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
220!
854
      // re-sample using rng random number seed used to generate source particle
855
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
220✔
856
                     settings::n_particles +
220✔
857
                   simulation::work_index[mpi::rank] + i;
220✔
858
      uint64_t seed = init_seed(id, STREAM_SOURCE);
220✔
859
      // re-sample source site
860
      auto site = sample_external_source(&seed);
220✔
861
      write_dataset(file_id, "weight", site.wgt);
220✔
862
      write_dataset(file_id, "energy", site.E);
220✔
863
      write_dataset(file_id, "xyz", site.r);
220✔
864
      write_dataset(file_id, "uvw", site.u);
220✔
865
      write_dataset(file_id, "time", site.time);
220✔
866
    }
867

868
    // Close file
869
    file_close(file_id);
352✔
870
  } // #pragma omp critical
871
}
352✔
872

873
void Particle::update_neutron_xs(
2,147,483,647✔
874
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
875
{
876
  // Get microscopic cross section cache
877
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
878

879
  // If the cache doesn't match, recalculate micro xs
880
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
881
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
882
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
883
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
884

885
    // If NCrystal is being used, update micro cross section cache
886
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
887
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
888
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
889
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
890
    }
891
  }
892
}
2,147,483,647✔
893

894
//==============================================================================
895
// Non-method functions
896
//==============================================================================
897
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,670,335,873✔
898
{
899
  if (simulation::current_batch <= settings::n_inactive ||
1,670,335,873✔
900
      simulation::surf_source_bank.full()) {
1,284,866,913✔
901
    return;
1,670,206,220✔
902
  }
903

904
  // If a cell/cellfrom/cellto parameter is defined
905
  if (settings::ssw_cell_id != C_NONE) {
337,077✔
906

907
    // Retrieve cell index and storage type
908
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,432✔
909

910
    if (surf.bc_) {
254,432✔
911
      // Leave if cellto with vacuum boundary condition
912
      if (surf.bc_->type() == "vacuum" &&
298,916✔
913
          settings::ssw_cell_type == SSWCellType::To) {
33,098✔
914
        return;
915
      }
916

917
      // Leave if other boundary condition than vacuum
918
      if (surf.bc_->type() != "vacuum") {
274,646✔
919
        return;
920
      }
921
    }
922

923
    // Check if the cell of interest has been exited
924
    bool exited = false;
925
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,663✔
926
      if (p.cell_last(i) == cell_idx) {
207,726✔
927
        exited = true;
73,762✔
928
      }
929
    }
930

931
    // Check if the cell of interest has been entered
932
    bool entered = false;
933
    for (int i = 0; i < p.n_coord(); ++i) {
297,965✔
934
      if (p.coord(i).cell() == cell_idx) {
172,028✔
935
        entered = true;
57,516✔
936
      }
937
    }
938

939
    // Vacuum boundary conditions: return if cell is not exited
940
    if (surf.bc_) {
125,937✔
941
      if (surf.bc_->type() == "vacuum" && !exited) {
41,926!
942
        return;
943
      }
944
    } else {
945

946
      // If we both enter and exit the cell of interest
947
      if (entered && exited) {
104,974✔
948
        return;
949
      }
950

951
      // If we did not enter nor exit the cell of interest
952
      if (!entered && !exited) {
77,771✔
953
        return;
954
      }
955

956
      // If cellfrom and the cell before crossing is not the cell of
957
      // interest
958
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,272✔
959
        return;
960
      }
961

962
      // If cellto and the cell after crossing is not the cell of interest
963
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,730✔
964
        return;
965
      }
966
    }
967
  }
968

969
  SourceSite site;
129,653✔
970
  site.r = p.r();
129,653✔
971
  site.u = p.u();
129,653✔
972
  site.E = p.E();
129,653✔
973
  site.time = p.time();
129,653✔
974
  site.wgt = p.wgt();
129,653✔
975
  site.delayed_group = p.delayed_group();
129,653✔
976
  site.surf_id = surf.id_;
129,653✔
977
  site.particle = p.type();
129,653✔
978
  site.parent_id = p.id();
129,653✔
979
  site.progeny_id = p.n_progeny();
129,653✔
980
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
981
}
982

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