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

openmc-dev / openmc / 13134187828

04 Feb 2025 11:13AM UTC coverage: 84.945% (+0.08%) from 84.869%
13134187828

Pull #3252

github

web-flow
Merge 6f397fdd5 into 59c398be8
Pull Request #3252: Adding vtkhdf option to write vtk data

80 of 92 new or added lines in 1 file covered. (86.96%)

1267 existing lines in 48 files now uncovered.

50221 of 59122 relevant lines covered (84.94%)

35221818.06 hits per line

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

92.72
/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,815,332✔
54
    mass = 0.0;
15,815,332✔
55
    break;
15,815,332✔
56
  case ParticleType::electron:
52,985,084✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,985,084✔
59
    break;
52,985,084✔
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);
911,455,995✔
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(
110,884,369✔
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)]) {
110,884,369✔
91
    return;
52,899,228✔
92
  }
93

94
  auto& bank = secondary_bank().emplace_back();
57,985,141✔
95
  bank.particle = type;
57,985,141✔
96
  bank.wgt = wgt;
57,985,141✔
97
  bank.r = r();
57,985,141✔
98
  bank.u = u;
57,985,141✔
99
  bank.E = settings::run_CE ? E : g();
57,985,141✔
100
  bank.time = time();
57,985,141✔
101
  bank_second_E() += bank.E;
57,985,141✔
102
}
103

104
void Particle::split(double wgt)
7,395,429✔
105
{
106
  auto& bank = secondary_bank().emplace_back();
7,395,429✔
107
  bank.particle = type();
7,395,429✔
108
  bank.wgt = wgt;
7,395,429✔
109
  bank.r = r();
7,395,429✔
110
  bank.u = u();
7,395,429✔
111
  bank.E = settings::run_CE ? E() : g();
7,395,429✔
112
  bank.time = time();
7,395,429✔
113
}
7,395,429✔
114

115
void Particle::from_source(const SourceSite* src)
228,514,333✔
116
{
117
  // Reset some attributes
118
  clear();
228,514,333✔
119
  surface() = SURFACE_NONE;
228,514,333✔
120
  cell_born() = C_NONE;
228,514,333✔
121
  material() = C_NONE;
228,514,333✔
122
  n_collision() = 0;
228,514,333✔
123
  fission() = false;
228,514,333✔
124
  zero_flux_derivs();
228,514,333✔
125

126
  // Copy attributes from source bank site
127
  type() = src->particle;
228,514,333✔
128
  wgt() = src->wgt;
228,514,333✔
129
  wgt_last() = src->wgt;
228,514,333✔
130
  r() = src->r;
228,514,333✔
131
  u() = src->u;
228,514,333✔
132
  r_born() = src->r;
228,514,333✔
133
  r_last_current() = src->r;
228,514,333✔
134
  r_last() = src->r;
228,514,333✔
135
  u_last() = src->u;
228,514,333✔
136
  if (settings::run_CE) {
228,514,333✔
137
    E() = src->E;
100,541,977✔
138
    g() = 0;
100,541,977✔
139
  } else {
140
    g() = static_cast<int>(src->E);
127,972,356✔
141
    g_last() = static_cast<int>(src->E);
127,972,356✔
142
    E() = data::mg.energy_bin_avg_[g()];
127,972,356✔
143
  }
144
  E_last() = E();
228,514,333✔
145
  time() = src->time;
228,514,333✔
146
  time_last() = src->time;
228,514,333✔
147
}
228,514,333✔
148

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

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

161
  // Reset event variables
162
  event() = TallyEvent::KILL;
2,147,483,647✔
163
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
164
  event_mt() = REACTION_NONE;
2,147,483,647✔
165

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

176
    // Set birth cell attribute
177
    if (cell_born() == C_NONE)
227,934,109✔
178
      cell_born() = lowest_coord().cell;
227,934,109✔
179

180
    // Initialize last cells from current cell
181
    for (int j = 0; j < n_coord(); ++j) {
480,313,737✔
182
      cell_last(j) = coord(j).cell;
252,379,628✔
183
    }
184
    n_coord_last() = n_coord();
227,934,109✔
185
  }
186

187
  // Write particle track.
188
  if (write_track())
2,147,483,647✔
189
    write_particle_track(*this);
11,591✔
190

191
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
192
    check_cell_overlap(*this);
×
193

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

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

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

225
  // Sample a distance to collision
