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

openmc-dev / openmc / 15914061027

26 Jun 2025 10:49PM UTC coverage: 85.241% (+0.002%) from 85.239%
15914061027

Pull #3461

github

web-flow
Merge 09b49b487 into 5c1021446
Pull Request #3461: Refactor and Harden Configuration Management

48 of 56 new or added lines in 1 file covered. (85.71%)

280 existing lines in 11 files now uncovered.

52596 of 61703 relevant lines covered (85.24%)

36708109.72 hits per line

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

92.43
/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:
17,338,034✔
54
    mass = 0.0;
17,338,034✔
55
    break;
17,338,034✔
56
  case ParticleType::electron:
51,300,172✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
51,300,172✔
59
    break;
51,300,172✔
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);
858,848,592✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

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

78
bool Particle::create_secondary(
107,159,204✔
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)]) {
107,159,204✔
84
    return false;
51,249,703✔
85
  }
86

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

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

108
  // Convert signed index to a singed surface ID
109
  if (surface() == SURFACE_NONE) {
4,085,747✔
110
    bank.surf_id = SURFACE_NONE;
4,085,747✔
111
  } else {
UNCOV
112
    int surf_id = model::surfaces[surface_index()]->id_;
×
UNCOV
113
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
×
114
  }
115
}
4,085,747✔
116

117
void Particle::from_source(const SourceSite* src)
219,519,500✔
118
{
119
  // Reset some attributes
120
  clear();
219,519,500✔
121
  surface() = SURFACE_NONE;
219,519,500✔
122
  cell_born() = C_NONE;
219,519,500✔
123
  material() = C_NONE;
219,519,500✔
124
  n_collision() = 0;
219,519,500✔
125
  fission() = false;
219,519,500✔
126
  zero_flux_derivs();
219,519,500✔
127
  lifetime() = 0.0;
219,519,500✔
128

129
  // Copy attributes from source bank site
130
  type() = src->particle;
219,519,500✔
131
  wgt() = src->wgt;
219,519,500✔
132
  wgt_last() = src->wgt;
219,519,500✔
133
  r() = src->r;
219,519,500✔
134
  u() = src->u;
219,519,500✔
135
  r_born() = src->r;
219,519,500✔
136
  r_last_current() = src->r;
219,519,500✔
137
  r_last() = src->r;
219,519,500✔
138
  u_last() = src->u;
219,519,500✔
139
  if (settings::run_CE) {
219,519,500✔
140
    E() = src->E;
103,889,326✔
141
    g() = 0;
103,889,326✔
142
  } else {
143
    g() = static_cast<int>(src->E);
115,630,174✔
144
    g_last() = static_cast<int>(src->E);
115,630,174✔
145
    E() = data::mg.energy_bin_avg_[g()];
115,630,174✔
146
  }
147
  E_last() = E();
219,519,500✔
148
  time() = src->time;
219,519,500✔
149
  time_last() = src->time;
219,519,500✔
150
  parent_nuclide() = src->parent_nuclide;
219,519,500✔
151

152
  // Convert signed surface ID to signed index
153
  if (src->surf_id != SURFACE_NONE) {
219,519,500✔
154
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,000✔
155
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,000✔
156
  }
157
}
219,519,500✔
158

