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

openmc-dev / openmc / 13596900305

28 Feb 2025 09:34PM UTC coverage: 85.032% (-0.008%) from 85.04%
13596900305

Pull #3070

github

web-flow
Merge 90e4f6147 into 39ad29d82
Pull Request #3070: Add option for survival biasing source normalization

15 of 21 new or added lines in 5 files covered. (71.43%)

93 existing lines in 4 files now uncovered.

51026 of 60008 relevant lines covered (85.03%)

32654012.9 hits per line

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

92.69
/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:
15,896,286✔
54
    mass = 0.0;
15,896,286✔
55
    break;
15,896,286✔
56
  case ParticleType::electron:
53,264,841✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
53,264,841✔
59
    break;
53,264,841✔
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);
891,632,853✔
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(
111,496,003✔
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)]) {
111,496,003✔
84
    return false;
53,181,636✔
85
  }
86

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

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

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

120
  // Copy attributes from source bank site
121
  type() = src->particle;
226,346,605✔
122
  wgt() = src->wgt;
226,346,605✔
123
  wgt_last() = src->wgt;
226,346,605✔
124
  // set particle history start weight
125
  wgt_born() = src->wgt;
226,346,605✔
126
  r() = src->r;
226,346,605✔
127
  u() = src->u;
226,346,605✔
128
  r_born() = src->r;
226,346,605✔
129
  r_last_current() = src->r;
226,346,605✔
130
  r_last() = src->r;
226,346,605✔
131
  u_last() = src->u;
226,346,605✔
132
  if (settings::run_CE) {
226,346,605✔
133
    E() = src->E;
98,177,449✔
134
    g() = 0;
98,177,449✔
135
  } else {
136
    g() = static_cast<int>(src->E);
128,169,156✔
137
    g_last() = static_cast<int>(src->E);
128,169,156✔
138
    E() = data::mg.energy_bin_avg_[g()];
128,169,156✔
139
  }
140
  E_last() = E();
226,346,605✔
141
  time() = src->time;
226,346,605✔
142
  time_last() = src->time;
226,346,605✔
143
  parent_nuclide() = src->parent_nuclide;
226,346,605✔
144
}
226,346,605✔
145

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

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

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

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

173
    // Set birth cell attribute
174
    if (cell_born() == C_NONE)
224,581,033✔
175
      cell_born() = lowest_coord().cell;
224,581,033✔
176

177
    // Initialize last cells from current cell
178
    for (int j = 0; j < n_coord(); ++j) {
472,751,175✔
179
      cell_last(j) = coord(j).cell;
248,170,142✔
180
    }
181
    n_coord_last() = n_coord();
224,581,033✔
182
  }
183

184
  // Write particle track.
185
  if (write_track())
2,147,483,647✔
186
    write_particle_track(*this);
11,591✔
187

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

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

206
      // Update the particle's group while we know we are multi-group
207
      g_last() = g();
2,147,483,647✔
208
    }
209
  } else {
210
    macro_xs().total = 0.0;
50,524,749✔
211
    macro_xs().absorption = 0.0;
50,524,749✔
212
    macro_xs().fission = 0.0;
50,524,749✔
213
    macro_xs().nu_fission = 0.0;
50,524,749✔
214
  }
215
}
216

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

222
  // Sample a distance to collision
223
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
224
    collision_distance() = 0.0;
53,264,841✔
225
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
226
    collision_distance() = INFINITY;
50,524,749✔
227
  } else {
228
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
229
  }
230

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

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

242
  // Kill particle if its time exceeds the cutoff
243
  bool hit_time_boundary = false;
2,147,483,647✔
244
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
245
  if (time() > time_cutoff) {
2,147,483,647✔
246
    double dt = time() - time_cutoff;
12,000✔
247
    time() = time_cutoff;
12,000✔
248

249
    double push_back_distance = speed() * dt;
12,000✔
250
    this->move_distance(-push_back_distance);
12,000✔
251
    hit_time_boundary = true;
12,000✔
252
  }
253

254
  // Score track-length tallies
255
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
256
    score_tracklength_tally(*this, distance);
1,325,985,179✔
257
  }
258

259
  // Score track-length estimate of k-eff
260
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
261
      type() == ParticleType::neutron) {
2,147,483,647✔
262
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
263
  }
264

