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

openmc-dev / openmc / 21043561037

15 Jan 2026 07:23PM UTC coverage: 81.388% (-0.7%) from 82.044%
21043561037

Pull #3734

github

web-flow
Merge 5e79b7b6f into 179048b80
Pull Request #3734: Specify temperature from a field (structured mesh only)

16703 of 22995 branches covered (72.64%)

Branch coverage included in aggregate %.

156 of 179 new or added lines in 12 files covered. (87.15%)

843 existing lines in 36 files now uncovered.

54487 of 64475 relevant lines covered (84.51%)

27592585.27 hits per line

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

84.5
/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
1,852,144,598✔
47
{
48
  if (settings::run_CE) {
1,852,144,598✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (this->type()) {
913,991,228!
52
    case ParticleType::neutron:
879,388,332✔
53
      mass = MASS_NEUTRON_EV;
879,388,332✔
54
      break;
879,388,332✔
55
    case ParticleType::photon:
10,060,772✔
56
      mass = 0.0;
10,060,772✔
57
      break;
10,060,772✔
58
    case ParticleType::electron:
24,542,124✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
24,542,124✔
61
      break;
24,542,124✔
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)) /
913,991,228✔
65
           (this->E() + mass);
913,991,228✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
938,153,370✔
68
    int macro_t = this->mg_xs_cache().t;
938,153,370✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
938,153,370✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
938,153,370✔
71
                   nullptr, nullptr, macro_t, macro_a);
938,153,370✔
72
  }
73
}
74

75
bool Particle::create_secondary(
51,181,845✔
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)]) {
51,181,845✔
81
    return false;
24,470,671✔
82
  }
83

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

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

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

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

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

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

160
void Particle::event_calculate_xs()
1,839,668,843✔
161
{
162
  // Set the random number stream
163
  stream() = STREAM_TRACKING;
1,839,668,843✔
164

165
  // Store pre-collision particle properties
166
  wgt_last() = wgt();
1,839,668,843✔
167
  E_last() = E();
1,839,668,843✔
168
  u_last() = u();
1,839,668,843✔
169
  r_last() = r();
1,839,668,843✔
170
  time_last() = time();
1,839,668,843✔
171

172
  // Reset event variables
173
  event() = TallyEvent::KILL;
1,839,668,843✔
174
  event_nuclide() = NUCLIDE_NONE;
1,839,668,843✔
175
  event_mt() = REACTION_NONE;
1,839,668,843✔
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) {
1,839,668,843✔
181
    if (!exhaustive_find_cell(*this)) {
104,310,642!
182
      mark_as_lost(
×
183
        "Could not find the cell containing particle " + std::to_string(id()));
×
184
      return;
×
185
    }
186

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
104,310,642!
189
      cell_born() = lowest_coord().cell();
104,310,642✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
216,263,498✔
193
      cell_last(j) = coord(j).cell();
111,952,856✔
194
    }
195
    n_coord_last() = n_coord();
104,310,642✔
196

197
    // Update temperature of the particle if temperature field
198
    if (settings::temperature_field_on) {
104,310,642✔
199
      simulation::temperature_field.update_particle_temperature(*this);
20,015✔
200
    }
201
  }
202

203
  // Write particle track.
204
  if (write_track())
1,839,668,843✔
205
    write_particle_track(*this);
4,785✔
206

207
  if (settings::check_overlaps)
1,839,668,843!
208
    check_cell_overlap(*this);
×
209

210
  // Calculate microscopic and macroscopic cross sections
211
  if (material() != MATERIAL_VOID) {
1,839,668,843✔
212
    if (settings::run_CE) {
1,788,841,787✔
213
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,006,505,195✔
214
          density_mult() != density_mult_last()) {
155,816,778✔
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);
694,875,999✔
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);
938,153,370✔
225

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
938,153,370✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
50,827,056✔
231
    macro_xs().absorption = 0.0;
50,827,056✔
232
    macro_xs().fission = 0.0;
50,827,056✔
233
    macro_xs().nu_fission = 0.0;
50,827,056✔
234
  }
235
}
236

237
void Particle::event_advance()
1,839,668,843✔
238
{
239
  // Find the distance to the nearest geometry boundary
240
  boundary() = distance_to_boundary(*this);
1,839,668,843✔
241

242
  // Sample a distance to collision
243
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
1,839,668,843✔
244
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
24,542,124!
245
  } else if (macro_xs().total == 0.0) {
1,815,126,719✔
246
    collision_distance() = INFINITY;
50,827,056✔
247
  } else {
248
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
1,764,299,663✔
249
  }