159
void Particle::event_calculate_xs()
2,147,483,647✔
160
{
161
  // Set the random number stream
162
  stream() = STREAM_TRACKING;
2,147,483,647✔
163

164
  // Store pre-collision particle properties
165
  wgt_last() = wgt();
2,147,483,647✔
166
  E_last() = E();
2,147,483,647✔
167
  u_last() = u();
2,147,483,647✔
168
  r_last() = r();
2,147,483,647✔
169
  time_last() = time();
2,147,483,647✔
170

171
  // Reset event variables
172
  event() = TallyEvent::KILL;
2,147,483,647✔
173
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
174
  event_mt() = REACTION_NONE;
2,147,483,647✔
175

176
  // If the cell hasn't been determined based on the particle's location,
177
  // initiate a search for the current cell. This generally happens at the
178
  // beginning of the history and again for any secondary particles
179
  if (lowest_coord().cell == C_NONE) {
2,147,483,647✔
180
    if (!exhaustive_find_cell(*this)) {
216,645,123✔
UNCOV
181
      mark_as_lost(
×
UNCOV
182
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
183
      return;
×
184
    }
185

186
    // Set birth cell attribute
187
    if (cell_born() == C_NONE)
216,645,123✔
188
      cell_born() = lowest_coord().cell;
216,645,123✔
189

190
    // Initialize last cells from current cell
191
    for (int j = 0; j < n_coord(); ++j) {
448,978,049✔
192
      cell_last(j) = coord(j).cell;
232,332,926✔
193
    }
194
    n_coord_last() = n_coord();
216,645,123✔
195
  }
196

197
  // Write particle track.
198
  if (write_track())
2,147,483,647✔
199
    write_particle_track(*this);
10,840✔
200

201
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
202
    check_cell_overlap(*this);
×
203

204
  // Calculate microscopic and macroscopic cross sections
205
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
206
    if (settings::run_CE) {
2,147,483,647✔
207
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,632,277,590✔
208
        // If the material is the same as the last material and the
209
        // temperature hasn't changed, we don't need to lookup cross
210
        // sections again.
211
        model::materials[material()]->calculate_xs(*this);
1,311,758,966✔
212
      }
213
    } else {
214
      // Get the MG data; unlike the CE case above, we have to re-calculate
215
      // cross sections for every collision since the cross sections may
216
      // be angle-dependent
217
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,702,466✔
218

219
      // Update the particle's group while we know we are multi-group
220
      g_last() = g();
2,062,702,466✔
221
    }
222
  } else {
223
    macro_xs().total = 0.0;
66,455,949✔
224
    macro_xs().absorption = 0.0;
66,455,949✔
225
    macro_xs().fission = 0.0;
66,455,949✔
226
    macro_xs().nu_fission = 0.0;
66,455,949✔
227
  }
228
}
229

230
void Particle::event_advance()
2,147,483,647✔
231
{
232
  // Find the distance to the nearest boundary
233
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
234

235
  // Sample a distance to collision
236
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
237
    collision_distance() = 0.0;
51,300,172✔
238
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
239
    collision_distance() = INFINITY;
66,455,949✔
240
  } else {
241
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
242
  }
243

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

247
  // Advance particle in space and time
248
  // Short-term solution until the surface source is revised and we can use
249
  // this->move_distance(distance)
250
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
251
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
252
  }
253
  double dt = distance / this->speed();
2,147,483,647✔
254
  this->time() += dt;
2,147,483,647✔
255
  this->lifetime() += dt;
2,147,483,647✔
256

257
  // Kill particle if its time exceeds the cutoff
258
  bool hit_time_boundary = false;
2,147,483,647✔
259
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
260
  if (time() > time_cutoff) {
2,147,483,647✔
261
    double dt = time() - time_cutoff;
11,000✔
262
    time() = time_cutoff;
11,000✔
263
    lifetime() = time_cutoff;
11,000✔
264

265
    double push_back_distance = speed() * dt;
11,000✔
266
    this->move_distance(-push_back_distance);
11,000✔
267
    hit_time_boundary = true;
11,000✔
268
  }
269

270
  // Score track-length tallies
271
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
272
    score_tracklength_tally(*this, distance);
1,244,452,704✔
273
  }
274

275
  // Score track-length estimate of k-eff
276
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
277
      type() == ParticleType::neutron) {
2,147,483,647✔
278
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
279
  }
280

281
  // Score flux derivative accumulators for differential tallies.
282
  if (!model::active_tallies.empty()) {
2,147,483,647✔
283
    score_track_derivative(*this, distance);
1,407,624,772✔
284
  }
285

286
  // Set particle weight to zero if it hit the time boundary
287
  if (hit_time_boundary) {
2,147,483,647✔
288
    wgt() = 0.0;
11,000✔
289
  }
290
}
2,147,483,647✔
291

