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

openmc-dev / openmc / 21489819490

29 Jan 2026 06:21PM UTC coverage: 80.077% (-1.9%) from 81.953%
21489819490

Pull #3757

github

web-flow
Merge d08626053 into f7a734189
Pull Request #3757: Testing point detectors

16004 of 22621 branches covered (70.75%)

Branch coverage included in aggregate %.

94 of 518 new or added lines in 26 files covered. (18.15%)

1021 existing lines in 52 files now uncovered.

53779 of 64524 relevant lines covered (83.35%)

8016833.26 hits per line

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

76.95
/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::mass() const
191,064,718✔
47
{
48
  // Determine mass in eV/c^2
49
  switch (this->type()) {
191,064,718!
50
  case ParticleType::neutron:
184,220,784✔
51
    return MASS_NEUTRON_EV;
184,220,784✔
52
  case ParticleType::photon:
1,982,883✔
53
    return 0.0;
1,982,883✔
54
  case ParticleType::electron:
4,861,051✔
55
  case ParticleType::positron:
56
    return MASS_ELECTRON_EV;
4,861,051✔
57
  }
NEW
58
  UNREACHABLE();
×
59
}
60

61
double Particle::speed() const
378,695,392✔
62
{
63
  if (settings::run_CE) {
378,695,392✔
64
    double mass = this->mass();
191,064,718✔
65
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
66
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
191,064,718✔
67
           (this->E() + mass);
191,064,718✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
187,630,674✔
70
    int macro_t = this->mg_xs_cache().t;
187,630,674✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
187,630,674✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
187,630,674✔
73
                   nullptr, nullptr, macro_t, macro_a);
187,630,674✔
74
  }
75
}
76

77
bool Particle::create_secondary(
10,138,784✔
78
  double wgt, Direction u, double E, ParticleType type)
79
{
80
  // If energy is below cutoff for this particle, don't create secondary
81
  // particle
82
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
10,138,784✔
83
    return false;
4,847,149✔
84
  }
85

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

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

107
  // Convert signed index to a signed surface ID
108
  if (surface() == SURFACE_NONE) {
371,452!
109
    bank.surf_id = SURFACE_NONE;
371,452✔
110
  } else {
UNCOV
111
    int surf_id = model::surfaces[surface_index()]->id_;
×
UNCOV
112
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
×
113
  }
114
}
371,452✔
115

116
void Particle::from_source(const SourceSite* src)
21,608,539✔
117
{
118
  // Reset some attributes
119
  clear();
21,608,539✔
120
  surface() = SURFACE_NONE;
21,608,539✔
121
  cell_born() = C_NONE;
21,608,539✔
122
  material() = C_NONE;
21,608,539✔
123
  n_collision() = 0;
21,608,539✔
124
  fission() = false;
21,608,539✔
125
  zero_flux_derivs();
21,608,539✔
126
  lifetime() = 0.0;
21,608,539✔
127
#ifdef OPENMC_DAGMC_ENABLED
128
  history().reset();
129
#endif
130

131
  // Copy attributes from source bank site
132
  type() = src->particle;
21,608,539✔
133
  wgt() = src->wgt;
21,608,539✔
134
  wgt_last() = src->wgt;
21,608,539✔
135
  r() = src->r;
21,608,539✔
136
  u() = src->u;
21,608,539✔
137
  r_born() = src->r;
21,608,539✔
138
  r_last_current() = src->r;
21,608,539✔
139
  r_last() = src->r;
21,608,539✔
140
  u_last() = src->u;
21,608,539✔
141
  if (settings::run_CE) {
21,608,539✔
142
    E() = src->E;
11,086,912✔
143
    g() = 0;
11,086,912✔
144
  } else {
145
    g() = static_cast<int>(src->E);
10,521,627✔
146
    g_last() = static_cast<int>(src->E);
10,521,627✔
147
    E() = data::mg.energy_bin_avg_[g()];
10,521,627✔
148
  }
149
  E_last() = E();
21,608,539✔
150
  time() = src->time;
21,608,539✔
151
  time_last() = src->time;
21,608,539✔
152
  parent_nuclide() = src->parent_nuclide;
21,608,539✔
153
  delayed_group() = src->delayed_group;
21,608,539✔
154

155
  // Convert signed surface ID to signed index
156
  if (src->surf_id != SURFACE_NONE) {
21,608,539✔
157
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
10,000✔
158
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
10,000!
159
  }
160
}
21,608,539✔
161

NEW
162
void Particle::initialize_pseudoparticle(
×
163
  Particle& p, Direction u_new, double E_new)