226
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
227
    collision_distance() = 0.0;
52,985,084✔
228
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
229
    collision_distance() = INFINITY;
50,524,841✔
230
  } else {
231
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
232
  }
233

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

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

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

252
    double push_back_distance = speed() * dt;
12,000✔
253
    this->move_distance(-push_back_distance);
12,000✔
254
    hit_time_boundary = true;
12,000✔
255
  }
256

257
  // Score track-length tallies
258
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
259
    score_tracklength_tally(*this, distance);
1,443,027,712✔
260
  }
261

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

268
  // Score flux derivative accumulators for differential tallies.
269
  if (!model::active_tallies.empty()) {
2,147,483,647✔
270
    score_track_derivative(*this, distance);
1,674,577,302✔
271
  }
272

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

279
void Particle::event_cross_surface()
1,757,318,441✔
280
{
281
  // Saving previous cell data
282
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
283
    cell_last(j) = coord(j).cell;
2,147,483,647✔
284
  }
285
  n_coord_last() = n_coord();
1,757,318,441✔
286

287
  // Set surface that particle is on and adjust coordinate levels
288
  surface() = boundary().surface;
1,757,318,441✔
289
  n_coord() = boundary().coord_level;
1,757,318,441✔
290

291
  if (boundary().lattice_translation[0] != 0 ||
1,757,318,441✔
292
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
293
      boundary().lattice_translation[2] != 0) {
1,518,660,527✔
294
    // Particle crosses lattice boundary
295

296
    bool verbose = settings::verbosity >= 10 || trace();
295,700,081✔
297
    cross_lattice(*this, boundary(), verbose);
295,700,081✔
298
    event() = TallyEvent::LATTICE;
295,700,081✔
299
  } else {
300
    // Particle crosses surface
301
    // TODO: off-by-one
302
    const auto& surf {model::surfaces[surface_index()].get()};
1,461,618,360✔
303
    // If BC, add particle to surface source before crossing surface
304
    if (surf->surf_source_ && surf->bc_) {
1,461,618,360✔
305
      add_surf_source_to_bank(*this, *surf);
684,872,202✔
306
    }
307
    this->cross_surface(*surf);
1,461,618,360✔
308
    // If no BC, add particle to surface source after crossing surface
309
    if (surf->surf_source_ && !surf->bc_) {
1,461,618,350✔
310
      add_surf_source_to_bank(*this, *surf);
775,756,358✔
311
    }
312
    if (settings::weight_window_checkpoint_surface) {
1,461,618,350✔
UNCOV
313
      apply_weight_windows(*this);
×
314
    }
315
    event() = TallyEvent::SURFACE;
1,461,618,350✔
316
  }
317
  // Score cell to cell partial currents
318
  if (!model::active_surface_tallies.empty()) {
1,757,318,431✔
319
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
320
  }
321
}
1,757,318,431✔
322

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

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

335
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
336
    score_surface_tally(*this, model::active_meshsurf_tallies);
147,745,526✔
337

338
  // Clear surface component
339
  surface() = SURFACE_NONE;
2,147,483,647✔
340

341
  if (settings::run_CE) {
2,147,483,647✔
342
    collision(*this);
820,067,322✔
343
  } else {
344
    collision_mg(*this);
1,948,075,116✔
345
  }
346

347
  // Score collision estimator tallies -- this is done after a collision
348
  // has occurred rather than before because we need information on the
349
  // outgoing energy for any tallies with an outgoing energy filter
350
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
351
    score_collision_tally(*this);
99,209,724✔
352
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
353
    if (settings::run_CE) {
174,566,582✔
354
      score_analog_tally_ce(*this);
173,256,170✔
355
    } else {
356
      score_analog_tally_mg(*this);
1,310,412✔
357
    }
358
  }
359

360
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
361
      type() == ParticleType::photon) {
18,456✔
362
    pht_collision_energy();
2,208✔
363
  }
364

365
  // Reset banked weight during collision
366
  n_bank() = 0;
2,147,483,647✔
367
  bank_second_E() = 0.0;
2,147,483,647✔
368
  wgt_bank() = 0.0;
2,147,483,647✔
369
  zero_delayed_bank();
2,147,483,647✔
370

371
  // Reset fission logical
372
  fission() = false;
2,147,483,647✔
373

374
  // Save coordinates for tallying purposes
375
  r_last_current() = r();