265
  // Score flux derivative accumulators for differential tallies.
266
  if (!model::active_tallies.empty()) {
2,147,483,647✔
267
    score_track_derivative(*this, distance);
1,467,652,341✔
268
  }
269

270
  // Set particle weight to zero if it hit the time boundary
271
  if (hit_time_boundary) {
2,147,483,647✔
272
    wgt() = 0.0;
12,000✔
273
  }
274
}
2,147,483,647✔
275

276
void Particle::event_cross_surface()
1,703,097,422✔
277
{
278
  // Saving previous cell data
279
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
280
    cell_last(j) = coord(j).cell;
2,147,483,647✔
281
  }
282
  n_coord_last() = n_coord();
1,703,097,422✔
283

284
  // Set surface that particle is on and adjust coordinate levels
285
  surface() = boundary().surface;
1,703,097,422✔
286
  n_coord() = boundary().coord_level;
1,703,097,422✔
287

288
  if (boundary().lattice_translation[0] != 0 ||
1,703,097,422✔
289
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
290
      boundary().lattice_translation[2] != 0) {
1,429,085,109✔
291
    // Particle crosses lattice boundary
292

293
    bool verbose = settings::verbosity >= 10 || trace();
351,772,905✔
294
    cross_lattice(*this, boundary(), verbose);
351,772,905✔
295
    event() = TallyEvent::LATTICE;
351,772,905✔
296
  } else {
297
    // Particle crosses surface
298
    const auto& surf {model::surfaces[surface_index()].get()};
1,351,324,517✔
299
    // If BC, add particle to surface source before crossing surface
300
    if (surf->surf_source_ && surf->bc_) {
1,351,324,517✔
301
      add_surf_source_to_bank(*this, *surf);
629,392,003✔
302
    }
303
    this->cross_surface(*surf);
1,351,324,517✔
304
    // If no BC, add particle to surface source after crossing surface
305
    if (surf->surf_source_ && !surf->bc_) {
1,351,324,507✔
306
      add_surf_source_to_bank(*this, *surf);
720,942,714✔
307
    }
308
    if (settings::weight_window_checkpoint_surface) {
1,351,324,507✔
UNCOV
309
      apply_weight_windows(*this);
×
310
    }
311
    event() = TallyEvent::SURFACE;
1,351,324,507✔
312
  }
313
  // Score cell to cell partial currents
314
  if (!model::active_surface_tallies.empty()) {
1,703,097,412✔
315
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
316
  }
317
}
1,703,097,412✔
318

319
void Particle::event_collide()
2,147,483,647✔
320
{
321
  // Score collision estimate of keff
322
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
323
      type() == ParticleType::neutron) {
2,147,483,647✔
324
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
325
  }
326

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

331
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
332
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,285,425✔
333

334
  // Clear surface component
335
  surface() = SURFACE_NONE;
2,147,483,647✔
336

337
  if (settings::run_CE) {
2,147,483,647✔
338
    collision(*this);
744,581,712✔
339
  } else {
340
    collision_mg(*this);
1,948,075,116✔
341
  }
342

343
  // Score collision estimator tallies -- this is done after a collision
344
  // has occurred rather than before because we need information on the
345
  // outgoing energy for any tallies with an outgoing energy filter
346
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
347
    score_collision_tally(*this);
99,219,315✔
348
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
349
    if (settings::run_CE) {
101,106,481✔
350
      score_analog_tally_ce(*this);
99,796,069✔
351
    } else {
352
      score_analog_tally_mg(*this);
1,310,412✔
353
    }
354
  }
355

356
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
357
      type() == ParticleType::photon) {
18,456✔
358
    pht_collision_energy();
2,208✔
359
  }
360

361
  // Reset banked weight during collision
362
  n_bank() = 0;
2,147,483,647✔
363
  bank_second_E() = 0.0;
2,147,483,647✔
364
  wgt_bank() = 0.0;
2,147,483,647✔
365
  zero_delayed_bank();
2,147,483,647✔
366

367
  // Reset fission logical
368
  fission() = false;
2,147,483,647✔
369

370
  // Save coordinates for tallying purposes
371
  r_last_current() = r();
2,147,483,647✔
372

373
  // Set last material to none since cross sections will need to be
374
  // re-evaluated
375
  material_last() = C_NONE;