292
void Particle::event_cross_surface()
2,022,136,385✔
293
{
294
  // Saving previous cell data
295
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
296
    cell_last(j) = coord(j).cell;
2,147,483,647✔
297
  }
298
  n_coord_last() = n_coord();
2,022,136,385✔
299

300
  // Set surface that particle is on and adjust coordinate levels
301
  surface() = boundary().surface;
2,022,136,385✔
302
  n_coord() = boundary().coord_level;
2,022,136,385✔
303

304
  if (boundary().lattice_translation[0] != 0 ||
2,022,136,385✔
305
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
306
      boundary().lattice_translation[2] != 0) {
1,537,107,821✔
307
    // Particle crosses lattice boundary
308

309
    bool verbose = settings::verbosity >= 10 || trace();
671,416,803✔
310
    cross_lattice(*this, boundary(), verbose);
671,416,803✔
311
    event() = TallyEvent::LATTICE;
671,416,803✔
312
  } else {
313
    // Particle crosses surface
314
    const auto& surf {model::surfaces[surface_index()].get()};
1,350,719,582✔
315
    // If BC, add particle to surface source before crossing surface
316
    if (surf->surf_source_ && surf->bc_) {
1,350,719,582✔
317
      add_surf_source_to_bank(*this, *surf);
633,486,858✔
318
    }
319
    this->cross_surface(*surf);
1,350,719,582✔
320
    // If no BC, add particle to surface source after crossing surface
321
    if (surf->surf_source_ && !surf->bc_) {
1,350,719,573✔
322
      add_surf_source_to_bank(*this, *surf);
716,329,306✔
323
    }
324
    if (settings::weight_window_checkpoint_surface) {
1,350,719,573✔
UNCOV
325
      apply_weight_windows(*this);
×
326
    }
327
    event() = TallyEvent::SURFACE;
1,350,719,573✔
328
  }
329
  // Score cell to cell partial currents
330
  if (!model::active_surface_tallies.empty()) {
2,022,136,376✔
331
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
332
  }
333
}
2,022,136,376✔
334

335
void Particle::event_collide()
2,147,483,647✔
336
{
337
  // Score collision estimate of keff
338
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
339
      type() == ParticleType::neutron) {
2,135,828,384✔
340
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,096,506,200✔
341
  }
342

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

347
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
348
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
349

350
  // Clear surface component
351
  surface() = SURFACE_NONE;
2,147,483,647✔
352

353
  if (settings::run_CE) {
2,147,483,647✔
354
    collision(*this);
722,448,808✔
355
  } else {
356
    collision_mg(*this);
1,781,765,117✔
357
  }
358

359
  // Score collision estimator tallies -- this is done after a collision
360
  // has occurred rather than before because we need information on the
361
  // outgoing energy for any tallies with an outgoing energy filter
362
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
363
    score_collision_tally(*this);
97,535,093✔
364
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
365
    if (settings::run_CE) {
113,305,951✔
366
      score_analog_tally_ce(*this);
112,104,740✔
367
    } else {
368
      score_analog_tally_mg(*this);
1,201,211✔
369
    }
370
  }
371

372
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
373
      type() == ParticleType::photon) {
16,918✔
374
    pht_collision_energy();
2,024✔
375
  }
376

377
  // Reset banked weight during collision
378
  n_bank() = 0;
2,147,483,647✔
379
  bank_second_E() = 0.0;
2,147,483,647✔
380
  wgt_bank() = 0.0;
2,147,483,647✔
381
  zero_delayed_bank();
2,147,483,647✔
382

383
  // Reset fission logical
384
  fission() = false;
2,147,483,647✔
385

386
  // Save coordinates for tallying purposes
387
  r_last_current() = r();
2,147,483,647✔
388

389
  // Set last material to none since cross sections will need to be
390
  // re-evaluated
391
  material_last() = C_NONE;
2,147,483,647✔
392

393
  // Set all directions to base level -- right now, after a collision, only
394
  // the base level directions are changed
