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

openmc-dev / openmc / 19058781736

04 Nov 2025 05:26AM UTC coverage: 82.008% (-3.1%) from 85.155%
19058781736

Pull #3252

github

web-flow
Merge b8a72730f into bd76fc056
Pull Request #3252: Adding vtkhdf option to write vtk data

16714 of 23236 branches covered (71.93%)

Branch coverage included in aggregate %.

61 of 66 new or added lines in 1 file covered. (92.42%)

3175 existing lines in 103 files now uncovered.

54243 of 63288 relevant lines covered (85.71%)

43393337.77 hits per line

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

85.33
/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 OPENMC_DAGMC_ENABLED
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
  if (settings::run_CE) {
2,147,483,647✔
48
    // Determine mass in eV/c^2
49
    double mass;
50
    switch (this->type()) {
1,978,233,717!
51
    case ParticleType::neutron:
1,901,841,328✔
52
      mass = MASS_NEUTRON_EV;
1,901,841,328✔
53
      break;
1,901,841,328✔
54
    case ParticleType::photon:
22,195,420✔
55
      mass = 0.0;
22,195,420✔
56
      break;
22,195,420✔
57
    case ParticleType::electron:
54,196,969✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
54,196,969✔
60
      break;
54,196,969✔
61
    }
62
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
63
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,978,233,717✔
64
           (this->E() + mass);
1,978,233,717✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
67
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
71
  }
72
}
73

74
bool Particle::create_secondary(
113,039,562✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
113,039,562✔
80
    return false;
54,040,434✔
81
  }
82

83
  auto& bank = secondary_bank().emplace_back();
58,999,128✔
84
  bank.particle = type;
58,999,128✔
85
  bank.wgt = wgt;
58,999,128✔
86
  bank.r = r();
58,999,128✔
87
  bank.u = u;
58,999,128✔
88
  bank.E = settings::run_CE ? E : g();
58,999,128!
89
  bank.time = time();
58,999,128✔
90
  bank_second_E() += bank.E;
58,999,128✔
91
  return true;
58,999,128✔
92
}
93

94
void Particle::split(double wgt)
4,163,460✔
95
{
96
  auto& bank = secondary_bank().emplace_back();
4,163,460✔
97
  bank.particle = type();
4,163,460✔
98
  bank.wgt = wgt;
4,163,460✔
99
  bank.r = r();
4,163,460✔
100
  bank.u = u();
4,163,460✔
101
  bank.E = settings::run_CE ? E() : g();
4,163,460✔
102
  bank.time = time();
4,163,460✔
103

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,163,460✔
106
    bank.surf_id = SURFACE_NONE;
4,163,440✔
107
  } else {
108
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
109
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20!
110
  }
111
}
4,163,460✔
112

113
void Particle::from_source(const SourceSite* src)
234,857,082✔
114
{
115
  // Reset some attributes
116
  clear();
234,857,082✔
117
  surface() = SURFACE_NONE;
234,857,082✔
118
  cell_born() = C_NONE;
234,857,082✔
119
  material() = C_NONE;
234,857,082✔
120
  n_collision() = 0;
234,857,082✔
121
  fission() = false;
234,857,082✔
122
  zero_flux_derivs();
234,857,082✔
123
  lifetime() = 0.0;
234,857,082✔
124

125
  // Copy attributes from source bank site
126
  type() = src->particle;
234,857,082✔
127
  wgt() = src->wgt;
234,857,082✔
128
  wgt_last() = src->wgt;
234,857,082✔
129
  r() = src->r;
234,857,082✔
130
  u() = src->u;
234,857,082✔
131
  r_born() = src->r;
234,857,082✔
132
  r_last_current() = src->r;
234,857,082✔
133
  r_last() = src->r;
234,857,082✔
134
  u_last() = src->u;
234,857,082✔
135
  if (settings::run_CE) {
234,857,082✔
136
    E() = src->E;
119,216,365✔
137
    g() = 0;
119,216,365✔
138
  } else {
139
    g() = static_cast<int>(src->E);
115,640,717✔
140
    g_last() = static_cast<int>(src->E);
115,640,717✔
141
    E() = data::mg.energy_bin_avg_[g()];
115,640,717✔
142
  }
143
  E_last() = E();
234,857,082✔
144
  time() = src->time;
234,857,082✔
145
  time_last() = src->time;
234,857,082✔
146
  parent_nuclide() = src->parent_nuclide;
234,857,082✔
147
  delayed_group() = src->delayed_group;
234,857,082✔
148

149
  // Convert signed surface ID to signed index
150
  if (src->surf_id != SURFACE_NONE) {
234,857,082✔
151
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
152
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020!
153
  }
154
}
234,857,082✔
155

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

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

