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

openmc-dev / openmc / 20278515727

16 Dec 2025 06:26PM UTC coverage: 81.822% (-0.1%) from 81.92%
20278515727

Pull #3493

github

web-flow
Merge 7f36869a3 into bbfa18d72
Pull Request #3493: Implement vector fitting to replace external `vectfit` package

17013 of 23575 branches covered (72.17%)

Branch coverage included in aggregate %.

188 of 207 new or added lines in 3 files covered. (90.82%)

3101 existing lines in 56 files now uncovered.

54973 of 64404 relevant lines covered (85.36%)

41385524.25 hits per line

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

85.41
/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;
51
    switch (this->type()) {
1,833,014,138!
52
    case ParticleType::neutron:
1,763,829,266✔
53
      mass = MASS_NEUTRON_EV;
1,763,829,266✔
54
      break;
1,763,829,266✔
55
    case ParticleType::photon:
20,118,524✔
56
      mass = 0.0;
20,118,524✔
57
      break;
20,118,524✔
58
    case ParticleType::electron:
49,066,348✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
49,066,348✔
61
      break;
49,066,348✔
62
    }
63
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
64
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,833,014,138✔
65
           (this->E() + mass);
1,833,014,138✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,876,306,740✔
68
    int macro_t = this->mg_xs_cache().t;
1,876,306,740✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
1,876,306,740✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,876,306,740✔
71
                   nullptr, nullptr, macro_t, macro_a);
1,876,306,740✔
72
  }
73
}
74

75
bool Particle::create_secondary(
102,325,482✔
76
  double wgt, Direction u, double E, ParticleType type)
77
{
78
  // If energy is below cutoff for this particle, don't create secondary
79
  // particle
80
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
102,325,482✔
81
    return false;
48,923,577✔
82
  }
83

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

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

105
  // Convert signed index to a signed surface ID
106
  if (surface() == SURFACE_NONE) {
3,716,405✔
107
    bank.surf_id = SURFACE_NONE;
3,716,069✔
108
  } else {
109
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
110
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
111
  }
112
}
3,716,405✔
113

114
void Particle::from_source(const SourceSite* src)
210,622,911✔
115
{
116
  // Reset some attributes
117
  clear();
210,622,911✔
118
  surface() = SURFACE_NONE;
210,622,911✔
119
  cell_born() = C_NONE;
210,622,911✔
120
  material() = C_NONE;
210,622,911✔
121
  n_collision() = 0;
210,622,911✔
122
  fission() = false;
210,622,911✔
123
  zero_flux_derivs();
210,622,911✔
124
  lifetime() = 0.0;
210,622,911✔
125
#ifdef OPENMC_DAGMC_ENABLED
126
  history().reset();
21,221,127✔
127
#endif
128

129
  // Copy attributes from source bank site
130
  type() = src->particle;
210,622,911✔
131
  wgt() = src->wgt;
210,622,911✔
132
  wgt_last() = src->wgt;
210,622,911✔
133
  r() = src->r;
210,622,911✔
134
  u() = src->u;
210,622,911✔
135
  r_born() = src->r;
210,622,911✔
136
  r_last_current() = src->r;
210,622,911✔
137
  r_last() = src->r;
210,622,911✔
138
  u_last() = src->u;
210,622,911✔
139
  if (settings::run_CE) {
210,622,911✔
140
    E() = src->E;
105,454,921✔
141
    g() = 0;
105,454,921✔
142
  } else {
143
    g() = static_cast<int>(src->E);
105,167,990✔
144
    g_last() = static_cast<int>(src->E);
105,167,990✔
145
    E() = data::mg.energy_bin_avg_[g()];
105,167,990✔
146
  }
147
  E_last() = E();
210,622,911✔
148
  time() = src->time;
210,622,911✔
149
  time_last() = src->time;
210,622,911✔
150
  parent_nuclide() = src->parent_nuclide;
210,622,911✔
151
  delayed_group() = src->delayed_group;
210,622,911✔
152

153
  // Convert signed surface ID to signed index
154
  if (src->surf_id != SURFACE_NONE) {
210,622,911✔
155
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
100,336✔
156
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
100,336!
157
  }
158
}
210,622,911✔
159

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

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

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

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

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
207,759,201!
189
      cell_born() = lowest_coord().cell();
207,759,201✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
430,696,632✔
193
      cell_last(j) = coord(j).cell();
222,937,431✔
194
    }
195
    n_coord_last() = n_coord();
207,759,201✔
196
  }
197