164
{
165
  // Reset some attributes
NEW
166
  clear();
×
NEW
167
  surface() = SURFACE_NONE;
×
NEW
168
  cell_born() = C_NONE;
×
NEW
169
  material() = C_NONE;
×
NEW
170
  n_collision() = 0;
×
NEW
171
  fission() = false;
×
NEW
172
  zero_flux_derivs();
×
NEW
173
  lifetime() = 0.0;
×
174

175
  // Copy attributes from particle
NEW
176
  type() = p.type();
×
NEW
177
  wgt() = p.wgt();
×
NEW
178
  wgt_last() = p.wgt();
×
NEW
179
  r() = p.r();
×
NEW
180
  u() = u_new;
×
NEW
181
  r_born() = p.r();
×
NEW
182
  r_last_current() = p.r();
×
NEW
183
  r_last() = p.r();
×
NEW
184
  u_last() = p.u();
×
NEW
185
  if (settings::run_CE) {
×
NEW
186
    E() = E_new;
×
NEW
187
    g() = 0;
×
188
  } else {
NEW
189
    g() = static_cast<int>(E_new);
×
NEW
190
    g_last() = static_cast<int>(E_new);
×
NEW
191
    E() = data::mg.energy_bin_avg_[g()];
×
192
  }
NEW
193
  E_last() = E();
×
NEW
194
  time() = p.time();
×
NEW
195
  time_last() = p.time();
×
NEW
196
}
×
197

198
void Particle::event_calculate_xs()
376,200,241✔
199
{
200
  // Set the random number stream
201
  stream() = STREAM_TRACKING;
376,200,241✔
202

203
  // Store pre-collision particle properties
204
  wgt_last() = wgt();
376,200,241✔
205
  E_last() = E();
376,200,241✔
206
  u_last() = u();
376,200,241✔
207
  r_last() = r();
376,200,241✔
208
  time_last() = time();
376,200,241✔
209

210
  // Reset event variables
211
  event() = TallyEvent::KILL;
376,200,241✔
212
  event_nuclide() = NUCLIDE_NONE;
376,200,241✔
213
  event_mt() = REACTION_NONE;
376,200,241✔
214

215
  // If the cell hasn't been determined based on the particle's location,
216
  // initiate a search for the current cell. This generally happens at the
217
  // beginning of the history and again for any secondary particles
218
  if (lowest_coord().cell() == C_NONE) {
376,200,241✔
219
    if (!exhaustive_find_cell(*this)) {
20,837,340!
220
      mark_as_lost(
×
221
        "Could not find the cell containing particle " + std::to_string(id()));
×
222
      return;
×
223
    }
224

225
    // Set birth cell attribute
226
    if (cell_born() == C_NONE)
20,837,340!
227
      cell_born() = lowest_coord().cell();
20,837,340✔
228

229
    // Initialize last cells from current cell
230
    for (int j = 0; j < n_coord(); ++j) {
43,224,618✔
231
      cell_last(j) = coord(j).cell();
22,387,278✔
232
    }
233
    n_coord_last() = n_coord();
20,837,340✔
234
  }
235

236
  // Write particle track.
237
  if (write_track())
376,200,241✔
238
    write_particle_track(*this);
753✔
239

240
  if (settings::check_overlaps)
376,200,241!
241
    check_cell_overlap(*this);
×
242

243
  // Calculate microscopic and macroscopic cross sections
244
  if (material() != MATERIAL_VOID) {
376,200,241✔
245
    if (settings::run_CE) {
366,034,810✔
246
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
210,462,566✔
247
          density_mult() != density_mult_last()) {
32,058,430✔
248
        // If the material is the same as the last material and the
249
        // temperature hasn't changed, we don't need to lookup cross
250
        // sections again.
251
        model::materials[material()]->calculate_xs(*this);
146,346,578✔
252
      }
253
    } else {
254
      // Get the MG data; unlike the CE case above, we have to re-calculate
255
      // cross sections for every collision since the cross sections may
256
      // be angle-dependent
257
      data::mg.macro_xs_[material()].calculate_xs(*this);
187,630,674✔
258

259
      // Update the particle's group while we know we are multi-group
260
      g_last() = g();
187,630,674✔
261
    }
262
  } else {
263
    macro_xs().total = 0.0;
10,165,431✔
264
    macro_xs().absorption = 0.0;
10,165,431✔
265
    macro_xs().fission = 0.0;
10,165,431✔
266
    macro_xs().nu_fission = 0.0;
10,165,431✔
267
  }
268
}
269

270
void Particle::event_advance()
376,200,241✔
271
{
272
  // Find the distance to the nearest boundary
273
  boundary() = distance_to_boundary(*this);
376,200,241✔
274

275
  // Sample a distance to collision
276
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
376,200,241✔
277
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
4,861,051!
278
  } else if (macro_xs().total == 0.0) {
371,339,190✔
279
    collision_distance() = INFINITY;
10,165,431✔
280
  } else {
281
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
361,173,759✔
282
  }
283

284
  double speed = this->speed();
376,200,241✔
285
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
376,200,241✔
286
  double distance_cutoff =
287
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
376,200,241✔
288

289
  // Select smaller of the three distances
290
  double distance =
291
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
376,200,241✔
292

293
  // Advance particle in space and time
294
  this->move_distance(distance);
376,200,241✔
295
  double dt = distance / speed;
376,200,241✔
296
  this->time() += dt;
376,200,241✔
297
  this->lifetime() += dt;
376,200,241✔
298

299
  // Score timed track-length tallies
300
  if (!model::active_timed_tracklength_tallies.empty()) {
376,200,241✔
301
    score_timed_tracklength_tally(*this, distance);
329,847✔
302
  }
303

304
  // Score track-length tallies
305
  if (!model::active_tracklength_tallies.empty()) {
376,200,241✔
306
    score_tracklength_tally(*this, distance);
141,376,060✔
307
  }