168
  // Reset event variables
169
  event() = TallyEvent::KILL;
2,147,483,647✔
170
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
171
  event_mt() = REACTION_NONE;
2,147,483,647✔
172

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

183
    // Set birth cell attribute
184
    if (cell_born() == C_NONE)
231,331,161!
185
      cell_born() = lowest_coord().cell();
231,331,161✔
186

187
    // Initialize last cells from current cell
188
    for (int j = 0; j < n_coord(); ++j) {
479,842,363✔
189
      cell_last(j) = coord(j).cell();
248,511,202✔
190
    }
191
    n_coord_last() = n_coord();
231,331,161✔
192
  }
193

194
  // Write particle track.
195
  if (write_track())
2,147,483,647✔
196
    write_particle_track(*this);
10,814✔
197

198
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
199
    check_cell_overlap(*this);
×
200

201
  // Calculate microscopic and macroscopic cross sections
202
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
203
    if (settings::run_CE) {
2,147,483,647✔
204
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
205
          density_mult() != density_mult_last()) {
382,084,446✔
206
        // If the material is the same as the last material and the
207
        // temperature hasn't changed, we don't need to lookup cross
208
        // sections again.
209
        model::materials[material()]->calculate_xs(*this);
1,501,163,851✔
210
      }
211
    } else {
212
      // Get the MG data; unlike the CE case above, we have to re-calculate
213
      // cross sections for every collision since the cross sections may
214
      // be angle-dependent
215
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
216

217
      // Update the particle's group while we know we are multi-group
218
      g_last() = g();
2,063,937,414✔
219
    }
220
  } else {
221
    macro_xs().total = 0.0;
67,548,351✔
222
    macro_xs().absorption = 0.0;
67,548,351✔
223
    macro_xs().fission = 0.0;
67,548,351✔
224
    macro_xs().nu_fission = 0.0;
67,548,351✔
225
  }
226
}
227

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

233
  // Sample a distance to collision
234
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
235
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
54,196,969!
236
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
237
    collision_distance() = INFINITY;
67,548,351✔
238
  } else {
239
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
240
  }
241

242
  double speed = this->speed();
2,147,483,647✔
243
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
244
  double distance_cutoff =
245
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
246

247
  // Select smaller of the three distances
248
  double distance =
249
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
250

251
  // Advance particle in space and time
252
  this->move_distance(distance);
2,147,483,647✔
253
  double dt = distance / speed;
2,147,483,647✔
254
  this->time() += dt;
2,147,483,647✔
255
  this->lifetime() += dt;
2,147,483,647✔
256

257
  // Score timed track-length tallies
258
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
259
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
260
  }
261

262
  // Score track-length tallies
263
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
264
    score_tracklength_tally(*this, distance);
1,428,678,011✔
265
  }
266

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

273
  // Score flux derivative accumulators for differential tallies.
274
  if (!model::active_tallies.empty()) {
2,147,483,647✔
275
    score_track_derivative(*this, distance);
1,605,082,477✔
276
  }
277

278
  // Set particle weight to zero if it hit the time boundary
279
  if (distance == distance_cutoff) {
2,147,483,647✔
280
    wgt() = 0.0;
224,928✔
281
  }
282
}
2,147,483,647✔
283

284
void Particle::event_cross_surface()
2,147,483,647✔
285
{
286
  // Saving previous cell data
287
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
288
    cell_last(j) = coord(j).cell();
2,147,483,647✔
289
  }
