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

openmc-dev / openmc / 9617074623

21 Jun 2024 04:53PM UTC coverage: 84.715% (+0.03%) from 84.688%
9617074623

Pull #3042

github

web-flow
Merge 47e50a3a9 into 4bd0b09e6
Pull Request #3042: Rely on std::filesystem for file_utils

26 of 31 new or added lines in 5 files covered. (83.87%)

921 existing lines in 34 files now uncovered.

48900 of 57723 relevant lines covered (84.71%)

31496763.14 hits per line

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

92.52
/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:
12,380,640✔
54
    mass = 0.0;
12,380,640✔
55
    break;
12,380,640✔
56
  case ParticleType::electron:
48,812,844✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
48,812,844✔
59
    break;
48,812,844✔
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);
901,324,504✔
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
void Particle::move_distance(double length)
12,000✔
79
{
80
  for (int j = 0; j < n_coord(); ++j) {
24,000✔
81
    coord(j).r += length * coord(j).u;
12,000✔
82
  }
83
}
12,000✔
84

85
void Particle::create_secondary(
104,277,635✔
86
  double wgt, Direction u, double E, ParticleType type)
87
{
88
  // If energy is below cutoff for this particle, don't create secondary
89
  // particle
90
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
104,277,635✔
91
    return;
48,693,348✔
92
  }
93

94
  secondary_bank().emplace_back();
55,584,287✔
95

96
  auto& bank {secondary_bank().back()};
55,584,287✔
97
  bank.particle = type;
55,584,287✔
98
  bank.wgt = wgt;
55,584,287✔
99
  bank.r = r();
55,584,287✔
100
  bank.u = u;
55,584,287✔
101
  bank.E = settings::run_CE ? E : g();
55,584,287✔
102
  bank.time = time();
55,584,287✔
103

104
  n_bank_second() += 1;
55,584,287✔
105
}
106

107
void Particle::from_source(const SourceSite* src)
215,377,082✔
108
{
109
  // Reset some attributes
110
  clear();
215,377,082✔
111
  surface() = 0;
215,377,082✔
112
  cell_born() = C_NONE;
215,377,082✔
113
  material() = C_NONE;
215,377,082✔
114
  n_collision() = 0;
215,377,082✔
115
  fission() = false;
215,377,082✔
116
  zero_flux_derivs();
215,377,082✔
117

118
  // Copy attributes from source bank site
119
  type() = src->particle;
215,377,082✔
120
  wgt() = src->wgt;
215,377,082✔
121
  wgt_last() = src->wgt;
215,377,082✔
122
  r() = src->r;
215,377,082✔
123
  u() = src->u;
215,377,082✔
124
  r_born() = src->r;
215,377,082✔
125
  r_last_current() = src->r;
215,377,082✔
126
  r_last() = src->r;
215,377,082✔
127
  u_last() = src->u;
215,377,082✔
128
  if (settings::run_CE) {
215,377,082✔
129
    E() = src->E;
93,985,082✔
130
    g() = 0;
93,985,082✔
131
  } else {
132
    g() = static_cast<int>(src->E);
121,392,000✔
133
    g_last() = static_cast<int>(src->E);
121,392,000✔
134
    E() = data::mg.energy_bin_avg_[g()];
121,392,000✔
135
  }
136
  E_last() = E();
215,377,082✔
137
  time() = src->time;
215,377,082✔
138
  time_last() = src->time;
215,377,082✔
139
}
215,377,082✔
140

141
void Particle::event_calculate_xs()
2,147,483,647✔
142
{
143
  // Set the random number stream
144
  stream() = STREAM_TRACKING;
2,147,483,647✔
145

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

153
  // Reset event variables
154
  event() = TallyEvent::KILL;
2,147,483,647✔
155
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
156
  event_mt() = REACTION_NONE;
2,147,483,647✔
157

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

168
    // Set birth cell attribute
169
    if (cell_born() == C_NONE)
214,992,458✔
170
      cell_born() = lowest_coord().cell;
214,992,458✔
171

172
    // Initialize last cells from current cell
173
    for (int j = 0; j < n_coord(); ++j) {
441,268,278✔
174
      cell_last(j) = coord(j).cell;
226,275,820✔
175
    }
176
    n_coord_last() = n_coord();
214,992,458✔
177
  }
178

179
  // Write particle track.
180
  if (write_track())
