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

openmc-dev / openmc / 21043587909

15 Jan 2026 07:25PM UTC coverage: 81.332% (-0.7%) from 82.044%
21043587909

Pull #3734

github

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

16365 of 22657 branches covered (72.23%)

Branch coverage included in aggregate %.

157 of 180 new or added lines in 12 files covered. (87.22%)

681 existing lines in 43 files now uncovered.

54412 of 64365 relevant lines covered (84.54%)

23556062.71 hits per line

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

84.27
/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,479,179,473✔
47
{
48
  if (settings::run_CE) {
1,479,179,473✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (this->type()) {
728,656,777!
52
    case ParticleType::neutron:
700,969,930✔
53
      mass = MASS_NEUTRON_EV;
700,969,930✔
54
      break;
700,969,930✔
55
    case ParticleType::photon:
8,050,742✔
56
      mass = 0.0;
8,050,742✔
57
      break;
8,050,742✔
58
    case ParticleType::electron:
19,636,105✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
19,636,105✔
61
      break;
19,636,105✔
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)) /
728,656,777✔
65
           (this->E() + mass);
728,656,777✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
750,522,696✔
68
    int macro_t = this->mg_xs_cache().t;
750,522,696✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
750,522,696✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
750,522,696✔
71
                   nullptr, nullptr, macro_t, macro_a);
750,522,696✔
72
  }
73
}
74

75
bool Particle::create_secondary(
40,943,593✔
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)]) {
40,943,593✔
81
    return false;
19,579,070✔
82
  }
83

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

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

105
  // Convert signed index to a signed surface ID
106
  if (surface() == SURFACE_NONE) {
1,485,808!
107
    bank.surf_id = SURFACE_NONE;
1,485,808✔
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,485,808✔
113

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

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

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

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

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

172
  // Reset event variables
173
  event() = TallyEvent::KILL;
1,469,198,869✔
174
  event_nuclide() = NUCLIDE_NONE;
1,469,198,869✔
175
  event_mt() = REACTION_NONE;
1,469,198,869✔
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,469,198,869✔
181
    if (!exhaustive_find_cell(*this)) {
83,273,063!
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)
83,273,063!
189
      cell_born() = lowest_coord().cell();
83,273,063✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
172,657,654✔
193
      cell_last(j) = coord(j).cell();
89,384,591✔
194
    }
195
    n_coord_last() = n_coord();
83,273,063✔
196

197
    // Update temperature of the particle if temperature field
198
    if (settings::temperature_field_on) {
83,273,063✔
199
      simulation::temperature_field.update_particle_temperature(*this);
16,012✔
200
    }
201
  }
202

203
  // Write particle track.
204
  if (write_track())
1,469,198,869✔
205
    write_particle_track(*this);
4,070✔
206

207
  if (settings::check_overlaps)
1,469,198,869!
208
    check_cell_overlap(*this);
×
209

210
  // Calculate microscopic and macroscopic cross sections
211
  if (material() != MATERIAL_VOID) {
1,469,198,869✔
212
    if (settings::run_CE) {
1,428,542,423✔
213
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
802,335,843✔
214
          density_mult() != density_mult_last()) {
124,316,116✔
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);
553,707,099✔
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);
750,522,696✔
225

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
750,522,696✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
40,656,446✔
231
    macro_xs().absorption = 0.0;
40,656,446✔
232
    macro_xs().fission = 0.0;
40,656,446✔
233
    macro_xs().nu_fission = 0.0;
40,656,446✔
234
  }
235
}
236

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

242
  // Sample a distance to collision
243
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
1,469,198,869✔
244
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
19,636,105!
245
  } else if (macro_xs().total == 0.0) {
1,449,562,764✔
246
    collision_distance() = INFINITY;
40,656,446✔
247
  } else {
248
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
1,408,906,318✔
249
  }
250

251
  // Find the distance to the nearest temperature mesh cell surface
252
  double distance_tmesh = INFTY;
1,469,198,869✔
253
  if (settings::temperature_field_on) {
1,469,198,869✔
254
    distance_tmesh =
255
      simulation::temperature_field.distance_to_next_boundary(r(), u());
496,028✔
256
  }
257

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

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

268
  // Prepare the stop condition
269
  if (distance == distance_cutoff) {
1,469,198,869✔
270
    next_event() = EVENT_TIME_CUTOFF;
81,792✔
271
  } else if (distance == boundary().distance()) {
1,469,117,077✔
272
    next_event() = EVENT_CROSS_SURFACE;
500,991,361✔
273
  } else if (distance == distance_tmesh) {
968,125,716✔
274
    next_event() = EVENT_CROSS_TEMPERATURE_MESH;
112,188✔
275
  } else if (distance == collision_distance()) {
968,013,528!
276
    next_event() = EVENT_COLLIDE;
968,013,528✔
277
  }
