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

openmc-dev / openmc / 22543795118

01 Mar 2026 12:51PM UTC coverage: 81.251%. First build
22543795118

Pull #3843

github

web-flow
Merge 7c9bddf14 into b3788f11e
Pull Request #3843: Implement cell importance variance reduction scheme.

16975 of 24306 branches covered (69.84%)

Branch coverage included in aggregate %.

59 of 107 new or added lines in 6 files covered. (55.14%)

56819 of 66516 relevant lines covered (85.42%)

43123887.61 hits per line

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

83.37
/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/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

36
#ifdef OPENMC_DAGMC_ENABLED
37
#include "DagMC.hpp"
38
#endif
39

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
2,081,681,680✔
51
    switch (type().pdg_number()) {
2,081,681,680✔
52
    case PDG_NEUTRON:
53
      mass = MASS_NEUTRON_EV;
54
    case PDG_ELECTRON:
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
2,081,681,680✔
57
    default:
2,081,681,680✔
58
      mass = this->type().mass() * AMU_EV;
2,081,681,680✔
59
    }
60

61
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
62
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,081,681,680✔
63
           (this->E() + mass);
2,081,681,680✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,876,306,740✔
66
    int macro_t = this->mg_xs_cache().t;
1,876,306,740✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
1,876,306,740✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,876,306,740✔
69
                   nullptr, nullptr, macro_t, macro_a);
1,876,306,740✔
70
  }
71
}
72

73
bool Particle::create_secondary(
102,223,005✔
74
  double wgt, Direction u, double E, ParticleType type)