2,147,483,647✔
376

377
  // Set last material to none since cross sections will need to be
378
  // re-evaluated
379
  material_last() = C_NONE;
2,147,483,647✔
380

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

395
  // Score flux derivative accumulators for differential tallies.
396
  if (!model::active_tallies.empty())
2,147,483,647✔
397
    score_collision_derivative(*this);
718,700,875✔
398

399
#ifdef DAGMC
400
  history().reset();
243,309,019✔
401
#endif
402
}
2,147,483,647✔
403

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

414
  // Check for secondary particles if this particle is dead
415
  if (!alive()) {
2,147,483,647✔
416
    // Write final position for this particle
417
    if (write_track()) {
227,933,759✔
418
      write_particle_track(*this);
7,082✔
419
    }
420

421
    // If no secondary particles, break out of event loop
422
    if (secondary_bank().empty())
227,933,759✔
423
      return;
162,349,836✔
424

425
    from_source(&secondary_bank().back());
65,583,923✔
426
    secondary_bank().pop_back();
65,583,923✔
427
    n_event() = 0;
65,583,923✔
428
    bank_second_E() = 0.0;
65,583,923✔
429

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

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

456
    // Enter new particle in particle track file
457
    if (write_track())
65,583,923✔
458
      add_particle_track(*this);
5,942✔
459
  }
460
}
461

462
void Particle::event_death()
162,350,836✔
463
{
464
#ifdef DAGMC
465
  history().reset();
14,046,165✔
466
#endif
467

468
  // Finish particle track output.
469
  if (write_track()) {
162,350,836✔
470
    finalize_particle_track(*this);
1,140✔
471
  }
472

473
// Contribute tally reduction variables to global accumulator
474
#pragma omp atomic
81,987,032✔
475
  global_tally_absorption += keff_tally_absorption();
162,350,836✔
476
#pragma omp atomic
82,439,376✔
477
  global_tally_collision += keff_tally_collision();
162,350,836✔
478
#pragma omp atomic
81,378,192✔
479
  global_tally_tracklength += keff_tally_tracklength();
162,350,836✔
480
#pragma omp atomic
81,084,443✔
481
  global_tally_leakage += keff_tally_leakage();
162,350,836✔
482

483
  // Reset particle tallies once accumulated
484
  keff_tally_absorption() = 0.0;
162,350,836✔
485
  keff_tally_collision() = 0.0;
162,350,836✔
486
  keff_tally_tracklength() = 0.0;
162,350,836✔
487
  keff_tally_leakage() = 0.0;
162,350,836✔
488

489
  if (!model::active_pulse_height_tallies.empty()) {
162,350,836✔
490
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
491
  }
492

493
  // Record the number of progeny created by this particle.
494
  // This data will be used to efficiently sort the fission bank.
495
  if (settings::run_mode == RunMode::EIGENVALUE) {
162,350,836✔
496
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,595,600✔
497
    simulation::progeny_per_particle[offset] = n_progeny();
148,595,600✔
498
  }
499
}
162,350,836✔
500

501
void Particle::pht_collision_energy()
2,208✔
502
{
503
  // Adds the energy particles lose in a collision to the pulse-height
504

505
  // determine index of cell in pulse_height_cells
506
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
507
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
508

509
  if (it != model::pulse_height_cells.end()) {
2,208✔
510
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
511
    pht_storage()[index] += E_last() - E();
2,208✔
512

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

522
void Particle::pht_secondary_particles()
660✔
523
{
524
  // Removes the energy of secondary produced particles from the pulse-height
525

526
  // determine index of cell in pulse_height_cells
527
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
528
    model::pulse_height_cells.end(), cell_born());
660✔
529

530
  if (it != model::pulse_height_cells.end()) {
660✔
531
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
532
    pht_storage()[index] -= E();
660✔
533
  }
534
}
660✔
535

536
void Particle::cross_surface(const Surface& surf)
1,461,618,360✔
537
{
538

539
  if (settings::verbosity >= 10 || trace()) {
1,461,618,360✔
540
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
541
  }
542

543
// if we're crossing a CSG surface, make sure the DAG history is reset
544
#ifdef DAGMC
545
  if (surf.geom_type() == GeometryType::CSG)
140,273,363✔
546
    history().reset();
140,238,047✔
547
#endif
548

549
  // Handle any applicable boundary conditions.
550
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,461,618,360✔
551
    surf.bc_->handle_particle(*this, surf);
685,132,173✔
552
    return;
685,132,173✔
553
  }
554

555
  // ==========================================================================
556
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
557

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

571
    cell_instance() = 0;
28,265✔
572
    if (cell->distribcell_index_ >= 0)
28,265✔
573
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
574

575
    material() = cell->material(cell_instance());
28,265✔
576
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
577
    return;
28,265✔
578
  }