290
  n_coord_last() = n_coord();
2,147,483,647✔
291

292
  // Set surface that particle is on and adjust coordinate levels
293
  surface() = boundary().surface();
2,147,483,647✔
294
  n_coord() = boundary().coord_level();
2,147,483,647✔
295

296
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
297
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
298
      boundary().lattice_translation()[2] != 0) {
1,699,240,767✔
299
    // Particle crosses lattice boundary
300

301
    bool verbose = settings::verbosity >= 10 || trace();
684,273,556!
302
    cross_lattice(*this, boundary(), verbose);
684,273,556✔
303
    event() = TallyEvent::LATTICE;
684,273,556✔
304
  } else {
305
    // Particle crosses surface
306
    const auto& surf {model::surfaces[surface_index()].get()};
1,511,783,874✔
307
    // If BC, add particle to surface source before crossing surface
308
    if (surf->surf_source_ && surf->bc_) {
1,511,783,874✔
309
      add_surf_source_to_bank(*this, *surf);
691,434,163✔
310
    }
311
    this->cross_surface(*surf);
1,511,783,874✔
312
    // If no BC, add particle to surface source after crossing surface
313
    if (surf->surf_source_ && !surf->bc_) {
1,511,783,865✔
314
      add_surf_source_to_bank(*this, *surf);
819,111,875✔
315
    }
316
    if (settings::weight_window_checkpoint_surface) {
1,511,783,865✔
317
      apply_weight_windows(*this);
396!
318
    }
319
    event() = TallyEvent::SURFACE;
1,511,783,865✔
320
  }
321
  // Score cell to cell partial currents
322
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
323
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
324
  }
325
}
2,147,483,647✔
326

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

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

339
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
340
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,765,935✔
341

342
  // Clear surface component
343
  surface() = SURFACE_NONE;
2,147,483,647✔
344

345
  if (settings::run_CE) {
2,147,483,647✔
346
    collision(*this);
803,887,776✔
347
  } else {
348
    collision_mg(*this);
1,783,060,477✔
349
  }
350

351
  // Score collision estimator tallies -- this is done after a collision
352
  // has occurred rather than before because we need information on the
353
  // outgoing energy for any tallies with an outgoing energy filter
354
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
355
    score_collision_tally(*this);
108,094,101✔
356
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
357
    if (settings::run_CE) {
113,977,167✔
358
      score_analog_tally_ce(*this);
112,768,905✔
359
    } else {
360
      score_analog_tally_mg(*this);
1,208,262✔
361
    }
362
  }
363

364
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
365
      type() == ParticleType::photon) {
16,918✔
366
    pht_collision_energy();
2,024✔
367
  }
368

369
  // Reset banked weight during collision
370
  n_bank() = 0;
2,147,483,647✔
371
  bank_second_E() = 0.0;
2,147,483,647✔
372
  wgt_bank() = 0.0;
2,147,483,647✔
373
  zero_delayed_bank();
2,147,483,647✔
374

375
  // Reset fission logical
376
  fission() = false;
2,147,483,647✔
377

378
  // Save coordinates for tallying purposes
379
  r_last_current() = r();
2,147,483,647✔
380

381
  // Set last material to none since cross sections will need to be
382
  // re-evaluated
383
  material_last() = C_NONE;
2,147,483,647✔
384

385
  // Set all directions to base level -- right now, after a collision, only
386
  // the base level directions are changed
387
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
388
    if (coord(j + 1).rotated()) {
120,478,296✔
389
      // If next level is rotated, apply rotation matrix
390
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
391
      const auto& u {coord(j).u()};
10,426,614✔
392
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
393
    } else {
394
      // Otherwise, copy this level's direction
395
      coord(j + 1).u() = coord(j).u();
110,051,682✔
396
    }
397
  }
398

399
  // Score flux derivative accumulators for differential tallies.
400
  if (!model::active_tallies.empty())
2,147,483,647✔
401
    score_collision_derivative(*this);
681,319,900✔
402

403
#ifdef OPENMC_DAGMC_ENABLED
404
  history().reset();
239,620,046✔
405
#endif
406
}
2,147,483,647✔
407

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

418
  // Check for secondary particles if this particle is dead
419
  if (!alive()) {
2,147,483,647✔
420
    // Write final position for this particle
421
    if (write_track()) {
231,330,757✔
422
      write_particle_track(*this);
6,674✔
423
    }
424

425
    // If no secondary particles, break out of event loop
426
    if (secondary_bank().empty())
231,330,757✔
427
      return;
167,829,438✔
428

429
    from_source(&secondary_bank().back());
63,501,319✔
430
    secondary_bank().pop_back();
63,501,319✔
431
    n_event() = 0;
63,501,319✔
432
    bank_second_E() = 0.0;
63,501,319✔
433

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

451
        // Initialize last cells from current cell
452
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
453
          cell_last(j) = coord(j).cell();
605✔
454
        }
455
        n_coord_last() = n_coord();
605✔
456
      }
457
      pht_secondary_particles();
605✔
458
    }
459

460
    // Enter new particle in particle track file
461
    if (write_track())
63,501,319✔
462
      add_particle_track(*this);
5,604✔
463
  }
464
}
465

466
void Particle::event_death()
167,830,438✔
467
{
468
#ifdef OPENMC_DAGMC_ENABLED
469
  history().reset();
15,462,422✔
470
#endif
471

472
  // Finish particle track output.
473
  if (write_track()) {
167,830,438✔
474
    finalize_particle_track(*this);
1,070✔
475
  }
476

477
// Contribute tally reduction variables to global accumulator
478
#pragma omp atomic
93,049,656✔
479
  global_tally_absorption += keff_tally_absorption();
167,830,438✔
480
#pragma omp atomic
92,734,613✔
481
  global_tally_collision += keff_tally_collision();
167,830,438✔
482
#pragma omp atomic
92,645,786✔
483
  global_tally_tracklength += keff_tally_tracklength();
167,830,438✔
484
#pragma omp atomic
92,415,555✔
485
  global_tally_leakage += keff_tally_leakage();
167,830,438✔
486

487
  // Reset particle tallies once accumulated
488
  keff_tally_absorption() = 0.0;
167,830,438✔
489
  keff_tally_collision() = 0.0;
167,830,438✔
490
  keff_tally_tracklength() = 0.0;
167,830,438✔
491
  keff_tally_leakage() = 0.0;
167,830,438✔
492

493
  if (!model::active_pulse_height_tallies.empty()) {
167,830,438✔
494
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
495
  }
496

497
  // Record the number of progeny created by this particle.
498
  // This data will be used to efficiently sort the fission bank.
499
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,830,438✔
500
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,101,200✔
501
    simulation::progeny_per_particle[offset] = n_progeny();
141,101,200✔
502
  }
503
}
167,830,438✔
504

505
void Particle::pht_collision_energy()
2,024✔
506
{
507
  // Adds the energy particles lose in a collision to the pulse-height
508

509
  // determine index of cell in pulse_height_cells
510
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
511
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
512

513
  if (it != model::pulse_height_cells.end()) {
2,024!
514
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
515
    pht_storage()[index] += E_last() - E();
2,024✔
516

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

526
void Particle::pht_secondary_particles()
605✔
527
{
528
  // Removes the energy of secondary produced particles from the pulse-height
529

530
  // determine index of cell in pulse_height_cells
531
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
532
    model::pulse_height_cells.end(), cell_born());
605✔
533

534
  if (it != model::pulse_height_cells.end()) {
605!
535
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
536
    pht_storage()[index] -= E();
605✔
537
  }
538
}
605✔
539

540
void Particle::cross_surface(const Surface& surf)
1,513,369,512✔
541
{
542

543
  if (settings::verbosity >= 10 || trace()) {
1,513,369,512✔
544
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
545
  }
546

547
// if we're crossing a CSG surface, make sure the DAG history is reset
548
#ifdef OPENMC_DAGMC_ENABLED
549
  if (surf.geom_type() == GeometryType::CSG)
151,352,127✔
550
    history().reset();
151,307,350✔
551
#endif
552

553
  // Handle any applicable boundary conditions.
554
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
555
      settings::run_mode != RunMode::VOLUME) {
691,949,831✔
556
    surf.bc_->handle_particle(*this, surf);
691,786,271✔
557
    return;
691,786,271✔
558
  }
559

560
  // ==========================================================================
561
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
562

563
#ifdef OPENMC_DAGMC_ENABLED
564
  // in DAGMC, we know what the next cell should be
565
  if (surf.geom_type() == GeometryType::DAG) {
84,141,041✔
566
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
37,445✔
567
                       lowest_coord().universe()) -
37,445✔
568
                     1;
37,445✔
569
    // save material, temperature, and density multiplier
570
    material_last() = material();
37,445✔
571
    sqrtkT_last() = sqrtkT();
37,445✔
572
    density_mult_last() = density_mult();
37,445✔
573
    // set new cell value
574
    lowest_coord().cell() = i_cell;
37,445✔
575
    auto& cell = model::cells[i_cell];
37,445✔
576

577
    cell_instance() = 0;
37,445✔
578
    if (cell->distribcell_index_ >= 0)
37,445✔
579
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
36,421✔
580

581
    material() = cell->material(cell_instance());
37,445✔
582
    sqrtkT() = cell->sqrtkT(cell_instance());
37,445✔
583
    density_mult() = cell->density_mult(cell_instance());
37,445✔
584
    return;
37,445✔
585
  }
586
#endif
587

588
  bool verbose = settings::verbosity >= 10 || trace();
821,545,796!
589
  if (neighbor_list_find_cell(*this, verbose)) {
821,545,796✔
590
    return;
821,515,885✔
591
  }
592

593
  // ==========================================================================
594
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
595

596
  // Remove lower coordinate levels
597
  n_coord() = 1;
29,911✔
598
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
599

600
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,911!
601
    // If a cell is still not found, there are two possible causes: 1) there is
602
    // a void in the model, and 2) the particle hit a surface at a tangent. If
603
    // the particle is really traveling tangent to a surface, if we move it
604
    // forward a tiny bit it should fix the problem.
605

606
    surface() = SURFACE_NONE;
5,799✔
607
    n_coord() = 1;
5,799✔
608
    r() += TINY_BIT * u();
5,799✔
609

610
    // Couldn't find next cell anywhere! This probably means there is an actual
611
    // undefined region in the geometry.
612

613
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
614
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
615
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
616
                   " it could not be located in any cell and it did not leak.");
617
      return;
5,790✔
618
    }
619
  }
620
}
621

622
void Particle::cross_vacuum_bc(const Surface& surf)
37,076,816✔
623
{
624
  // Score any surface current tallies -- note that the particle is moved
625
  // forward slightly so that if the mesh boundary is on the surface, it is
626
  // still processed
627

628
  if (!model::active_meshsurf_tallies.empty()) {
37,076,816✔
629
    // TODO: Find a better solution to score surface currents than
630
    // physically moving the particle forward slightly
631

632
    r() += TINY_BIT * u();
1,012,214✔
633
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,012,214✔
634
  }
635

636
  // Score to global leakage tally
637
  keff_tally_leakage() += wgt();
37,076,816✔
638

639
  // Kill the particle
640
  wgt() = 0.0;
37,076,816✔
641

642
  // Display message
643
  if (settings::verbosity >= 10 || trace()) {
37,076,816!
644
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
645
  }
646
}
37,076,816✔
647

648
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
655,053,298✔
649
{
650
  // Do not handle reflective boundary conditions on lower universes
651
  if (n_coord() != 1) {
655,053,298!
UNCOV
652
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
653
                 " off surface in a lower universe.");
UNCOV
654
    return;
×
655
  }
656

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

664
  if (!model::active_surface_tallies.empty()) {
655,053,298✔
665
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
666
  }
667

668
  if (!model::active_meshsurf_tallies.empty()) {
655,053,298✔
669
    Position r {this->r()};
51,095,741✔
670
    this->r() -= TINY_BIT * u();
51,095,741✔
671
    score_surface_tally(*this, model::active_meshsurf_tallies);
51,095,741✔
672
    this->r() = r;
51,095,741✔
673
  }