308

309
  // Score track-length estimate of k-eff
310
  if (settings::run_mode == RunMode::EIGENVALUE &&
690,929,132✔
311
      type() == ParticleType::neutron) {
314,728,891✔
312
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
311,100,492✔
313
  }
314

315
  // Score flux derivative accumulators for differential tallies.
316
  if (!model::active_tallies.empty()) {
376,200,241✔
317
    score_track_derivative(*this, distance);
156,336,863✔
318
  }
319

320
  // Set particle weight to zero if it hit the time boundary
321
  if (distance == distance_cutoff) {
376,200,241✔
322
    wgt() = 0.0;
20,448✔
323
  }
324
}
376,200,241✔
325

326
void Particle::event_cross_surface()
202,628,171✔
327
{
328
  // Saving previous cell data
329
  for (int j = 0; j < n_coord(); ++j) {
589,510,121✔
330
    cell_last(j) = coord(j).cell();
386,881,950✔
331
  }
332
  n_coord_last() = n_coord();
202,628,171✔
333

334
  // Set surface that particle is on and adjust coordinate levels
335
  surface() = boundary().surface();
202,628,171✔
336
  n_coord() = boundary().coord_level();
202,628,171✔
337

338
  if (boundary().lattice_translation()[0] != 0 ||
202,628,171✔
339
      boundary().lattice_translation()[1] != 0 ||
356,873,456✔
340
      boundary().lattice_translation()[2] != 0) {
154,245,285✔
341
    // Particle crosses lattice boundary
342

343
    bool verbose = settings::verbosity >= 10 || trace();
65,522,845!
344
    cross_lattice(*this, boundary(), verbose);
65,522,845✔
345
    event() = TallyEvent::LATTICE;
65,522,845✔
346
  } else {
347
    // Particle crosses surface
348
    const auto& surf {model::surfaces[surface_index()].get()};
137,105,326✔
349
    // If BC, add particle to surface source before crossing surface
350
    if (surf->surf_source_ && surf->bc_) {
137,105,326✔
351
      add_surf_source_to_bank(*this, *surf);
62,556,276✔
352
    }
353
    this->cross_surface(*surf);
137,105,326✔
354
    // If no BC, add particle to surface source after crossing surface
355
    if (surf->surf_source_ && !surf->bc_) {
137,105,325✔
356
      add_surf_source_to_bank(*this, *surf);
74,432,239✔
357
    }
358
    if (settings::weight_window_checkpoint_surface) {
137,105,325!
UNCOV
359
      apply_weight_windows(*this);
×
360
    }
361
    event() = TallyEvent::SURFACE;
137,105,325✔
362
  }
363
  // Score cell to cell partial currents
364
  if (!model::active_surface_tallies.empty()) {
202,628,170✔
365
    score_surface_tally(*this, model::active_surface_tallies);
3,174,797✔
366
  }
367
}
202,628,170✔
368

369
void Particle::event_collide()
247,730,818✔
370
{
371
  // Score collision estimate of keff
372
  if (settings::run_mode == RunMode::EIGENVALUE &&
444,596,740✔
373
      type() == ParticleType::neutron) {
196,865,922✔
374
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
193,239,144✔
375
  }
376

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

381
  if (!model::active_meshsurf_tallies.empty())
247,730,818✔
382
    score_surface_tally(*this, model::active_meshsurf_tallies);
5,736,266✔
383

384
  // Clear surface component
385
  surface() = SURFACE_NONE;
247,730,818✔
386

387
  if (settings::run_CE) {
247,730,818✔
388
    collision(*this);
85,634,411✔
389
  } else {
390
    collision_mg(*this);
162,096,407✔
391
  }
392

393
  // Collision track feature to recording particle interaction
394
  if (settings::collision_track) {
247,730,818✔
395
    collision_track_record(*this);
13,799✔
396
  }
397

398
  // Score collision estimator tallies -- this is done after a collision
399
  // has occurred rather than before because we need information on the
400
  // outgoing energy for any tallies with an outgoing energy filter
401
  if (!model::active_collision_tallies.empty())
247,730,818✔
402
    score_collision_tally(*this);
9,425,164✔
403
  if (!model::active_analog_tallies.empty()) {
247,730,818✔
404
    if (settings::run_CE) {
26,507,882✔
405
      score_analog_tally_ce(*this);
26,398,040✔
406
    } else {
407
      score_analog_tally_mg(*this);
109,842✔
408
    }
409
  }
410

411
  if (!model::active_pulse_height_tallies.empty() &&
247,732,356✔
412
      type() == ParticleType::photon) {
1,538✔
413
    pht_collision_energy();
184✔
414
  }
415

416
  // Reset banked weight during collision
417
  n_bank() = 0;
247,730,818✔
418
  bank_second_E() = 0.0;
247,730,818✔
419
  wgt_bank() = 0.0;
247,730,818✔
420
  zero_delayed_bank();
247,730,818✔
421

422
  // Reset fission logical
423
  fission() = false;
247,730,818✔
424

425
  // Save coordinates for tallying purposes
426
  r_last_current() = r();
247,730,818✔
427

428
  // Set last material to none since cross sections will need to be
429
  // re-evaluated
430
  material_last() = C_NONE;
247,730,818✔
431

432
  // Set all directions to base level -- right now, after a collision, only
433
  // the base level directions are changed
434
  for (int j = 0; j < n_coord() - 1; ++j) {
260,782,498✔
435
    if (coord(j + 1).rotated()) {
13,051,680✔
436
      // If next level is rotated, apply rotation matrix
437
      const auto& m {model::cells[coord(j).cell()]->rotation_};
947,874✔
438
      const auto& u {coord(j).u()};
947,874✔
439
      coord(j + 1).u() = u.rotate(m);
947,874✔
440
    } else {
441
      // Otherwise, copy this level's direction
442
      coord(j + 1).u() = coord(j).u();
12,103,806✔
443
    }
444
  }
445

446
  // Score flux derivative accumulators for differential tallies.
447
  if (!model::active_tallies.empty())
247,730,818✔
448
    score_collision_derivative(*this);
74,041,922✔
449

450
#ifdef OPENMC_DAGMC_ENABLED
451
  history().reset();
452
#endif
453
}
247,730,818✔
454

