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

openmc-dev / openmc / 15235297504

25 May 2025 07:00AM UTC coverage: 85.213% (-0.007%) from 85.22%
15235297504

Pull #3404

github

web-flow
Merge 726881146 into a7d1ceba3
Pull Request #3404: New Feature: electron/positron independent source.

22 of 28 new or added lines in 5 files covered. (78.57%)

37 existing lines in 2 files now uncovered.

52348 of 61432 relevant lines covered (85.21%)

36908247.05 hits per line

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

92.8
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef DAGMC
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  // Determine mass in eV/c^2
48
  double mass;
49
  switch (this->type()) {
2,147,483,647✔
50
  case ParticleType::neutron:
2,147,483,647✔
51
    mass = MASS_NEUTRON_EV;
2,147,483,647✔
52
    break;
2,147,483,647✔
53
  case ParticleType::photon:
18,413,082✔
54
    mass = 0.0;
18,413,082✔
55
    break;
18,413,082✔
56
  case ParticleType::electron:
49,282,308✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
49,282,308✔
59
    break;
49,282,308✔
60
  }
61

62
  if (this->E() < 1.0e-9 * mass) {
2,147,483,647✔
63
    // If the energy is much smaller than the mass, revert to non-relativistic
64
    // formula. The 1e-9 criterion is specifically chosen as the point below
65
    // which the error from using the non-relativistic formula is less than the
66
    // round-off eror when using the relativistic formula (see analysis at
67
    // https://gist.github.com/paulromano/da3b473fe3df33de94b265bdff0c7817)
68
    return C_LIGHT * std::sqrt(2 * this->E() / mass);
854,672,649✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

73
    // Calculate speed via v = c * sqrt(1 - γ^-2)
74
    return C_LIGHT * std::sqrt(1 - inv_gamma * inv_gamma);
2,147,483,647✔
75
  }
76
}
77

78
bool Particle::create_secondary(
103,029,088✔
79
  double wgt, Direction u, double E, ParticleType type)
80
{
81
  // If energy is below cutoff for this particle, don't create secondary
82
  // particle
83
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
103,029,088✔
84
    return false;
49,104,780✔
85
  }
86

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

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

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

121
  // Copy attributes from source bank site
122
  type() = src->particle;
219,871,876✔
123
  wgt() = src->wgt;
219,871,876✔
124
  wgt_last() = src->wgt;
219,871,876✔
125
  r() = src->r;
219,871,876✔
126
  u() = src->u;
219,871,876✔
127
  r_born() = src->r;
219,871,876✔
128
  r_last_current() = src->r;
219,871,876✔
129
  r_last() = src->r;
219,871,876✔
130
  u_last() = src->u;
219,871,876✔
131
  if (settings::run_CE) {
219,871,876✔
132
    E() = src->E;
101,238,383✔
133
    g() = 0;
101,238,383✔
134
  } else {
135
    g() = static_cast<int>(src->E);
118,633,493✔
136
    g_last() = static_cast<int>(src->E);
118,633,493✔
137
    E() = data::mg.energy_bin_avg_[g()];
118,633,493✔
138
  }
139
  E_last() = E();
219,871,876✔
140
  time() = src->time;
219,871,876✔
141
  time_last() = src->time;
219,871,876✔
142
  parent_nuclide() = src->parent_nuclide;
219,871,876✔
143
}
219,871,876✔
144

145
void Particle::event_calculate_xs()
2,147,483,647✔
146
{
147
  // Set the random number stream
148
  stream() = STREAM_TRACKING;
2,147,483,647✔
149

150
  // Store pre-collision particle properties
151
  wgt_last() = wgt();
2,147,483,647✔
152
  E_last() = E();
2,147,483,647✔
153
  u_last() = u();
2,147,483,647✔
154
  r_last() = r();
2,147,483,647✔
155
  time_last() = time();
2,147,483,647✔
156

157
  // Reset event variables
158
  event() = TallyEvent::KILL;
2,147,483,647✔
159
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
160
  event_mt() = REACTION_NONE;
2,147,483,647✔
161

162
  // If the cell hasn't been determined based on the particle's location,
163
  // initiate a search for the current cell. This generally happens at the
164
  // beginning of the history and again for any secondary particles
165
  if (lowest_coord().cell == C_NONE) {
2,147,483,647✔
166
    if (!exhaustive_find_cell(*this)) {
217,108,335✔
167
      mark_as_lost(
×
168
        "Could not find the cell containing particle " + std::to_string(id()));
×
169
      return;
×
170
    }
171

172
    // Set birth cell attribute
173
    if (cell_born() == C_NONE)
217,108,335✔
174
      cell_born() = lowest_coord().cell;
217,108,335✔
175

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
455,846,909✔
178
      cell_last(j) = coord(j).cell;
238,738,574✔
179
    }
180
    n_coord_last() = n_coord();
217,108,335✔
181
  }