75
{
76
  // If energy is below cutoff for this particle, don't create secondary
77
  // particle
78
  int idx = type.transport_index();
102,223,005✔
79
  if (idx == C_NONE) {
102,223,005!
80
    return false;
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
102,223,005✔
83
    return false;
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
53,338,598✔
88

89
  auto& bank = secondary_bank().emplace_back();
53,338,598✔
90
  bank.particle = type;
53,338,598✔
91
  bank.wgt = wgt;
53,338,598✔
92
  bank.r = r();
53,338,598!
93
  bank.u = u;
53,338,598✔
94
  bank.E = settings::run_CE ? E : g();
53,338,598!
95
  bank.time = time();
53,338,598✔
96
  bank_second_E() += bank.E;
53,338,598✔
97
  return true;
53,338,598✔
98
}
99

100
void Particle::split(double wgt)
3,859,553✔
101
{
102
  auto& bank = secondary_bank().emplace_back();
3,859,553✔
103
  bank.particle = type();
3,859,553✔
104
  bank.wgt = wgt;
3,859,553✔
105
  bank.r = r();
3,859,553✔
106
  bank.u = u();
3,859,553✔
107
  bank.E = settings::run_CE ? E() : g();
3,859,553✔
108
  bank.time = time();
3,859,553✔
109

110
  // Convert signed index to a signed surface ID
111
  if (surface() == SURFACE_NONE) {
3,859,553✔
112
    bank.surf_id = SURFACE_NONE;
3,859,363✔
113
  } else {
114
    int surf_id = model::surfaces[surface_index()]->id_;
190!
115
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
190!
116
  }
117
}
3,859,553✔
118

119
void Particle::from_source(const SourceSite* src)
218,467,927✔
120
{
121
  // Reset some attributes
122
  clear();
218,467,927✔
123
  surface() = SURFACE_NONE;
218,467,927✔
124
  cell_born() = C_NONE;
218,467,927✔
125
  material() = C_NONE;
218,467,927✔
126
  n_collision() = 0;
218,467,927✔
127
  fission() = false;
218,467,927✔
128
  zero_flux_derivs();
218,467,927✔
129
  lifetime() = 0.0;
218,467,927✔
130
#ifdef OPENMC_DAGMC_ENABLED
131
  history().reset();
132
#endif
133

134
  // Copy attributes from source bank site
135
  type() = src->particle;
218,467,927✔
136
  wgt() = src->wgt;
218,467,927✔
137
  wgt_last() = src->wgt;
218,467,927✔
138
  r() = src->r;
218,467,927✔
139
  u() = src->u;
218,467,927✔
140
  r_born() = src->r;
218,467,927✔
141
  r_last_current() = src->r;
218,467,927✔
142
  r_last() = src->r;
218,467,927✔
143
  u_last() = src->u;
218,467,927✔
144
  if (settings::run_CE) {
218,467,927✔
145
    E() = src->E;
113,081,657✔
146
    g() = 0;
113,081,657✔
147
  } else {
148
    g() = static_cast<int>(src->E);
105,386,270✔
149
    g_last() = static_cast<int>(src->E);
105,386,270✔
150
    E() = data::mg.energy_bin_avg_[g()];
105,386,270✔
151
  }
152
  E_last() = E();
218,467,927✔
153
  time() = src->time;
218,467,927✔
154
  time_last() = src->time;
218,467,927✔
155
  parent_nuclide() = src->parent_nuclide;
218,467,927✔
156
  delayed_group() = src->delayed_group;
218,467,927✔
157

158
  // Convert signed surface ID to signed index
159
  if (src->surf_id != SURFACE_NONE) {
218,467,927✔
160
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
100,190✔
161
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
100,190✔
162
  }
163
}
218,467,927✔
164

165
void Particle::event_calculate_xs()
2,147,483,647✔
166
{
167
  // Set the random number stream
168
  stream() = STREAM_TRACKING;
2,147,483,647✔
169

170
  // Store pre-collision particle properties
171
  wgt_last() = wgt();
2,147,483,647✔
172
  E_last() = E();
2,147,483,647✔
173
  u_last() = u();
2,147,483,647✔
174
  r_last() = r();
2,147,483,647✔
175
  time_last() = time();
2,147,483,647✔
176

177
  // Reset event variables
178
  event() = TallyEvent::KILL;
2,147,483,647✔
179
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
180
  event_mt() = REACTION_NONE;
2,147,483,647✔
181

182
  // If the cell hasn't been determined based on the particle's location,
183
  // initiate a search for the current cell. This generally happens at the
184
  // beginning of the history and again for any secondary particles
185
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
186
    if (!exhaustive_find_cell(*this)) {
210,585,937!
187
      mark_as_lost(
×
188
        "Could not find the cell containing particle " + std::to_string(id()));
×
189
      return;
×
190
    }
191

192
    // Set birth cell attribute
193
    if (cell_born() == C_NONE)
210,585,937!
194
      cell_born() = lowest_coord().cell();
210,585,937✔
195

196
    // Initialize last cells from current cell
197
    for (int j = 0; j < n_coord(); ++j) {
437,051,070✔
198
      cell_last(j) = coord(j).cell();
226,465,133✔
199
    }
200
    n_coord_last() = n_coord();
210,585,937✔
201
  }
202

203
  // Write particle track.
204
  if (write_track())
2,147,483,647✔
205
    write_particle_track(*this);
9,027✔
206

207
  if (settings::check_overlaps)
2,147,483,647!
208
    check_cell_overlap(*this);
×
209

210
  // Calculate microscopic and macroscopic cross sections
211
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
212
    if (settings::run_CE) {
2,147,483,647✔
213
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,955,079,206✔
214
          density_mult() != density_mult_last()) {
338,777,708✔
215
        // If the material is the same as the last material and the
216
        // temperature hasn't changed, we don't need to lookup cross
217
        // sections again.
218
        model::materials[material()]->calculate_xs(*this);
1,616,310,218✔
219
      }
220
    } else {
221
      // Get the MG data; unlike the CE case above, we have to re-calculate
222
      // cross sections for every collision since the cross sections may
223
      // be angle-dependent
224
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,876,306,740✔
225

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
1,876,306,740✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
101,650,964✔
231
    macro_xs().absorption = 0.0;
101,650,964✔
232
    macro_xs().fission = 0.0;
101,650,964✔
233
    macro_xs().nu_fission = 0.0;
101,650,964✔
234
  }
235
}
236

237
void Particle::event_advance()
2,147,483,647✔
238
{
239
  // Find the distance to the nearest boundary
240
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
241

242
  // Sample a distance to collision
243
  if (type() == ParticleType::electron() ||
2,147,483,647✔
244
      type() == ParticleType::positron()) {
2,147,483,647✔
245
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
98,045,930!
246
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
247
    collision_distance() = INFINITY;
101,650,964✔
248
  } else {
249
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
250
  }
251

252
  double speed = this->speed();
2,147,483,647✔
253
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
254
  double distance_cutoff =
2,147,483,647✔
255
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
256

257
  // Select smaller of the three distances
258
  double distance =
2,147,483,647✔
259
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
260

261
  // Advance particle in space and time
262
  this->move_distance(distance);
2,147,483,647✔
263
  double dt = distance / speed;
2,147,483,647✔
264
  this->time() += dt;
2,147,483,647✔
265
  this->lifetime() += dt;
2,147,483,647✔
266

267
  // Score timed track-length tallies
268
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
269
    score_timed_tracklength_tally(*this, distance);
3,298,470✔
270
  }
271

272
  // Score track-length tallies
273
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
274
    score_tracklength_tally(*this, distance);
1,553,394,587✔
275
  }