250

251
  // Find the distance to the nearest temperature mesh cell surface
252
  double distance_tmesh = INFTY;
1,839,668,843✔
253
  if (settings::temperature_field_on) {
1,839,668,843✔
254
    distance_tmesh =
255
      simulation::temperature_field.distance_to_next_boundary(r(), u());
620,035✔
256
  }
257

258
  // Calculate the distance corresponding to the time cutoff
259
  double speed = this->speed();
1,839,668,843✔
260
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
1,839,668,843✔
261
  double distance_cutoff =
262
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
1,839,668,843✔
263

264
  // Select smaller distance
265
  double distance = std::min({boundary().distance(), collision_distance(),
1,839,668,843✔
266
    distance_cutoff, distance_tmesh});
267

268
  // Prepare the stop condition
269
  if (distance == distance_cutoff) {
1,839,668,843✔
270
    next_event() = EVENT_TIME_CUTOFF;
102,240✔
271
  } else if (distance == boundary().distance()) {
1,839,566,603✔
272
    next_event() = EVENT_CROSS_SURFACE;
627,686,088✔
273
  } else if (distance == distance_tmesh) {
1,211,880,515✔
274
    next_event() = EVENT_CROSS_TEMPERATURE_MESH;
140,235✔
275
  } else if (distance == collision_distance()) {
1,211,740,280!
276
    next_event() = EVENT_COLLIDE;
1,211,740,280✔
277
  }
278

279
  // Advance particle in space and time
280
  this->move_distance(distance);
1,839,668,843✔
281
  double dt = distance / speed;
1,839,668,843✔
282
  this->time() += dt;
1,839,668,843✔
283
  this->lifetime() += dt;
1,839,668,843✔
284

285
  // Score timed track-length tallies
286
  if (!model::active_timed_tracklength_tallies.empty()) {
1,839,668,843✔
287
    score_timed_tracklength_tally(*this, distance);
1,649,235✔
288
  }
289

290
  // Score track-length tallies
291
  if (!model::active_tracklength_tallies.empty()) {
1,839,668,843✔
292
    score_tracklength_tally(*this, distance);
669,173,001✔
293
  }
294

295
  // Score track-length estimate of k-eff
296
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
297
      type() == ParticleType::neutron) {
1,558,698,061✔
298
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
1,540,556,066✔
299
  }
300

301
  // Score flux derivative accumulators for differential tallies.
302
  if (!model::active_tallies.empty()) {
1,839,668,843✔
303
    score_track_derivative(*this, distance);
747,344,380✔
304
  }
305
}
1,839,668,843✔
306

307
void Particle::event_cross_temperature_mesh()
140,235✔
308
{
309
  // Update temperature of the particle
310
  simulation::temperature_field.update_particle_temperature(*this);
140,235✔
311
}
140,235✔
312

313
void Particle::event_cross_surface()
991,911,013✔
314
{
315
  // Saving previous cell data
316
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
317
    cell_last(j) = coord(j).cell();
1,908,224,302✔
318
  }
319
  n_coord_last() = n_coord();
991,911,013✔
320

321
  // Set surface that particle is on and adjust coordinate levels
322
  surface() = boundary().surface();
991,911,013✔
323
  n_coord() = boundary().coord_level();
991,911,013✔
324

325
  if (boundary().lattice_translation()[0] != 0 ||
991,911,013✔
326
      boundary().lattice_translation()[1] != 0 ||
1,745,462,900✔
327
      boundary().lattice_translation()[2] != 0) {
753,551,887✔
328
    // Particle crosses lattice boundary
329

330
    bool verbose = settings::verbosity >= 10 || trace();
324,060,446!
331
    cross_lattice(*this, boundary(), verbose);
324,060,446✔
332
    event() = TallyEvent::LATTICE;
324,060,446✔
333
  } else {
334
    // Particle crosses surface
335
    const auto& surf {model::surfaces[surface_index()].get()};
667,850,567✔
336
    // If BC, add particle to surface source before crossing surface
337
    if (surf->surf_source_ && surf->bc_) {
667,850,567✔
338
      add_surf_source_to_bank(*this, *surf);
307,365,980✔
339
    }
340
    this->cross_surface(*surf);
667,850,567✔
341
    // If no BC, add particle to surface source after crossing surface
342
    if (surf->surf_source_ && !surf->bc_) {
667,850,564✔
343
      add_surf_source_to_bank(*this, *surf);
359,900,534✔
344
    }
345
    if (settings::weight_window_checkpoint_surface) {
667,850,564!
UNCOV
346
      apply_weight_windows(*this);
×
347
    }
348
    event() = TallyEvent::SURFACE;
667,850,564✔
349
  }