455
void Particle::event_revive_from_secondary()
376,200,240✔
456
{
457
  // If particle has too many events, display warning and kill it
458
  ++n_event();
376,200,240✔
459
  if (n_event() == settings::max_particle_events) {
376,200,240!
460
    warning("Particle " + std::to_string(id()) +
×
461
            " underwent maximum number of events.");
462
    wgt() = 0.0;
×
463
  }
464

465
  // Check for secondary particles if this particle is dead
466
  if (!alive()) {
376,200,240✔
467
    // Write final position for this particle
468
    if (write_track()) {
20,837,394✔
469
      write_particle_track(*this);
408✔
470
    }
471

472
    // If no secondary particles, break out of event loop
473
    if (secondary_bank().empty())
20,837,394✔
474
      return;
15,174,275✔
475

476
    from_source(&secondary_bank().back());
5,663,119✔
477
    secondary_bank().pop_back();
5,663,119✔
478
    n_event() = 0;
5,663,119✔
479
    bank_second_E() = 0.0;
5,663,119✔
480

481
    // Subtract secondary particle energy from interim pulse-height results
482
    if (!model::active_pulse_height_tallies.empty() &&
5,664,528✔
483
        this->type() == ParticleType::photon) {
1,409✔
484
      // Since the birth cell of the particle has not been set we
485
      // have to determine it before the energy of the secondary particle can be
486
      // removed from the pulse-height of this cell.
487
      if (lowest_coord().cell() == C_NONE) {
55!
488
        bool verbose = settings::verbosity >= 10 || trace();
55!
489
        if (!exhaustive_find_cell(*this, verbose)) {
55!
490
          mark_as_lost("Could not find the cell containing particle " +
×
491
                       std::to_string(id()));
×
492
          return;
×
493
        }
494
        // Set birth cell attribute
495
        if (cell_born() == C_NONE)
55!
496
          cell_born() = lowest_coord().cell();
55✔
497

498
        // Initialize last cells from current cell
499
        for (int j = 0; j < n_coord(); ++j) {
110✔
500
          cell_last(j) = coord(j).cell();
55✔
501
        }
502
        n_coord_last() = n_coord();
55✔
503
      }
504
      pht_secondary_particles();
55✔
505
    }
506

507
    // Enter new particle in particle track file
508
    if (write_track())
5,663,119✔
509
      add_particle_track(*this);
338✔
510
  }
511
}
512

513
void Particle::event_death()
15,174,275✔
514
{
515
#ifdef OPENMC_DAGMC_ENABLED
516
  history().reset();
517
#endif
518

519
  // Finish particle track output.
520
  if (write_track()) {
15,174,275✔
521
    finalize_particle_track(*this);
70✔
522
  }
523

524
// Contribute tally reduction variables to global accumulator
525
#pragma omp atomic
526
  global_tally_absorption += keff_tally_absorption();
15,174,275✔
527
#pragma omp atomic
528
  global_tally_collision += keff_tally_collision();
15,174,275✔
529
#pragma omp atomic
530
  global_tally_tracklength += keff_tally_tracklength();
15,174,275✔
531
#pragma omp atomic
532
  global_tally_leakage += keff_tally_leakage();
15,174,275✔
533

534
  // Reset particle tallies once accumulated
535
  keff_tally_absorption() = 0.0;
15,174,275✔
536
  keff_tally_collision() = 0.0;
15,174,275✔
537
  keff_tally_tracklength() = 0.0;
15,174,275✔
538
  keff_tally_leakage() = 0.0;
15,174,275✔
539

540
  if (!model::active_pulse_height_tallies.empty()) {
15,174,275✔
541
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
500✔
542
  }
543

544
  // Record the number of progeny created by this particle.
545
  // This data will be used to efficiently sort the fission bank.
546
  if (settings::run_mode == RunMode::EIGENVALUE) {
15,174,275✔
547
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
12,813,200✔
548
    simulation::progeny_per_particle[offset] = n_progeny();
12,813,200✔
549
  }
550
}
15,174,275✔
551