2,147,483,647✔
376

377
  // Set all directions to base level -- right now, after a collision, only
378
  // the base level directions are changed
379
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
380
    if (coord(j + 1).rotated) {
129,164,659✔
381
      // If next level is rotated, apply rotation matrix
382
      const auto& m {model::cells[coord(j).cell]->rotation_};
11,339,220✔
383
      const auto& u {coord(j).u};
11,339,220✔
384
      coord(j + 1).u = u.rotate(m);
11,339,220✔
385
    } else {
386
      // Otherwise, copy this level's direction
387
      coord(j + 1).u = coord(j).u;
117,825,439✔
388
    }
389
  }
390

391
  // Score flux derivative accumulators for differential tallies.
392
  if (!model::active_tallies.empty())
2,147,483,647✔
393
    score_collision_derivative(*this);
643,215,265✔
394

395
#ifdef DAGMC
396
  history().reset();
225,789,663✔
397
#endif
398
}
2,147,483,647✔
399

400
void Particle::event_revive_from_secondary()
2,147,483,647✔
401
{
402
  // If particle has too many events, display warning and kill it
403
  ++n_event();
2,147,483,647✔
404
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
405
    warning("Particle " + std::to_string(id()) +
×
406
            " underwent maximum number of events.");
UNCOV
407
    wgt() = 0.0;
×
408
  }
409

410
  // Check for secondary particles if this particle is dead
411
  if (!alive()) {
2,147,483,647✔
412
    // Write final position for this particle
413
    if (write_track()) {
224,580,683✔
414
      write_particle_track(*this);
7,082✔
415
    }
416

417
    // If no secondary particles, break out of event loop
418
    if (secondary_bank().empty())
224,580,683✔
419
      return;
158,666,496✔
420

421
    from_source(&secondary_bank().back());
65,914,187✔
422
    secondary_bank().pop_back();
65,914,187✔
423
    n_event() = 0;
65,914,187✔
424
    bank_second_E() = 0.0;
65,914,187✔
425

426
    // Subtract secondary particle energy from interim pulse-height results
427
    if (!model::active_pulse_height_tallies.empty() &&
65,931,095✔
428
        this->type() == ParticleType::photon) {
16,908✔
429
      // Since the birth cell of the particle has not been set we
430
      // have to determine it before the energy of the secondary particle can be
431
      // removed from the pulse-height of this cell.
432
      if (lowest_coord().cell == C_NONE) {
660✔
433
        bool verbose = settings::verbosity >= 10 || trace();
660✔
434
        if (!exhaustive_find_cell(*this, verbose)) {
660✔
435
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
436
                       std::to_string(id()));
×
UNCOV
437
          return;
×
438
        }
439
        // Set birth cell attribute
440
        if (cell_born() == C_NONE)
660✔
441
          cell_born() = lowest_coord().cell;
660✔
442

443
        // Initialize last cells from current cell
444
        for (int j = 0; j < n_coord(); ++j) {
1,320✔
445
          cell_last(j) = coord(j).cell;
660✔
446
        }
447
        n_coord_last() = n_coord();
660✔
448
      }
449
      pht_secondary_particles();
660✔
450
    }
451

452
    // Enter new particle in particle track file
453
    if (write_track())
65,914,187✔
454
      add_particle_track(*this);
5,942✔
455
  }
456
}
457

458
void Particle::event_death()
158,667,496✔
459
{
460
#ifdef DAGMC
461
  history().reset();
13,192,385✔
462
#endif
463

464
  // Finish particle track output.
465
  if (write_track()) {
158,667,496✔
466
    finalize_particle_track(*this);
1,140✔
467
  }
468

469
// Contribute tally reduction variables to global accumulator
470
#pragma omp atomic
79,350,634✔
471
  global_tally_absorption += keff_tally_absorption();
158,667,496✔
472
#pragma omp atomic
79,179,808✔
473
  global_tally_collision += keff_tally_collision();
158,667,496✔
474
#pragma omp atomic
79,114,245✔
475
  global_tally_tracklength += keff_tally_tracklength();
158,667,496✔
476
#pragma omp atomic
78,808,608✔
477
  global_tally_leakage += keff_tally_leakage();
158,667,496✔
478

479
  // Reset particle tallies once accumulated
480
  keff_tally_absorption() = 0.0;
158,667,496✔
481
  keff_tally_collision() = 0.0;
158,667,496✔
482
  keff_tally_tracklength() = 0.0;
158,667,496✔
483
  keff_tally_leakage() = 0.0;
158,667,496✔
484

485
  if (!model::active_pulse_height_tallies.empty()) {
158,667,496✔
486
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
487
  }
488

489
  // Record the number of progeny created by this particle.
490
  // This data will be used to efficiently sort the fission bank.
491
  if (settings::run_mode == RunMode::EIGENVALUE) {
158,667,496✔
492
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
144,899,600✔
493
    simulation::progeny_per_particle[offset] = n_progeny();
144,899,600✔
494
  }
495
}
158,667,496✔
496

497
void Particle::pht_collision_energy()
2,208✔
498
{
499
  // Adds the energy particles lose in a collision to the pulse-height
500

501
  // determine index of cell in pulse_height_cells
502
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
503
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
504

505
  if (it != model::pulse_height_cells.end()) {
2,208✔
506
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
507
    pht_storage()[index] += E_last() - E();
2,208✔
508

509
    // If the energy of the particle is below the cutoff, it will not be sampled
510
    // so its energy is added to the pulse-height in the cell
511
    int photon = static_cast<int>(ParticleType::photon);
2,208✔
512
    if (E() < settings::energy_cutoff[photon]) {
2,208✔
513
      pht_storage()[index] += E();
900✔
514
    }
515
  }
516
}
2,208✔
517

518
void Particle::pht_secondary_particles()
660✔
519
{
520
  // Removes the energy of secondary produced particles from the pulse-height
521

522
  // determine index of cell in pulse_height_cells
523
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
524
    model::pulse_height_cells.end(), cell_born());
660✔
525

526
  if (it != model::pulse_height_cells.end()) {
660✔
527
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
528
    pht_storage()[index] -= E();
660✔
529
  }
530
}
660✔
531

532
void Particle::cross_surface(const Surface& surf)
1,352,379,749✔
533
{
534

535
  if (settings::verbosity >= 10 || trace()) {
1,352,379,749✔
536
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
537
  }
538

539
// if we're crossing a CSG surface, make sure the DAG history is reset
540
#ifdef DAGMC
541
  if (surf.geom_type() == GeometryType::CSG)
112,549,875✔
542
    history().reset();
112,514,559✔
543
#endif
544

545
  // Handle any applicable boundary conditions.
546
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,352,379,749✔
547
    surf.bc_->handle_particle(*this, surf);
629,651,974✔
548
    return;
629,651,974✔
549
  }
550

551
  // ==========================================================================
552
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
553

554
#ifdef DAGMC
555
  // in DAGMC, we know what the next cell should be
556
  if (surf.geom_type() == GeometryType::DAG) {
60,395,193✔
557
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
558
                       lowest_coord().universe) -
28,265✔
559
                     1;
28,265✔
560
    // save material and temp
561
    material_last() = material();
28,265✔
562
    sqrtkT_last() = sqrtkT();
28,265✔
563
    // set new cell value
564
    lowest_coord().cell = i_cell;
28,265✔
565
    auto& cell = model::cells[i_cell];
28,265✔
566

567
    cell_instance() = 0;
28,265✔
568
    if (cell->distribcell_index_ >= 0)
28,265✔
569
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
570

571
    material() = cell->material(cell_instance());
28,265✔
572
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
573
    return;
28,265✔
574
  }
575
#endif
576

577
  bool verbose = settings::verbosity >= 10 || trace();
722,699,510✔
578
  if (neighbor_list_find_cell(*this, verbose)) {
722,699,510✔
579
    return;
722,668,942✔
580
  }
581

582
  // ==========================================================================
583
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
584

585
  // Remove lower coordinate levels
586
  n_coord() = 1;
30,568✔
587
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
588

589
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
30,568✔
590
    // If a cell is still not found, there are two possible causes: 1) there is
591
    // a void in the model, and 2) the particle hit a surface at a tangent. If
592
    // the particle is really traveling tangent to a surface, if we move it
593
    // forward a tiny bit it should fix the problem.
594

595
    surface() = SURFACE_NONE;
6,268✔
596
    n_coord() = 1;
6,268✔
597
    r() += TINY_BIT * u();
6,268✔
598

