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

openmc-dev / openmc / 13209514200

07 Feb 2025 11:06PM UTC coverage: 84.905% (+0.04%) from 84.867%
13209514200

Pull #2655

github

web-flow
Merge ada075afa into 6e0f156d3
Pull Request #2655: Raytrace plots

392 of 442 new or added lines in 5 files covered. (88.69%)

1006 existing lines in 45 files now uncovered.

50343 of 59293 relevant lines covered (84.91%)

34881754.74 hits per line

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

92.66
/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,822,014✔
54
    mass = 0.0;
15,822,014✔
55
    break;
15,822,014✔
56
  case ParticleType::electron:
52,992,952✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,992,952✔
59
    break;
52,992,952✔
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);
908,431,459✔
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::create_secondary(
110,898,490✔
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)]) {
110,898,490✔
84
    return;
52,907,175✔
85
  }
86

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

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

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

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

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

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

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

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

169
    // Set birth cell attribute
170
    if (cell_born() == C_NONE)
227,372,584✔
171
      cell_born() = lowest_coord().cell;
227,372,584✔
172

173
    // Initialize last cells from current cell
174
    for (int j = 0; j < n_coord(); ++j) {
479,059,471✔
175
      cell_last(j) = coord(j).cell;
251,686,887✔
176
    }
177
    n_coord_last() = n_coord();
227,372,584✔
178
  }
179

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

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

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

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

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

218
  // Sample a distance to collision
219
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
220
    collision_distance() = 0.0;
52,992,952✔
221
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
222
    collision_distance() = INFINITY;
50,524,863✔
223
  } else {
224
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
225
  }
226

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

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

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

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

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

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

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

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

272
void Particle::event_cross_surface()
1,736,992,339✔
273
{
274
  // Saving previous cell data
275
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
276
    cell_last(j) = coord(j).cell;
2,147,483,647✔
277
  }
278
  n_coord_last() = n_coord();
1,736,992,339✔
279

280
  // Set surface that particle is on and adjust coordinate levels
281
  surface() = boundary().surface;
1,736,992,339✔
282
  n_coord() = boundary().coord_level;
1,736,992,339✔
283

284
  if (boundary().lattice_translation[0] != 0 ||
1,736,992,339✔
285
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
286
      boundary().lattice_translation[2] != 0) {
1,499,572,773✔
287
    // Particle crosses lattice boundary
288

289
    bool verbose = settings::verbosity >= 10 || trace();
294,461,736✔
290
    cross_lattice(*this, boundary(), verbose);
294,461,736✔
291
    event() = TallyEvent::LATTICE;
294,461,736✔
292
  } else {
293
    // Particle crosses surface
294
    // TODO: off-by-one
295
    const auto& surf {model::surfaces[surface_index()].get()};
1,442,530,603✔
296
    // If BC, add particle to surface source before crossing surface
297
    if (surf->surf_source_ && surf->bc_) {
1,442,530,603✔
298
      add_surf_source_to_bank(*this, *surf);
675,324,360✔
299
    }
300
    this->cross_surface(*surf);
1,442,530,603✔
301
    // If no BC, add particle to surface source after crossing surface
302
    if (surf->surf_source_ && !surf->bc_) {
1,442,530,593✔
303
      add_surf_source_to_bank(*this, *surf);
766,216,443✔
304
    }
305
    if (settings::weight_window_checkpoint_surface) {
1,442,530,593✔
UNCOV
306
      apply_weight_windows(*this);
×
307
    }
308
    event() = TallyEvent::SURFACE;
1,442,530,593✔
309
  }
310
  // Score cell to cell partial currents
311
  if (!model::active_surface_tallies.empty()) {
1,736,992,329✔
312
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
313
  }
314
}
1,736,992,329✔
315

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

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

328
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
329
    score_surface_tally(*this, model::active_meshsurf_tallies);
136,443,972✔
330

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

334
  if (settings::run_CE) {
2,147,483,647✔
335
    collision(*this);
808,405,911✔
336
  } else {
337
    collision_mg(*this);
1,948,075,116✔
338
  }
339

340
  // Score collision estimator tallies -- this is done after a collision
341
  // has occurred rather than before because we need information on the
342
  // outgoing energy for any tallies with an outgoing energy filter
343
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
344
    score_collision_tally(*this);
99,224,274✔
345
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
346
    if (settings::run_CE) {
163,265,028✔
347
      score_analog_tally_ce(*this);
161,954,616✔
348
    } else {
349
      score_analog_tally_mg(*this);
1,310,412✔
350
    }
351
  }
352

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

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

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

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

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

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

388
  // Score flux derivative accumulators for differential tallies.
389
  if (!model::active_tallies.empty())
2,147,483,647✔
390
    score_collision_derivative(*this);
707,039,464✔
391

392
#ifdef DAGMC
393
  history().reset();
243,106,935✔
394
#endif
395
}
2,147,483,647✔
396

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

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

414
    // If no secondary particles, break out of event loop