NEW
552
void Particle::event_advance_pseudo(double& total_distance, double& mfp)
×
553
{
554
  // Find the distance to the nearest boundary
NEW
555
  boundary() = distance_to_boundary(*this);
×
556

NEW
557
  double speed = this->speed();
×
NEW
558
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
×
559
  double distance_cutoff =
NEW
560
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
×
561

NEW
562
  if (distance_cutoff < boundary().distance()) {
×
NEW
563
    wgt() = 0.0;
×
NEW
564
    return;
×
565
  }
566

567
  // Select smaller of the two distances
NEW
568
  double distance = std::min({boundary().distance(), total_distance});
×
569

570
  // Advance particle in space and time
NEW
571
  this->move_distance(distance);
×
NEW
572
  double dt = distance / speed;
×
NEW
573
  this->time() += dt;
×
NEW
574
  this->lifetime() += dt;
×
NEW
575
  mfp += distance * macro_xs().total;
×
NEW
576
  total_distance -= distance;
×
577
}
578

NEW
579
void Particle::event_cross_surface_pseudo()
×
580
{
581
  // Saving previous cell data
NEW
582
  for (int j = 0; j < n_coord(); ++j) {
×
NEW
583
    cell_last(j) = coord(j).cell();
×
584
  }
NEW
585
  n_coord_last() = n_coord();
×
586

587
  // Set surface that particle is on and adjust coordinate levels
NEW
588
  surface() = boundary().surface();
×
NEW
589
  n_coord() = boundary().coord_level();
×
590

NEW
591
  if (boundary().lattice_translation()[0] != 0 ||
×
NEW
592
      boundary().lattice_translation()[1] != 0 ||
×
NEW
593
      boundary().lattice_translation()[2] != 0) {
×
594
    // Particle crosses lattice boundary
595

NEW
596
    bool verbose = settings::verbosity >= 10 || trace();
×
NEW
597
    cross_lattice(*this, boundary(), verbose);
×
NEW
598
    event() = TallyEvent::LATTICE;
×
599
  } else {
600
    // Particle crosses surface
NEW
601
    const auto& surf {model::surfaces[surface_index()].get()};
×
NEW
602
    this->cross_surface(*surf);
×
NEW
603
    event() = TallyEvent::SURFACE;
×
604
  }
NEW
605
}
×
606

607
void Particle::pht_collision_energy()
184✔
608
{
609
  // Adds the energy particles lose in a collision to the pulse-height
610

611
  // determine index of cell in pulse_height_cells
612
  auto it = std::find(model::pulse_height_cells.begin(),
184✔
613
    model::pulse_height_cells.end(), lowest_coord().cell());
184✔
614

615
  if (it != model::pulse_height_cells.end()) {
184!
616
    int index = std::distance(model::pulse_height_cells.begin(), it);
184✔
617
    pht_storage()[index] += E_last() - E();
184✔
618

619
    // If the energy of the particle is below the cutoff, it will not be sampled
620
    // so its energy is added to the pulse-height in the cell
621
    int photon = static_cast<int>(ParticleType::photon);
184✔
622
    if (E() < settings::energy_cutoff[photon]) {
184✔
623
      pht_storage()[index] += E();
75✔
624
    }
625
  }
626
}
184✔
627

628
void Particle::pht_secondary_particles()
55✔
629
{
630
  // Removes the energy of secondary produced particles from the pulse-height
631

632
  // determine index of cell in pulse_height_cells
633
  auto it = std::find(model::pulse_height_cells.begin(),
55✔
634
    model::pulse_height_cells.end(), cell_born());
55✔
635

636
  if (it != model::pulse_height_cells.end()) {
55!
637
    int index = std::distance(model::pulse_height_cells.begin(), it);
55✔
638
    pht_storage()[index] -= E();
55✔
639
  }
640
}
55✔
641

642
void Particle::cross_surface(const Surface& surf)
137,265,876✔
643
{
644

645
  if (settings::verbosity >= 10 || trace()) {
137,265,876✔
646
    write_message(1, "    Crossing surface {}", surf.id_);
3✔
647
  }
648

649
// if we're crossing a CSG surface, make sure the DAG history is reset
650
#ifdef OPENMC_DAGMC_ENABLED
651
  if (surf.geom_type() == GeometryType::CSG)
652
    history().reset();
653
#endif
654

655
  // Handle any applicable boundary conditions.
656
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
199,865,856!
657
      settings::run_mode != RunMode::VOLUME) {
62,599,980✔
658
    surf.bc_->handle_particle(*this, surf);
62,589,076✔
659
    return;
62,589,076✔
660
  }
661

662
  // ==========================================================================
663
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
664

665
#ifdef OPENMC_DAGMC_ENABLED
666
  // in DAGMC, we know what the next cell should be
667
  if (surf.geom_type() == GeometryType::DAG) {
668
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
669
                       lowest_coord().universe()) -
670
                     1;
671
    // save material, temperature, and density multiplier
672
    material_last() = material();
673
    sqrtkT_last() = sqrtkT();
674
    density_mult_last() = density_mult();
675
    // set new cell value
676
    lowest_coord().cell() = i_cell;
677
    auto& cell = model::cells[i_cell];
678

679
    cell_instance() = 0;
680
    if (cell->distribcell_index_ >= 0)
681
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
682

683
    material() = cell->material(cell_instance());