395
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
396
    if (coord(j + 1).rotated) {
113,048,918✔
397
      // If next level is rotated, apply rotation matrix
398
      const auto& m {model::cells[coord(j).cell]->rotation_};
10,394,285✔
399
      const auto& u {coord(j).u};
10,394,285✔
400
      coord(j + 1).u = u.rotate(m);
10,394,285✔
401
    } else {
402
      // Otherwise, copy this level's direction
403
      coord(j + 1).u = coord(j).u;
102,654,633✔
404
    }
405
  }
406

407
  // Score flux derivative accumulators for differential tallies.
408
  if (!model::active_tallies.empty())
2,147,483,647✔
409
    score_collision_derivative(*this);
622,332,971✔
410

411
#ifdef DAGMC
412
  history().reset();
234,644,024✔
413
#endif
414
}
2,147,483,647✔
415

416
void Particle::event_revive_from_secondary()
2,147,483,647✔
417
{
418
  // If particle has too many events, display warning and kill it
419
  ++n_event();
2,147,483,647✔
420
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
UNCOV
421
    warning("Particle " + std::to_string(id()) +
×
422
            " underwent maximum number of events.");
UNCOV
423
    wgt() = 0.0;
×
424
  }
425

426
  // Check for secondary particles if this particle is dead
427
  if (!alive()) {
2,147,483,647✔
428
    // Write final position for this particle
429
    if (write_track()) {
216,644,718✔
430
      write_particle_track(*this);
6,676✔
431
    }
432

433
    // If no secondary particles, break out of event loop
434
    if (secondary_bank().empty())
216,644,718✔
435
      return;
156,310,715✔
436

437
    from_source(&secondary_bank().back());
60,334,003✔
438
    secondary_bank().pop_back();
60,334,003✔
439
    n_event() = 0;
60,334,003✔
440
    bank_second_E() = 0.0;
60,334,003✔
441

442
    // Subtract secondary particle energy from interim pulse-height results
443
    if (!model::active_pulse_height_tallies.empty() &&
60,349,502✔
444
        this->type() == ParticleType::photon) {
15,499✔
445
      // Since the birth cell of the particle has not been set we
446
      // have to determine it before the energy of the secondary particle can be
447
      // removed from the pulse-height of this cell.
448
      if (lowest_coord().cell == C_NONE) {
605✔
449
        bool verbose = settings::verbosity >= 10 || trace();
605✔
450
        if (!exhaustive_find_cell(*this, verbose)) {
605✔
UNCOV
451
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
452
                       std::to_string(id()));
×
UNCOV
453
          return;
×
454
        }
455
        // Set birth cell attribute
456
        if (cell_born() == C_NONE)
605✔
457
          cell_born() = lowest_coord().cell;
605✔
458

459
        // Initialize last cells from current cell
460
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
461
          cell_last(j) = coord(j).cell;
605✔
462
        }
463
        n_coord_last() = n_coord();
605✔
464
      }
465
      pht_secondary_particles();
605✔
466
    }
467

468
    // Enter new particle in particle track file
469
    if (write_track())
60,334,003✔
470
      add_particle_track(*this);
5,606✔
471
  }
472
}
473

474
void Particle::event_death()
156,311,715✔
475
{
476
#ifdef DAGMC
477
  history().reset();
14,536,599✔
478
#endif
479

480
  // Finish particle track output.
481
  if (write_track()) {
156,311,715✔
482
    finalize_particle_track(*this);
1,070✔
483
  }
484

485
// Contribute tally reduction variables to global accumulator
486
#pragma omp atomic
86,138,302✔
487
  global_tally_absorption += keff_tally_absorption();
156,311,715✔
488
#pragma omp atomic
85,953,322✔
489
  global_tally_collision += keff_tally_collision();
156,311,715✔
490
#pragma omp atomic
85,826,176✔
491
  global_tally_tracklength += keff_tally_tracklength();
156,311,715✔
492
#pragma omp atomic
85,616,074✔
493
  global_tally_leakage += keff_tally_leakage();
156,311,715✔
494

495
  // Reset particle tallies once accumulated
496
  keff_tally_absorption() = 0.0;
156,311,715✔
497
  keff_tally_collision() = 0.0;
156,311,715✔
498
  keff_tally_tracklength() = 0.0;
156,311,715✔
499
  keff_tally_leakage() = 0.0;
156,311,715✔
500

501
  if (!model::active_pulse_height_tallies.empty()) {
156,311,715✔
502
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
503
  }
504

505
  // Record the number of progeny created by this particle.
506
  // This data will be used to efficiently sort the fission bank.
507
  if (settings::run_mode == RunMode::EIGENVALUE) {
156,311,715✔
508
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,397,897✔
509
    simulation::progeny_per_particle[offset] = n_progeny();
133,397,897✔
510
  }
511
}
156,311,715✔
512