599
    // Couldn't find next cell anywhere! This probably means there is an actual
600
    // undefined region in the geometry.
601

602
    if (!exhaustive_find_cell(*this, verbose)) {
6,268✔
603
      mark_as_lost("After particle " + std::to_string(id()) +
18,794✔
604
                   " crossed surface " + std::to_string(surf.id_) +
25,052✔
605
                   " it could not be located in any cell and it did not leak.");
606
      return;
6,258✔
607
    }
608
  }
609
}
610

611
void Particle::cross_vacuum_bc(const Surface& surf)
21,956,657✔
612
{
613
  // Score any surface current tallies -- note that the particle is moved
614
  // forward slightly so that if the mesh boundary is on the surface, it is
615
  // still processed
616

617
  if (!model::active_meshsurf_tallies.empty()) {
21,956,657✔
618
    // TODO: Find a better solution to score surface currents than
619
    // physically moving the particle forward slightly
620

621
    r() += TINY_BIT * u();
1,107,095✔
622
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,107,095✔
623
  }
624

625
  // Score to global leakage tally
626
  keff_tally_leakage() += wgt();
21,956,657✔
627

628
  // Kill the particle
629
  wgt() = 0.0;
21,956,657✔
630

631
  // Display message
632
  if (settings::verbosity >= 10 || trace()) {
21,956,657✔
633
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
634
  }
635
}
21,956,657✔
636

637
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
608,088,905✔
638
{
639
  // Do not handle reflective boundary conditions on lower universes
640
  if (n_coord() != 1) {
608,088,905✔
641
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
642
                 " off surface in a lower universe.");
UNCOV
643
    return;
×
644
  }
645

646
  // Score surface currents since reflection causes the direction of the
647
  // particle to change. For surface filters, we need to score the tallies
648
  // twice, once before the particle's surface attribute has changed and
649
  // once after. For mesh surface filters, we need to artificially move
650
  // the particle slightly back in case the surface crossing is coincident
651
  // with a mesh boundary
652

653
  if (!model::active_surface_tallies.empty()) {
608,088,905✔
654
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
655
  }
656

657
  if (!model::active_meshsurf_tallies.empty()) {
608,088,905✔
658
    Position r {this->r()};
55,050,482✔
659
    this->r() -= TINY_BIT * u();
55,050,482✔
660
    score_surface_tally(*this, model::active_meshsurf_tallies);
55,050,482✔
661
    this->r() = r;
55,050,482✔
662
  }
663

664
  // Set the new particle direction
665
  u() = new_u;
608,088,905✔
666

667
  // Reassign particle's cell and surface
668
  coord(0).cell = cell_last(0);
608,088,905✔
669
  surface() = -surface();
608,088,905✔
670

671
  // If a reflective surface is coincident with a lattice or universe
672
  // boundary, it is necessary to redetermine the particle's coordinates in
673
  // the lower universes.
674
  // (unless we're using a dagmc model, which has exactly one universe)
675
  n_coord() = 1;
608,088,905✔
676
  if (surf.geom_type() != GeometryType::DAG &&
1,216,175,271✔
677
      !neighbor_list_find_cell(*this)) {
608,086,366✔
678
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
679
                 std::to_string(surf.id_) + ".");
×
UNCOV
680
    return;
×
681
  }
682

683
  // Set previous coordinate going slightly past surface crossing
684
  r_last_current() = r() + TINY_BIT * u();
608,088,905✔
685

686
  // Diagnostic message
687
  if (settings::verbosity >= 10 || trace()) {
608,088,905✔
UNCOV
688
    write_message(1, "    Reflected from surface {}", surf.id_);
×
689
  }
690
}
691