276

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

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

287
  // Set particle weight to zero if it hit the time boundary
288
  if (distance == distance_cutoff) {
2,147,483,647✔
289
    wgt() = 0.0;
204,480✔
290
  }
291
}
2,147,483,647✔
292

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

301
  auto instance_last = cell_instance();
2,147,483,647✔
302

303
  // Set surface that particle is on and adjust coordinate levels
304
  surface() = boundary().surface();
2,147,483,647✔
305
  n_coord() = boundary().coord_level();
2,147,483,647✔
306

307
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
308
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
309
      boundary().lattice_translation()[2] != 0) {
1,690,235,454✔
310
    // Particle crosses lattice boundary
311

312
    bool verbose = settings::verbosity >= 10 || trace();
671,071,425!
313
    cross_lattice(*this, boundary(), verbose);
671,071,425✔
314
    event() = TallyEvent::LATTICE;
671,071,425✔
315
  } else {
316
    // Particle crosses surface
317
    const auto& surf {model::surfaces[surface_index()].get()};
1,518,834,313✔
318
    // If BC, add particle to surface source before crossing surface
319
    if (surf->surf_source_ && surf->bc_) {
1,518,834,313✔
320
      add_surf_source_to_bank(*this, *surf);
654,312,119✔
321
    }
322
    this->cross_surface(*surf);
1,518,834,313✔
323
    double importance =
1,518,834,305✔
324
      model::cells[coord(n_coord() - 1).cell()]->importance(cell_instance());
1,518,834,305✔
325
    if (importance == 0.0) {
1,518,834,305!
NEW
326
      wgt() = 0.0;
×
NEW
327
      return;
×
328
    }
329
    // If no BC, add particle to surface source after crossing surface
330
    if (surf->surf_source_ && !surf->bc_) {
1,518,834,305✔
331
      add_surf_source_to_bank(*this, *surf);
863,406,563✔
332
    }
333
    if (settings::weight_window_checkpoint_surface) {
1,518,834,305✔
334
      apply_weight_windows(*this);
58,340✔
335
    }
336
    if (simulation::cell_importances) {
1,518,834,305!
NEW
337
      double importance_last =
×
NEW
338
        model::cells[cell_last(n_coord_last() - 1)]->importance(instance_last);
×
NEW
339
      if (importance != importance_last) {
×
NEW
340
        if (importance < importance_last) {
×
NEW
341
          if (importance_last * prn(current_seed()) < importance) {
×
NEW
342
            wgt() *= importance_last / importance;
×
343
          } else {
NEW
344
            wgt() = 0.;
×
NEW
345
            return;
×
346
          }
347
        } else {
348
          // do not further split the particle if above the limit
NEW
349
          if (n_split() >= settings::max_history_splits)
×
350
            return;
351

NEW
352
          double num_split =
×
NEW
353
            std::min(static_cast<int>(std::ceil(importance / importance_last)),
×
NEW
354
              settings::max_history_splits);
×
NEW
355
          n_split() += num_split;
×
356

357
          // Create secondaries and divide weight among all particles
NEW
358
          int i_split = std::round(num_split);
×
NEW
359
          for (int l = 0; l < i_split - 1; l++) {
×
NEW
360
            split(wgt() / num_split);
×
361
          }
362
          // remaining weight is applied to current particle
NEW
363
          wgt() /= num_split;
×
364
        }
365
      }
366
    }
367
    event() = TallyEvent::SURFACE;
1,518,834,305✔
368
  }
369
  // Score cell to cell partial currents
370
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
371
    score_surface_tally(*this, model::active_surface_tallies);
31,747,970✔
372
  }
373
}
374

375
void Particle::event_collide()
2,147,483,647✔
376
{
377

378
  // Score collision estimate of keff
379
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
380
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,944,537,119✔
381
  }
382

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

387
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
388
    score_surface_tally(*this, model::active_meshsurf_tallies);
57,362,660✔
389

390
  // Clear surface component
391
  surface() = SURFACE_NONE;
2,147,483,647✔
392

393
  if (settings::run_CE) {
2,147,483,647✔
394
    collision(*this);
971,633,962✔
395
  } else {
396
    collision_mg(*this);
1,620,964,070✔
397
  }
398

399
  // Collision track feature to recording particle interaction
400
  if (settings::collision_track) {
2,147,483,647✔
401
    collision_track_record(*this);
136,288✔
402
  }
403

404
  // Score collision estimator tallies -- this is done after a collision
405
  // has occurred rather than before because we need information on the
406
  // outgoing energy for any tallies with an outgoing energy filter
407
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
408
    score_collision_tally(*this);