513
void Particle::pht_collision_energy()
2,024✔
514
{
515
  // Adds the energy particles lose in a collision to the pulse-height
516

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

521
  if (it != model::pulse_height_cells.end()) {
2,024✔
522
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
523
    pht_storage()[index] += E_last() - E();
2,024✔
524

525
    // If the energy of the particle is below the cutoff, it will not be sampled
526
    // so its energy is added to the pulse-height in the cell
527
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
528
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
529
      pht_storage()[index] += E();
825✔
530
    }
531
  }
532
}
2,024✔
533

534
void Particle::pht_secondary_particles()
605✔
535
{
536
  // Removes the energy of secondary produced particles from the pulse-height
537

538
  // determine index of cell in pulse_height_cells
539
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
540
    model::pulse_height_cells.end(), cell_born());
605✔
541

542
  if (it != model::pulse_height_cells.end()) {
605✔
543
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
544
    pht_storage()[index] -= E();
605✔
545
  }
546
}
605✔
547

548
void Particle::cross_surface(const Surface& surf)
1,351,702,850✔
549
{
550

551
  if (settings::verbosity >= 10 || trace()) {
1,351,702,850✔
552
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
553
  }
554

555
// if we're crossing a CSG surface, make sure the DAG history is reset
556
#ifdef DAGMC
557
  if (surf.geom_type() == GeometryType::CSG)
130,812,265✔
558
    history().reset();
130,776,949✔
559
#endif
560

561
  // Handle any applicable boundary conditions.
562
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,351,702,850✔
563
    surf.bc_->handle_particle(*this, surf);
633,724,475✔
564
    return;
633,724,475✔
565
  }
566

567
  // ==========================================================================
568
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
569

570
#ifdef DAGMC
571
  // in DAGMC, we know what the next cell should be
572
  if (surf.geom_type() == GeometryType::DAG) {
69,206,975✔
573
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
574
                       lowest_coord().universe) -
28,265✔
575
                     1;
28,265✔
576
    // save material and temp
577
    material_last() = material();
28,265✔
578
    sqrtkT_last() = sqrtkT();
28,265✔
579
    // set new cell value
580
    lowest_coord().cell = i_cell;
28,265✔
581
    auto& cell = model::cells[i_cell];
28,265✔
582

583
    cell_instance() = 0;
28,265✔
584
    if (cell->distribcell_index_ >= 0)
28,265✔
585
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
586

587
    material() = cell->material(cell_instance());
28,265✔
588
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
589
    return;
28,265✔
590
  }
591
#endif
592

593
  bool verbose = settings::verbosity >= 10 || trace();
717,950,110✔
594
  if (neighbor_list_find_cell(*this, verbose)) {
717,950,110✔
595
    return;
717,922,091✔
596
  }
597

598
  // ==========================================================================
599
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
600

601
  // Remove lower coordinate levels
602
  n_coord() = 1;
28,019✔
603
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
604

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

611
    surface() = SURFACE_NONE;
5,744✔
612
    n_coord() = 1;
5,744✔
613
    r() += TINY_BIT * u();
5,744✔
614

615
    // Couldn't find next cell anywhere! This probably means there is an actual
616
    // undefined region in the geometry.
617

618
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
619
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
620
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
621
                   " it could not be located in any cell and it did not leak.");