692
void Particle::cross_periodic_bc(
727,164✔
693
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
694
{
695
  // Do not handle periodic boundary conditions on lower universes
696
  if (n_coord() != 1) {
727,164✔
UNCOV
697
    mark_as_lost(
×
UNCOV
698
      "Cannot transfer particle " + std::to_string(id()) +
×
699
      " across surface in a lower universe. Boundary conditions must be "
700
      "applied to root universe.");
UNCOV
701
    return;
×
702
  }
703

704
  // Score surface currents since reflection causes the direction of the
705
  // particle to change -- artificially move the particle slightly back in
706
  // case the surface crossing is coincident with a mesh boundary
707
  if (!model::active_meshsurf_tallies.empty()) {
727,164✔
708
    Position r {this->r()};
×
709
    this->r() -= TINY_BIT * u();
×
UNCOV
710
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
711
    this->r() = r;
×
712
  }
713

714
  // Adjust the particle's location and direction.
715
  r() = new_r;
727,164✔
716
  u() = new_u;
727,164✔
717

718
  // Reassign particle's surface
719
  surface() = new_surface;
727,164✔
720

721
  // Figure out what cell particle is in now
722
  n_coord() = 1;
727,164✔
723

724
  if (!neighbor_list_find_cell(*this)) {
727,164✔
725
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
726
                 "boundary on surface " +
×
UNCOV
727
                 std::to_string(surf.id_) +
×
728
                 ". The normal vector "
729
                 "of one periodic surface may need to be reversed.");
UNCOV
730
    return;
×
731
  }
732

733
  // Set previous coordinate going slightly past surface crossing
734
  r_last_current() = r() + TINY_BIT * u();
727,164✔
735

736
  // Diagnostic message
737
  if (settings::verbosity >= 10 || trace()) {
727,164✔
UNCOV
738
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
739
  }
740
}
741

742
void Particle::mark_as_lost(const char* message)
6,268✔
743
{
744
  // Print warning and write lost particle file
745
  warning(message);
6,268✔
746
  if (settings::max_write_lost_particles < 0 ||
6,268✔
747
      simulation::n_lost_particles < settings::max_write_lost_particles) {
6,000✔
748
    write_restart();
353✔
749
  }
750
  // Increment number of lost particles
751
  wgt() = 0.0;
6,268✔
752
#pragma omp atomic
3,124✔
753
  simulation::n_lost_particles += 1;
3,144✔
754

755
  // Count the total number of simulated particles (on this processor)
756
  auto n = simulation::current_batch * settings::gen_per_batch *
6,268✔
757
           simulation::work_per_rank;
758

759
  // Abort the simulation if the maximum number of lost particles has been
760
  // reached
761
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
6,268✔
762
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10✔
763
    fatal_error("Maximum number of lost particles has been reached.");
10✔
764
  }
765
}
6,258✔
766

767
void Particle::write_restart() const
353✔
768
{
769
  // Dont write another restart file if in particle restart mode
770
  if (settings::run_mode == RunMode::PARTICLE)
353✔
771
    return;
24✔
772

773
  // Set up file name
774
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
775
    simulation::current_batch, id());
619✔
776

777
#pragma omp critical(WriteParticleRestart)
314✔
778
  {
779
    // Create file
780
    hid_t file_id = file_open(filename, 'w');
329✔
781

782
    // Write filetype and version info
783
    write_attribute(file_id, "filetype", "particle restart");
329✔
784
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
329✔
785
    write_attribute(file_id, "openmc_version", VERSION);
329✔
786
#ifdef GIT_SHA1
787
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
788
#endif
789

790
    // Write data to file
791
    write_dataset(file_id, "current_batch", simulation::current_batch);
329✔
792
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
329✔
793
    write_dataset(file_id, "current_generation", simulation::current_gen);
329✔
794
    write_dataset(file_id, "n_particles", settings::n_particles);
329✔
795
    switch (settings::run_mode) {
329✔
796
    case RunMode::FIXED_SOURCE:
245✔
797
      write_dataset(file_id, "run_mode", "fixed source");
245✔
798
      break;
245✔
799
    case RunMode::EIGENVALUE:
84✔
800
      write_dataset(file_id, "run_mode", "eigenvalue");
84✔
801
      break;
84✔
802
    case RunMode::PARTICLE:
×
803
      write_dataset(file_id, "run_mode", "particle restart");
×
804
      break;
×
UNCOV
805
    default:
×
UNCOV
806
      break;
×
807
    }
808
    write_dataset(file_id, "id", id());
329✔
809
    write_dataset(file_id, "type", static_cast<int>(type()));
329✔
810

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

834
    // Close file
835
    file_close(file_id);
329✔
836
  } // #pragma omp critical
837
}
329✔
838

839
void Particle::update_neutron_xs(
2,147,483,647✔
840
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
841
{
842
  // Get microscopic cross section cache
843
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
844

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

850
    // If NCrystal is being used, update micro cross section cache
851
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
852
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,723✔
853
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,723✔
854
    }
855
  }