350

351
  // Update temperature of the particle if temperature field
352
  if (settings::temperature_field_on) {
991,911,010✔
353
    simulation::temperature_field.update_particle_temperature(*this);
141,110✔
354
  }
355

356
  // Score cell to cell partial currents
357
  if (!model::active_surface_tallies.empty()) {
991,911,010✔
358
    score_surface_tally(*this, model::active_surface_tallies);
15,873,985✔
359
  }
360
}
991,911,010✔
361

362
void Particle::event_collide()
1,211,740,280✔
363
{
364
  // Score collision estimate of keff
365
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
366
      type() == ParticleType::neutron) {
981,419,075✔
367
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
963,285,185✔
368
  }
369

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

374
  if (!model::active_meshsurf_tallies.empty())
1,211,740,280✔
375
    score_surface_tally(*this, model::active_meshsurf_tallies);
28,681,330✔
376

377
  // Clear surface component
378
  surface() = SURFACE_NONE;
1,211,740,280✔
379

380
  if (settings::run_CE) {
1,211,740,280✔
381
    collision(*this);
401,258,245✔
382
  } else {
383
    collision_mg(*this);
810,482,035✔
384
  }
385

386
  // Collision track feature to recording particle interaction
387
  if (settings::collision_track) {
1,211,740,280✔
388
    collision_track_record(*this);
68,995✔
389
  }
390

391
  // Score collision estimator tallies -- this is done after a collision
392
  // has occurred rather than before because we need information on the
393
  // outgoing energy for any tallies with an outgoing energy filter
394
  if (!model::active_collision_tallies.empty())
1,211,740,280✔
395
    score_collision_tally(*this);
49,442,494✔
396
  if (!model::active_analog_tallies.empty()) {
1,211,740,280✔
397
    if (settings::run_CE) {
106,517,975✔
398
      score_analog_tally_ce(*this);
105,968,765✔
399
    } else {
400
      score_analog_tally_mg(*this);
549,210✔
401
    }
402
  }
403

404
  if (!model::active_pulse_height_tallies.empty() &&
1,211,747,970✔
405
      type() == ParticleType::photon) {
7,690✔
406
    pht_collision_energy();
920✔
407
  }
408

409
  // Reset banked weight during collision
410
  n_bank() = 0;
1,211,740,280✔
411
  bank_second_E() = 0.0;
1,211,740,280✔
412
  wgt_bank() = 0.0;
1,211,740,280✔
413
  zero_delayed_bank();
1,211,740,280✔
414

415
  // Reset fission logical
416
  fission() = false;
1,211,740,280✔
417

418
  // Save coordinates for tallying purposes
419
  r_last_current() = r();
1,211,740,280✔
420

421
  // Set last material to none since cross sections will need to be
422
  // re-evaluated
423
  material_last() = C_NONE;
1,211,740,280✔
424

425
  // Set all directions to base level -- right now, after a collision, only
426
  // the base level directions are changed
427
  for (int j = 0; j < n_coord() - 1; ++j) {
1,272,717,229✔
428
    if (coord(j + 1).rotated()) {
60,976,949✔
429
      // If next level is rotated, apply rotation matrix
430
      const auto& m {model::cells[coord(j).cell()]->rotation_};
4,739,370✔
431
      const auto& u {coord(j).u()};
4,739,370✔
432
      coord(j + 1).u() = u.rotate(m);
4,739,370✔
433
    } else {
434
      // Otherwise, copy this level's direction
435
      coord(j + 1).u() = coord(j).u();
56,237,579✔
436
    }
437
  }
438

439
  // Score flux derivative accumulators for differential tallies.
440
  if (!model::active_tallies.empty())
1,211,740,280✔
441
    score_collision_derivative(*this);
345,168,067✔
442

443
#ifdef OPENMC_DAGMC_ENABLED
444
  history().reset();
445
#endif
446
}
1,211,740,280✔
447

448
void Particle::event_revive_from_secondary()
1,839,668,840✔
449
{
450
  // If particle has too many events, display warning and kill it
451
  ++n_event();
1,839,668,840✔
452
  if (n_event() == settings::max_particle_events) {
1,839,668,840!
453
    warning("Particle " + std::to_string(id()) +
×
454
            " underwent maximum number of events.");
455
    wgt() = 0.0;
×
456
  }
457

458
  // Check for secondary particles if this particle is dead
459
  if (!alive()) {
1,839,668,840✔
460
    // Write final position for this particle
461
    if (write_track()) {
104,310,914✔
462
      write_particle_track(*this);
2,916✔
463
    }
464

465
    // If no secondary particles, break out of event loop
466
    if (secondary_bank().empty())
104,310,914✔
467
      return;
75,632,131✔
468

469
    from_source(&secondary_bank().back());
28,678,783✔
470
    secondary_bank().pop_back();
28,678,783✔
471
    n_event() = 0;
28,678,783✔
472
    bank_second_E() = 0.0;
28,678,783✔
473

474
    // Subtract secondary particle energy from interim pulse-height results
475
    if (!model::active_pulse_height_tallies.empty() &&
28,685,828✔
476
        this->type() == ParticleType::photon) {
7,045✔
477
      // Since the birth cell of the particle has not been set we
478
      // have to determine it before the energy of the secondary particle can be
479
      // removed from the pulse-height of this cell.
480
      if (lowest_coord().cell() == C_NONE) {
275!
481
        bool verbose = settings::verbosity >= 10 || trace();
275!
482
        if (!exhaustive_find_cell(*this, verbose)) {
275!
483
          mark_as_lost("Could not find the cell containing particle " +
×
484
                       std::to_string(id()));
×
485
          return;
×
486
        }
487
        // Set birth cell attribute
488
        if (cell_born() == C_NONE)
275!
489
          cell_born() = lowest_coord().cell();
275✔
490

491
        // Initialize last cells from current cell
492
        for (int j = 0; j < n_coord(); ++j) {
550✔
493
          cell_last(j) = coord(j).cell();
275✔
494
        }
495
        n_coord_last() = n_coord();
275✔
496
      }
497
      pht_secondary_particles();
275✔
498
    }
499

500
    // Enter new particle in particle track file
501
    if (write_track())
28,678,783✔
502
      add_particle_track(*this);
2,446✔
503
  }
504
}
505

506
void Particle::event_death()
75,632,131✔
507
{
508
#ifdef OPENMC_DAGMC_ENABLED
509
  history().reset();
510
#endif
511

512
  // Finish particle track output.
513
  if (write_track()) {
75,632,131✔
514
    finalize_particle_track(*this);
470✔
515
  }
516

517
// Contribute tally reduction variables to global accumulator
518
#pragma omp atomic
30,315,781✔
519
  global_tally_absorption += keff_tally_absorption();
75,632,131✔
520
#pragma omp atomic
30,314,320✔
521
  global_tally_collision += keff_tally_collision();
75,632,131✔
522
#pragma omp atomic
30,314,353✔
523
  global_tally_tracklength += keff_tally_tracklength();
75,632,131✔
524
#pragma omp atomic
30,341,851✔
525
  global_tally_leakage += keff_tally_leakage();
75,632,131✔
526

527
  // Reset particle tallies once accumulated
528
  keff_tally_absorption() = 0.0;
75,632,131✔
529
  keff_tally_collision() = 0.0;
75,632,131✔
530
  keff_tally_tracklength() = 0.0;
75,632,131✔
531
  keff_tally_leakage() = 0.0;
75,632,131✔
532

533
  if (!model::active_pulse_height_tallies.empty()) {
75,632,131✔
534
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
2,500✔
535
  }
536

537
  // Record the number of progeny created by this particle.
538
  // This data will be used to efficiently sort the fission bank.
539
  if (settings::run_mode == RunMode::EIGENVALUE) {
75,632,131✔
540
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
63,978,000✔
541
    simulation::progeny_per_particle[offset] = n_progeny();
63,978,000✔
542
  }
543
}
75,632,131✔
544

545
void Particle::pht_collision_energy()
920✔
546
{
547
  // Adds the energy particles lose in a collision to the pulse-height
548

549
  // determine index of cell in pulse_height_cells
550
  auto it = std::find(model::pulse_height_cells.begin(),
920✔
551
    model::pulse_height_cells.end(), lowest_coord().cell());
920✔
552

553
  if (it != model::pulse_height_cells.end()) {
920!
554
    int index = std::distance(model::pulse_height_cells.begin(), it);
920✔
555
    pht_storage()[index] += E_last() - E();
920✔
556

557
    // If the energy of the particle is below the cutoff, it will not be sampled
558
    // so its energy is added to the pulse-height in the cell
559
    int photon = static_cast<int>(ParticleType::photon);
920✔
560
    if (E() < settings::energy_cutoff[photon]) {
920✔
561
      pht_storage()[index] += E();
375✔
562
    }
563
  }
564
}
920✔
565