579
#endif
580

581
  bool verbose = settings::verbosity >= 10 || trace();
776,457,922✔
582
  if (neighbor_list_find_cell(*this, verbose)) {
776,457,922✔
583
    return;
776,427,354✔
584
  }
585

586
  // ==========================================================================
587
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
588

589
  // Remove lower coordinate levels
590
  n_coord() = 1;
30,568✔
591
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
592

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

599
    surface() = SURFACE_NONE;
6,268✔
600
    n_coord() = 1;
6,268✔
601
    r() += TINY_BIT * u();
6,268✔
602

603
    // Couldn't find next cell anywhere! This probably means there is an actual
604
    // undefined region in the geometry.
605

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

615
void Particle::cross_vacuum_bc(const Surface& surf)
22,930,051✔
616
{
617
  // Score any surface current tallies -- note that the particle is moved
618
  // forward slightly so that if the mesh boundary is on the surface, it is
619
  // still processed
620

621
  if (!model::active_meshsurf_tallies.empty()) {
22,930,051✔
622
    // TODO: Find a better solution to score surface currents than
623
    // physically moving the particle forward slightly
624

625
    r() += TINY_BIT * u();
2,092,690✔
626
    score_surface_tally(*this, model::active_meshsurf_tallies);
2,092,690✔
627
  }
628

629
  // Score to global leakage tally
630
  keff_tally_leakage() += wgt();
22,930,051✔
631

632
  // Kill the particle
633
  wgt() = 0.0;
22,930,051✔
634

635
  // Display message
636
  if (settings::verbosity >= 10 || trace()) {
22,930,051✔
637
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
638
  }
639
}
22,930,051✔
640

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

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

657
  if (!model::active_surface_tallies.empty()) {
662,595,710✔
658
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
659
  }
660

661
  if (!model::active_meshsurf_tallies.empty()) {
662,595,710✔
662
    Position r {this->r()};
109,473,760✔
663
    this->r() -= TINY_BIT * u();
109,473,760✔
664
    score_surface_tally(*this, model::active_meshsurf_tallies);
109,473,760✔
665
    this->r() = r;
109,473,760✔
666
  }
667

668
  // Set the new particle direction
669
  u() = new_u;
662,595,710✔
670

671
  // Reassign particle's cell and surface
672
  coord(0).cell = cell_last(0);
662,595,710✔
673
  surface() = -surface();
662,595,710✔
674

675
  // If a reflective surface is coincident with a lattice or universe
676
  // boundary, it is necessary to redetermine the particle's coordinates in
677
  // the lower universes.
678
  // (unless we're using a dagmc model, which has exactly one universe)
679
  n_coord() = 1;
662,595,710✔
680
  if (surf.geom_type() != GeometryType::DAG &&
1,325,188,881✔
681
      !neighbor_list_find_cell(*this)) {
662,593,171✔
UNCOV
682
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
683
                 std::to_string(surf.id_) + ".");
×
UNCOV
684
    return;
×
685
  }
686

687
  // Set previous coordinate going slightly past surface crossing
688
  r_last_current() = r() + TINY_BIT * u();
662,595,710✔
689

690
  // Diagnostic message
691
  if (settings::verbosity >= 10 || trace()) {
662,595,710✔
692
    write_message(1, "    Reflected from surface {}", surf.id_);
×
693
  }
694
}
695

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

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

718
  // Adjust the particle's location and direction.
719
  r() = new_r;
727,164✔
720
  u() = new_u;
727,164✔
721

722
  // Reassign particle's surface
723
  surface() = new_surface;
727,164✔
724

725
  // Figure out what cell particle is in now
726
  n_coord() = 1;
727,164✔
727

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

737
  // Set previous coordinate going slightly past surface crossing
738
  r_last_current() = r() + TINY_BIT * u();
727,164✔
739

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

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

759
  // Count the total number of simulated particles (on this processor)
760
  auto n = simulation::current_batch * settings::gen_per_batch *