674

675
  // Set the new particle direction
676
  u() = new_u;
655,053,298✔
677

678
  // Reassign particle's cell and surface
679
  coord(0).cell() = cell_last(0);
655,053,298✔
680
  surface() = -surface();
655,053,298✔
681

682
  // If a reflective surface is coincident with a lattice or universe
683
  // boundary, it is necessary to redetermine the particle's coordinates in
684
  // the lower universes.
685
  // (unless we're using a dagmc model, which has exactly one universe)
686
  n_coord() = 1;
655,053,298✔
687
  if (surf.geom_type() != GeometryType::DAG &&
1,310,103,838!
688
      !neighbor_list_find_cell(*this)) {
655,050,540!
UNCOV
689
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
690
                 std::to_string(surf.id_) + ".");
×
UNCOV
691
    return;
×
692
  }
693

694
  // Set previous coordinate going slightly past surface crossing
695
  r_last_current() = r() + TINY_BIT * u();
655,053,298✔
696

697
  // Diagnostic message
698
  if (settings::verbosity >= 10 || trace()) {
655,053,298!
UNCOV
699
    write_message(1, "    Reflected from surface {}", surf.id_);
×
700
  }
701
}
702

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

715
  // Score surface currents since reflection causes the direction of the
716
  // particle to change -- artificially move the particle slightly back in
717
  // case the surface crossing is coincident with a mesh boundary
718
  if (!model::active_meshsurf_tallies.empty()) {
661,623!
UNCOV
719
    Position r {this->r()};
×
UNCOV
720
    this->r() -= TINY_BIT * u();
×
UNCOV
721
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
722
    this->r() = r;
×
723
  }
724

725
  // Adjust the particle's location and direction.
726
  r() = new_r;
661,623✔
727
  u() = new_u;
661,623✔
728

729
  // Reassign particle's surface
730
  surface() = new_surface;
661,623✔
731

732
  // Figure out what cell particle is in now
733
  n_coord() = 1;
661,623✔
734

735
  if (!neighbor_list_find_cell(*this)) {
661,623!
UNCOV
736
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
737
                 "boundary on surface " +
×
UNCOV
738
                 std::to_string(surf.id_) +
×
739
                 ". The normal vector "
740
                 "of one periodic surface may need to be reversed.");
741
    return;
×
742
  }
743

744
  // Set previous coordinate going slightly past surface crossing
745
  r_last_current() = r() + TINY_BIT * u();
661,623✔
746

747
  // Diagnostic message
748
  if (settings::verbosity >= 10 || trace()) {
661,623!
UNCOV
749
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
750
  }
751
}
752

753
void Particle::mark_as_lost(const char* message)
5,799✔
754
{
755
  // Print warning and write lost particle file
756
  warning(message);
5,799✔
757
  if (settings::max_write_lost_particles < 0 ||
5,799✔
758
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
759
    write_restart();
379✔
760
  }
761
  // Increment number of lost particles
762
  wgt() = 0.0;
5,799✔
763
#pragma omp atomic
3,154✔
764
  simulation::n_lost_particles += 1;
2,645✔
765

766
  // Count the total number of simulated particles (on this processor)
767
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
768
           simulation::work_per_rank;
769

770
  // Abort the simulation if the maximum number of lost particles has been
771
  // reached
772
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
773
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
774
    fatal_error("Maximum number of lost particles has been reached.");
9✔
775
  }
776
}
5,790✔
777

778
void Particle::write_restart() const
379✔
779
{
780
  // Dont write another restart file if in particle restart mode
781
  if (settings::run_mode == RunMode::PARTICLE)
379✔
782
    return;
22✔
783

784
  // Set up file name
785
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
786
    simulation::current_batch, id());
665✔
787

788
#pragma omp critical(WriteParticleRestart)
374✔
789
  {
790
    // Create file
791
    hid_t file_id = file_open(filename, 'w');
357✔
792

793
    // Write filetype and version info
794
    write_attribute(file_id, "filetype", "particle restart");
357✔
795
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
357✔
796
    write_attribute(file_id, "openmc_version", VERSION);
357✔
797
#ifdef GIT_SHA1
798
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
799
#endif
800

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

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

845
    // Close file
846
    file_close(file_id);
357✔
847
  } // #pragma omp critical
848
}
357✔
849

850
void Particle::update_neutron_xs(
2,147,483,647✔
851
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
852
{
853
  // Get microscopic cross section cache
854
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
855

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

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

871
//==============================================================================
872
// Non-method functions
873
//==============================================================================
874

875
std::string particle_type_to_str(ParticleType type)
3,258,770✔
876
{
877
  switch (type) {
3,258,770!
878
  case ParticleType::neutron:
2,464,228✔
879
    return "neutron";
2,464,228✔
880
  case ParticleType::photon:
794,278✔
881
    return "photon";
794,278✔
882
  case ParticleType::electron:
132✔
883
    return "electron";
132✔
884
  case ParticleType::positron:
132✔
885
    return "positron";
132✔
886
  }
UNCOV
887
  UNREACHABLE();
×
888
}
889

890
ParticleType str_to_particle_type(std::string str)
3,520,932✔
891
{
892
  if (str == "neutron") {
3,520,932✔
893
    return ParticleType::neutron;
806,542✔
894
  } else if (str == "photon") {
2,714,390✔
895
    return ParticleType::photon;
2,714,304✔
896
  } else if (str == "electron") {
86✔
897
    return ParticleType::electron;
43✔
898
  } else if (str == "positron") {
43!
899
    return ParticleType::positron;
43✔
900
  } else {
UNCOV
901
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
902
  }
903
}
904

905
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,510,546,038✔
906
{
907
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
908
      simulation::surf_source_bank.full()) {
1,201,383,850✔
909
    return;
1,510,416,385✔
910
  }
911

912
  // If a cell/cellfrom/cellto parameter is defined
913
  if (settings::ssw_cell_id != C_NONE) {
337,086✔
914

915
    // Retrieve cell index and storage type
916
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,441✔
917

918
    if (surf.bc_) {
254,441✔
919
      // Leave if cellto with vacuum boundary condition
920
      if (surf.bc_->type() == "vacuum" &&
182,560!
921
          settings::ssw_cell_type == SSWCellType::To) {
33,100✔
922
        return;
12,136✔
923
      }
924

925
      // Leave if other boundary condition than vacuum
926
      if (surf.bc_->type() != "vacuum") {
137,324✔
927
        return;
116,360✔
928
      }
929
    }
930

931
    // Check if the cell of interest has been exited
932
    bool exited = false;
125,945✔
933
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,679✔
934
      if (p.cell_last(i) == cell_idx) {
207,734✔
935
        exited = true;
73,765✔
936
      }
937
    }
938

939
    // Check if the cell of interest has been entered
940
    bool entered = false;
125,945✔
941
    for (int i = 0; i < p.n_coord(); ++i) {
297,981✔
942
      if (p.coord(i).cell() == cell_idx) {
172,036✔
943
        entered = true;
57,517✔
944
      }
945
    }
946

947
    // Vacuum boundary conditions: return if cell is not exited
948
    if (surf.bc_) {
125,945✔
949
      if (surf.bc_->type() == "vacuum" && !exited) {
20,964!
950
        return;
14,664✔
951
      }
952
    } else {
953

954
      // If we both enter and exit the cell of interest
955
      if (entered && exited) {
104,981✔
956
        return;
27,203✔
957
      }
958

959
      // If we did not enter nor exit the cell of interest
960
      if (!entered && !exited) {
77,778✔
961
        return;
13,502✔
962
      }
963

964
      // If cellfrom and the cell before crossing is not the cell of
965
      // interest
966
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,276✔
967
        return;
11,543✔
968
      }
969

970
      // If cellto and the cell after crossing is not the cell of interest
971
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
972
        return;
12,025✔
973
      }
974
    }
975
  }
976

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

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