278

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

285
  // Score timed track-length tallies
286
  if (!model::active_timed_tracklength_tallies.empty()) {
1,469,198,869✔
287
    score_timed_tracklength_tally(*this, distance);
1,319,388✔
288
  }
289

290
  // Score track-length tallies
291
  if (!model::active_tracklength_tallies.empty()) {
1,469,198,869✔
292
    score_tracklength_tally(*this, distance);
535,516,424✔
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,246,607,235✔
298
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
1,232,093,639✔
299
  }
300

301
  // Score flux derivative accumulators for differential tallies.
302
  if (!model::active_tallies.empty()) {
1,469,198,869✔
303
    score_track_derivative(*this, distance);
595,359,636✔
304
  }
305
}
1,469,198,869✔
306

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

313
void Particle::event_cross_surface()
792,371,301✔
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,525,107,337✔
318
  }
319
  n_coord_last() = n_coord();
792,371,301✔
320

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

325
  if (boundary().lattice_translation()[0] != 0 ||
792,371,301✔
326
      boundary().lattice_translation()[1] != 0 ||
1,394,094,426✔
327
      boundary().lattice_translation()[2] != 0) {
601,723,125✔
328
    // Particle crosses lattice boundary
329

330
    bool verbose = settings::verbosity >= 10 || trace();
259,208,012!
331
    cross_lattice(*this, boundary(), verbose);
259,208,012✔
332
    event() = TallyEvent::LATTICE;
259,208,012✔
333
  } else {
334
    // Particle crosses surface
335
    const auto& surf {model::surfaces[surface_index()].get()};
533,163,289✔
336
    // If BC, add particle to surface source before crossing surface
337
    if (surf->surf_source_ && surf->bc_) {
533,163,289✔
338
      add_surf_source_to_bank(*this, *surf);
245,732,143✔
339
    }
340
    this->cross_surface(*surf);
533,163,289✔
341
    // If no BC, add particle to surface source after crossing surface
342
    if (surf->surf_source_ && !surf->bc_) {
533,163,285✔
343
      add_surf_source_to_bank(*this, *surf);
286,963,902✔
344
    }
345
    if (settings::weight_window_checkpoint_surface) {
533,163,285!
UNCOV
346
      apply_weight_windows(*this);
×
347
    }
348
    event() = TallyEvent::SURFACE;
533,163,285✔
349
  }
350

351
  // Update temperature of the particle if temperature field
352
  if (settings::temperature_field_on) {
792,371,297✔
353
    simulation::temperature_field.update_particle_temperature(*this);
112,888✔
354
  }
355

356
  // Score cell to cell partial currents
357
  if (!model::active_surface_tallies.empty()) {
792,371,297✔
358
    score_surface_tally(*this, model::active_surface_tallies);
12,699,188✔
359
  }
360
}
792,371,297✔
361

362
void Particle::event_collide()
968,013,528✔
363
{
364
  // Score collision estimate of keff
365
  if (settings::run_mode == RunMode::EIGENVALUE &&
1,753,107,649✔
366
      type() == ParticleType::neutron) {
785,094,121✔
367
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
770,587,009✔
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())
968,013,528✔
375
    score_surface_tally(*this, model::active_meshsurf_tallies);
22,945,064✔
376

377
  // Clear surface component
378
  surface() = SURFACE_NONE;
968,013,528✔
379

380
  if (settings::run_CE) {
968,013,528✔
381
    collision(*this);
319,627,900✔
382
  } else {
383
    collision_mg(*this);
648,385,628✔
384
  }
385

386
  // Collision track feature to recording particle interaction
387
  if (settings::collision_track) {
968,013,528✔
388
    collision_track_record(*this);
55,196✔
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())
968,013,528✔
395
    score_collision_tally(*this);
37,700,863✔
396
  if (!model::active_analog_tallies.empty()) {
968,013,528✔
397
    if (settings::run_CE) {
85,214,380✔
398
      score_analog_tally_ce(*this);
84,775,012✔
399
    } else {
400
      score_analog_tally_mg(*this);
439,368✔
401
    }
402
  }
403

404
  if (!model::active_pulse_height_tallies.empty() &&
968,019,680✔
405
      type() == ParticleType::photon) {
6,152✔
406
    pht_collision_energy();
736✔
407
  }
408

409
  // Reset banked weight during collision
410
  n_bank() = 0;
968,013,528✔
411
  bank_second_E() = 0.0;
968,013,528✔
412
  wgt_bank() = 0.0;
968,013,528✔
413
  zero_delayed_bank();
968,013,528✔
414

415
  // Reset fission logical
416
  fission() = false;
968,013,528✔
417

418
  // Save coordinates for tallying purposes
419
  r_last_current() = r();
968,013,528✔
420

421
  // Set last material to none since cross sections will need to be
422
  // re-evaluated
423
  material_last() = C_NONE;
968,013,528✔
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,016,753,958✔
428
    if (coord(j + 1).rotated()) {
48,740,430✔
429
      // If next level is rotated, apply rotation matrix
430
      const auto& m {model::cells[coord(j).cell()]->rotation_};
3,791,496✔
431
      const auto& u {coord(j).u()};
3,791,496✔
432
      coord(j + 1).u() = u.rotate(m);
3,791,496✔
433
    } else {
434
      // Otherwise, copy this level's direction
435
      coord(j + 1).u() = coord(j).u();
44,948,934✔
436
    }
437
  }
438

439
  // Score flux derivative accumulators for differential tallies.
440
  if (!model::active_tallies.empty())
968,013,528✔
441
    score_collision_derivative(*this);
274,770,467✔
442

443
#ifdef OPENMC_DAGMC_ENABLED
444
  history().reset();
445
#endif
446
}
968,013,528✔
447

448
void Particle::event_revive_from_secondary()
1,469,198,865✔
449
{
450
  // If particle has too many events, display warning and kill it
451
  ++n_event();
1,469,198,865✔
452
  if (n_event() == settings::max_particle_events) {
1,469,198,865!
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,469,198,865✔
460
    // Write final position for this particle
461
    if (write_track()) {
83,273,279✔
462
      write_particle_track(*this);
2,516✔
463
    }
464

465
    // If no secondary particles, break out of event loop
466
    if (secondary_bank().empty())
83,273,279✔
467
      return;
60,422,820✔
468

469
    from_source(&secondary_bank().back());
22,850,459✔
470
    secondary_bank().pop_back();
22,850,459✔
471
    n_event() = 0;
22,850,459✔
472
    bank_second_E() = 0.0;
22,850,459✔
473

474
    // Subtract secondary particle energy from interim pulse-height results
475
    if (!model::active_pulse_height_tallies.empty() &&
22,856,095✔
476
        this->type() == ParticleType::photon) {
5,636✔
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) {
220!
481
        bool verbose = settings::verbosity >= 10 || trace();
220!
482
        if (!exhaustive_find_cell(*this, verbose)) {
220!
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)
220!
489
          cell_born() = lowest_coord().cell();
220✔
490

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

500
    // Enter new particle in particle track file
501
    if (write_track())
22,850,459✔
502
      add_particle_track(*this);
2,116✔
503
  }
504
}
505

506
void Particle::event_death()
60,422,820✔
507
{
508
#ifdef OPENMC_DAGMC_ENABLED
509
  history().reset();
510
#endif
511

512
  // Finish particle track output.
513
  if (write_track()) {
60,422,820✔
514
    finalize_particle_track(*this);
400✔
515
  }
516

517
// Contribute tally reduction variables to global accumulator
518
#pragma omp atomic
519
  global_tally_absorption += keff_tally_absorption();
60,422,820✔
520
#pragma omp atomic
521
  global_tally_collision += keff_tally_collision();
60,422,820✔
522
#pragma omp atomic
523
  global_tally_tracklength += keff_tally_tracklength();
60,422,820✔
524
#pragma omp atomic
525
  global_tally_leakage += keff_tally_leakage();
60,422,820✔
526

527
  // Reset particle tallies once accumulated
528
  keff_tally_absorption() = 0.0;
60,422,820✔
529
  keff_tally_collision() = 0.0;
60,422,820✔
530
  keff_tally_tracklength() = 0.0;
60,422,820✔
531
  keff_tally_leakage() = 0.0;
60,422,820✔
532

533
  if (!model::active_pulse_height_tallies.empty()) {
60,422,820✔
534
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
2,000✔
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) {
60,422,820✔
540
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
51,180,800✔
541
    simulation::progeny_per_particle[offset] = n_progeny();
51,180,800✔
542
  }
543
}
60,422,820✔
544

545
void Particle::pht_collision_energy()
736✔
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(),
736✔
551
    model::pulse_height_cells.end(), lowest_coord().cell());
736✔
552

553
  if (it != model::pulse_height_cells.end()) {
736!
554
    int index = std::distance(model::pulse_height_cells.begin(), it);
736✔
555
    pht_storage()[index] += E_last() - E();
736✔
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);
736✔
560
    if (E() < settings::energy_cutoff[photon]) {
736✔
561
      pht_storage()[index] += E();
300✔
562
    }
563
  }
564
}
736✔
565

566
void Particle::pht_secondary_particles()
220✔
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(),
220✔
572
    model::pulse_height_cells.end(), cell_born());
220✔
573

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

580
void Particle::cross_surface(const Surface& surf)
533,588,817✔
581
{
582

583
  if (settings::verbosity >= 10 || trace()) {
533,588,817✔
584
    write_message(1, "    Crossing surface {}", surf.id_);
12✔
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 &&
779,495,776!
595
      settings::run_mode != RunMode::VOLUME) {
245,906,959✔
596
    surf.bc_->handle_particle(*this, surf);
245,863,343✔
597
    return;
245,863,343✔
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();
287,725,474!
629
  if (neighbor_list_find_cell(*this, verbose)) {
287,725,474✔
630
    return;
287,714,590✔
631
  }
632

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

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

640
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
10,884!
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,116✔
647
    n_coord() = 1;
2,116✔
648
    r() += TINY_BIT * u();
2,116✔
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,116!
654
      mark_as_lost("After particle " + std::to_string(id()) +
6,344✔
655
                   " crossed surface " + std::to_string(surf.id_) +
8,456✔
656
                   " it could not be located in any cell and it did not leak.");
657
      return;
2,112✔
658
    }
659
  }
660
}
661