6,268✔
761
           simulation::work_per_rank;
762

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

771
void Particle::write_restart() const
353✔
772
{
773
  // Dont write another restart file if in particle restart mode
774
  if (settings::run_mode == RunMode::PARTICLE)
353✔
775
    return;
24✔
776

777
  // Set up file name
778
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
779
    simulation::current_batch, id());
619✔
780

781
#pragma omp critical(WriteParticleRestart)
314✔
782
  {
783
    // Create file
784
    hid_t file_id = file_open(filename, 'w');
329✔
785

786
    // Write filetype and version info
787
    write_attribute(file_id, "filetype", "particle restart");
329✔
788
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
329✔
789
    write_attribute(file_id, "openmc_version", VERSION);
329✔
790
#ifdef GIT_SHA1
791
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
329✔
792
#endif
793

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

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

838
    // Close file
839
    file_close(file_id);
329✔
840
  } // #pragma omp critical
841
}
329✔
842

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

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

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

862
//==============================================================================
863
// Non-method functions
864
//==============================================================================
865

866
std::string particle_type_to_str(ParticleType type)
3,252,552✔
867
{
868
  switch (type) {
3,252,552✔
869
  case ParticleType::neutron:
2,456,004✔
870
    return "neutron";
2,456,004✔
871
  case ParticleType::photon:
796,308✔
872
    return "photon";
796,308✔
873
  case ParticleType::electron:
120✔
874
    return "electron";
120✔
875
  case ParticleType::positron:
120✔
876
    return "positron";
120✔
877
  }
UNCOV
878
  UNREACHABLE();
×
879
}
880

881
ParticleType str_to_particle_type(std::string str)
3,390,873✔
882
{
883
  if (str == "neutron") {
3,390,873✔
884
    return ParticleType::neutron;
780,032✔
885
  } else if (str == "photon") {
2,610,841✔
886
    return ParticleType::photon;
2,610,773✔
887
  } else if (str == "electron") {
68✔
888
    return ParticleType::electron;
34✔
889
  } else if (str == "positron") {
34✔
890
    return ParticleType::positron;
34✔
891
  } else {
UNCOV
892
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
893
  }
894
}
895

896
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,460,628,560✔
897
{
898
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
899
      simulation::surf_source_bank.full()) {
1,150,985,641✔
900
    return;
1,460,511,962✔
901
  }
902

903
  // If a cell/cellfrom/cellto parameter is defined
904
  if (settings::ssw_cell_id != C_NONE) {
349,629✔
905

906
    // Retrieve cell index and storage type
907
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,434✔
908

909
    if (surf.bc_) {
283,434✔
910
      // Leave if cellto with vacuum boundary condition
911
      if (surf.bc_->type() == "vacuum" &&
202,454✔
912
          settings::ssw_cell_type == SSWCellType::To) {
35,216✔
913
        return;
13,071✔
914
      }
915

916
      // Leave if other boundary condition than vacuum
917
      if (surf.bc_->type() != "vacuum") {
154,167✔
918
        return;
132,022✔
919
      }
920
    }
921

922
    // Check if the cell of interest has been exited
923
    bool exited = false;
138,341✔
924
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,529✔
925
      if (p.cell_last(i) == cell_idx) {
228,188✔
926
        exited = true;
81,191✔
927
      }
928
    }
929

930
    // Check if the cell of interest has been entered
931
    bool entered = false;
138,341✔
932
    for (int i = 0; i < p.n_coord(); ++i) {
328,928✔
933
      if (p.coord(i).cell == cell_idx) {
190,587✔
934
        entered = true;
64,717✔
935
      }
936
    }
937

938
    // Vacuum boundary conditions: return if cell is not exited
939
    if (surf.bc_) {
138,341✔
940
      if (surf.bc_->type() == "vacuum" && !exited) {
22,145✔
941
        return;
15,245✔
942
      }
943
    } else {
944

945
      // If we both enter and exit the cell of interest
946
      if (entered && exited) {
116,196✔
947
        return;
31,409✔
948
      }
949

950
      // If we did not enter nor exit the cell of interest
951
      if (!entered && !exited) {
84,787✔
952
        return;
15,497✔
953
      }
954

955
      // If cellfrom and the cell before crossing is not the cell of
956
      // interest
957
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
69,290✔
958
        return;
12,665✔
959
      }
960

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

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

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