684
    sqrtkT() = cell->sqrtkT(cell_instance());
685
    density_mult() = cell->density_mult(cell_instance());
686
    return;
687
  }
688
#endif
689

690
  bool verbose = settings::verbosity >= 10 || trace();
74,676,800!
691
  if (neighbor_list_find_cell(*this, verbose)) {
74,676,800✔
692
    return;
74,674,079✔
693
  }
694

695
  // ==========================================================================
696
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
697

698
  // Remove lower coordinate levels
699
  n_coord() = 1;
2,721✔
700
  bool found = exhaustive_find_cell(*this, verbose);
2,721✔
701

702
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
2,721!
703
    // If a cell is still not found, there are two possible causes: 1) there is
704
    // a void in the model, and 2) the particle hit a surface at a tangent. If
705
    // the particle is really traveling tangent to a surface, if we move it
706
    // forward a tiny bit it should fix the problem.
707

708
    surface() = SURFACE_NONE;
529✔
709
    n_coord() = 1;
529✔
710
    r() += TINY_BIT * u();
529✔
711

712
    // Couldn't find next cell anywhere! This probably means there is an actual
713
    // undefined region in the geometry.
714

715
    if (!exhaustive_find_cell(*this, verbose)) {
529!
716
      mark_as_lost("After particle " + std::to_string(id()) +
1,586✔
717
                   " crossed surface " + std::to_string(surf.id_) +
2,114✔
718
                   " it could not be located in any cell and it did not leak.");
719
      return;
528✔
720
    }
721
  }
722
}
723

724
void Particle::cross_vacuum_bc(const Surface& surf)
3,154,320✔
725
{
726
  // Score any surface current tallies -- note that the particle is moved
727
  // forward slightly so that if the mesh boundary is on the surface, it is
728
  // still processed
729

730
  if (!model::active_meshsurf_tallies.empty()) {
3,154,320✔
731
    // TODO: Find a better solution to score surface currents than
732
    // physically moving the particle forward slightly
733

734
    r() += TINY_BIT * u();
85,202✔
735
    score_surface_tally(*this, model::active_meshsurf_tallies);
85,202✔
736
  }
737

738
  // Score to global leakage tally
739
  keff_tally_leakage() += wgt();
3,154,320✔
740

741
  // Kill the particle
742
  wgt() = 0.0;
3,154,320✔
743

744
  // Display message
745
  if (settings::verbosity >= 10 || trace()) {
3,154,320!
746
    write_message(1, "    Leaked out of surface {}", surf.id_);
1✔
747
  }
748
}
3,154,320✔
749

750
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
59,320,662✔
751
{
752
  // Do not handle reflective boundary conditions on lower universes
753
  if (n_coord() != 1) {
59,320,662!
754
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
755
                 " off surface in a lower universe.");
756
    return;
×
757
  }
758

759
  // Score surface currents since reflection causes the direction of the
760
  // particle to change. For surface filters, we need to score the tallies
761
  // twice, once before the particle's surface attribute has changed and
762
  // once after. For mesh surface filters, we need to artificially move
763
  // the particle slightly back in case the surface crossing is coincident
764
  // with a mesh boundary
765

766
  if (!model::active_surface_tallies.empty()) {
59,320,662✔
767
    score_surface_tally(*this, model::active_surface_tallies);
25,911✔
768
  }
769

770
  if (!model::active_meshsurf_tallies.empty()) {
59,320,662✔
771
    Position r {this->r()};
4,262,317✔
772
    this->r() -= TINY_BIT * u();
4,262,317✔
773
    score_surface_tally(*this, model::active_meshsurf_tallies);
4,262,317✔
774
    this->r() = r;
4,262,317✔
775
  }
776

777
  // Set the new particle direction
778
  u() = new_u;
59,320,662✔
779

780
  // Reassign particle's cell and surface
781
  coord(0).cell() = cell_last(0);
59,320,662✔
782
  surface() = -surface();
59,320,662✔
783

784
  // If a reflective surface is coincident with a lattice or universe
785
  // boundary, it is necessary to redetermine the particle's coordinates in
786
  // the lower universes.
787
  // (unless we're using a dagmc model, which has exactly one universe)
788
  n_coord() = 1;
59,320,662✔
789
  if (surf.geom_type() != GeometryType::DAG &&
118,641,324!
790
      !neighbor_list_find_cell(*this)) {
59,320,662!
791
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
792
                 std::to_string(surf.id_) + ".");
×
793
    return;
×
794
  }
795

796
  // Set previous coordinate going slightly past surface crossing
797
  r_last_current() = r() + TINY_BIT * u();
59,320,662✔
798

799
  // Diagnostic message
800
  if (settings::verbosity >= 10 || trace()) {
59,320,662!
801
    write_message(1, "    Reflected from surface {}", surf.id_);
×
802
  }
803
}
804

805
void Particle::cross_periodic_bc(
205,500✔
806
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
807
{
808
  // Do not handle periodic boundary conditions on lower universes
809
  if (n_coord() != 1) {
205,500!
810
    mark_as_lost(
×
811
      "Cannot transfer particle " + std::to_string(id()) +
×
812
      " across surface in a lower universe. Boundary conditions must be "
813
      "applied to root universe.");
814
    return;
×
815
  }
816

817
  // Score surface currents since reflection causes the direction of the
818
  // particle to change -- artificially move the particle slightly back in
819
  // case the surface crossing is coincident with a mesh boundary
820
  if (!model::active_meshsurf_tallies.empty()) {
205,500!
821
    Position r {this->r()};
×
822
    this->r() -= TINY_BIT * u();
×
823
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
824
    this->r() = r;
×
825
  }
826

827
  // Adjust the particle's location and direction.
828
  r() = new_r;
205,500✔
829
  u() = new_u;
205,500✔
830

831
  // Reassign particle's surface
832
  surface() = new_surface;
205,500✔
833

834
  // Figure out what cell particle is in now
835
  n_coord() = 1;
205,500✔
836

837
  if (!neighbor_list_find_cell(*this)) {
205,500!
838
    mark_as_lost("Couldn't find particle after hitting periodic "
×
839
                 "boundary on surface " +
×
840
                 std::to_string(surf.id_) + ".");
×
841
    return;
×
842
  }
843

844
  // Set previous coordinate going slightly past surface crossing
845
  r_last_current() = r() + TINY_BIT * u();
205,500✔
846

847
  // Diagnostic message
848
  if (settings::verbosity >= 10 || trace()) {
205,500!
849
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
850
  }
851
}
852

853
void Particle::mark_as_lost(const char* message)
529✔
854
{
855
  // Print warning and write lost particle file
856
  warning(message);
529✔
857
  if (settings::max_write_lost_particles < 0 ||
529✔
858
      simulation::n_lost_particles < settings::max_write_lost_particles) {
500✔
859
    write_restart();
34✔
860
  }
861
  // Increment number of lost particles
862
  wgt() = 0.0;
529✔
863
#pragma omp atomic
864
  simulation::n_lost_particles += 1;
529✔
865

866
  // Count the total number of simulated particles (on this processor)
867
  auto n = simulation::current_batch * settings::gen_per_batch *
529✔
868
           simulation::work_per_rank;
869

870
  // Abort the simulation if the maximum number of lost particles has been
871
  // reached
872
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
529✔
873
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
1!
874
    fatal_error("Maximum number of lost particles has been reached.");
1✔
875
  }
876
}
528✔
877

878
void Particle::write_restart() const
34✔
879
{
880
  // Dont write another restart file if in particle restart mode
881
  if (settings::run_mode == RunMode::PARTICLE)
34✔
882
    return;
2✔
883

884
  // Set up file name
885
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
886
    simulation::current_batch, id());
64✔
887

888
#pragma omp critical(WriteParticleRestart)
889
  {
890
    // Create file
891
    hid_t file_id = file_open(filename, 'w');
32✔
892

893
    // Write filetype and version info
894
    write_attribute(file_id, "filetype", "particle restart");
32✔
895
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
32✔
896
    write_attribute(file_id, "openmc_version", VERSION);
32✔
897
#ifdef GIT_SHA1
898
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
899
#endif
900

901
    // Write data to file
902
    write_dataset(file_id, "current_batch", simulation::current_batch);
32✔
903
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
32✔
904
    write_dataset(file_id, "current_generation", simulation::current_gen);
32✔
905
    write_dataset(file_id, "n_particles", settings::n_particles);
32✔
906
    switch (settings::run_mode) {
32!
907
    case RunMode::FIXED_SOURCE:
20✔
908
      write_dataset(file_id, "run_mode", "fixed source");
20✔
909
      break;
20✔
910
    case RunMode::EIGENVALUE:
12✔
911
      write_dataset(file_id, "run_mode", "eigenvalue");
12✔
912
      break;
12✔
913
    case RunMode::PARTICLE:
×
914
      write_dataset(file_id, "run_mode", "particle restart");
×
915
      break;
×
916
    default:
×
917
      break;
×
918
    }
919
    write_dataset(file_id, "id", id());
32✔
920
    write_dataset(file_id, "type", static_cast<int>(type()));
32✔
921

922
    int64_t i = current_work();
32✔
923
    if (settings::run_mode == RunMode::EIGENVALUE) {
32✔
924
      // take source data from primary bank for eigenvalue simulation
925
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
12✔
926
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
12✔
927
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
12✔
928
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
12✔
929
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
12✔
930
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
20!
931
      // re-sample using rng random number seed used to generate source particle
932
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
20✔
933
                     settings::n_particles +
20✔
934
                   simulation::work_index[mpi::rank] + i;
20✔
935
      uint64_t seed = init_seed(id, STREAM_SOURCE);
20✔
936
      // re-sample source site
937
      auto site = sample_external_source(&seed);
20✔
938
      write_dataset(file_id, "weight", site.wgt);
20✔
939
      write_dataset(file_id, "energy", site.E);
20✔
940
      write_dataset(file_id, "xyz", site.r);
20✔
941
      write_dataset(file_id, "uvw", site.u);
20✔
942
      write_dataset(file_id, "time", site.time);
20✔
943
    }
944

945
    // Close file
946
    file_close(file_id);
32✔
947
  } // #pragma omp critical
948
}
32✔
949