415
    if (secondary_bank().empty())
227,372,234✔
416
      return;
161,780,816✔
417

418
    from_source(&secondary_bank().back());
65,591,418✔
419
    secondary_bank().pop_back();
65,591,418✔
420
    n_event() = 0;
65,591,418✔
421
    bank_second_E() = 0.0;
65,591,418✔
422

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

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

449
    // Enter new particle in particle track file
450
    if (write_track())
65,591,418✔
451
      add_particle_track(*this);
5,942✔
452
  }
453
}
454

455
void Particle::event_death()
161,781,816✔
456
{
457
#ifdef DAGMC
458
  history().reset();
14,038,145✔
459
#endif
460

461
  // Finish particle track output.
462
  if (write_track()) {
161,781,816✔
463
    finalize_particle_track(*this);
1,140✔
464
  }
465

466
// Contribute tally reduction variables to global accumulator
467
#pragma omp atomic
81,462,004✔
468
  global_tally_absorption += keff_tally_absorption();
161,781,816✔
469
#pragma omp atomic
81,684,318✔
470
  global_tally_collision += keff_tally_collision();
161,781,816✔
471
#pragma omp atomic
81,293,279✔
472
  global_tally_tracklength += keff_tally_tracklength();
161,781,816✔
473
#pragma omp atomic
80,800,956✔
474
  global_tally_leakage += keff_tally_leakage();
161,781,816✔
475

476
  // Reset particle tallies once accumulated
477
  keff_tally_absorption() = 0.0;
161,781,816✔
478
  keff_tally_collision() = 0.0;
161,781,816✔
479
  keff_tally_tracklength() = 0.0;
161,781,816✔
480
  keff_tally_leakage() = 0.0;
161,781,816✔
481

482
  if (!model::active_pulse_height_tallies.empty()) {
161,781,816✔
483
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
484
  }
485

486
  // Record the number of progeny created by this particle.
487
  // This data will be used to efficiently sort the fission bank.
488
  if (settings::run_mode == RunMode::EIGENVALUE) {
161,781,816✔
489
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,026,600✔
490
    simulation::progeny_per_particle[offset] = n_progeny();
148,026,600✔
491
  }
492
}
161,781,816✔
493

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

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

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

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

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

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

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

529
void Particle::cross_surface(const Surface& surf)
1,442,530,603✔
530
{
531

532
  if (settings::verbosity >= 10 || trace()) {
1,442,530,603✔
533
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
534
  }
535

536
// if we're crossing a CSG surface, make sure the DAG history is reset
537
#ifdef DAGMC
538
  if (surf.geom_type() == GeometryType::CSG)
138,547,518✔
539
    history().reset();
138,512,202✔
540
#endif
541

542
  // Handle any applicable boundary conditions.
543
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,442,530,603✔
544
    surf.bc_->handle_particle(*this, surf);
675,584,331✔
545
    return;
675,584,331✔
546
  }
547

548
  // ==========================================================================
549
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
550

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

564
    cell_instance() = 0;
28,265✔
565
    if (cell->distribcell_index_ >= 0)
28,265✔
566
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
567

568
    material() = cell->material(cell_instance());
28,265✔
569
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
570
    return;
28,265✔
571
  }
572
#endif
573

574
  bool verbose = settings::verbosity >= 10 || trace();
766,918,007✔
575
  if (neighbor_list_find_cell(*this, verbose)) {
766,918,007✔
576
    return;
766,887,439✔
577
  }
578

579
  // ==========================================================================
580
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
581

582
  // Remove lower coordinate levels
583
  n_coord() = 1;
30,568✔
584
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
585

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

592
    surface() = SURFACE_NONE;
6,268✔
593
    n_coord() = 1;
6,268✔
594
    r() += TINY_BIT * u();
6,268✔
595

596
    // Couldn't find next cell anywhere! This probably means there is an actual
597
    // undefined region in the geometry.
598

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

608
void Particle::cross_vacuum_bc(const Surface& surf)
22,778,402✔
609
{
610
  // Score any surface current tallies -- note that the particle is moved
611
  // forward slightly so that if the mesh boundary is on the surface, it is
612
  // still processed
613

614
  if (!model::active_meshsurf_tallies.empty()) {
22,778,402✔
615
    // TODO: Find a better solution to score surface currents than
616
    // physically moving the particle forward slightly
617

618
    r() += TINY_BIT * u();
1,941,060✔
619
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,941,060✔
620
  }
621

622
  // Score to global leakage tally
623
  keff_tally_leakage() += wgt();
22,778,402✔
624

625
  // Kill the particle
626
  wgt() = 0.0;
22,778,402✔
627

628
  // Display message
629
  if (settings::verbosity >= 10 || trace()) {
22,778,402✔
630
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
631
  }
632
}
22,778,402✔
633

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

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

650
  if (!model::active_surface_tallies.empty()) {
653,199,517✔
651
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
652
  }
653