622
      return;
5,735✔
623
    }
624
  }
625
}
626

627
void Particle::cross_vacuum_bc(const Surface& surf)
30,466,649✔
628
{
629
  // Score any surface current tallies -- note that the particle is moved
630
  // forward slightly so that if the mesh boundary is on the surface, it is
631
  // still processed
632

633
  if (!model::active_meshsurf_tallies.empty()) {
30,466,649✔
634
    // TODO: Find a better solution to score surface currents than
635
    // physically moving the particle forward slightly
636

637
    r() += TINY_BIT * u();
1,021,265✔
638
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
639
  }
640

641
  // Score to global leakage tally
642
  keff_tally_leakage() += wgt();
30,466,649✔
643

644
  // Kill the particle
645
  wgt() = 0.0;
30,466,649✔
646

647
  // Display message
648
  if (settings::verbosity >= 10 || trace()) {
30,466,649✔
649
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
650
  }
651
}
30,466,649✔
652

653
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
603,618,864✔
654
{
655
  // Do not handle reflective boundary conditions on lower universes
656
  if (n_coord() != 1) {
603,618,864✔
UNCOV
657
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
658
                 " off surface in a lower universe.");
UNCOV
659
    return;
×
660
  }
661

662
  // Score surface currents since reflection causes the direction of the
663
  // particle to change. For surface filters, we need to score the tallies
664
  // twice, once before the particle's surface attribute has changed and
665
  // once after. For mesh surface filters, we need to artificially move
666
  // the particle slightly back in case the surface crossing is coincident
667
  // with a mesh boundary
668

669
  if (!model::active_surface_tallies.empty()) {
603,618,864✔
670
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
671
  }
672

673
  if (!model::active_meshsurf_tallies.empty()) {
603,618,864✔
674
    Position r {this->r()};
50,811,809✔
675
    this->r() -= TINY_BIT * u();
50,811,809✔
676
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
677
    this->r() = r;
50,811,809✔
678
  }
679

680
  // Set the new particle direction
681
  u() = new_u;
603,618,864✔
682

683
  // Reassign particle's cell and surface
684
  coord(0).cell = cell_last(0);
603,618,864✔
685
  surface() = -surface();
603,618,864✔
686

687
  // If a reflective surface is coincident with a lattice or universe
688
  // boundary, it is necessary to redetermine the particle's coordinates in
689
  // the lower universes.
690
  // (unless we're using a dagmc model, which has exactly one universe)
691
  n_coord() = 1;
603,618,864✔
692
  if (surf.geom_type() != GeometryType::DAG &&
1,207,235,189✔
693
      !neighbor_list_find_cell(*this)) {
603,616,325✔
UNCOV
694
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
695
                 std::to_string(surf.id_) + ".");
×
UNCOV
696
    return;
×
697
  }
698

699
  // Set previous coordinate going slightly past surface crossing
700
  r_last_current() = r() + TINY_BIT * u();
603,618,864✔
701

702
  // Diagnostic message
703
  if (settings::verbosity >= 10 || trace()) {
603,618,864✔
UNCOV
704
    write_message(1, "    Reflected from surface {}", surf.id_);
×
705
  }
706
}
707