182

183
  // Write particle track.
184
  if (write_track())
2,147,483,647✔
185
    write_particle_track(*this);
10,835✔
186

187
  if (settings::check_overlaps)
2,147,483,647✔
188
    check_cell_overlap(*this);
×
189

190
  // Calculate microscopic and macroscopic cross sections
191
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
192
    if (settings::run_CE) {
2,147,483,647✔
193
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,607,686,376✔
194
        // If the material is the same as the last material and the
195
        // temperature hasn't changed, we don't need to lookup cross
196
        // sections again.
197
        model::materials[material()]->calculate_xs(*this);
1,288,949,927✔
198
      }
199
    } else {
200
      // Get the MG data; unlike the CE case above, we have to re-calculate
201
      // cross sections for every collision since the cross sections may
202
      // be angle-dependent
203
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,079,768,108✔
204

205
      // Update the particle's group while we know we are multi-group
206
      g_last() = g();
2,079,768,108✔
207
    }
208
  } else {
209
    macro_xs().total = 0.0;
66,440,882✔
210
    macro_xs().absorption = 0.0;
66,440,882✔
211
    macro_xs().fission = 0.0;
66,440,882✔
212
    macro_xs().nu_fission = 0.0;
66,440,882✔
213
  }
214
}
215

216
void Particle::event_advance()
2,147,483,647✔
217
{
218
  // Find the distance to the nearest boundary
219
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
220

221
  // Sample a distance to collision
222
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
223
    collision_distance() = INFINITY;
49,282,308✔
224
    if (material() != MATERIAL_VOID) {
49,282,308✔
225
      double density = model::materials[material()]->density();
49,282,308✔
226
      if (density > 0.0)
49,282,308✔
227
        collision_distance() = 0.0;
49,282,308✔
228
    }
229
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
230
    collision_distance() = INFINITY;
66,440,882✔
231
  } else {
232
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
233
  }
234

235
  // Select smaller of the two distances
236
  double distance = std::min(boundary().distance, collision_distance());
2,147,483,647✔
237

238
  // Advance particle in space and time
239
  // Short-term solution until the surface source is revised and we can use
240
  // this->move_distance(distance)
241
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
242
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
243
  }
244
  double dt = distance / this->speed();
2,147,483,647✔
245
  this->time() += dt;
2,147,483,647✔
246
  this->lifetime() += dt;
2,147,483,647✔
247

248
  // Kill particle if its time exceeds the cutoff
249
  bool hit_time_boundary = false;
2,147,483,647✔
250
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
251
  if (time() > time_cutoff) {
2,147,483,647✔
252
    double dt = time() - time_cutoff;
11,000✔
253
    time() = time_cutoff;
11,000✔
254
    lifetime() = time_cutoff;
11,000✔
255

256
    double push_back_distance = speed() * dt;
11,000✔
257
    this->move_distance(-push_back_distance);
11,000✔
258
    hit_time_boundary = true;
11,000✔
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,239,859,475✔
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,400,252,399✔
275
  }
276

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

283
void Particle::event_cross_surface()
2,029,166,270✔
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,029,166,270✔
290

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

295
  if (boundary().lattice_translation[0] != 0 ||
2,029,166,270✔
296
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
297
      boundary().lattice_translation[2] != 0) {
1,536,415,813✔
298
    // Particle crosses lattice boundary
299

300
    bool verbose = settings::verbosity >= 10 || trace();
683,294,578✔
301
    cross_lattice(*this, boundary(), verbose);
683,294,578✔
302
    event() = TallyEvent::LATTICE;
683,294,578✔
303
  } else {
304
    // Particle crosses surface
305
    const auto& surf {model::surfaces[surface_index()].get()};
1,345,871,692✔
306
    // If BC, add particle to surface source before crossing surface
307
    if (surf->surf_source_ && surf->bc_) {
1,345,871,692✔
308
      add_surf_source_to_bank(*this, *surf);
632,803,809✔
309
    }
310
    this->cross_surface(*surf);
1,345,871,692✔
311
    // If no BC, add particle to surface source after crossing surface
312
    if (surf->surf_source_ && !surf->bc_) {
1,345,871,683✔
313
      add_surf_source_to_bank(*this, *surf);
712,164,465✔
314
    }
315
    if (settings::weight_window_checkpoint_surface) {
1,345,871,683✔
UNCOV
316
      apply_weight_windows(*this);
×
317
    }
318
    event() = TallyEvent::SURFACE;
1,345,871,683✔
319
  }
320
  // Score cell to cell partial currents
321
  if (!model::active_surface_tallies.empty()) {
2,029,166,261✔
322
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
323
  }