856
}
2,147,483,647✔
857

858
//==============================================================================
859
// Non-method functions
860
//==============================================================================
861

862
std::string particle_type_to_str(ParticleType type)
3,252,576✔
863
{
864
  switch (type) {
3,252,576✔
865
  case ParticleType::neutron:
2,456,004✔
866
    return "neutron";
2,456,004✔
867
  case ParticleType::photon:
796,332✔
868
    return "photon";
796,332✔
869
  case ParticleType::electron:
120✔
870
    return "electron";
120✔
871
  case ParticleType::positron:
120✔
872
    return "positron";
120✔
873
  }
UNCOV
874
  UNREACHABLE();
×
875
}
876

877
ParticleType str_to_particle_type(std::string str)
3,014,998✔
878
{
879
  if (str == "neutron") {
3,014,998✔
880
    return ParticleType::neutron;
691,201✔
881
  } else if (str == "photon") {
2,323,797✔
882
    return ParticleType::photon;
2,323,729✔
883
  } else if (str == "electron") {
68✔
884
    return ParticleType::electron;
34✔
885
  } else if (str == "positron") {
34✔
886
    return ParticleType::positron;
34✔
887
  } else {
UNCOV
888
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
889
  }
890
}
891

892
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,350,334,717✔
893
{
894
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
895
      simulation::surf_source_bank.full()) {
1,084,721,610✔
896
    return;
1,350,218,119✔
897
  }
898

899
  // If a cell/cellfrom/cellto parameter is defined
900
  if (settings::ssw_cell_id != C_NONE) {
349,636✔
901

902
    // Retrieve cell index and storage type
903
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,441✔
904

905
    if (surf.bc_) {
283,441✔
906
      // Leave if cellto with vacuum boundary condition
907
      if (surf.bc_->type() == "vacuum" &&
202,458✔
908
          settings::ssw_cell_type == SSWCellType::To) {
35,218✔
909
        return;
13,071✔
910
      }
911

912
      // Leave if other boundary condition than vacuum
913
      if (surf.bc_->type() != "vacuum") {
154,169✔
914
        return;
132,022✔
915
      }
916
    }
917

918
    // Check if the cell of interest has been exited
919
    bool exited = false;
138,348✔
920
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,543✔
921
      if (p.cell_last(i) == cell_idx) {
228,195✔
922
        exited = true;
81,191✔
923
      }
924
    }
925

926
    // Check if the cell of interest has been entered
927
    bool entered = false;
138,348✔
928
    for (int i = 0; i < p.n_coord(); ++i) {
328,942✔
929
      if (p.coord(i).cell == cell_idx) {
190,594✔
930
        entered = true;
64,718✔
931
      }
932
    }
933

934
    // Vacuum boundary conditions: return if cell is not exited
935
    if (surf.bc_) {
138,348✔
936
      if (surf.bc_->type() == "vacuum" && !exited) {
22,147✔
937
        return;
15,247✔
938
      }
939
    } else {
940

941
      // If we both enter and exit the cell of interest
942
      if (entered && exited) {
116,201✔
943
        return;
31,409✔
944
      }
945

946
      // If we did not enter nor exit the cell of interest
947
      if (!entered && !exited) {
84,792✔
948
        return;
15,501✔
949
      }
950

951
      // If cellfrom and the cell before crossing is not the cell of
952
      // interest
953
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
69,291✔
954
        return;
12,666✔
955
      }
956

957
      // If cellto and the cell after crossing is not the cell of interest
958
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
56,625✔
959
        return;
13,122✔
960
      }
961
    }
962
  }
963

964
  SourceSite site;
116,598✔
965
  site.r = p.r();
116,598✔
966
  site.u = p.u();
116,598✔
967
  site.E = p.E();
116,598✔
968
  site.time = p.time();
116,598✔
969
  site.wgt = p.wgt();
116,598✔
970
  site.delayed_group = p.delayed_group();
116,598✔
971
  site.surf_id = surf.id_;
116,598✔
972
  site.particle = p.type();
116,598✔
973
  site.parent_id = p.id();
116,598✔
974
  site.progeny_id = p.n_progeny();
116,598✔
975
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
116,598✔
976
}
977

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