2,147,483,647✔
181
    write_particle_track(*this);
11,589✔
182

183
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
184
    check_cell_overlap(*this);
×
185

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

201
      // Update the particle's group while we know we are multi-group
202
      g_last() = g();
2,147,483,647✔
203
    }
204
  } else {
205
    macro_xs().total = 0.0;
50,401,308✔
206
    macro_xs().absorption = 0.0;
50,401,308✔
207
    macro_xs().fission = 0.0;
50,401,308✔
208
    macro_xs().nu_fission = 0.0;
50,401,308✔
209
  }
210
}
211

212
void Particle::event_advance()
2,147,483,647✔
213
{
214
  // Find the distance to the nearest boundary
215
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
216

217
  // Sample a distance to collision
218
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
219
    collision_distance() = 0.0;
48,812,844✔
220
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
221
    collision_distance() = INFINITY;
50,401,308✔
222
  } else {
223
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
224
  }
225

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

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

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

244
    double push_back_distance = speed() * dt;
12,000✔
245
    this->move_distance(-push_back_distance);
12,000✔
246
    hit_time_boundary = true;
12,000✔
247
  }
248

249
  // Score track-length tallies
250
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
251
    score_tracklength_tally(*this, distance);
1,326,832,255✔
252
  }
253

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

260
  // Score flux derivative accumulators for differential tallies.
261
  if (!model::active_tallies.empty()) {
2,147,483,647✔
262
    score_track_derivative(*this, distance);
1,516,637,787✔
263
  }
264

265
  // Set particle weight to zero if it hit the time boundary
266
  if (hit_time_boundary) {
2,147,483,647✔
267
    wgt() = 0.0;
12,000✔
268
  }
269
}
2,147,483,647✔
270

271
void Particle::event_cross_surface()
1,429,521,800✔
272
{
273
  // Saving previous cell data
274
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
275
    cell_last(j) = coord(j).cell;
2,091,767,201✔
276
  }
277
  n_coord_last() = n_coord();
1,429,521,800✔
278

279
  // Set surface that particle is on and adjust coordinate levels
280
  surface() = boundary().surface_index;
1,429,521,800✔
281
  n_coord() = boundary().coord_level;
1,429,521,800✔
282

283
  if (boundary().lattice_translation[0] != 0 ||
1,429,521,800✔
284
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
285
      boundary().lattice_translation[2] != 0) {
1,336,777,969✔
286
    // Particle crosses lattice boundary
287

288
    bool verbose = settings::verbosity >= 10 || trace();
112,682,822✔
289
    cross_lattice(*this, boundary(), verbose);
112,682,822✔
290
    event() = TallyEvent::LATTICE;
112,682,822✔
291
  } else {
292
    // Particle crosses surface
293
    // TODO: off-by-one
294
    const auto& surf {model::surfaces[std::abs(surface()) - 1].get()};
1,316,838,978✔
295
    // If BC, add particle to surface source before crossing surface
296
    if (surf->surf_source_ && surf->bc_) {
1,316,838,978✔
297
      add_surf_source_to_bank(*this, *surf);
639,503,559✔
298
    }
299
    cross_surface(*surf);
1,316,838,978✔
300
    // If no BC, add particle to surface source after crossing surface
301
    if (surf->surf_source_ && !surf->bc_) {
1,316,838,972✔
302
      add_surf_source_to_bank(*this, *surf);
676,345,623✔
303
    }
304
    if (settings::weight_window_checkpoint_surface) {
1,316,838,972✔
UNCOV
305
      apply_weight_windows(*this);
×
306
    }
307
    event() = TallyEvent::SURFACE;
1,316,838,972✔
308
  }
309
  // Score cell to cell partial currents
310
  if (!model::active_surface_tallies.empty()) {
1,429,521,794✔
311
    score_surface_tally(*this, model::active_surface_tallies);
4,922,392✔
312
  }
313
}
1,429,521,794✔
314

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

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

327
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
328
    score_surface_tally(*this, model::active_meshsurf_tallies);
113,840,864✔
329

330
  // Clear surface component
331
  surface() = 0;
2,147,483,647✔
332

333
  if (settings::run_CE) {
2,147,483,647✔
334
    collision(*this);
776,315,090✔
335
  } else {
336
    collision_mg(*this);
1,939,604,940✔
337
  }
338

339
  // Score collision estimator tallies -- this is done after a collision
340
  // has occurred rather than before because we need information on the
341
  // outgoing energy for any tallies with an outgoing energy filter
342
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
343
    score_collision_tally(*this);
91,602,840✔
344
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
345
    if (settings::run_CE) {
140,661,920✔
346
      score_analog_tally_ce(*this);
139,351,508✔
347
    } else {
348
      score_analog_tally_mg(*this);
1,310,412✔
349
    }
350
  }
351

352
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
353
      type() == ParticleType::photon) {
18,456✔
354
    pht_collision_energy();
2,208✔
355
  }
356

357
  // Reset banked weight during collision
358
  n_bank() = 0;
2,147,483,647✔
359
  n_bank_second() = 0;
2,147,483,647✔
360
  wgt_bank() = 0.0;
2,147,483,647✔
361
  zero_delayed_bank();
2,147,483,647✔
362

363
  // Reset fission logical
364
  fission() = false;
2,147,483,647✔
365

366
  // Save coordinates for tallying purposes
367
  r_last_current() = r();
2,147,483,647✔
368

369
  // Set last material to none since cross sections will need to be
370
  // re-evaluated
371
  material_last() = C_NONE;
2,147,483,647✔
372

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

387
  // Score flux derivative accumulators for differential tallies.
388
  if (!model::active_tallies.empty())
2,147,483,647✔
389
    score_collision_derivative(*this);
667,688,546✔
390

391
#ifdef DAGMC
392
  history().reset();
241,838,794✔
393
#endif
394
}
2,147,483,647✔
395

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

406
  // Check for secondary particles if this particle is dead
407
  if (!alive()) {
2,147,483,647✔
408
    // Write final position for this particle
409
    if (write_track()) {
214,992,112✔
410
      write_particle_track(*this);
7,082✔
411
    }
412

413
    // If no secondary particles, break out of event loop
414
    if (secondary_bank().empty())
214,992,112✔
415
      return;
159,204,568✔
416

417
    from_source(&secondary_bank().back());
55,787,544✔
418
    secondary_bank().pop_back();
55,787,544✔
419
    n_event() = 0;
55,787,544✔
420

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

438
        // Initialize last cells from current cell
439
        for (int j = 0; j < n_coord(); ++j) {
1,320✔
440
          cell_last(j) = coord(j).cell;
660✔
441
        }
442
        n_coord_last() = n_coord();
660✔
443
      }
444
      pht_secondary_particles();
660✔
445
    }
446

447
    // Enter new particle in particle track file
448
    if (write_track())
55,787,544✔
449
      add_particle_track(*this);
5,942✔
450
  }
451
}
452

453
void Particle::event_death()
159,205,568✔
454
{
455
#ifdef DAGMC
456
  history().reset();
13,924,133✔
457
#endif
458

459
  // Finish particle track output.
460
  if (write_track()) {
159,205,568✔
461
    finalize_particle_track(*this);
1,140✔
462
  }
463

464
// Contribute tally reduction variables to global accumulator
465
#pragma omp atomic
80,409,383✔
466
  global_tally_absorption += keff_tally_absorption();
159,205,568✔
467
#pragma omp atomic
80,812,688✔
468
  global_tally_collision += keff_tally_collision();
159,205,568✔
469
#pragma omp atomic
80,388,289✔
470
  global_tally_tracklength += keff_tally_tracklength();
159,205,568✔
471
#pragma omp atomic
79,804,499✔
472
  global_tally_leakage += keff_tally_leakage();
159,205,568✔
473

474
  // Reset particle tallies once accumulated
475
  keff_tally_absorption() = 0.0;
159,205,568✔
476
  keff_tally_collision() = 0.0;
159,205,568✔
477
  keff_tally_tracklength() = 0.0;
159,205,568✔
478
  keff_tally_leakage() = 0.0;
159,205,568✔
479

480
  if (!model::active_pulse_height_tallies.empty()) {
159,205,568✔
481
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
482
  }
483

484
  // Record the number of progeny created by this particle.
485
  // This data will be used to efficiently sort the fission bank.
486
  if (settings::run_mode == RunMode::EIGENVALUE) {
159,205,568✔
487
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
146,840,600✔
488
    simulation::progeny_per_particle[offset] = n_progeny();
146,840,600✔
489
  }
490
}
159,205,568✔
491

492
void Particle::pht_collision_energy()
2,208✔
493
{
494
  // Adds the energy particles lose in a collision to the pulse-height
495

496
  // determine index of cell in pulse_height_cells
497
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
498
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
499

500
  if (it != model::pulse_height_cells.end()) {
2,208✔
501
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
502
    pht_storage()[index] += E_last() - E();
2,208✔
503

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

513
void Particle::pht_secondary_particles()
660✔
514
{
515
  // Removes the energy of secondary produced particles from the pulse-height
516

517
  // determine index of cell in pulse_height_cells
518
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
519
    model::pulse_height_cells.end(), cell_born());
660✔
520

521
  if (it != model::pulse_height_cells.end()) {
660✔
522
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
523
    pht_storage()[index] -= E();
660✔
524
  }
525
}
660✔
526

527
void Particle::cross_surface(const Surface& surf)
1,316,838,978✔
528
{
529

530
  if (settings::verbosity >= 10 || trace()) {
1,316,838,978✔
531
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
532
  }
533

534
// if we're crossing a CSG surface, make sure the DAG history is reset
535
#ifdef DAGMC
536
  if (surf.geom_type_ == GeometryType::CSG)
132,730,091✔
537
    history().reset();
132,701,229✔
538
#endif
539

540
  // Handle any applicable boundary conditions.
541
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,316,838,978✔
542
    surf.bc_->handle_particle(*this, surf);
639,763,530✔
543
    return;
639,763,530✔
544
  }
545

546
  // ==========================================================================
547
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
548

549
#ifdef DAGMC
550
  // in DAGMC, we know what the next cell should be
551
  if (surf.geom_type_ == GeometryType::DAG) {
68,224,841✔
552
    int32_t i_cell = next_cell(std::abs(surface()), cell_last(n_coord() - 1),
24,619✔
553
                       lowest_coord().universe) -
24,619✔
554
                     1;
24,619✔
555
    // save material and temp
556
    material_last() = material();
24,619✔
557
    sqrtkT_last() = sqrtkT();
24,619✔
558
    // set new cell value
559
    lowest_coord().cell = i_cell;
24,619✔
560
    cell_instance() = 0;
24,619✔
561
    material() = model::cells[i_cell]->material_[0];
24,619✔
562
    sqrtkT() = model::cells[i_cell]->sqrtkT_[0];
24,619✔
563
    return;
24,619✔
564
  }
565
#endif
566

567
  bool verbose = settings::verbosity >= 10 || trace();
677,050,829✔
568
  if (neighbor_list_find_cell(*this, verbose)) {
677,050,829✔
569
    return;
677,020,301✔
570
  }
571

572
  // ==========================================================================
573
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
574

575
  // Remove lower coordinate levels
576
  n_coord() = 1;
30,528✔
577
  bool found = exhaustive_find_cell(*this, verbose);
30,528✔
578

579
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
30,528✔
580
    // If a cell is still not found, there are two possible causes: 1) there is
581
    // a void in the model, and 2) the particle hit a surface at a tangent. If
582
    // the particle is really traveling tangent to a surface, if we move it
583
    // forward a tiny bit it should fix the problem.
584

585
    surface() = 0;
6,228✔
586
    n_coord() = 1;
6,228✔
587
    r() += TINY_BIT * u();
6,228✔
588

589
    // Couldn't find next cell anywhere! This probably means there is an actual
590
    // undefined region in the geometry.
591

592
    if (!exhaustive_find_cell(*this, verbose)) {
6,228✔
593
      mark_as_lost("After particle " + std::to_string(id()) +
18,678✔
594
                   " crossed surface " + std::to_string(surf.id_) +
24,900✔
595
                   " it could not be located in any cell and it did not leak.");
596
      return;
6,222✔
597
    }
598
  }
599
}
600

601
void Particle::cross_vacuum_bc(const Surface& surf)
22,214,482✔
602
{
603
  // Score any surface current tallies -- note that the particle is moved
604
  // forward slightly so that if the mesh boundary is on the surface, it is
605
  // still processed
606

607
  if (!model::active_meshsurf_tallies.empty()) {
22,214,482✔
608
    // TODO: Find a better solution to score surface currents than
609
    // physically moving the particle forward slightly
610

611
    r() += TINY_BIT * u();
1,637,800✔
612
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,637,800✔
613
  }
614

615
  // Score to global leakage tally
616
  keff_tally_leakage() += wgt();
22,214,482✔
617

618
  // Kill the particle
619
  wgt() = 0.0;
22,214,482✔
620

621
  // Display message
622
  if (settings::verbosity >= 10 || trace()) {
22,214,482✔
623
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
624
  }
625
}
22,214,482✔
626

627
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
617,942,636✔
628
{
629
  // Do not handle reflective boundary conditions on lower universes
630
  if (n_coord() != 1) {
617,942,636✔
UNCOV
631
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
632
                 " off surface in a lower universe.");
UNCOV
633
    return;
×
634
  }
635

636
  // Score surface currents since reflection causes the direction of the
637
  // particle to change. For surface filters, we need to score the tallies
638
  // twice, once before the particle's surface attribute has changed and
639
  // once after. For mesh surface filters, we need to artificially move
640
  // the particle slightly back in case the surface crossing is coincident
641
  // with a mesh boundary
642

643
  if (!model::active_surface_tallies.empty()) {
617,942,636✔
644
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
645
  }
646

647
  if (!model::active_meshsurf_tallies.empty()) {
617,942,636✔
648
    Position r {this->r()};
84,355,324✔
649
    this->r() -= TINY_BIT * u();
84,355,324✔
650
    score_surface_tally(*this, model::active_meshsurf_tallies);
84,355,324✔
651
    this->r() = r;
84,355,324✔
652
  }
653

654
  // Set the new particle direction
655
  u() = new_u;
617,942,636✔
656

657
  // Reassign particle's cell and surface
658
  coord(0).cell = cell_last(0);
617,942,636✔
659
  surface() = -surface();
617,942,636✔
660

661
  // If a reflective surface is coincident with a lattice or universe
662
  // boundary, it is necessary to redetermine the particle's coordinates in
663
  // the lower universes.
664
  // (unless we're using a dagmc model, which has exactly one universe)
665
  n_coord() = 1;
617,942,636✔
666
  if (surf.geom_type_ != GeometryType::DAG && !neighbor_list_find_cell(*this)) {
617,942,636✔
UNCOV
667
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
668
                 std::to_string(surf.id_) + ".");
×
UNCOV
669
    return;
×
670
  }
671

672
  // Set previous coordinate going slightly past surface crossing
673
  r_last_current() = r() + TINY_BIT * u();
617,942,636✔
674

675
  // Diagnostic message
676
  if (settings::verbosity >= 10 || trace()) {
617,942,636✔
UNCOV
677
    write_message(1, "    Reflected from surface {}", surf.id_);
×
678
  }
679
}
680

681
void Particle::cross_periodic_bc(
727,164✔
682
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
683
{
684
  // Do not handle periodic boundary conditions on lower universes
685
  if (n_coord() != 1) {
727,164✔
UNCOV
686
    mark_as_lost(
×
UNCOV
687
      "Cannot transfer particle " + std::to_string(id()) +
×
688
      " across surface in a lower universe. Boundary conditions must be "
689
      "applied to root universe.");
UNCOV
690
    return;
×
691
  }
692

693
  // Score surface currents since reflection causes the direction of the
694
  // particle to change -- artificially move the particle slightly back in
695
  // case the surface crossing is coincident with a mesh boundary
696
  if (!model::active_meshsurf_tallies.empty()) {
727,164✔
UNCOV
697
    Position r {this->r()};
×
UNCOV
698
    this->r() -= TINY_BIT * u();
×
UNCOV
699
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
700
    this->r() = r;
×
701
  }
702

703
  // Adjust the particle's location and direction.
704
  r() = new_r;
727,164✔
705
  u() = new_u;
727,164✔
706

707
  // Reassign particle's surface
708
  surface() = new_surface;
727,164✔
709

710
  // Figure out what cell particle is in now
711
  n_coord() = 1;
727,164✔
712

713
  if (!neighbor_list_find_cell(*this)) {
727,164✔
714
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
715
                 "boundary on surface " +
×
UNCOV
716
                 std::to_string(surf.id_) +
×
717
                 ". The normal vector "
718
                 "of one periodic surface may need to be reversed.");
UNCOV
719
    return;
×
720
  }
721

722
  // Set previous coordinate going slightly past surface crossing
723
  r_last_current() = r() + TINY_BIT * u();
727,164✔
724

725
  // Diagnostic message
726
  if (settings::verbosity >= 10 || trace()) {
727,164✔
UNCOV
727
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
728
  }
729
}
730

731
void Particle::mark_as_lost(const char* message)
6,228✔
732
{
733
  // Print warning and write lost particle file
734
  warning(message);
6,228✔
735
  if (settings::max_write_lost_particles < 0 ||
6,228✔
736
      simulation::n_lost_particles < settings::max_write_lost_particles) {
6,000✔
737
    write_restart();
313✔
738
  }
739
  // Increment number of lost particles
740
  wgt() = 0.0;
6,228✔
741
#pragma omp atomic
3,084✔
742
  simulation::n_lost_particles += 1;
3,144✔
743

744
  // Count the total number of simulated particles (on this processor)
745
  auto n = simulation::current_batch * settings::gen_per_batch *
6,228✔
746
           simulation::work_per_rank;
747

748
  // Abort the simulation if the maximum number of lost particles has been
749
  // reached
750
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
6,228✔
751
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
6✔
752
    fatal_error("Maximum number of lost particles has been reached.");
6✔
753
  }
754
}
6,222✔
755

756
void Particle::write_restart() const
313✔
757
{
758
  // Dont write another restart file if in particle restart mode
759
  if (settings::run_mode == RunMode::PARTICLE)
313✔
760
    return;
24✔
761

762
  // Set up file name
763
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
764
    simulation::current_batch, id());
289✔
765

766
#pragma omp critical(WriteParticleRestart)
234✔
767
  {
768
    // Create file
769
    hid_t file_id = file_open(filename, 'w');
289✔
770

771
    // Write filetype and version info
772
    write_attribute(file_id, "filetype", "particle restart");
289✔
773
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
289✔
774
    write_attribute(file_id, "openmc_version", VERSION);
289✔
775
#ifdef GIT_SHA1
776
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
289✔
777
#endif
778

779
    // Write data to file
780
    write_dataset(file_id, "current_batch", simulation::current_batch);
289✔
781
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
289✔
782
    write_dataset(file_id, "current_generation", simulation::current_gen);
289✔
783
    write_dataset(file_id, "n_particles", settings::n_particles);
289✔
784
    switch (settings::run_mode) {
289✔
785
    case RunMode::FIXED_SOURCE:
205✔
786
      write_dataset(file_id, "run_mode", "fixed source");
205✔
787
      break;
205✔
788
    case RunMode::EIGENVALUE:
84✔
789
      write_dataset(file_id, "run_mode", "eigenvalue");
84✔
790
      break;
84✔
UNCOV
791
    case RunMode::PARTICLE:
×
UNCOV
792
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
793
      break;
×
UNCOV
794
    default:
×
UNCOV
795
      break;
×
796
    }
797
    write_dataset(file_id, "id", id());
289✔
798
    write_dataset(file_id, "type", static_cast<int>(type()));
289✔
799

800
    int64_t i = current_work();
289✔
801
    if (settings::run_mode == RunMode::EIGENVALUE) {
289✔
802
      // take source data from primary bank for eigenvalue simulation
803
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
84✔
804
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
84✔
805
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
84✔
806
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
84✔
807
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
84✔
808
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
205✔
809
      // re-sample using rng random number seed used to generate source particle
810
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
205✔
811
                     settings::n_particles +
205✔
812
                   simulation::work_index[mpi::rank] + i;
205✔
813
      uint64_t seed = init_seed(id, STREAM_SOURCE);
205✔
814
      // re-sample source site
815
      auto site = sample_external_source(&seed);
205✔
816
      write_dataset(file_id, "weight", site.wgt);
205✔
817
      write_dataset(file_id, "energy", site.E);
205✔
818
      write_dataset(file_id, "xyz", site.r);
205✔
819
      write_dataset(file_id, "uvw", site.u);
205✔
820
      write_dataset(file_id, "time", site.time);
205✔
821
    }
822

823
    // Close file
824
    file_close(file_id);
289✔
825
  } // #pragma omp critical
826
}
289✔
827

828
void Particle::update_neutron_xs(
2,147,483,647✔
829
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
830
{
831
  // Get microscopic cross section cache
832
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
833

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

839
    // If NCrystal is being used, update micro cross section cache
840
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
841
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,722✔
842
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,722✔
843
    }
844
  }
845
}
2,147,483,647✔
846

847
//==============================================================================
848
// Non-method functions
849
//==============================================================================
850

851
std::string particle_type_to_str(ParticleType type)
3,245,772✔
852
{
853
  switch (type) {
3,245,772✔
854
  case ParticleType::neutron:
2,450,772✔
855
    return "neutron";
2,450,772✔
856
  case ParticleType::photon:
794,760✔
857
    return "photon";
794,760✔
858
  case ParticleType::electron:
120✔
859
    return "electron";
120✔
860
  case ParticleType::positron:
120✔
861
    return "positron";
120✔
862
  }
UNCOV
863
  UNREACHABLE();
×
864
}
865

866
ParticleType str_to_particle_type(std::string str)
3,230,655✔
867
{
868
  if (str == "neutron") {
3,230,655✔
869
    return ParticleType::neutron;
738,368✔
870
  } else if (str == "photon") {
2,492,287✔
871
    return ParticleType::photon;
2,492,219✔
872
  } else if (str == "electron") {
68✔
873
    return ParticleType::electron;
34✔
874
  } else if (str == "positron") {
34✔
875
    return ParticleType::positron;
34✔
876
  } else {
UNCOV
877
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
878
  }
879
}
880

881
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,315,849,182✔
882
{
883
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
884
      simulation::surf_source_bank.full()) {
1,077,507,222✔
885
    return;
1,315,780,309✔
886
  }
887

888
  // If a cell/cellfrom/cellto parameter is defined
889
  if (settings::ssw_cell_id != C_NONE) {
282,564✔
890

891
    // Retrieve cell index and storage type
892
    int cell_idx = model::cell_map[settings::ssw_cell_id];
252,160✔
893

894
    if (surf.bc_) {
252,160✔
895
      // Leave if cellto with vacuum boundary condition
896
      if (surf.bc_->type() == "vacuum" &&
190,404✔
897
          settings::ssw_cell_type == SSWCellType::To) {
29,191✔
898
        return;
11,982✔
899
      }
900

901
      // Leave if other boundary condition than vacuum
902
      if (surf.bc_->type() != "vacuum") {
149,231✔
903
        return;
132,022✔
904
      }
905
    }
906

907
    // Check if the cell of interest has been exited
908
    bool exited = false;
108,156✔
909
    for (int i = 0; i < p.n_coord_last(); ++i) {
287,779✔
910
      if (p.cell_last(i) == cell_idx) {
179,623✔
911
        exited = true;
65,540✔
912
      }
913
    }
914

915
    // Check if the cell of interest has been entered
916
    bool entered = false;
108,156✔
917
    for (int i = 0; i < p.n_coord(); ++i) {
258,208✔
918
      if (p.coord(i).cell == cell_idx) {
150,052✔
919
        entered = true;
53,694✔
920
      }
921
    }
922

923
    // Vacuum boundary conditions: return if cell is not exited
924
    if (surf.bc_) {
108,156✔
925
      if (surf.bc_->type() == "vacuum" && !exited) {
17,209✔
926
        return;
10,309✔
927
      }
928
    } else {
929

930
      // If we both enter and exit the cell of interest
931
      if (entered && exited) {
90,947✔
932
        return;
25,687✔
933
      }
934

935
      // If we did not enter nor exit the cell of interest
936
      if (!entered && !exited) {
65,260✔
937
        return;
11,200✔
938
      }
939

940
      // If cellfrom and the cell before crossing is not the cell of
941
      // interest
942
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
54,060✔
943
        return;
11,322✔
944
      }
945

946
      // If cellto and the cell after crossing is not the cell of interest
947
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
42,738✔
948
        return;
11,169✔
949
      }
950
    }
951
  }
952

953
  SourceSite site;
68,873✔
954
  site.r = p.r();
68,873✔
955
  site.u = p.u();
68,873✔
956
  site.E = p.E();
68,873✔
957
  site.time = p.time();
68,873✔
958
  site.wgt = p.wgt();
68,873✔
959
  site.delayed_group = p.delayed_group();
68,873✔
960
  site.surf_id = surf.id_;
68,873✔
961
  site.particle = p.type();
68,873✔
962
  site.parent_id = p.id();
68,873✔
963
  site.progeny_id = p.n_progeny();
68,873✔
964
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
68,873✔
965
}
966

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