96,853,111✔
409
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
410
    if (settings::run_CE) {
368,908,530✔
411
      score_analog_tally_ce(*this);
367,810,110✔
412
    } else {
413
      score_analog_tally_mg(*this);
1,098,420✔
414
    }
415
  }
416

417
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
418
    pht_collision_energy();
1,840✔
419
  }
420

421
  // Reset banked weight during collision
422
  n_bank() = 0;
2,147,483,647✔
423
  bank_second_E() = 0.0;
2,147,483,647✔
424
  wgt_bank() = 0.0;
2,147,483,647✔
425

426
  // Clear number of secondaries in this collision. This is
427
  // distinct from the number of created neutrons n_bank() above!
428
  n_secondaries() = 0;
2,147,483,647✔
429

430
  zero_delayed_bank();
2,147,483,647✔
431

432
  // Reset fission logical
433
  fission() = false;
2,147,483,647✔
434

435
  // Save coordinates for tallying purposes
436
  r_last_current() = r();
2,147,483,647✔
437

438
  // Set last material to none since cross sections will need to be
439
  // re-evaluated
440
  material_last() = C_NONE;
2,147,483,647✔
441

442
  // Set all directions to base level -- right now, after a collision, only
443
  // the base level directions are changed
444
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
445
    if (coord(j + 1).rotated()) {
146,395,638✔
446
      // If next level is rotated, apply rotation matrix
447
      const auto& m {model::cells[coord(j).cell()]->rotation_};
9,478,740✔
448
      const auto& u {coord(j).u()};
9,478,740✔
449
      coord(j + 1).u() = u.rotate(m);
9,478,740✔
450
    } else {
451
      // Otherwise, copy this level's direction
452
      coord(j + 1).u() = coord(j).u();
136,916,898✔
453
    }
454
  }
455

456
  // Score flux derivative accumulators for differential tallies.
457
  if (!model::active_tallies.empty())
2,147,483,647✔
458
    score_collision_derivative(*this);
849,678,845✔
459

460
#ifdef OPENMC_DAGMC_ENABLED
461
  history().reset();
462
#endif
463
}
2,147,483,647✔
464

465
void Particle::event_revive_from_secondary()
2,147,483,647✔
466
{
467
  // If particle has too many events, display warning and kill it
468
  ++n_event();
2,147,483,647✔
469
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
470
    warning("Particle " + std::to_string(id()) +
×
471
            " underwent maximum number of events.");
472
    wgt() = 0.0;
×
473
  }
474

475
  // Check for secondary particles if this particle is dead
476
  if (!alive()) {
2,147,483,647✔
477
    // Write final position for this particle
478
    if (write_track()) {
210,585,479✔
479
      write_particle_track(*this);
5,394✔
480
    }
481

482
    // If no secondary particles, break out of event loop
483
    if (secondary_bank().empty())
210,585,479✔
484
      return;
485

486
    from_source(&secondary_bank().back());
57,309,893✔
487
    secondary_bank().pop_back();
57,309,893✔
488
    n_event() = 0;
57,309,893✔
489
    bank_second_E() = 0.0;
57,309,893✔
490

491
    // Subtract secondary particle energy from interim pulse-height results
492
    if (!model::active_pulse_height_tallies.empty() &&
57,309,893✔
493
        this->type().is_photon()) {
14,090✔
494
      // Since the birth cell of the particle has not been set we
495
      // have to determine it before the energy of the secondary particle can be
496
      // removed from the pulse-height of this cell.
497
      if (lowest_coord().cell() == C_NONE) {
550!
498
        bool verbose = settings::verbosity >= 10 || trace();
550!
499
        if (!exhaustive_find_cell(*this, verbose)) {
550!
500
          mark_as_lost("Could not find the cell containing particle " +
×
501
                       std::to_string(id()));
×
502
          return;
×
503
        }
504
        // Set birth cell attribute
505
        if (cell_born() == C_NONE)
550!
506
          cell_born() = lowest_coord().cell();
550✔
507

508
        // Initialize last cells from current cell
509
        for (int j = 0; j < n_coord(); ++j) {
1,100✔
510
          cell_last(j) = coord(j).cell();
550✔
511
        }
512
        n_coord_last() = n_coord();
550✔
513
      }
514
      pht_secondary_particles();
550✔
515
    }
516

517
    // Enter new particle in particle track file
518
    if (write_track())
57,309,893✔
519
      add_particle_track(*this);
4,514✔
520
  }
521
}
522