198
  // Write particle track.
199
  if (write_track())
2,147,483,647✔
200
    write_particle_track(*this);
9,540✔
201

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

205
  // Calculate microscopic and macroscopic cross sections
206
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
207
    if (settings::run_CE) {
2,147,483,647✔
208
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,028,923,858✔
209
          density_mult() != density_mult_last()) {
322,523,472✔
210
        // If the material is the same as the last material and the
211
        // temperature hasn't changed, we don't need to lookup cross
212
        // sections again.
213
        model::materials[material()]->calculate_xs(*this);
1,383,885,634✔
214
      }
215
    } else {
216
      // Get the MG data; unlike the CE case above, we have to re-calculate
217
      // cross sections for every collision since the cross sections may
218
      // be angle-dependent
219
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,876,306,740✔
220

221
      // Update the particle's group while we know we are multi-group
222
      g_last() = g();
1,876,306,740✔
223
    }
224
  } else {
225
    macro_xs().total = 0.0;
101,662,242✔
226
    macro_xs().absorption = 0.0;
101,662,242✔
227
    macro_xs().fission = 0.0;
101,662,242✔
228
    macro_xs().nu_fission = 0.0;
101,662,242✔
229
  }
230
}
231

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

237
  // Sample a distance to collision
238
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
239
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
49,066,348!
240
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
241
    collision_distance() = INFINITY;
101,662,242✔
242
  } else {
243
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
244
  }
245

246
  double speed = this->speed();
2,147,483,647✔
247
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
248
  double distance_cutoff =
249
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
250

251
  // Select smaller of the three distances
252
  double distance =
253
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
254

255
  // Advance particle in space and time
256
  this->move_distance(distance);
2,147,483,647✔
257
  double dt = distance / speed;
2,147,483,647✔
258
  this->time() += dt;
2,147,483,647✔
259
  this->lifetime() += dt;
2,147,483,647✔
260

261
  // Score timed track-length tallies
262
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_timed_tracklength_tally(*this, distance);
3,298,470✔
264
  }
265

266
  // Score track-length tallies
267
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
268
    score_tracklength_tally(*this, distance);
1,351,516,510✔
269
  }
270

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

277
  // Score flux derivative accumulators for differential tallies.
278
  if (!model::active_tallies.empty()) {
2,147,483,647✔
279
    score_track_derivative(*this, distance);
1,505,998,330✔
280
  }
281

282
  // Set particle weight to zero if it hit the time boundary
283
  if (distance == distance_cutoff) {
2,147,483,647✔
284
    wgt() = 0.0;
204,480✔
285
  }
286
}
2,147,483,647✔
287

288
void Particle::event_cross_surface()
1,980,417,501✔
289
{
290
  // Saving previous cell data
291
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
292
    cell_last(j) = coord(j).cell();
2,147,483,647✔
293
  }
294
  n_coord_last() = n_coord();
1,980,417,501✔
295

296
  // Set surface that particle is on and adjust coordinate levels
297
  surface() = boundary().surface();
1,980,417,501✔
298
  n_coord() = boundary().coord_level();
1,980,417,501✔
299

300
  if (boundary().lattice_translation()[0] != 0 ||
1,980,417,501✔
301
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
302
      boundary().lattice_translation()[2] != 0) {
1,496,246,509✔
303
    // Particle crosses lattice boundary
304

305
    bool verbose = settings::verbosity >= 10 || trace();
654,586,554!
306
    cross_lattice(*this, boundary(), verbose);
654,586,554✔
307
    event() = TallyEvent::LATTICE;
654,586,554✔
308
  } else {
309
    // Particle crosses surface
310
    const auto& surf {model::surfaces[surface_index()].get()};
1,325,830,947✔
311
    // If BC, add particle to surface source before crossing surface
312
    if (surf->surf_source_ && surf->bc_) {
1,325,830,947✔
313
      add_surf_source_to_bank(*this, *surf);
611,698,511✔
314
    }
315
    this->cross_surface(*surf);
1,325,830,947✔
316
    // If no BC, add particle to surface source after crossing surface
317
    if (surf->surf_source_ && !surf->bc_) {
1,325,830,939✔
318
      add_surf_source_to_bank(*this, *surf);
713,011,411✔
319
    }
320
    if (settings::weight_window_checkpoint_surface) {
1,325,830,939✔
321
      apply_weight_windows(*this);
10,738!
322
    }
323
    event() = TallyEvent::SURFACE;
1,325,830,939✔
324
  }
325
  // Score cell to cell partial currents
326
  if (!model::active_surface_tallies.empty()) {
1,980,417,493✔
327
    score_surface_tally(*this, model::active_surface_tallies);
31,747,970✔
328
  }
329
}
1,980,417,493✔
330

331
void Particle::event_collide()
2,147,483,647✔
332
{
333
  // Score collision estimate of keff
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
335
      type() == ParticleType::neutron) {
1,959,787,266✔
336
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,923,519,486✔
337
  }
338

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

343
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
344
    score_surface_tally(*this, model::active_meshsurf_tallies);
57,362,660✔
345

346
  // Clear surface component
347
  surface() = SURFACE_NONE;
2,147,483,647✔
348

349
  if (settings::run_CE) {
2,147,483,647✔
350
    collision(*this);
799,216,985✔
351
  } else {
352
    collision_mg(*this);
1,620,964,070✔
353
  }
354

355
  // Collision track feature to recording particle interaction
356
  if (settings::collision_track) {
2,147,483,647✔
357
    collision_track_record(*this);
136,288✔
358
  }
359

360
  // Score collision estimator tallies -- this is done after a collision
361
  // has occurred rather than before because we need information on the
362
  // outgoing energy for any tallies with an outgoing energy filter
363
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
364
    score_collision_tally(*this);
97,612,106✔
365
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
366
    if (settings::run_CE) {
213,270,956✔
367
      score_analog_tally_ce(*this);
212,172,536✔
368
    } else {
369
      score_analog_tally_mg(*this);
1,098,420✔
370
    }
371
  }
372

373
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
374
      type() == ParticleType::photon) {
15,380✔
375
    pht_collision_energy();
1,840✔
376
  }
377

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

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

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

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

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

408
  // Score flux derivative accumulators for differential tallies.
409
  if (!model::active_tallies.empty())
2,147,483,647✔
410
    score_collision_derivative(*this);
689,808,996✔
411

412
#ifdef OPENMC_DAGMC_ENABLED
413
  history().reset();
244,256,490✔
414
#endif
415
}
2,147,483,647✔
416

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

427
  // Check for secondary particles if this particle is dead
428
  if (!alive()) {
2,147,483,647✔
429
    // Write final position for this particle
430
    if (write_track()) {
207,758,743✔
431
      write_particle_track(*this);
5,828✔
432
    }
433

434
    // If no secondary particles, break out of event loop
435
    if (secondary_bank().empty())
207,758,743✔
436
      return;
150,436,946✔
437

438
    from_source(&secondary_bank().back());
57,321,797✔
439
    secondary_bank().pop_back();
57,321,797✔
440
    n_event() = 0;
57,321,797✔
441
    bank_second_E() = 0.0;
57,321,797✔
442

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

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

469
    // Enter new particle in particle track file
470
    if (write_track())
57,321,797✔
471
      add_particle_track(*this);
4,888✔
472
  }
473
}
474

475
void Particle::event_death()
150,437,946✔
476
{
477
#ifdef OPENMC_DAGMC_ENABLED
478
  history().reset();
15,117,135✔
479
#endif
480

481
  // Finish particle track output.
482
  if (write_track()) {
150,437,946✔
483
    finalize_particle_track(*this);
940✔
484
  }
485

486
// Contribute tally reduction variables to global accumulator
487
#pragma omp atomic
90,976,544✔
488
  global_tally_absorption += keff_tally_absorption();
150,437,946✔
489
#pragma omp atomic
90,637,045✔
490
  global_tally_collision += keff_tally_collision();
150,437,946✔
491
#pragma omp atomic
90,651,697✔
492
  global_tally_tracklength += keff_tally_tracklength();
150,437,946✔
493
#pragma omp atomic
90,473,701✔
494
  global_tally_leakage += keff_tally_leakage();
150,437,946✔
495

496
  // Reset particle tallies once accumulated
497
  keff_tally_absorption() = 0.0;
150,437,946✔
498
  keff_tally_collision() = 0.0;
150,437,946✔
499
  keff_tally_tracklength() = 0.0;
150,437,946✔
500
  keff_tally_leakage() = 0.0;
150,437,946✔
501

502
  if (!model::active_pulse_height_tallies.empty()) {
150,437,946✔
503
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,000✔
504
  }
505

506
  // Record the number of progeny created by this particle.
507
  // This data will be used to efficiently sort the fission bank.
508
  if (settings::run_mode == RunMode::EIGENVALUE) {
150,437,946✔
509
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
127,246,500✔
510
    simulation::progeny_per_particle[offset] = n_progeny();
127,246,500✔
511
  }
512
}
150,437,946✔
513

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

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

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

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

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

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

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

549
void Particle::cross_surface(const Surface& surf)
1,326,894,767✔
550
{
551

552
  if (settings::verbosity >= 10 || trace()) {
1,326,894,767✔
553
    write_message(1, "    Crossing surface {}", surf.id_);
30✔
554
  }
555

556
// if we're crossing a CSG surface, make sure the DAG history is reset
557
#ifdef OPENMC_DAGMC_ENABLED
558
  if (surf.geom_type() == GeometryType::CSG)
133,369,213✔
559
    history().reset();
133,314,094✔
560
#endif
561

562
  // Handle any applicable boundary conditions.
563
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,939,021,626!
564
      settings::run_mode != RunMode::VOLUME) {
612,126,859✔
565
    surf.bc_->handle_particle(*this, surf);
612,017,819✔
566
    return;
612,017,819✔
567
  }
568

569
  // ==========================================================================
570
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
571

572
#ifdef OPENMC_DAGMC_ENABLED
573
  // in DAGMC, we know what the next cell should be
574
  if (surf.geom_type() == GeometryType::DAG) {
71,732,316✔
575
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
576
                       lowest_coord().universe()) -
44,310✔
577
                     1;
44,310✔
578
    // save material, temperature, and density multiplier
579
    material_last() = material();
44,310✔
580
    sqrtkT_last() = sqrtkT();
44,310✔
581
    density_mult_last() = density_mult();
44,310✔
582
    // set new cell value
583
    lowest_coord().cell() = i_cell;
44,310✔
584
    auto& cell = model::cells[i_cell];
44,310✔
585

586
    cell_instance() = 0;
44,310✔
587
    if (cell->distribcell_index_ >= 0)
44,310✔
588
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
589

590
    material() = cell->material(cell_instance());
44,310✔
591
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
592
    density_mult() = cell->density_mult(cell_instance());
44,310✔
593
    return;
44,310✔
594
  }
595
#endif
596

597
  bool verbose = settings::verbosity >= 10 || trace();
714,832,638!
598
  if (neighbor_list_find_cell(*this, verbose)) {
714,832,638✔
599
    return;
714,805,448✔
600
  }
601

602
  // ==========================================================================
603
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
604

605
  // Remove lower coordinate levels
606
  n_coord() = 1;
27,190✔
607
  bool found = exhaustive_find_cell(*this, verbose);
27,190✔
608

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

615
    surface() = SURFACE_NONE;
5,270✔
616
    n_coord() = 1;
5,270✔
617
    r() += TINY_BIT * u();
5,270✔
618

619
    // Couldn't find next cell anywhere! This probably means there is an actual
620
    // undefined region in the geometry.
621

622
    if (!exhaustive_find_cell(*this, verbose)) {
5,270!
623
      mark_as_lost("After particle " + std::to_string(id()) +
15,802✔
624
                   " crossed surface " + std::to_string(surf.id_) +
21,064✔
625
                   " it could not be located in any cell and it did not leak.");
626
      return;
5,262✔
627
    }
628
  }
629
}
630

631
void Particle::cross_vacuum_bc(const Surface& surf)
31,245,990✔
632
{
633
  // Score any surface current tallies -- note that the particle is moved
634
  // forward slightly so that if the mesh boundary is on the surface, it is
635
  // still processed
636

637
  if (!model::active_meshsurf_tallies.empty()) {
31,245,990✔
638
    // TODO: Find a better solution to score surface currents than
639
    // physically moving the particle forward slightly
640

641
    r() += TINY_BIT * u();
852,020✔
642
    score_surface_tally(*this, model::active_meshsurf_tallies);
852,020✔
643
  }
644

645
  // Score to global leakage tally
646
  keff_tally_leakage() += wgt();
31,245,990✔
647

648
  // Kill the particle
649
  wgt() = 0.0;
31,245,990✔
650

651
  // Display message
652
  if (settings::verbosity >= 10 || trace()) {
31,245,990!
653
    write_message(1, "    Leaked out of surface {}", surf.id_);
10✔
654
  }
655
}
31,245,990✔
656

657
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
580,952,601✔
658
{
659
  // Do not handle reflective boundary conditions on lower universes
660
  if (n_coord() != 1) {
580,952,601!
UNCOV
661
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
662
                 " off surface in a lower universe.");
UNCOV
663
    return;
×
664
  }
665

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

673
  if (!model::active_surface_tallies.empty()) {
580,952,601✔
674
    score_surface_tally(*this, model::active_surface_tallies);
259,110✔
675
  }
676

677
  if (!model::active_meshsurf_tallies.empty()) {
580,952,601✔
678
    Position r {this->r()};
42,623,170✔
679
    this->r() -= TINY_BIT * u();
42,623,170✔
680
    score_surface_tally(*this, model::active_meshsurf_tallies);
42,623,170✔
681
    this->r() = r;
42,623,170✔
682
  }
683

684
  // Set the new particle direction
685
  u() = new_u;
580,952,601✔
686

687
  // Reassign particle's cell and surface
688
  coord(0).cell() = cell_last(0);
580,952,601✔
689
  surface() = -surface();
580,952,601✔
690

691
  // If a reflective surface is coincident with a lattice or universe
692
  // boundary, it is necessary to redetermine the particle's coordinates in
693
  // the lower universes.
694
  // (unless we're using a dagmc model, which has exactly one universe)
695
  n_coord() = 1;
580,952,601✔
696
  if (surf.geom_type() != GeometryType::DAG &&
1,161,902,444!
697
      !neighbor_list_find_cell(*this)) {
580,949,843!
UNCOV
698
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
699
                 std::to_string(surf.id_) + ".");
×
UNCOV
700
    return;
×
701
  }
702

703
  // Set previous coordinate going slightly past surface crossing
704
  r_last_current() = r() + TINY_BIT * u();
580,952,601✔
705

706
  // Diagnostic message
707
  if (settings::verbosity >= 10 || trace()) {
580,952,601!
708
    write_message(1, "    Reflected from surface {}", surf.id_);
×
709
  }
710
}
711

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

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

734
  // Adjust the particle's location and direction.
735
  r() = new_r;
733,288✔
736
  u() = new_u;
733,288✔
737

738
  // Reassign particle's surface
739
  surface() = new_surface;
733,288✔
740

741
  // Figure out what cell particle is in now
742
  n_coord() = 1;
733,288✔
743

744
  if (!neighbor_list_find_cell(*this)) {
733,288!
UNCOV
745
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
746
                 "boundary on surface " +
×
UNCOV
747
                 std::to_string(surf.id_) +
×
748
                 ". The normal vector "
749
                 "of one periodic surface may need to be reversed.");
UNCOV
750
    return;
×
751
  }
752

753
  // Set previous coordinate going slightly past surface crossing
754
  r_last_current() = r() + TINY_BIT * u();
733,288✔
755

756
  // Diagnostic message
757
  if (settings::verbosity >= 10 || trace()) {
733,288!
UNCOV
758
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
759
  }
760
}
761

762
void Particle::mark_as_lost(const char* message)
5,270✔
763
{
764
  // Print warning and write lost particle file
765
  warning(message);
5,270✔
766
  if (settings::max_write_lost_particles < 0 ||
5,270✔
767
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,000✔
768
    write_restart();
340✔
769
  }
770
  // Increment number of lost particles
771
  wgt() = 0.0;
5,270✔
772
#pragma omp atomic
3,154✔
773
  simulation::n_lost_particles += 1;
2,116✔
774

775
  // Count the total number of simulated particles (on this processor)
776
  auto n = simulation::current_batch * settings::gen_per_batch *
5,270✔
777
           simulation::work_per_rank;
778

779
  // Abort the simulation if the maximum number of lost particles has been
780
  // reached
781
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,270✔
782
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
8!
783
    fatal_error("Maximum number of lost particles has been reached.");
8✔
784
  }
785
}
5,262✔
786

787
void Particle::write_restart() const
340✔
788
{
789
  // Dont write another restart file if in particle restart mode
790
  if (settings::run_mode == RunMode::PARTICLE)
340✔
791
    return;
20✔
792

793
  // Set up file name
794
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
795
    simulation::current_batch, id());
591✔
796

797
#pragma omp critical(WriteParticleRestart)
374✔
798
  {
799
    // Create file
800
    hid_t file_id = file_open(filename, 'w');
320✔
801

802
    // Write filetype and version info
803
    write_attribute(file_id, "filetype", "particle restart");
320✔
804
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
320✔
805
    write_attribute(file_id, "openmc_version", VERSION);
320✔
806
#ifdef GIT_SHA1
807
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
808
#endif
809

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

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

854
    // Close file
855
    file_close(file_id);
320✔
856
  } // #pragma omp critical
857
}
320✔
858

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

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

871
    // If NCrystal is being used, update micro cross section cache
872
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
873
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
874
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
10,017,230✔
875
      ncrystal_update_micro(ncrystal_xs, micro);
10,017,230✔
876
    }
877
  }
878
}
2,147,483,647✔
879

880
//==============================================================================
881
// Non-method functions
882
//==============================================================================
883

884
std::string particle_type_to_str(ParticleType type)
2,845,634✔
885
{
886
  switch (type) {
2,845,634!
887
  case ParticleType::neutron:
2,181,764✔
888
    return "neutron";
2,181,764✔
889
  case ParticleType::photon:
663,630✔
890
    return "photon";
663,630✔
891
  case ParticleType::electron:
120✔
892
    return "electron";
120✔
893
  case ParticleType::positron:
120✔
894
    return "positron";
120✔
895
  }
UNCOV
896
  UNREACHABLE();
×
897
}
898

899
ParticleType str_to_particle_type(std::string str)
2,901,382✔
900
{
901
  if (str == "neutron") {
2,901,382✔
902
    return ParticleType::neutron;
676,982✔
903
  } else if (str == "photon") {
2,224,400✔
904
    return ParticleType::photon;
2,224,324✔
905
  } else if (str == "electron") {
76✔
906
    return ParticleType::electron;
38✔
907
  } else if (str == "positron") {
38!
908
    return ParticleType::positron;
38✔
909
  } else {
UNCOV
910
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
911
  }
912
}
913

914
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,324,709,922✔
915
{
916
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
917
      simulation::surf_source_bank.full()) {
1,048,543,279✔
918
    return;
1,324,592,164✔
919
  }
920

921
  // If a cell/cellfrom/cellto parameter is defined
922
  if (settings::ssw_cell_id != C_NONE) {
305,207✔
923

924
    // Retrieve cell index and storage type
925
    int cell_idx = model::cell_map[settings::ssw_cell_id];
230,204✔
926

927
    if (surf.bc_) {
230,204✔
928
      // Leave if cellto with vacuum boundary condition
929
      if (surf.bc_->type() == "vacuum" &&
164,772!
930
          settings::ssw_cell_type == SSWCellType::To) {
30,024✔
931
        return;
11,010✔
932
      }
933

934
      // Leave if other boundary condition than vacuum
935
      if (surf.bc_->type() != "vacuum") {
123,738✔
936
        return;
104,724✔
937
      }
938
    }
939

940
    // Check if the cell of interest has been exited
941
    bool exited = false;
114,470✔
942
    for (int i = 0; i < p.n_coord_last(); ++i) {
302,783✔
943
      if (p.cell_last(i) == cell_idx) {
188,313✔
944
        exited = true;
66,877✔
945
      }
946
    }
947

948
    // Check if the cell of interest has been entered
949
    bool entered = false;
114,470✔
950
    for (int i = 0; i < p.n_coord(); ++i) {
270,511✔
951
      if (p.coord(i).cell() == cell_idx) {
156,041✔
952
        entered = true;
52,065✔
953
      }
954
    }
955

956
    // Vacuum boundary conditions: return if cell is not exited
957
    if (surf.bc_) {
114,470✔
958
      if (surf.bc_->type() == "vacuum" && !exited) {
19,014!
959
        return;
13,314✔
960
      }
961
    } else {
962

963
      // If we both enter and exit the cell of interest
964
      if (entered && exited) {
95,456✔
965
        return;
24,547✔
966
      }
967

968
      // If we did not enter nor exit the cell of interest
969
      if (!entered && !exited) {
70,909✔
970
        return;
12,461✔
971
      }
972

973
      // If cellfrom and the cell before crossing is not the cell of
974
      // interest
975
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
58,448✔
976
        return;
10,446✔
977
      }
978

979
      // If cellto and the cell after crossing is not the cell of interest
980
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
48,002✔
981
        return;
10,947✔
982
      }
983
    }
984
  }
985

986
  SourceSite site;
117,758✔
987
  site.r = p.r();
117,758✔
988
  site.u = p.u();
117,758✔
989
  site.E = p.E();
117,758✔
990
  site.time = p.time();
117,758✔
991
  site.wgt = p.wgt();
117,758✔
992
  site.delayed_group = p.delayed_group();
117,758✔
993
  site.surf_id = surf.id_;
117,758✔
994
  site.particle = p.type();
117,758✔
995
  site.parent_id = p.id();
117,758✔
996
  site.progeny_id = p.n_progeny();
117,758✔
997
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
117,758✔
998
}
999

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