708
void Particle::cross_periodic_bc(
666,318✔
709
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
710
{
711
  // Do not handle periodic boundary conditions on lower universes
712
  if (n_coord() != 1) {
666,318✔
713
    mark_as_lost(
×
UNCOV
714
      "Cannot transfer particle " + std::to_string(id()) +
×
715
      " across surface in a lower universe. Boundary conditions must be "
716
      "applied to root universe.");
UNCOV
717
    return;
×
718
  }
719

720
  // Score surface currents since reflection causes the direction of the
721
  // particle to change -- artificially move the particle slightly back in
722
  // case the surface crossing is coincident with a mesh boundary
723
  if (!model::active_meshsurf_tallies.empty()) {
666,318✔
UNCOV
724
    Position r {this->r()};
×
UNCOV
725
    this->r() -= TINY_BIT * u();
×
UNCOV
726
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
727
    this->r() = r;
×
728
  }
729

730
  // Adjust the particle's location and direction.
731
  r() = new_r;
666,318✔
732
  u() = new_u;
666,318✔
733

734
  // Reassign particle's surface
735
  surface() = new_surface;
666,318✔
736

737
  // Figure out what cell particle is in now
738
  n_coord() = 1;
666,318✔
739

740
  if (!neighbor_list_find_cell(*this)) {
666,318✔
UNCOV
741
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
742
                 "boundary on surface " +
×
UNCOV
743
                 std::to_string(surf.id_) +
×
744
                 ". The normal vector "
745
                 "of one periodic surface may need to be reversed.");
UNCOV
746
    return;
×
747
  }
748

749
  // Set previous coordinate going slightly past surface crossing
750
  r_last_current() = r() + TINY_BIT * u();
666,318✔
751

752
  // Diagnostic message
753
  if (settings::verbosity >= 10 || trace()) {
666,318✔
UNCOV
754
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
755
  }
756
}
757

758
void Particle::mark_as_lost(const char* message)
5,754✔
759
{
760
  // Print warning and write lost particle file
761
  warning(message);
5,754✔
762
  if (settings::max_write_lost_particles < 0 ||
5,754✔
763
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
764
    write_restart();
334✔
765
  }
766
  // Increment number of lost particles
767
  wgt() = 0.0;
5,754✔
768
#pragma omp atomic
3,134✔
769
  simulation::n_lost_particles += 1;
2,620✔
770

771
  // Count the total number of simulated particles (on this processor)
772
  auto n = simulation::current_batch * settings::gen_per_batch *
5,754✔
773
           simulation::work_per_rank;
774

775
  // Abort the simulation if the maximum number of lost particles has been
776
  // reached
777
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,754✔
778
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10✔
779
    fatal_error("Maximum number of lost particles has been reached.");
10✔
780
  }
781
}
5,744✔
782

783
void Particle::write_restart() const
334✔
784
{
785
  // Dont write another restart file if in particle restart mode
786
  if (settings::run_mode == RunMode::PARTICLE)
334✔
787
    return;
22✔
788

789
  // Set up file name
790
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
791
    simulation::current_batch, id());
585✔
792

793
#pragma omp critical(WriteParticleRestart)
334✔
794
  {
795
    // Create file
796
    hid_t file_id = file_open(filename, 'w');
312✔
797

798
    // Write filetype and version info
799
    write_attribute(file_id, "filetype", "particle restart");
312✔
800
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
312✔
801
    write_attribute(file_id, "openmc_version", VERSION);
312✔
802
#ifdef GIT_SHA1
803
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
804
#endif
805

806
    // Write data to file
807
    write_dataset(file_id, "current_batch", simulation::current_batch);
312✔
808
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
312✔
809
    write_dataset(file_id, "current_generation", simulation::current_gen);
312✔
810
    write_dataset(file_id, "n_particles", settings::n_particles);
312✔
811
    switch (settings::run_mode) {
312✔
812
    case RunMode::FIXED_SOURCE:
225✔
813
      write_dataset(file_id, "run_mode", "fixed source");
225✔
814
      break;
225✔
815
    case RunMode::EIGENVALUE:
87✔
816
      write_dataset(file_id, "run_mode", "eigenvalue");
87✔
817
      break;
87✔
UNCOV
818
    case RunMode::PARTICLE:
×
UNCOV
819
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
820
      break;
×
UNCOV
821
    default:
×
UNCOV
822
      break;
×
823
    }
824
    write_dataset(file_id, "id", id());
312✔
825
    write_dataset(file_id, "type", static_cast<int>(type()));
312✔
826

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

850
    // Close file
851
    file_close(file_id);
312✔
852
  } // #pragma omp critical
853
}
312✔
854

855
void Particle::update_neutron_xs(
2,147,483,647✔
856
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
857
{
858
  // Get microscopic cross section cache
859
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
860

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

866
    // If NCrystal is being used, update micro cross section cache
867
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
868
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
869
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
870
    }
871
  }