523
void Particle::event_death()
153,276,586✔
524
{
525
#ifdef OPENMC_DAGMC_ENABLED
526
  history().reset();
527
#endif
528

529
  // Finish particle track output.
530
  if (write_track()) {
153,276,586✔
531
    finalize_particle_track(*this);
880✔
532
  }
533

534
// Contribute tally reduction variables to global accumulator
535
#pragma omp atomic
77,512,551✔
536
  global_tally_absorption += keff_tally_absorption();
153,276,586✔
537
#pragma omp atomic
77,730,272✔
538
  global_tally_collision += keff_tally_collision();
153,276,586✔
539
#pragma omp atomic
77,370,815✔
540
  global_tally_tracklength += keff_tally_tracklength();
153,276,586✔
541
#pragma omp atomic
76,882,445✔
542
  global_tally_leakage += keff_tally_leakage();
153,276,586✔
543

544
  // Reset particle tallies once accumulated
545
  keff_tally_absorption() = 0.0;
153,276,586✔
546
  keff_tally_collision() = 0.0;
153,276,586✔
547
  keff_tally_tracklength() = 0.0;
153,276,586✔
548
  keff_tally_leakage() = 0.0;
153,276,586✔
549

550
  if (!model::active_pulse_height_tallies.empty()) {
153,276,586✔
551
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,000✔
552
  }
553

554
  // Record the number of progeny created by this particle.
555
  // This data will be used to efficiently sort the fission bank.
556
  if (settings::run_mode == RunMode::EIGENVALUE) {
153,276,586✔
557
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
128,560,000✔
558
    simulation::progeny_per_particle[offset] = n_progeny();
128,560,000✔
559
  }
560
}
153,276,586✔
561

562
void Particle::pht_collision_energy()
1,840✔
563
{
564
  // Adds the energy particles lose in a collision to the pulse-height
565

566
  // determine index of cell in pulse_height_cells
567
  auto it = std::find(model::pulse_height_cells.begin(),
1,840✔
568
    model::pulse_height_cells.end(), lowest_coord().cell());
1,840!
569

570
  if (it != model::pulse_height_cells.end()) {
1,840!
571
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,840✔
572
    pht_storage()[index] += E_last() - E();
1,840✔
573

574
    // If the energy of the particle is below the cutoff, it will not be sampled
575
    // so its energy is added to the pulse-height in the cell
576
    int photon = ParticleType::photon().transport_index();
1,840✔
577
    if (E() < settings::energy_cutoff[photon]) {
1,840✔
578
      pht_storage()[index] += E();
750✔
579
    }
580
  }
581
}
1,840✔
582

583
void Particle::pht_secondary_particles()
550✔
584
{
585
  // Removes the energy of secondary produced particles from the pulse-height
586

587
  // determine index of cell in pulse_height_cells
588
  auto it = std::find(model::pulse_height_cells.begin(),
550✔
589
    model::pulse_height_cells.end(), cell_born());
550!
590

591
  if (it != model::pulse_height_cells.end()) {
550!
592
    int index = std::distance(model::pulse_height_cells.begin(), it);
550✔
593
    pht_storage()[index] -= E();
550✔
594
  }
595
}
550✔
596

597
void Particle::cross_surface(const Surface& surf)
1,520,565,693✔
598
{
599

600
  if (settings::verbosity >= 10 || trace()) {
1,520,565,693✔
601
    write_message(1, "    Crossing surface {}", surf.id_);
60✔
602
  }
603

604
// if we're crossing a CSG surface, make sure the DAG history is reset
605
#ifdef OPENMC_DAGMC_ENABLED
606
  if (surf.geom_type() == GeometryType::CSG)
607
    history().reset();
608
#endif
609

610
  // Handle any applicable boundary conditions.
611
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,520,565,693!
612
      settings::run_mode != RunMode::VOLUME) {
613
    surf.bc_->handle_particle(*this, surf);
654,630,065✔
614
    return;
654,630,065✔
615
  }
616

617
  // ==========================================================================
618
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
619

620
#ifdef OPENMC_DAGMC_ENABLED
621
  // in DAGMC, we know what the next cell should be
622
  if (surf.geom_type() == GeometryType::DAG) {
623
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
624
                       lowest_coord().universe()) -
625
                     1;
626
    // save material, temperature, and density multiplier
627
    material_last() = material();
628
    sqrtkT_last() = sqrtkT();
629
    density_mult_last() = density_mult();
630
    // set new cell value
631
    lowest_coord().cell() = i_cell;
632
    auto& cell = model::cells[i_cell];
633

634
    cell_instance() = 0;
635
    if (cell->distribcell_index_ >= 0)
636
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
637

638
    material() = cell->material(cell_instance());
639
    sqrtkT() = cell->sqrtkT(cell_instance());
640
    density_mult() = cell->density_mult(cell_instance());
641
    return;