566
void Particle::pht_secondary_particles()
275✔
567
{
568
  // Removes the energy of secondary produced particles from the pulse-height
569

570
  // determine index of cell in pulse_height_cells
571
  auto it = std::find(model::pulse_height_cells.begin(),
275✔
572
    model::pulse_height_cells.end(), cell_born());
275✔
573

574
  if (it != model::pulse_height_cells.end()) {
275!
575
    int index = std::distance(model::pulse_height_cells.begin(), it);
275✔
576
    pht_storage()[index] -= E();
275✔
577
  }
578
}
275✔
579

580
void Particle::cross_surface(const Surface& surf)
668,382,477✔
581
{
582

583
  if (settings::verbosity >= 10 || trace()) {
668,382,477✔
584
    write_message(1, "    Crossing surface {}", surf.id_);
15✔
585
  }
586

587
// if we're crossing a CSG surface, make sure the DAG history is reset
588
#ifdef OPENMC_DAGMC_ENABLED
589
  if (surf.geom_type() == GeometryType::CSG)
590
    history().reset();
591
#endif
592

593
  // Handle any applicable boundary conditions.
594
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
975,966,977!
595
      settings::run_mode != RunMode::VOLUME) {
307,584,500✔
596
    surf.bc_->handle_particle(*this, surf);
307,529,980✔
597
    return;
307,529,980✔
598
  }
599

600
  // ==========================================================================
601
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
602

603
#ifdef OPENMC_DAGMC_ENABLED
604
  // in DAGMC, we know what the next cell should be
605
  if (surf.geom_type() == GeometryType::DAG) {
606
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
607
                       lowest_coord().universe()) -
608
                     1;
609
    // save material, temperature, and density multiplier
610
    material_last() = material();
611
    sqrtkT_last() = sqrtkT();
612
    density_mult_last() = density_mult();
613
    // set new cell value
614
    lowest_coord().cell() = i_cell;
615
    auto& cell = model::cells[i_cell];
616

617
    cell_instance() = 0;
618
    if (cell->distribcell_index_ >= 0)
619
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
620

621
    material() = cell->material(cell_instance());
622
    sqrtkT() = cell->sqrtkT(cell_instance());
623
    density_mult() = cell->density_mult(cell_instance());
624
    return;
625
  }
626
#endif
627

628
  bool verbose = settings::verbosity >= 10 || trace();
360,852,497!
629
  if (neighbor_list_find_cell(*this, verbose)) {
360,852,497✔
630
    return;
360,838,912✔
631
  }
632

633
  // ==========================================================================
634
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
635

636
  // Remove lower coordinate levels
637
  n_coord() = 1;
13,585✔
638
  bool found = exhaustive_find_cell(*this, verbose);
13,585✔
639

640
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
13,585!
641
    // If a cell is still not found, there are two possible causes: 1) there is
642
    // a void in the model, and 2) the particle hit a surface at a tangent. If
643
    // the particle is really traveling tangent to a surface, if we move it
644
    // forward a tiny bit it should fix the problem.
645

646
    surface() = SURFACE_NONE;
2,625✔
647
    n_coord() = 1;
2,625✔
648
    r() += TINY_BIT * u();
2,625✔
649

650
    // Couldn't find next cell anywhere! This probably means there is an actual
651
    // undefined region in the geometry.
652

653
    if (!exhaustive_find_cell(*this, verbose)) {
2,625!
654
      mark_as_lost("After particle " + std::to_string(id()) +
7,872✔
655
                   " crossed surface " + std::to_string(surf.id_) +
10,494✔
656
                   " it could not be located in any cell and it did not leak.");
657
      return;
2,622✔
658
    }
659
  }
660
}
661

662
void Particle::cross_vacuum_bc(const Surface& surf)
15,948,684✔
663
{
664
  // Score any surface current tallies -- note that the particle is moved
665
  // forward slightly so that if the mesh boundary is on the surface, it is
666
  // still processed
667

668
  if (!model::active_meshsurf_tallies.empty()) {
15,948,684✔
669
    // TODO: Find a better solution to score surface currents than
670
    // physically moving the particle forward slightly
671

672
    r() += TINY_BIT * u();
426,010✔
673
    score_surface_tally(*this, model::active_meshsurf_tallies);
426,010✔
674
  }
675

676
  // Score to global leakage tally
677
  keff_tally_leakage() += wgt();
15,948,684✔
678

679
  // Kill the particle
680
  wgt() = 0.0;
15,948,684✔
681

682
  // Display message
683
  if (settings::verbosity >= 10 || trace()) {
15,948,684!
684
    write_message(1, "    Leaked out of surface {}", surf.id_);
5✔
685
  }
686
}
15,948,684✔
687

688
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
291,015,175✔
689
{
690
  // Do not handle reflective boundary conditions on lower universes
691
  if (n_coord() != 1) {
291,015,175!
692
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
693
                 " off surface in a lower universe.");
694
    return;
×
695
  }
696

697
  // Score surface currents since reflection causes the direction of the
698
  // particle to change. For surface filters, we need to score the tallies
699
  // twice, once before the particle's surface attribute has changed and
700
  // once after. For mesh surface filters, we need to artificially move
701
  // the particle slightly back in case the surface crossing is coincident
702
  // with a mesh boundary
703

704
  if (!model::active_surface_tallies.empty()) {
291,015,175✔
705
    score_surface_tally(*this, model::active_surface_tallies);
129,555✔
706
  }
707

708
  if (!model::active_meshsurf_tallies.empty()) {
291,015,175✔
709
    Position r {this->r()};
21,311,585✔
710
    this->r() -= TINY_BIT * u();
21,311,585✔
711
    score_surface_tally(*this, model::active_meshsurf_tallies);
21,311,585✔
712
    this->r() = r;
21,311,585✔
713
  }
714

715
  // Set the new particle direction
716
  u() = new_u;
291,015,175✔
717

718
  // Reassign particle's cell and surface
719
  coord(0).cell() = cell_last(0);
291,015,175✔
720
  surface() = -surface();
291,015,175✔
721

722
  // If a reflective surface is coincident with a lattice or universe
723
  // boundary, it is necessary to redetermine the particle's coordinates in
724
  // the lower universes.
725
  // (unless we're using a dagmc model, which has exactly one universe)
726
  n_coord() = 1;
291,015,175✔
727
  if (surf.geom_type() != GeometryType::DAG &&
582,030,350!
728
      !neighbor_list_find_cell(*this)) {
291,015,175!
729
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
730
                 std::to_string(surf.id_) + ".");
×
731
    return;
×
732
  }
733

734
  // Set previous coordinate going slightly past surface crossing
735
  r_last_current() = r() + TINY_BIT * u();
291,015,175✔
736

737
  // Diagnostic message
738
  if (settings::verbosity >= 10 || trace()) {
291,015,175!
739
    write_message(1, "    Reflected from surface {}", surf.id_);
×
740
  }
741
}
742

743
void Particle::cross_periodic_bc(
1,023,151✔
744
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
745
{
746
  // Do not handle periodic boundary conditions on lower universes
747
  if (n_coord() != 1) {
1,023,151!
748
    mark_as_lost(
×
749
      "Cannot transfer particle " + std::to_string(id()) +
×
750
      " across surface in a lower universe. Boundary conditions must be "
751
      "applied to root universe.");
752
    return;
×
753
  }
754

755
  // Score surface currents since reflection causes the direction of the
756
  // particle to change -- artificially move the particle slightly back in
757
  // case the surface crossing is coincident with a mesh boundary
758
  if (!model::active_meshsurf_tallies.empty()) {
1,023,151!
759
    Position r {this->r()};
×
760
    this->r() -= TINY_BIT * u();
×
761
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
762
    this->r() = r;
×
763
  }
764

765
  // Adjust the particle's location and direction.
766
  r() = new_r;
1,023,151✔
767
  u() = new_u;
1,023,151✔
768

769
  // Reassign particle's surface
770
  surface() = new_surface;
1,023,151✔
771

772
  // Figure out what cell particle is in now
773
  n_coord() = 1;
1,023,151✔
774

775
  if (!neighbor_list_find_cell(*this)) {
1,023,151!
776
    mark_as_lost("Couldn't find particle after hitting periodic "
×
777
                 "boundary on surface " +
×
778
                 std::to_string(surf.id_) + ".");
×
779
    return;
×
780
  }
781

782
  // Set previous coordinate going slightly past surface crossing
783
  r_last_current() = r() + TINY_BIT * u();
1,023,151✔
784

785
  // Diagnostic message
786
  if (settings::verbosity >= 10 || trace()) {
1,023,151!
787
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
788
  }
789
}
790

791
void Particle::mark_as_lost(const char* message)
2,625✔
792
{
793
  // Print warning and write lost particle file
794
  warning(message);
2,625✔
795
  if (settings::max_write_lost_particles < 0 ||
2,625✔
796
      simulation::n_lost_particles < settings::max_write_lost_particles) {
2,500✔
797
    write_restart();
160✔
798
  }
799
  // Increment number of lost particles
800
  wgt() = 0.0;
2,625✔
801
#pragma omp atomic
1,038✔
802
  simulation::n_lost_particles += 1;
1,587✔
803

804
  // Count the total number of simulated particles (on this processor)
805
  auto n = simulation::current_batch * settings::gen_per_batch *
2,625✔
806
           simulation::work_per_rank;
807

808
  // Abort the simulation if the maximum number of lost particles has been
809
  // reached
810
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
2,625✔
811
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
3!
812
    fatal_error("Maximum number of lost particles has been reached.");
3✔
813
  }
814
}
2,622✔
815

816
void Particle::write_restart() const
160✔
817
{
818
  // Dont write another restart file if in particle restart mode
819
  if (settings::run_mode == RunMode::PARTICLE)
160✔
820
    return;
10✔
821

822
  // Set up file name
823
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
824
    simulation::current_batch, id());
251✔
825

826
#pragma omp critical(WriteParticleRestart)
98✔
827
  {
828
    // Create file
829
    hid_t file_id = file_open(filename, 'w');
150✔
830

831
    // Write filetype and version info
832
    write_attribute(file_id, "filetype", "particle restart");
150✔
833
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
150✔
834
    write_attribute(file_id, "openmc_version", VERSION);
150✔
835
#ifdef GIT_SHA1
836
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
837
#endif
838

839
    // Write data to file
840
    write_dataset(file_id, "current_batch", simulation::current_batch);
150✔
841
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
150✔
842
    write_dataset(file_id, "current_generation", simulation::current_gen);
150✔
843
    write_dataset(file_id, "n_particles", settings::n_particles);
150✔
844
    switch (settings::run_mode) {
150!
845
    case RunMode::FIXED_SOURCE:
90✔
846
      write_dataset(file_id, "run_mode", "fixed source");
90✔
847
      break;
90✔
848
    case RunMode::EIGENVALUE:
60✔
849
      write_dataset(file_id, "run_mode", "eigenvalue");
60✔
850
      break;
60✔
851
    case RunMode::PARTICLE:
×
852
      write_dataset(file_id, "run_mode", "particle restart");
×
853
      break;
×
854
    default:
×
855
      break;
×
856
    }
857
    write_dataset(file_id, "id", id());
150✔
858
    write_dataset(file_id, "type", static_cast<int>(type()));
150✔
859

860
    int64_t i = current_work();
150✔
861
    if (settings::run_mode == RunMode::EIGENVALUE) {
150✔
862
      // take source data from primary bank for eigenvalue simulation
863
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
60✔
864
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
60✔
865
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
60✔
866
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
60✔
867
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
60✔
868
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
90!
869
      // re-sample using rng random number seed used to generate source particle
870
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
90✔
871
                     settings::n_particles +
90✔
872
                   simulation::work_index[mpi::rank] + i;
90✔
873
      uint64_t seed = init_seed(id, STREAM_SOURCE);
90✔
874
      // re-sample source site
875
      auto site = sample_external_source(&seed);
90✔
876
      write_dataset(file_id, "weight", site.wgt);
90✔
877
      write_dataset(file_id, "energy", site.E);
90✔
878
      write_dataset(file_id, "xyz", site.r);
90✔
879
      write_dataset(file_id, "uvw", site.u);
90✔
880
      write_dataset(file_id, "time", site.time);
90✔
881
    }
882

883
    // Close file
884
    file_close(file_id);
150✔
885
  } // #pragma omp critical
886
}
150✔
887

888
void Particle::update_neutron_xs(
2,147,483,647✔
889
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
890
{
891
  // Get microscopic cross section cache
892
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
893

894
  // If the cache doesn't match, recalculate micro xs
895
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
896
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
897
      ncrystal_xs != micro.ncrystal_xs) {
1,146,427,345!
898
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,004,831,499✔
899

900
    // If NCrystal is being used, update micro cross section cache
901
    micro.ncrystal_xs = ncrystal_xs;
2,004,831,499✔
902
    if (ncrystal_xs >= 0.0) {
2,004,831,499✔
903
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
5,008,615✔
904
      ncrystal_update_micro(ncrystal_xs, micro);
5,008,615✔
905
    }
906
  }
907
}
2,147,483,647✔
908

909
//==============================================================================
910
// Non-method functions
911
//==============================================================================
912

913
std::string particle_type_to_str(ParticleType type)
1,422,815✔
914
{
915
  switch (type) {
1,422,815!
916
  case ParticleType::neutron:
1,090,880✔
917
    return "neutron";
1,090,880✔
918
  case ParticleType::photon:
331,815✔
919
    return "photon";
331,815✔
920
  case ParticleType::electron:
60✔
921
    return "electron";
60✔
922
  case ParticleType::positron:
60✔
923
    return "positron";
60✔
924
  }
925
  UNREACHABLE();
×
926
}
927

928
ParticleType str_to_particle_type(std::string str)
1,462,373✔
929
{
930
  if (str == "neutron") {
1,462,373✔
931
    return ParticleType::neutron;
343,668✔
932
  } else if (str == "photon") {
1,118,705✔
933
    return ParticleType::photon;
1,118,667✔
934
  } else if (str == "electron") {
38✔
935
    return ParticleType::electron;
19✔
936
  } else if (str == "positron") {
19!
937
    return ParticleType::positron;
19✔
938
  } else {
939
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
940
  }
941
}
942

943
void add_surf_source_to_bank(Particle& p, const Surface& surf)
667,266,514✔
944
{
945
  if (simulation::current_batch <= settings::n_inactive ||
1,194,555,245✔
946
      simulation::surf_source_bank.full()) {
527,288,731✔
947
    return;
667,207,039✔
948
  }
949

950
  // If a cell/cellfrom/cellto parameter is defined
951
  if (settings::ssw_cell_id != C_NONE) {
159,388✔
952

953
    // Retrieve cell index and storage type
954
    int cell_idx = model::cell_map[settings::ssw_cell_id];
121,178✔
955

956
    if (surf.bc_) {
121,178✔
957
      // Leave if cellto with vacuum boundary condition
958
      if (surf.bc_->type() == "vacuum" &&
88,930!
959
          settings::ssw_cell_type == SSWCellType::To) {
15,375✔
960
        return;
5,630✔
961
      }
962

963
      // Leave if other boundary condition than vacuum
964
      if (surf.bc_->type() != "vacuum") {
67,925✔
965
        return;
58,180✔
966
      }
967
    }
968

969
    // Check if the cell of interest has been exited
970
    bool exited = false;
57,368✔
971
    for (int i = 0; i < p.n_coord_last(); ++i) {
154,466✔
972
      if (p.cell_last(i) == cell_idx) {
97,098✔
973
        exited = true;
34,440✔
974
      }
975
    }
976

977
    // Check if the cell of interest has been entered
978
    bool entered = false;
57,368✔
979
    for (int i = 0; i < p.n_coord(); ++i) {
137,336✔
980
      if (p.coord(i).cell() == cell_idx) {
79,968✔
981
        entered = true;
27,258✔
982
      }
983
    }
984

985
    // Vacuum boundary conditions: return if cell is not exited
986
    if (surf.bc_) {
57,368✔
987
      if (surf.bc_->type() == "vacuum" && !exited) {
9,745!
988
        return;
6,745✔
989
      }
990
    } else {
991

992
      // If we both enter and exit the cell of interest
993
      if (entered && exited) {
47,623✔
994
        return;
13,280✔
995
      }
996

997
      // If we did not enter nor exit the cell of interest
998
      if (!entered && !exited) {
34,343✔
999
        return;
5,205✔
1000
      }
1001

1002
      // If cellfrom and the cell before crossing is not the cell of
1003
      // interest
1004
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
29,138✔
1005
        return;
5,483✔
1006
      }
1007

1008
      // If cellto and the cell after crossing is not the cell of interest
1009
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
23,655✔
1010
        return;
5,390✔
1011
      }
1012
    }
1013
  }
1014

1015
  SourceSite site;
59,475✔
1016
  site.r = p.r();
59,475✔
1017
  site.u = p.u();
59,475✔
1018
  site.E = p.E();
59,475✔
1019
  site.time = p.time();
59,475✔
1020
  site.wgt = p.wgt();
59,475✔
1021
  site.delayed_group = p.delayed_group();
59,475✔
1022
  site.surf_id = surf.id_;
59,475✔
1023
  site.particle = p.type();
59,475✔
1024
  site.parent_id = p.id();
59,475✔
1025
  site.progeny_id = p.n_progeny();
59,475✔
1026
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
59,475✔
1027
}
1028

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