872
}
2,147,483,647✔
873

874
//==============================================================================
875
// Non-method functions
876
//==============================================================================
877

878
std::string particle_type_to_str(ParticleType type)
3,130,193✔
879
{
880
  switch (type) {
3,130,193✔
881
  case ParticleType::neutron:
2,399,936✔
882
    return "neutron";
2,399,936✔
883
  case ParticleType::photon:
729,993✔
884
    return "photon";
729,993✔
885
  case ParticleType::electron:
132✔
886
    return "electron";
132✔
887
  case ParticleType::positron:
132✔
888
    return "positron";
132✔
889
  }
890
  UNREACHABLE();
×
891
}
892

893
ParticleType str_to_particle_type(std::string str)
2,955,783✔
894
{
895
  if (str == "neutron") {
2,955,783✔
896
    return ParticleType::neutron;
676,426✔
897
  } else if (str == "photon") {
2,279,357✔
898
    return ParticleType::photon;
2,279,271✔
899
  } else if (str == "electron") {
86✔
900
    return ParticleType::electron;
43✔
901
  } else if (str == "positron") {
43✔
902
    return ParticleType::positron;
43✔
903
  } else {
UNCOV
904
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
905
  }
906
}
907

908
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,349,816,164✔
909
{
910
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
911
      simulation::surf_source_bank.full()) {
1,059,468,170✔
912
    return;
1,349,709,399✔
913
  }
914

915
  // If a cell/cellfrom/cellto parameter is defined
916
  if (settings::ssw_cell_id != C_NONE) {
319,268✔
917

918
    // Retrieve cell index and storage type
919
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,707✔
920

921
    if (surf.bc_) {
258,707✔
922
      // Leave if cellto with vacuum boundary condition
923
      if (surf.bc_->type() == "vacuum" &&
184,448✔
924
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
925
        return;
11,953✔
926
      }
927

928
      // Leave if other boundary condition than vacuum
929
      if (surf.bc_->type() != "vacuum") {
140,281✔
930
        return;
120,020✔
931
      }
932
    }
933

934
    // Check if the cell of interest has been exited
935
    bool exited = false;
126,734✔
936
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,345✔
937
      if (p.cell_last(i) == cell_idx) {
208,611✔
938
        exited = true;
74,235✔
939
      }
940
    }
941

942
    // Check if the cell of interest has been entered
943
    bool entered = false;
126,734✔
944
    for (int i = 0; i < p.n_coord(); ++i) {
301,041✔
945
      if (p.coord(i).cell == cell_idx) {
174,307✔
946
        entered = true;
59,100✔
947
      }
948
    }
949

950
    // Vacuum boundary conditions: return if cell is not exited
951
    if (surf.bc_) {
126,734✔
952
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
953
        return;
13,961✔
954
      }
955
    } else {
956

957
      // If we both enter and exit the cell of interest
958
      if (entered && exited) {
106,473✔
959
        return;
28,613✔
960
      }
961

962
      // If we did not enter nor exit the cell of interest
963
      if (!entered && !exited) {
77,860✔
964
        return;
14,351✔
965
      }
966

967
      // If cellfrom and the cell before crossing is not the cell of
968
      // interest
969
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,509✔
970
        return;
11,567✔
971
      }
972

973
      // If cellto and the cell after crossing is not the cell of interest
974
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
975
        return;
12,038✔
976
      }
977
    }
978
  }
979

980
  SourceSite site;
106,765✔
981
  site.r = p.r();
106,765✔
982
  site.u = p.u();
106,765✔
983
  site.E = p.E();
106,765✔
984
  site.time = p.time();
106,765✔
985
  site.wgt = p.wgt();
106,765✔
986
  site.delayed_group = p.delayed_group();
106,765✔
987
  site.surf_id = surf.id_;
106,765✔
988
  site.particle = p.type();
106,765✔
989
  site.parent_id = p.id();
106,765✔
990
  site.progeny_id = p.n_progeny();
106,765✔
991
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
106,765✔
992
}
993

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