642
  }
643
#endif
644

645
  bool verbose = settings::verbosity >= 10 || trace();
865,935,628!
646
  if (neighbor_list_find_cell(*this, verbose)) {
865,935,628✔
647
    return;
648
  }
649

650
  // ==========================================================================
651
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
652

653
  // Remove lower coordinate levels
654
  n_coord() = 1;
27,190✔
655
  bool found = exhaustive_find_cell(*this, verbose);
27,190✔
656

657
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
27,190!
658
    // If a cell is still not found, there are two possible causes: 1) there is
659
    // a void in the model, and 2) the particle hit a surface at a tangent. If
660
    // the particle is really traveling tangent to a surface, if we move it
661
    // forward a tiny bit it should fix the problem.
662

663
    surface() = SURFACE_NONE;
5,270✔
664
    n_coord() = 1;
5,270✔
665
    r() += TINY_BIT * u();
5,270✔
666

667
    // Couldn't find next cell anywhere! This probably means there is an actual
668
    // undefined region in the geometry.
669

670
    if (!exhaustive_find_cell(*this, verbose)) {
5,270!
671
      mark_as_lost("After particle " + std::to_string(id()) +
21,064✔
672
                   " crossed surface " + std::to_string(surf.id_) +
15,802✔
673
                   " it could not be located in any cell and it did not leak.");
674
      return;
5,262✔
675
    }
676
  }
677
}
678

679
void Particle::cross_vacuum_bc(const Surface& surf)
31,719,128✔
680
{
681
  // Score any surface current tallies -- note that the particle is moved
682
  // forward slightly so that if the mesh boundary is on the surface, it is
683
  // still processed
684

685
  if (!model::active_meshsurf_tallies.empty()) {
31,719,128✔
686
    // TODO: Find a better solution to score surface currents than
687
    // physically moving the particle forward slightly
688

689
    r() += TINY_BIT * u();
852,020✔
690
    score_surface_tally(*this, model::active_meshsurf_tallies);
852,020✔
691
  }
692

693
  // Score to global leakage tally
694
  keff_tally_leakage() += wgt();
31,719,128✔
695

696
  // Kill the particle
697
  wgt() = 0.0;
31,719,128✔
698

699
  // Display message
700
  if (settings::verbosity >= 10 || trace()) {
31,719,128!
701
    write_message(1, "    Leaked out of surface {}", surf.id_);
20✔
702
  }
703
}
31,719,128✔
704

705
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
621,783,792✔
706
{
707
  // Do not handle reflective boundary conditions on lower universes
708
  if (n_coord() != 1) {
621,783,792!
709
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
710
                 " off surface in a lower universe.");
711
    return;
×
712
  }
713

714
  // Score surface currents since reflection causes the direction of the
715
  // particle to change. For surface filters, we need to score the tallies
716
  // twice, once before the particle's surface attribute has changed and
717
  // once after. For mesh surface filters, we need to artificially move
718
  // the particle slightly back in case the surface crossing is coincident
719
  // with a mesh boundary
720

721
  if (!model::active_surface_tallies.empty()) {
621,783,792✔
722
    score_surface_tally(*this, model::active_surface_tallies);
259,110✔
723
  }
724

725
  if (!model::active_meshsurf_tallies.empty()) {
621,783,792✔
726
    Position r {this->r()};
42,623,170✔
727
    this->r() -= TINY_BIT * u();
42,623,170✔
728
    score_surface_tally(*this, model::active_meshsurf_tallies);
42,623,170✔
729
    this->r() = r;
42,623,170✔
730
  }
731

732
  // Set the new particle direction
733
  u() = new_u;
621,783,792✔
734

735
  // Reassign particle's cell and surface
736
  coord(0).cell() = cell_last(0);
621,783,792✔
737
  surface() = -surface();
621,783,792✔
738

739
  // If a reflective surface is coincident with a lattice or universe
740
  // boundary, it is necessary to redetermine the particle's coordinates in
741
  // the lower universes.
742
  // (unless we're using a dagmc model, which has exactly one universe)
743
  n_coord() = 1;
621,783,792✔
744
  if (surf.geom_type() != GeometryType::DAG &&
1,243,567,584!
745
      !neighbor_list_find_cell(*this)) {
621,783,792✔
746
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
747
                 std::to_string(surf.id_) + ".");
×
748
    return;
×
749
  }
750

751
  // Set previous coordinate going slightly past surface crossing
752
  r_last_current() = r() + TINY_BIT * u();
621,783,792✔
753

754
  // Diagnostic message
755
  if (settings::verbosity >= 10 || trace()) {
621,783,792!
756
    write_message(1, "    Reflected from surface {}", surf.id_);
×
757
  }