950
void Particle::update_neutron_xs(
666,174,245✔
951
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
952
{
953
  // Get microscopic cross section cache
954
  auto& micro = this->neutron_xs(i_nuclide);
666,174,245✔
955

956
  // If the cache doesn't match, recalculate micro xs
957
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
912,097,652✔
958
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
1,148,301,356✔
959
      ncrystal_xs != micro.ncrystal_xs) {
236,203,704!
960
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
429,970,541✔
961

962
    // If NCrystal is being used, update micro cross section cache
963
    micro.ncrystal_xs = ncrystal_xs;
429,970,541✔
964
    if (ncrystal_xs >= 0.0) {
429,970,541✔
965
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,723✔
966
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,723✔
967
    }
968
  }
969
}
666,174,245✔
970

971
//==============================================================================
972
// Non-method functions
973
//==============================================================================
974

975
std::string particle_type_to_str(ParticleType type)
284,563✔
976
{
977
  switch (type) {
284,563!
978
  case ParticleType::neutron:
218,176✔
979
    return "neutron";
218,176✔
980
  case ParticleType::photon:
66,363✔
981
    return "photon";
66,363✔
982
  case ParticleType::electron:
12✔
983
    return "electron";
12✔
984
  case ParticleType::positron:
12✔
985
    return "positron";
12✔
986
  }
987
  UNREACHABLE();
×
988
}
989

990
ParticleType str_to_particle_type(std::string str)
261,592✔
991
{
992
  if (str == "neutron") {
261,592✔
993
    return ParticleType::neutron;
61,775✔
994
  } else if (str == "photon") {
199,817✔
995
    return ParticleType::photon;
199,811✔
996
  } else if (str == "electron") {
6✔
997
    return ParticleType::electron;
3✔
998
  } else if (str == "positron") {
3!
999
    return ParticleType::positron;
3✔
1000
  } else {
1001
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
1002
  }
1003
}
1004

1005
void add_surf_source_to_bank(Particle& p, const Surface& surf)
136,988,515✔
1006
{
1007
  if (simulation::current_batch <= settings::n_inactive ||
244,243,388✔
1008
      simulation::surf_source_bank.full()) {
107,254,873✔
1009
    return;
136,976,620✔
1010
  }
1011

1012
  // If a cell/cellfrom/cellto parameter is defined
1013
  if (settings::ssw_cell_id != C_NONE) {
31,878✔
1014

1015
    // Retrieve cell index and storage type
1016
    int cell_idx = model::cell_map[settings::ssw_cell_id];
24,236✔
1017

1018
    if (surf.bc_) {
24,236✔
1019
      // Leave if cellto with vacuum boundary condition
1020
      if (surf.bc_->type() == "vacuum" &&
17,786!
1021
          settings::ssw_cell_type == SSWCellType::To) {
3,075✔
1022
        return;
1,126✔
1023
      }
1024

1025
      // Leave if other boundary condition than vacuum
1026
      if (surf.bc_->type() != "vacuum") {
13,585✔
1027
        return;
11,636✔
1028
      }
1029
    }
1030

1031
    // Check if the cell of interest has been exited
1032
    bool exited = false;
11,474✔
1033
    for (int i = 0; i < p.n_coord_last(); ++i) {
30,894✔
1034
      if (p.cell_last(i) == cell_idx) {
19,420✔
1035
        exited = true;
6,888✔
1036
      }
1037
    }
1038

1039
    // Check if the cell of interest has been entered
1040
    bool entered = false;
11,474✔
1041
    for (int i = 0; i < p.n_coord(); ++i) {
27,468✔
1042
      if (p.coord(i).cell() == cell_idx) {
15,994✔
1043
        entered = true;
5,452✔
1044
      }
1045
    }
1046

1047
    // Vacuum boundary conditions: return if cell is not exited
1048
    if (surf.bc_) {
11,474✔
1049
      if (surf.bc_->type() == "vacuum" && !exited) {
1,949!
1050
        return;
1,349✔
1051
      }
1052
    } else {
1053

1054
      // If we both enter and exit the cell of interest
1055
      if (entered && exited) {
9,525✔
1056
        return;
2,656✔
1057
      }
1058

1059
      // If we did not enter nor exit the cell of interest
1060
      if (!entered && !exited) {
6,869✔
1061
        return;
1,041✔
1062
      }
1063

1064
      // If cellfrom and the cell before crossing is not the cell of
1065
      // interest
1066
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
5,828✔
1067
        return;
1,097✔
1068
      }
1069

1070
      // If cellto and the cell after crossing is not the cell of interest
1071
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
4,731✔
1072
        return;
1,078✔
1073
      }
1074
    }
1075
  }
1076

1077
  SourceSite site;
11,895✔
1078
  site.r = p.r();
11,895✔
1079
  site.u = p.u();
11,895✔
1080
  site.E = p.E();
11,895✔
1081
  site.time = p.time();
11,895✔
1082
  site.wgt = p.wgt();
11,895✔
1083
  site.delayed_group = p.delayed_group();
11,895✔
1084
  site.surf_id = surf.id_;
11,895✔
1085
  site.particle = p.type();
11,895✔
1086
  site.parent_id = p.id();
11,895✔
1087
  site.progeny_id = p.n_progeny();
11,895✔
1088
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
11,895✔
1089
}
1090

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