324
}
2,029,166,261✔
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,171,401✔
331
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,090,845,950✔
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);
703,907,888✔
346
  } else {
347
    collision_mg(*this);
1,785,735,523✔
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);
93,598,561✔
355
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
356
    if (settings::run_CE) {
107,654,602✔
357
      score_analog_tally_ce(*this);
106,453,391✔
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) {
119,670,579✔
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;
109,276,294✔
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);
607,906,549✔
401

402
#ifdef DAGMC
403
  history().reset();
228,171,611✔
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()) {
217,107,931✔
421
      write_particle_track(*this);
6,674✔
422
    }
423

424
    // If no secondary particles, break out of event loop
425
    if (secondary_bank().empty())
217,107,931✔
426
      return;
156,069,911✔
427

428
    from_source(&secondary_bank().back());
61,038,020✔
429
    secondary_bank().pop_back();
61,038,020✔
430
    n_event() = 0;
61,038,020✔
431
    bank_second_E() = 0.0;
61,038,020✔
432

433
    // Subtract secondary particle energy from interim pulse-height results
434
    if (!model::active_pulse_height_tallies.empty() &&
61,053,519✔
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())
61,038,020✔
461
      add_particle_track(*this);
5,604✔
462
  }
463
}
464

465
void Particle::event_death()
156,070,911✔
466
{
467
#ifdef DAGMC
468
  history().reset();
14,263,385✔
469
#endif
470

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

476
// Contribute tally reduction variables to global accumulator
477
#pragma omp atomic
85,794,234✔
478
  global_tally_absorption += keff_tally_absorption();
156,070,911✔
479
#pragma omp atomic
86,155,012✔
480
  global_tally_collision += keff_tally_collision();
156,070,911✔
481
#pragma omp atomic
85,604,827✔
482
  global_tally_tracklength += keff_tally_tracklength();
156,070,911✔
483
#pragma omp atomic
85,303,008✔
484
  global_tally_leakage += keff_tally_leakage();
156,070,911✔
485

486
  // Reset particle tallies once accumulated
487
  keff_tally_absorption() = 0.0;
156,070,911✔
488
  keff_tally_collision() = 0.0;
156,070,911✔
489
  keff_tally_tracklength() = 0.0;
156,070,911✔
490
  keff_tally_leakage() = 0.0;
156,070,911✔
491

492
  if (!model::active_pulse_height_tallies.empty()) {
156,070,911✔
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) {
156,070,911✔
499
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,120,800✔
500
    simulation::progeny_per_particle[offset] = n_progeny();
133,120,800✔
501
  }
502
}
156,070,911✔
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,346,838,988✔
540
{
541

542
  if (settings::verbosity >= 10 || trace()) {
1,346,838,988✔
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 DAGMC
548
  if (surf.geom_type() == GeometryType::CSG)
123,185,317✔
549
    history().reset();
123,150,001✔
550
#endif
551

552
  // Handle any applicable boundary conditions.
553
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,346,838,988✔
554
    surf.bc_->handle_particle(*this, surf);
633,041,426✔
555
    return;
633,041,426✔
556
  }
557

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

561
#ifdef DAGMC
562
  // in DAGMC, we know what the next cell should be
563
  if (surf.geom_type() == GeometryType::DAG) {
65,516,359✔
564
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
565
                       lowest_coord().universe) -
28,265✔
566
                     1;
28,265✔
567
    // save material and temp
568
    material_last() = material();
28,265✔
569
    sqrtkT_last() = sqrtkT();
28,265✔
570
    // set new cell value
571
    lowest_coord().cell = i_cell;
28,265✔
572
    auto& cell = model::cells[i_cell];
28,265✔
573

574
    cell_instance() = 0;
28,265✔
575
    if (cell->distribcell_index_ >= 0)
28,265✔
576
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
577

578
    material() = cell->material(cell_instance());
28,265✔
579
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
580
    return;
28,265✔
581
  }
582
#endif
583

584
  bool verbose = settings::verbosity >= 10 || trace();
713,769,297✔
585
  if (neighbor_list_find_cell(*this, verbose)) {
713,769,297✔
586
    return;
713,741,278✔
587
  }
588

589
  // ==========================================================================
590
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
591

592
  // Remove lower coordinate levels
593
  n_coord() = 1;
28,019✔
594
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
595

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

602
    surface() = SURFACE_NONE;
5,744✔
603
    n_coord() = 1;
5,744✔
604
    r() += TINY_BIT * u();
5,744✔
605

606
    // Couldn't find next cell anywhere! This probably means there is an actual
607
    // undefined region in the geometry.
608

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

618
void Particle::cross_vacuum_bc(const Surface& surf)
30,370,681✔
619
{
620
  // Score any surface current tallies -- note that the particle is moved
621
  // forward slightly so that if the mesh boundary is on the surface, it is
622
  // still processed
623

624
  if (!model::active_meshsurf_tallies.empty()) {
30,370,681✔
625
    // TODO: Find a better solution to score surface currents than
626
    // physically moving the particle forward slightly
627

628
    r() += TINY_BIT * u();
945,340✔
629
    score_surface_tally(*this, model::active_meshsurf_tallies);
945,340✔
630
  }
631

632
  // Score to global leakage tally
633
  keff_tally_leakage() += wgt();
30,370,681✔
634

635
  // Kill the particle
636
  wgt() = 0.0;
30,370,681✔
637

638
  // Display message
639
  if (settings::verbosity >= 10 || trace()) {
30,370,681✔
640
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
641
  }
642
}
30,370,681✔
643

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

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

660
  if (!model::active_surface_tallies.empty()) {
603,031,783✔
661
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
662
  }
663

664
  if (!model::active_meshsurf_tallies.empty()) {
603,031,783✔
665
    Position r {this->r()};
46,625,403✔
666
    this->r() -= TINY_BIT * u();
46,625,403✔
667
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,625,403✔
668
    this->r() = r;
46,625,403✔
669
  }
670

671
  // Set the new particle direction
672
  u() = new_u;
603,031,783✔
673

674
  // Reassign particle's cell and surface
675
  coord(0).cell = cell_last(0);
603,031,783✔
676
  surface() = -surface();
603,031,783✔
677

678
  // If a reflective surface is coincident with a lattice or universe
679
  // boundary, it is necessary to redetermine the particle's coordinates in
680
  // the lower universes.
681
  // (unless we're using a dagmc model, which has exactly one universe)
682
  n_coord() = 1;
603,031,783✔
683
  if (surf.geom_type() != GeometryType::DAG &&
1,206,061,027✔
684
      !neighbor_list_find_cell(*this)) {
603,029,244✔
UNCOV
685
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
686
                 std::to_string(surf.id_) + ".");
×
UNCOV
687
    return;
×
688
  }
689

690
  // Set previous coordinate going slightly past surface crossing
691
  r_last_current() = r() + TINY_BIT * u();
603,031,783✔
692

693
  // Diagnostic message
694
  if (settings::verbosity >= 10 || trace()) {
603,031,783✔
UNCOV
695
    write_message(1, "    Reflected from surface {}", surf.id_);
×
696
  }
697
}
698

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

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

721
  // Adjust the particle's location and direction.
722
  r() = new_r;
666,318✔
723
  u() = new_u;
666,318✔
724

725
  // Reassign particle's surface
726
  surface() = new_surface;
666,318✔
727

728
  // Figure out what cell particle is in now
729
  n_coord() = 1;
666,318✔
730

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

740
  // Set previous coordinate going slightly past surface crossing
741
  r_last_current() = r() + TINY_BIT * u();
666,318✔
742

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

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

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

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

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

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

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

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

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

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

841
    // Close file
842
    file_close(file_id);
302✔
843
  } // #pragma omp critical
844
}
302✔
845

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

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

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

865
//==============================================================================
866
// Non-method functions
867
//==============================================================================
868

869
std::string particle_type_to_str(ParticleType type)
3,130,116✔
870
{
871
  switch (type) {
3,130,116✔
872
  case ParticleType::neutron:
2,399,925✔
873
    return "neutron";
2,399,925✔
874
  case ParticleType::photon:
729,971✔
875
    return "photon";
729,971✔
876
  case ParticleType::electron:
110✔
877
    return "electron";
110✔
878
  case ParticleType::positron:
110✔
879
    return "positron";
110✔
880
  }
UNCOV
881
  UNREACHABLE();
×
882
}
883

884
ParticleType str_to_particle_type(std::string str)
2,938,415✔
885
{
886
  if (str == "neutron") {
2,938,415✔
887
    return ParticleType::neutron;
671,110✔
888
  } else if (str == "photon") {
2,267,305✔
889
    return ParticleType::photon;
2,267,241✔
890
  } else if (str == "electron") {
64✔
891
    return ParticleType::electron;
32✔
892
  } else if (str == "positron") {
32✔
893
    return ParticleType::positron;
32✔
894
  } else {
UNCOV
895
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
896
  }
897
}
898

899
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,344,968,274✔
900
{
901
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
902
      simulation::surf_source_bank.full()) {
1,058,507,663✔
903
    return;
1,344,861,509✔
904
  }
905

906
  // If a cell/cellfrom/cellto parameter is defined
907
  if (settings::ssw_cell_id != C_NONE) {
319,267✔
908

909
    // Retrieve cell index and storage type
910
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
911

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

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

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

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

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

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

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

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

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

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

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