758
}
759

760
void Particle::cross_periodic_bc(
2,041,205✔
761
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
762
{
763
  // Do not handle periodic boundary conditions on lower universes
764
  if (n_coord() != 1) {
2,041,205!
765
    mark_as_lost(
×
766
      "Cannot transfer particle " + std::to_string(id()) +
×
767
      " across surface in a lower universe. Boundary conditions must be "
768
      "applied to root universe.");
769
    return;
×
770
  }
771

772
  // Score surface currents since reflection causes the direction of the
773
  // particle to change -- artificially move the particle slightly back in
774
  // case the surface crossing is coincident with a mesh boundary
775
  if (!model::active_meshsurf_tallies.empty()) {
2,041,205!
776
    Position r {this->r()};
×
777
    this->r() -= TINY_BIT * u();
×
778
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
779
    this->r() = r;
×
780
  }
781

782
  // Adjust the particle's location and direction.
783
  r() = new_r;
2,041,205✔
784
  u() = new_u;
2,041,205✔
785

786
  // Reassign particle's surface
787
  surface() = new_surface;
2,041,205✔
788

789
  // Figure out what cell particle is in now
790
  n_coord() = 1;
2,041,205✔
791

792
  if (!neighbor_list_find_cell(*this)) {
2,041,205!
793
    mark_as_lost("Couldn't find particle after hitting periodic "
×
794
                 "boundary on surface " +
×
795
                 std::to_string(surf.id_) + ".");
×
796
    return;
×
797
  }
798

799
  // Set previous coordinate going slightly past surface crossing
800
  r_last_current() = r() + TINY_BIT * u();
2,041,205✔
801

802
  // Diagnostic message
803
  if (settings::verbosity >= 10 || trace()) {
2,041,205!
804
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
805
  }
806
}
807

808
void Particle::mark_as_lost(const char* message)
5,270✔
809
{
810
  // Print warning and write lost particle file
811
  warning(message);
5,270✔
812
  if (settings::max_write_lost_particles < 0 ||
5,270✔
813
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,000✔
814
    write_restart();
335✔
815
  }
816
  // Increment number of lost particles
817
  wgt() = 0.0;
5,270✔
818
#pragma omp atomic
2,625✔
819
  simulation::n_lost_particles += 1;
2,645✔
820

821
  // Count the total number of simulated particles (on this processor)
822
  auto n = simulation::current_batch * settings::gen_per_batch *
5,270✔
823
           simulation::work_per_rank;
824

825
  // Abort the simulation if the maximum number of lost particles has been
826
  // reached
827
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,270✔
828
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
8!
829
    fatal_error("Maximum number of lost particles has been reached.");
8✔
830
  }
831
}
5,262✔
832

833
void Particle::write_restart() const
335✔
834
{
835
  // Dont write another restart file if in particle restart mode
836
  if (settings::run_mode == RunMode::PARTICLE)
335✔
837
    return;
20✔
838

839
  // Set up file name
840
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
315✔
841
    simulation::current_batch, id());
315✔
842

843
#pragma omp critical(WriteParticleRestart)
150✔
844
  {
315✔
845
    // Create file
846
    hid_t file_id = file_open(filename, 'w');
315✔
847

848
    // Write filetype and version info
849
    write_attribute(file_id, "filetype", "particle restart");
315✔
850
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
315✔
851
    write_attribute(file_id, "openmc_version", VERSION);
315✔
852
#ifdef GIT_SHA1
853
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
854
#endif
855

856
    // Write data to file
857
    write_dataset(file_id, "current_batch", simulation::current_batch);
315✔
858
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
315✔
859
    write_dataset(file_id, "current_generation", simulation::current_gen);
315✔
860
    write_dataset(file_id, "n_particles", settings::n_particles);
315✔
861
    switch (settings::run_mode) {
315!
862
    case RunMode::FIXED_SOURCE:
195✔
863
      write_dataset(file_id, "run_mode", "fixed source");
195✔
864
      break;
90✔
865
    case RunMode::EIGENVALUE:
120✔
866
      write_dataset(file_id, "run_mode", "eigenvalue");
120✔
867
      break;
60✔
868
    case RunMode::PARTICLE:
×
869
      write_dataset(file_id, "run_mode", "particle restart");
×
870
      break;
871
    default:
872
      break;
873
    }
874
    write_dataset(file_id, "id", id());
315✔
875
    write_dataset(file_id, "type", type().pdg_number());
315✔
876

877
    int64_t i = current_work();
315✔
878
    if (settings::run_mode == RunMode::EIGENVALUE) {
315✔
879
      // take source data from primary bank for eigenvalue simulation
880
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
120✔
881
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
120✔
882
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
120✔
883
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
120✔
884
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
120✔
885
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
195!
886
      // re-sample using rng random number seed used to generate source particle
887
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
195✔
888
                     settings::n_particles +
195✔
889
                   simulation::work_index[mpi::rank] + i;
195✔
890
      uint64_t seed = init_seed(id, STREAM_SOURCE);
195✔
891
      // re-sample source site
892
      auto site = sample_external_source(&seed);
195✔
893
      write_dataset(file_id, "weight", site.wgt);
195✔
894
      write_dataset(file_id, "energy", site.E);
195✔
895
      write_dataset(file_id, "xyz", site.r);
195✔
896
      write_dataset(file_id, "uvw", site.u);
195✔
897
      write_dataset(file_id, "time", site.time);
195✔
898
    }
899

900
    // Close file
901
    file_close(file_id);
315✔
902
  } // #pragma omp critical