654
  if (!model::active_meshsurf_tallies.empty()) {
653,199,517✔
655
    Position r {this->r()};
101,100,948✔
656
    this->r() -= TINY_BIT * u();
101,100,948✔
657
    score_surface_tally(*this, model::active_meshsurf_tallies);
101,100,948✔
658
    this->r() = r;
101,100,948✔
659
  }
660

661
  // Set the new particle direction
662
  u() = new_u;
653,199,517✔
663

664
  // Reassign particle's cell and surface
665
  coord(0).cell = cell_last(0);
653,199,517✔
666
  surface() = -surface();
653,199,517✔
667

668
  // If a reflective surface is coincident with a lattice or universe
669
  // boundary, it is necessary to redetermine the particle's coordinates in
670
  // the lower universes.
671
  // (unless we're using a dagmc model, which has exactly one universe)
672
  n_coord() = 1;
653,199,517✔
673
  if (surf.geom_type() != GeometryType::DAG &&
1,306,396,495✔
674
      !neighbor_list_find_cell(*this)) {
653,196,978✔
UNCOV
675
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
676
                 std::to_string(surf.id_) + ".");
×
UNCOV
677
    return;
×
678
  }
679

680
  // Set previous coordinate going slightly past surface crossing
681
  r_last_current() = r() + TINY_BIT * u();
653,199,517✔
682

683
  // Diagnostic message
684
  if (settings::verbosity >= 10 || trace()) {
653,199,517✔
685
    write_message(1, "    Reflected from surface {}", surf.id_);
×
686
  }
687
}
688

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

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

711
  // Adjust the particle's location and direction.
712
  r() = new_r;
727,164✔
713
  u() = new_u;
727,164✔
714

715
  // Reassign particle's surface
716
  surface() = new_surface;
727,164✔
717

718
  // Figure out what cell particle is in now
719
  n_coord() = 1;
727,164✔
720

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

730
  // Set previous coordinate going slightly past surface crossing
731
  r_last_current() = r() + TINY_BIT * u();
727,164✔
732

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

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

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

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

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

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

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

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

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

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

831
    // Close file
832
    file_close(file_id);
329✔
833
  } // #pragma omp critical
834
}
329✔
835

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

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

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

855
//==============================================================================
856
// Non-method functions
857
//==============================================================================
858

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

874
ParticleType str_to_particle_type(std::string str)
3,331,139✔
875
{
876
  if (str == "neutron") {
3,331,139✔
877
    return ParticleType::neutron;
765,796✔
878
  } else if (str == "photon") {
2,565,343✔
879
    return ParticleType::photon;
2,565,275✔
880
  } else if (str == "electron") {
68✔
881
    return ParticleType::electron;
34✔
882
  } else if (str == "positron") {
34✔
883
    return ParticleType::positron;
34✔
884
  } else {
UNCOV
885
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
886
  }
887
}
888

889
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,441,540,803✔
890
{
891
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
892
      simulation::surf_source_bank.full()) {
1,139,672,636✔
893
    return;
1,441,424,205✔
894
  }
895

896
  // If a cell/cellfrom/cellto parameter is defined
897
  if (settings::ssw_cell_id != C_NONE) {
349,631✔
898

899
    // Retrieve cell index and storage type
900
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,436✔
901

902
    if (surf.bc_) {
283,436✔
903
      // Leave if cellto with vacuum boundary condition
904
      if (surf.bc_->type() == "vacuum" &&
202,456✔
905
          settings::ssw_cell_type == SSWCellType::To) {
35,217✔
906
        return;
13,071✔
907
      }
908

909
      // Leave if other boundary condition than vacuum
910
      if (surf.bc_->type() != "vacuum") {
154,168✔
911
        return;
132,022✔
912
      }
913
    }
914

915
    // Check if the cell of interest has been exited
916
    bool exited = false;
138,343✔
917
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,533✔
918
      if (p.cell_last(i) == cell_idx) {
228,190✔
919
        exited = true;
81,191✔
920
      }
921
    }
922

923
    // Check if the cell of interest has been entered
924
    bool entered = false;
138,343✔
925
    for (int i = 0; i < p.n_coord(); ++i) {
328,932✔
926
      if (p.coord(i).cell == cell_idx) {
190,589✔
927
        entered = true;
64,716✔
928
      }
929
    }
930

931
    // Vacuum boundary conditions: return if cell is not exited
932
    if (surf.bc_) {
138,343✔
933
      if (surf.bc_->type() == "vacuum" && !exited) {
22,146✔
934
        return;
15,246✔
935
      }
936
    } else {
937

938
      // If we both enter and exit the cell of interest
939
      if (entered && exited) {
116,197✔
940
        return;
31,409✔
941
      }
942

943
      // If we did not enter nor exit the cell of interest
944
      if (!entered && !exited) {
84,788✔
945
        return;
15,499✔
946
      }
947

948
      // If cellfrom and the cell before crossing is not the cell of
949
      // interest
950
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
69,289✔
951
        return;
12,664✔
952
      }
953

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

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

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

© 2025 Coveralls, Inc