662
void Particle::cross_vacuum_bc(const Surface& surf)
12,618,371✔
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()) {
12,618,371✔
669
    // TODO: Find a better solution to score surface currents than
670
    // physically moving the particle forward slightly
671

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

676
  // Score to global leakage tally
677
  keff_tally_leakage() += wgt();
12,618,371✔
678

679
  // Kill the particle
680
  wgt() = 0.0;
12,618,371✔
681

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

688
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
232,792,032✔
689
{
690
  // Do not handle reflective boundary conditions on lower universes
691
  if (n_coord() != 1) {
232,792,032!
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()) {
232,792,032✔
705
    score_surface_tally(*this, model::active_surface_tallies);
103,644✔
706
  }
707

708
  if (!model::active_meshsurf_tallies.empty()) {
232,792,032✔
709
    Position r {this->r()};
17,049,268✔
710
    this->r() -= TINY_BIT * u();
17,049,268✔
711
    score_surface_tally(*this, model::active_meshsurf_tallies);
17,049,268✔
712
    this->r() = r;
17,049,268✔
713
  }
714

715
  // Set the new particle direction
716
  u() = new_u;
232,792,032✔
717

718
  // Reassign particle's cell and surface
719
  coord(0).cell() = cell_last(0);
232,792,032✔
720
  surface() = -surface();
232,792,032✔
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;
232,792,032✔
727
  if (surf.geom_type() != GeometryType::DAG &&
465,584,064!
728
      !neighbor_list_find_cell(*this)) {
232,792,032!
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();
232,792,032✔
736

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

743
void Particle::cross_periodic_bc(
818,564✔
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) {
818,564!
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()) {
818,564!
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;
818,564✔
767
  u() = new_u;
818,564✔
768

769
  // Reassign particle's surface
770
  surface() = new_surface;
818,564✔
771

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

775
  if (!neighbor_list_find_cell(*this)) {
818,564!
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();
818,564✔
784

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

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

804
  // Count the total number of simulated particles (on this processor)
805
  auto n = simulation::current_batch * settings::gen_per_batch *
2,116✔
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,116✔
811
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
4!
812
    fatal_error("Maximum number of lost particles has been reached.");
4✔
813
  }
814
}
2,112✔
815

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

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

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

831
    // Write filetype and version info
832
    write_attribute(file_id, "filetype", "particle restart");
138✔
833
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
138✔
834
    write_attribute(file_id, "openmc_version", VERSION);
138✔
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);
138✔
841
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
138✔
842
    write_dataset(file_id, "current_generation", simulation::current_gen);
138✔
843
    write_dataset(file_id, "n_particles", settings::n_particles);
138✔
844
    switch (settings::run_mode) {
138!
845
    case RunMode::FIXED_SOURCE:
90✔
846
      write_dataset(file_id, "run_mode", "fixed source");
90✔
847
      break;
90✔
848
    case RunMode::EIGENVALUE:
48✔
849
      write_dataset(file_id, "run_mode", "eigenvalue");
48✔
850
      break;
48✔
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());
138✔
858
    write_dataset(file_id, "type", static_cast<int>(type()));
138✔
859

860
    int64_t i = current_work();
138✔
861
    if (settings::run_mode == RunMode::EIGENVALUE) {
138✔
862
      // take source data from primary bank for eigenvalue simulation
863
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
48✔
864
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
48✔
865
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
48✔
866
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
48✔
867
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
48✔
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);
138✔
885
  } // #pragma omp critical
886
}
138✔
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) {
914,581,414!
898
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
1,598,098,427✔
899

900
    // If NCrystal is being used, update micro cross section cache
901
    micro.ncrystal_xs = ncrystal_xs;
1,598,098,427✔
902
    if (ncrystal_xs >= 0.0) {
1,598,098,427✔
903
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
4,006,892✔
904
      ncrystal_update_micro(ncrystal_xs, micro);
4,006,892✔
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,138,252✔
914
{
915
  switch (type) {
1,138,252!
916
  case ParticleType::neutron:
872,704✔
917
    return "neutron";
872,704✔
918
  case ParticleType::photon:
265,452✔
919
    return "photon";
265,452✔
920
  case ParticleType::electron:
48✔
921
    return "electron";
48✔
922
  case ParticleType::positron:
48✔
923
    return "positron";
48✔
924
  }
925
  UNREACHABLE();
×
926
}
927

928
ParticleType str_to_particle_type(std::string str)
1,185,002✔
929
{
930
  if (str == "neutron") {
1,185,002✔
931
    return ParticleType::neutron;
280,548✔
932
  } else if (str == "photon") {
904,454✔
933
    return ParticleType::photon;
904,422✔
934
  } else if (str == "electron") {
32✔
935
    return ParticleType::electron;
16✔
936
  } else if (str == "positron") {
16!
937
    return ParticleType::positron;
16✔
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)
532,696,045✔
944
{
945
  if (simulation::current_batch <= settings::n_inactive ||
953,410,434✔
946
      simulation::surf_source_bank.full()) {
420,714,389✔
947
    return;
532,648,465✔
948
  }
949

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

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

956
    if (surf.bc_) {
96,944✔
957
      // Leave if cellto with vacuum boundary condition
958
      if (surf.bc_->type() == "vacuum" &&
71,144!
959
          settings::ssw_cell_type == SSWCellType::To) {
12,300✔
960
        return;
4,504✔
961
      }
962

963
      // Leave if other boundary condition than vacuum
964
      if (surf.bc_->type() != "vacuum") {
54,340✔
965
        return;
46,544✔
966
      }
967
    }
968

969
    // Check if the cell of interest has been exited
970
    bool exited = false;
45,896✔
971
    for (int i = 0; i < p.n_coord_last(); ++i) {
123,576✔
972
      if (p.cell_last(i) == cell_idx) {
77,680✔
973
        exited = true;
27,552✔
974
      }
975
    }
976

977
    // Check if the cell of interest has been entered
978
    bool entered = false;
45,896✔
979
    for (int i = 0; i < p.n_coord(); ++i) {
109,872✔
980
      if (p.coord(i).cell() == cell_idx) {
63,976✔
981
        entered = true;
21,808✔
982
      }
983
    }
984

985
    // Vacuum boundary conditions: return if cell is not exited
986
    if (surf.bc_) {
45,896✔
987
      if (surf.bc_->type() == "vacuum" && !exited) {
7,796!
988
        return;
5,396✔
989
      }
990
    } else {
991

992
      // If we both enter and exit the cell of interest
993
      if (entered && exited) {
38,100✔
994
        return;
10,624✔
995
      }
996

997
      // If we did not enter nor exit the cell of interest
998
      if (!entered && !exited) {
27,476✔
999
        return;
4,164✔
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) {
23,312✔
1005
        return;
4,388✔
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) {
18,924✔
1010
        return;
4,312✔
1011
      }
1012
    }
1013
  }
1014

1015
  SourceSite site;
47,580✔
1016
  site.r = p.r();
47,580✔
1017
  site.u = p.u();
47,580✔
1018
  site.E = p.E();
47,580✔
1019
  site.time = p.time();
47,580✔
1020
  site.wgt = p.wgt();
47,580✔
1021
  site.delayed_group = p.delayed_group();
47,580✔
1022
  site.surf_id = surf.id_;
47,580✔
1023
  site.particle = p.type();
47,580✔
1024
  site.parent_id = p.id();
47,580✔
1025
  site.progeny_id = p.n_progeny();
47,580✔
1026
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
47,580✔
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