903
}
315✔
904

905
void Particle::update_neutron_xs(
2,147,483,647✔
906
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
907
{
908
  // Get microscopic cross section cache
909
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
910

911
  // If the cache doesn't match, recalculate micro xs
912
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
913
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
914
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
915
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
916

917
    // If NCrystal is being used, update micro cross section cache
918
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
919
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
920
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
10,017,230✔
921
      ncrystal_update_micro(ncrystal_xs, micro);
10,017,230✔
922
    }
923
  }
924
}
2,147,483,647✔
925

926
//==============================================================================
927
// Non-method functions
928
//==============================================================================
929
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,517,718,682✔
930
{
931
  if (simulation::current_batch <= settings::n_inactive ||
1,517,718,682✔
932
      simulation::surf_source_bank.full()) {
1,167,343,867✔
933
    return;
1,517,605,028✔
934
  }
935

936
  // If a cell/cellfrom/cellto parameter is defined
937
  if (settings::ssw_cell_id != C_NONE) {
295,201✔
938

939
    // Retrieve cell index and storage type
940
    int cell_idx = model::cell_map[settings::ssw_cell_id];
221,431✔
941

942
    if (surf.bc_) {
221,431✔
943
      // Leave if cellto with vacuum boundary condition
944
      if (surf.bc_->type() == "vacuum" &&
266,098✔
945
          settings::ssw_cell_type == SSWCellType::To) {
28,325✔
946
        return;
947
      }
948

949
      // Leave if other boundary condition than vacuum
950
      if (surf.bc_->type() != "vacuum") {
245,830✔
951
        return;
952
      }
953
    }
954

955
    // Check if the cell of interest has been exited
956
    bool exited = false;
957
    for (int i = 0; i < p.n_coord_last(); ++i) {
286,391✔
958
      if (p.cell_last(i) == cell_idx) {
179,818✔
959
        exited = true;
64,166✔
960
      }
961
    }
962

963
    // Check if the cell of interest has been entered
964
    bool entered = false;
965
    for (int i = 0; i < p.n_coord(); ++i) {
254,519✔
966
      if (p.coord(i).cell() == cell_idx) {
147,946✔
967
        entered = true;
50,542✔
968
      }
969
    }
970

971
    // Vacuum boundary conditions: return if cell is not exited
972
    if (surf.bc_) {
106,573✔
973
      if (surf.bc_->type() == "vacuum" && !exited) {
36,382!
974
        return;
975
      }
976
    } else {
977

978
      // If we both enter and exit the cell of interest
979
      if (entered && exited) {
88,382✔
980
        return;
981
      }
982

983
      // If we did not enter nor exit the cell of interest
984
      if (!entered && !exited) {
63,835✔
985
        return;
986
      }
987

988
      // If cellfrom and the cell before crossing is not the cell of
989
      // interest
990
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
54,214✔
991
        return;
992
      }
993

994
      // If cellto and the cell after crossing is not the cell of interest
995
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
44,129✔
996
        return;
997
      }
998
    }
999
  }
1000

1001
  SourceSite site;
113,654✔
1002
  site.r = p.r();
113,654✔
1003
  site.u = p.u();
113,654✔
1004
  site.E = p.E();
113,654✔
1005
  site.time = p.time();
113,654✔
1006
  site.wgt = p.wgt();
113,654✔
1007
  site.delayed_group = p.delayed_group();
113,654✔
1008
  site.surf_id = surf.id_;
113,654✔
1009
  site.particle = p.type();
113,654✔
1010
  site.parent_id = p.id();
113,654✔
1011
  site.progeny_id = p.n_progeny();
113,654✔
1012
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
113,654✔
1013
}
1014

1015
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc