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

openmc-dev / openmc / 12971699935

26 Jan 2025 05:13AM UTC coverage: 84.856% (-0.009%) from 84.865%
12971699935

Pull #3129

github

web-flow
Merge f8a88a3c9 into 2bea7f338
Pull Request #3129: Compute material volumes in mesh elements based on raytracing

204 of 230 new or added lines in 3 files covered. (88.7%)

772 existing lines in 29 files now uncovered.

50223 of 59186 relevant lines covered (84.86%)

35109960.84 hits per line

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

92.72
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef DAGMC
36
#include "DagMC.hpp"
37
#endif
38

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  // Determine mass in eV/c^2
48
  double mass;
49
  switch (this->type()) {
2,147,483,647✔
50
  case ParticleType::neutron:
2,147,483,647✔
51
    mass = MASS_NEUTRON_EV;
2,147,483,647✔
52
    break;
2,147,483,647✔
53
  case ParticleType::photon:
15,822,708✔
54
    mass = 0.0;
15,822,708✔
55
    break;
15,822,708✔
56
  case ParticleType::electron:
52,993,802✔
57
  case ParticleType::positron:
58
    mass = MASS_ELECTRON_EV;
52,993,802✔
59
    break;
52,993,802✔
60
  }
61

62
  if (this->E() < 1.0e-9 * mass) {
2,147,483,647✔
63
    // If the energy is much smaller than the mass, revert to non-relativistic
64
    // formula. The 1e-9 criterion is specifically chosen as the point below
65
    // which the error from using the non-relativistic formula is less than the
66
    // round-off eror when using the relativistic formula (see analysis at
67
    // https://gist.github.com/paulromano/da3b473fe3df33de94b265bdff0c7817)
68
    return C_LIGHT * std::sqrt(2 * this->E() / mass);
911,636,807✔
69
  } else {
70
    // Calculate inverse of Lorentz factor
71
    const double inv_gamma = mass / (this->E() + mass);
2,147,483,647✔
72

73
    // Calculate speed via v = c * sqrt(1 - γ^-2)
74
    return C_LIGHT * std::sqrt(1 - inv_gamma * inv_gamma);
2,147,483,647✔
75
  }
76
}
77

78
void Particle::move_distance(double length)
1,959,948✔
79
{
80
  for (int j = 0; j < n_coord(); ++j) {
3,919,896✔
81
    coord(j).r += length * coord(j).u;
1,959,948✔
82
  }
83
}
1,959,948✔
84

85
void Particle::create_secondary(
110,901,965✔
86
  double wgt, Direction u, double E, ParticleType type)
87
{
88
  // If energy is below cutoff for this particle, don't create secondary
89
  // particle
90
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
110,901,965✔
91
    return;
52,908,030✔
92
  }
93

94
  auto& bank = secondary_bank().emplace_back();
57,993,935✔
95
  bank.particle = type;
57,993,935✔
96
  bank.wgt = wgt;
57,993,935✔
97
  bank.r = r();
57,993,935✔
98
  bank.u = u;
57,993,935✔
99
  bank.E = settings::run_CE ? E : g();
57,993,935✔
100
  bank.time = time();
57,993,935✔
101
  bank_second_E() += bank.E;
57,993,935✔
102
}
103

104
void Particle::split(double wgt)
7,396,613✔
105
{
106
  auto& bank = secondary_bank().emplace_back();
7,396,613✔
107
  bank.particle = type();
7,396,613✔
108
  bank.wgt = wgt;
7,396,613✔
109
  bank.r = r();
7,396,613✔
110
  bank.u = u();
7,396,613✔
111
  bank.E = settings::run_CE ? E() : g();
7,396,613✔
112
  bank.time = time();
7,396,613✔
113
}
7,396,613✔
114

115
void Particle::from_source(const SourceSite* src)
229,507,239✔
116
{
117
  // Reset some attributes
118
  clear();
229,507,239✔
119
  surface() = SURFACE_NONE;
229,507,239✔
120
  cell_born() = C_NONE;
229,507,239✔
121
  material() = C_NONE;
229,507,239✔
122
  n_collision() = 0;
229,507,239✔
123
  fission() = false;
229,507,239✔
124
  zero_flux_derivs();
229,507,239✔
125

126
  // Copy attributes from source bank site
127
  type() = src->particle;
229,507,239✔
128
  wgt() = src->wgt;
229,507,239✔
129
  wgt_last() = src->wgt;
229,507,239✔
130
  r() = src->r;
229,507,239✔
131
  u() = src->u;
229,507,239✔
132
  r_born() = src->r;
229,507,239✔
133
  r_last_current() = src->r;
229,507,239✔
134
  r_last() = src->r;
229,507,239✔
135
  u_last() = src->u;
229,507,239✔
136
  if (settings::run_CE) {
229,507,239✔
137
    E() = src->E;
101,556,483✔
138
    g() = 0;
101,556,483✔
139
  } else {
140
    g() = static_cast<int>(src->E);
127,950,756✔
141
    g_last() = static_cast<int>(src->E);
127,950,756✔
142
    E() = data::mg.energy_bin_avg_[g()];
127,950,756✔
143
  }
144
  E_last() = E();
229,507,239✔
145
  time() = src->time;
229,507,239✔
146
  time_last() = src->time;
229,507,239✔
147
}
229,507,239✔
148

149
void Particle::event_calculate_xs()
2,147,483,647✔
150
{
151
  // Set the random number stream
152
  stream() = STREAM_TRACKING;
2,147,483,647✔
153

154
  // Store pre-collision particle properties
155
  wgt_last() = wgt();
2,147,483,647✔
156
  E_last() = E();
2,147,483,647✔
157
  u_last() = u();
2,147,483,647✔
158
  r_last() = r();
2,147,483,647✔
159
  time_last() = time();
2,147,483,647✔
160

161
  // Reset event variables
162
  event() = TallyEvent::KILL;
2,147,483,647✔
163
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
164
  event_mt() = REACTION_NONE;
2,147,483,647✔
165

166
  // If the cell hasn't been determined based on the particle's location,
167
  // initiate a search for the current cell. This generally happens at the
168
  // beginning of the history and again for any secondary particles
169
  if (lowest_coord().cell == C_NONE) {
2,147,483,647✔
170
    if (!exhaustive_find_cell(*this)) {
227,960,067✔
UNCOV
171
      mark_as_lost(
×
UNCOV
172
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
173
      return;
×
174
    }
175

176
    // Set birth cell attribute
177
    if (cell_born() == C_NONE)
227,960,067✔
178
      cell_born() = lowest_coord().cell;
227,960,067✔
179

180
    // Initialize last cells from current cell
181
    for (int j = 0; j < n_coord(); ++j) {
480,369,663✔
182
      cell_last(j) = coord(j).cell;
252,409,596✔
183
    }
184
    n_coord_last() = n_coord();
227,960,067✔
185
  }
186

187
  // Write particle track.
188
  if (write_track())
2,147,483,647✔
189
    write_particle_track(*this);
11,603✔
190

191
  if (settings::check_overlaps)
2,147,483,647✔
UNCOV
192
    check_cell_overlap(*this);
×
193

194
  // Calculate microscopic and macroscopic cross sections
195
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
196
    if (settings::run_CE) {
2,147,483,647✔
197
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,914,126,552✔
198
        // If the material is the same as the last material and the
199
        // temperature hasn't changed, we don't need to lookup cross
200
        // sections again.
201
        model::materials[material()]->calculate_xs(*this);
1,501,980,586✔
202
      }
203
    } else {
204
      // Get the MG data; unlike the CE case above, we have to re-calculate
205
      // cross sections for every collision since the cross sections may
206
      // be angle-dependent
207
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,147,483,647✔
208

209
      // Update the particle's group while we know we are multi-group
210
      g_last() = g();
2,147,483,647✔
211
    }
212
  } else {
213
    macro_xs().total = 0.0;
50,524,814✔
214
    macro_xs().absorption = 0.0;
50,524,814✔
215
    macro_xs().fission = 0.0;
50,524,814✔
216
    macro_xs().nu_fission = 0.0;
50,524,814✔
217
  }
218
}
219

220
void Particle::event_advance()
2,147,483,647✔
221
{
222
  // Find the distance to the nearest boundary
223
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
224

225
  // Sample a distance to collision
226
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
227
    collision_distance() = 0.0;
52,993,802✔
228
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
229
    collision_distance() = INFINITY;
50,524,814✔
230
  } else {
231
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
232
  }
233

234
  // Select smaller of the two distances
235
  double distance = std::min(boundary().distance, collision_distance());
2,147,483,647✔
236

237
  // Advance particle in space and time
238
  // Short-term solution until the surface source is revised and we can use
239
  // this->move_distance(distance)
240
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
241
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
242
  }
243
  this->time() += distance / this->speed();
2,147,483,647✔
244

245
  // Kill particle if its time exceeds the cutoff
246
  bool hit_time_boundary = false;
2,147,483,647✔
247
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
248
  if (time() > time_cutoff) {
2,147,483,647✔
249
    double dt = time() - time_cutoff;
12,000✔
250
    time() = time_cutoff;
12,000✔
251

252
    double push_back_distance = speed() * dt;
12,000✔
253
    this->move_distance(-push_back_distance);
12,000✔
254
    hit_time_boundary = true;
12,000✔
255
  }
256

257
  // Score track-length tallies
258
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
259
    score_tracklength_tally(*this, distance);
1,447,018,910✔
260
  }
261

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

268
  // Score flux derivative accumulators for differential tallies.
269
  if (!model::active_tallies.empty()) {
2,147,483,647✔
270
    score_track_derivative(*this, distance);
1,678,568,500✔
271
  }
272

273
  // Set particle weight to zero if it hit the time boundary
274
  if (hit_time_boundary) {
2,147,483,647✔
275
    wgt() = 0.0;
12,000✔
276
  }
277
}
2,147,483,647✔
278

279
void Particle::event_cross_surface()
1,753,107,709✔
280
{
281
  // Saving previous cell data
282
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
283
    cell_last(j) = coord(j).cell;
2,147,483,647✔
284
  }
285
  n_coord_last() = n_coord();
1,753,107,709✔
286

287
  // Set surface that particle is on and adjust coordinate levels
288
  surface() = boundary().surface;
1,753,107,709✔
289
  n_coord() = boundary().coord_level;
1,753,107,709✔
290

291
  if (boundary().lattice_translation[0] != 0 ||
1,753,107,709✔
292
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
293
      boundary().lattice_translation[2] != 0) {
1,519,102,160✔
294
    // Particle crosses lattice boundary
295

296
    bool verbose = settings::verbosity >= 10 || trace();
288,680,463✔
297
    cross_lattice(*this, boundary(), verbose);
288,680,463✔
298
    event() = TallyEvent::LATTICE;
288,680,463✔
299
  } else {
300
    // Particle crosses surface
301
    const auto& surf {model::surfaces[surface_index()].get()};
1,464,427,246✔
302
    // If BC, add particle to surface source before crossing surface
303
    if (surf->surf_source_ && surf->bc_) {
1,464,427,246✔
304
      add_surf_source_to_bank(*this, *surf);
685,262,495✔
305
    }
306
    this->cross_surface(*surf);
1,464,427,246✔
307
    // If no BC, add particle to surface source after crossing surface
308
    if (surf->surf_source_ && !surf->bc_) {
1,464,427,236✔
309
      add_surf_source_to_bank(*this, *surf);
778,174,951✔
310
    }
311
    if (settings::weight_window_checkpoint_surface) {
1,464,427,236✔
UNCOV
312
      apply_weight_windows(*this);
×
313
    }
314
    event() = TallyEvent::SURFACE;
1,464,427,236✔
315
  }
316
  // Score cell to cell partial currents
317
  if (!model::active_surface_tallies.empty()) {
1,753,107,699✔
318
    score_surface_tally(*this, model::active_surface_tallies);
5,159,044✔
319
  }
320
}
1,753,107,699✔
321

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

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

334
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
335
    score_surface_tally(*this, model::active_meshsurf_tallies);
147,745,526✔
336

337
  // Clear surface component
338
  surface() = SURFACE_NONE;
2,147,483,647✔
339

340
  if (settings::run_CE) {
2,147,483,647✔
341
    collision(*this);
820,510,333✔
342
  } else {
343
    collision_mg(*this);
1,948,075,116✔
344
  }
345

346
  // Score collision estimator tallies -- this is done after a collision
347
  // has occurred rather than before because we need information on the
348
  // outgoing energy for any tallies with an outgoing energy filter
349
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
350
    score_collision_tally(*this);
99,225,818✔
351
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
352
    if (settings::run_CE) {
174,566,582✔
353
      score_analog_tally_ce(*this);
173,256,170✔
354
    } else {
355
      score_analog_tally_mg(*this);
1,310,412✔
356
    }
357
  }
358

359
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
360
      type() == ParticleType::photon) {
18,456✔
361
    pht_collision_energy();
2,208✔
362
  }
363

364
  // Reset banked weight during collision
365
  n_bank() = 0;
2,147,483,647✔
366
  bank_second_E() = 0.0;
2,147,483,647✔
367
  wgt_bank() = 0.0;
2,147,483,647✔
368
  zero_delayed_bank();
2,147,483,647✔
369

370
  // Reset fission logical
371
  fission() = false;
2,147,483,647✔
372

373
  // Save coordinates for tallying purposes
374
  r_last_current() = r();
2,147,483,647✔
375

376
  // Set last material to none since cross sections will need to be
377
  // re-evaluated
378
  material_last() = C_NONE;
2,147,483,647✔
379

380
  // Set all directions to base level -- right now, after a collision, only
381
  // the base level directions are changed
382
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
383
    if (coord(j + 1).rotated) {
146,882,258✔
384
      // If next level is rotated, apply rotation matrix
385
      const auto& m {model::cells[coord(j).cell]->rotation_};
11,339,220✔
386
      const auto& u {coord(j).u};
11,339,220✔
387
      coord(j + 1).u = u.rotate(m);
11,339,220✔
388
    } else {
389
      // Otherwise, copy this level's direction
390
      coord(j + 1).u = coord(j).u;
135,543,038✔
391
    }
392
  }
393

394
  // Score flux derivative accumulators for differential tallies.
395
  if (!model::active_tallies.empty())
2,147,483,647✔
396
    score_collision_derivative(*this);
719,143,886✔
397

398
#ifdef DAGMC
399
  history().reset();
243,309,271✔
400
#endif
401
}
2,147,483,647✔
402

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

413
  // Check for secondary particles if this particle is dead
414
  if (!alive()) {
2,147,483,647✔
415
    // Write final position for this particle
416
    if (write_track()) {
227,959,717✔
417
      write_particle_track(*this);
7,088✔
418
    }
419

420
    // If no secondary particles, break out of event loop
421
    if (secondary_bank().empty())
227,959,717✔
422
      return;
162,365,816✔
423

424
    from_source(&secondary_bank().back());
65,593,901✔
425
    secondary_bank().pop_back();
65,593,901✔
426
    n_event() = 0;
65,593,901✔
427
    bank_second_E() = 0.0;
65,593,901✔
428

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

446
        // Initialize last cells from current cell
447
        for (int j = 0; j < n_coord(); ++j) {
1,320✔
448
          cell_last(j) = coord(j).cell;
660✔
449
        }
450
        n_coord_last() = n_coord();
660✔
451
      }
452
      pht_secondary_particles();
660✔
453
    }
454

455
    // Enter new particle in particle track file
456
    if (write_track())
65,593,901✔
457
      add_particle_track(*this);
5,948✔
458
  }
459
}
460

461
void Particle::event_death()
162,366,816✔
462
{
463
#ifdef DAGMC
464
  history().reset();
14,046,145✔
465
#endif
466

467
  // Finish particle track output.
468
  if (write_track()) {
162,366,816✔
469
    finalize_particle_track(*this);
1,140✔
470
  }
471

472
// Contribute tally reduction variables to global accumulator
473
#pragma omp atomic
81,768,181✔
474
  global_tally_absorption += keff_tally_absorption();
162,366,816✔
475
#pragma omp atomic
81,967,699✔
476
  global_tally_collision += keff_tally_collision();
162,366,816✔
477
#pragma omp atomic
81,418,883✔
478
  global_tally_tracklength += keff_tally_tracklength();
162,366,816✔
479
#pragma omp atomic
81,082,721✔
480
  global_tally_leakage += keff_tally_leakage();
162,366,816✔
481

482
  // Reset particle tallies once accumulated
483
  keff_tally_absorption() = 0.0;
162,366,816✔
484
  keff_tally_collision() = 0.0;
162,366,816✔
485
  keff_tally_tracklength() = 0.0;
162,366,816✔
486
  keff_tally_leakage() = 0.0;
162,366,816✔
487

488
  if (!model::active_pulse_height_tallies.empty()) {
162,366,816✔
489
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
6,000✔
490
  }
491

492
  // Record the number of progeny created by this particle.
493
  // This data will be used to efficiently sort the fission bank.
494
  if (settings::run_mode == RunMode::EIGENVALUE) {
162,366,816✔
495
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
148,611,600✔
496
    simulation::progeny_per_particle[offset] = n_progeny();
148,611,600✔
497
  }
498
}
162,366,816✔
499

500
void Particle::pht_collision_energy()
2,208✔
501
{
502
  // Adds the energy particles lose in a collision to the pulse-height
503

504
  // determine index of cell in pulse_height_cells
505
  auto it = std::find(model::pulse_height_cells.begin(),
2,208✔
506
    model::pulse_height_cells.end(), lowest_coord().cell);
2,208✔
507

508
  if (it != model::pulse_height_cells.end()) {
2,208✔
509
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,208✔
510
    pht_storage()[index] += E_last() - E();
2,208✔
511

512
    // If the energy of the particle is below the cutoff, it will not be sampled
513
    // so its energy is added to the pulse-height in the cell
514
    int photon = static_cast<int>(ParticleType::photon);
2,208✔
515
    if (E() < settings::energy_cutoff[photon]) {
2,208✔
516
      pht_storage()[index] += E();
900✔
517
    }
518
  }
519
}
2,208✔
520

521
void Particle::pht_secondary_particles()
660✔
522
{
523
  // Removes the energy of secondary produced particles from the pulse-height
524

525
  // determine index of cell in pulse_height_cells
526
  auto it = std::find(model::pulse_height_cells.begin(),
660✔
527
    model::pulse_height_cells.end(), cell_born());
660✔
528

529
  if (it != model::pulse_height_cells.end()) {
660✔
530
    int index = std::distance(model::pulse_height_cells.begin(), it);
660✔
531
    pht_storage()[index] -= E();
660✔
532
  }
533
}
660✔
534

535
void Particle::cross_surface(const Surface& surf)
1,465,482,478✔
536
{
537

538
  if (settings::verbosity >= 10 || trace()) {
1,465,482,478✔
539
    write_message(1, "    Crossing surface {}", surf.id_);
36✔
540
  }
541

542
// if we're crossing a CSG surface, make sure the DAG history is reset
543
#ifdef DAGMC
544
  if (surf.geom_type() == GeometryType::CSG)
140,307,433✔
545
    history().reset();
140,272,117✔
546
#endif
547

548
  // Handle any applicable boundary conditions.
549
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,465,482,478✔
550
    surf.bc_->handle_particle(*this, surf);
685,522,466✔
551
    return;
685,522,466✔
552
  }
553

554
  // ==========================================================================
555
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
556

557
#ifdef DAGMC
558
  // in DAGMC, we know what the next cell should be
559
  if (surf.geom_type() == GeometryType::DAG) {
74,376,306✔
560
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
28,265✔
561
                       lowest_coord().universe) -
28,265✔
562
                     1;
28,265✔
563
    // save material and temp
564
    material_last() = material();
28,265✔
565
    sqrtkT_last() = sqrtkT();
28,265✔
566
    // set new cell value
567
    lowest_coord().cell = i_cell;
28,265✔
568
    auto& cell = model::cells[i_cell];
28,265✔
569

570
    cell_instance() = 0;
28,265✔
571
    if (cell->distribcell_index_ >= 0)
28,265✔
572
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
573

574
    material() = cell->material(cell_instance());
28,265✔
575
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
576
    return;
28,265✔
577
  }
578
#endif
579

580
  bool verbose = settings::verbosity >= 10 || trace();
779,931,747✔
581
  if (neighbor_list_find_cell(*this, verbose)) {
779,931,747✔
582
    return;
779,901,179✔
583
  }
584

585
  // ==========================================================================
586
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
587

588
  // Remove lower coordinate levels
589
  n_coord() = 1;
30,568✔
590
  bool found = exhaustive_find_cell(*this, verbose);
30,568✔
591

592
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
30,568✔
593
    // If a cell is still not found, there are two possible causes: 1) there is
594
    // a void in the model, and 2) the particle hit a surface at a tangent. If
595
    // the particle is really traveling tangent to a surface, if we move it
596
    // forward a tiny bit it should fix the problem.
597

598
    surface() = SURFACE_NONE;
6,268✔
599
    n_coord() = 1;
6,268✔
600
    r() += TINY_BIT * u();
6,268✔
601

602
    // Couldn't find next cell anywhere! This probably means there is an actual
603
    // undefined region in the geometry.
604

605
    if (!exhaustive_find_cell(*this, verbose)) {
6,268✔
606
      mark_as_lost("After particle " + std::to_string(id()) +
18,794✔
607
                   " crossed surface " + std::to_string(surf.id_) +
25,052✔
608
                   " it could not be located in any cell and it did not leak.");
609
      return;
6,258✔
610
    }
611
  }
612
}
613

614
void Particle::cross_vacuum_bc(const Surface& surf)
22,930,036✔
615
{
616
  // Score any surface current tallies -- note that the particle is moved
617
  // forward slightly so that if the mesh boundary is on the surface, it is
618
  // still processed
619

620
  if (!model::active_meshsurf_tallies.empty()) {
22,930,036✔
621
    // TODO: Find a better solution to score surface currents than
622
    // physically moving the particle forward slightly
623

624
    r() += TINY_BIT * u();
2,092,690✔
625
    score_surface_tally(*this, model::active_meshsurf_tallies);
2,092,690✔
626
  }
627

628
  // Score to global leakage tally
629
  keff_tally_leakage() += wgt();
22,930,036✔
630

631
  // Kill the particle
632
  wgt() = 0.0;
22,930,036✔
633

634
  // Display message
635
  if (settings::verbosity >= 10 || trace()) {
22,930,036✔
636
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
637
  }
638
}
22,930,036✔
639

640
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
662,986,018✔
641
{
642
  // Do not handle reflective boundary conditions on lower universes
643
  if (n_coord() != 1) {
662,986,018✔
UNCOV
644
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
645
                 " off surface in a lower universe.");
UNCOV
646
    return;
×
647
  }
648

649
  // Score surface currents since reflection causes the direction of the
650
  // particle to change. For surface filters, we need to score the tallies
651
  // twice, once before the particle's surface attribute has changed and
652
  // once after. For mesh surface filters, we need to artificially move
653
  // the particle slightly back in case the surface crossing is coincident
654
  // with a mesh boundary
655

656
  if (!model::active_surface_tallies.empty()) {
662,986,018✔
657
    score_surface_tally(*this, model::active_surface_tallies);
307,428✔
658
  }
659

660
  if (!model::active_meshsurf_tallies.empty()) {
662,986,018✔
661
    Position r {this->r()};
109,473,760✔
662
    this->r() -= TINY_BIT * u();
109,473,760✔
663
    score_surface_tally(*this, model::active_meshsurf_tallies);
109,473,760✔
664
    this->r() = r;
109,473,760✔
665
  }
666

667
  // Set the new particle direction
668
  u() = new_u;
662,986,018✔
669

670
  // Reassign particle's cell and surface
671
  coord(0).cell = cell_last(0);
662,986,018✔
672
  surface() = -surface();
662,986,018✔
673

674
  // If a reflective surface is coincident with a lattice or universe
675
  // boundary, it is necessary to redetermine the particle's coordinates in
676
  // the lower universes.
677
  // (unless we're using a dagmc model, which has exactly one universe)
678
  n_coord() = 1;
662,986,018✔
679
  if (surf.geom_type() != GeometryType::DAG &&
1,325,969,497✔
680
      !neighbor_list_find_cell(*this)) {
662,983,479✔
UNCOV
681
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
682
                 std::to_string(surf.id_) + ".");
×
UNCOV
683
    return;
×
684
  }
685

686
  // Set previous coordinate going slightly past surface crossing
687
  r_last_current() = r() + TINY_BIT * u();
662,986,018✔
688

689
  // Diagnostic message
690
  if (settings::verbosity >= 10 || trace()) {
662,986,018✔
691
    write_message(1, "    Reflected from surface {}", surf.id_);
×
692
  }
693
}
694

695
void Particle::cross_periodic_bc(
727,164✔
696
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
697
{
698
  // Do not handle periodic boundary conditions on lower universes
699
  if (n_coord() != 1) {
727,164✔
UNCOV
700
    mark_as_lost(
×
UNCOV
701
      "Cannot transfer particle " + std::to_string(id()) +
×
702
      " across surface in a lower universe. Boundary conditions must be "
703
      "applied to root universe.");
704
    return;
×
705
  }
706

707
  // Score surface currents since reflection causes the direction of the
708
  // particle to change -- artificially move the particle slightly back in
709
  // case the surface crossing is coincident with a mesh boundary
710
  if (!model::active_meshsurf_tallies.empty()) {
727,164✔
UNCOV
711
    Position r {this->r()};
×
UNCOV
712
    this->r() -= TINY_BIT * u();
×
UNCOV
713
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
714
    this->r() = r;
×
715
  }
716

717
  // Adjust the particle's location and direction.
718
  r() = new_r;
727,164✔
719
  u() = new_u;
727,164✔
720

721
  // Reassign particle's surface
722
  surface() = new_surface;
727,164✔
723

724
  // Figure out what cell particle is in now
725
  n_coord() = 1;
727,164✔
726

727
  if (!neighbor_list_find_cell(*this)) {
727,164✔
UNCOV
728
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
729
                 "boundary on surface " +
×
UNCOV
730
                 std::to_string(surf.id_) +
×
731
                 ". The normal vector "
732
                 "of one periodic surface may need to be reversed.");
UNCOV
733
    return;
×
734
  }
735

736
  // Set previous coordinate going slightly past surface crossing
737
  r_last_current() = r() + TINY_BIT * u();
727,164✔
738

739
  // Diagnostic message
740
  if (settings::verbosity >= 10 || trace()) {
727,164✔
UNCOV
741
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
742
  }
743
}
744

745
void Particle::mark_as_lost(const char* message)
6,268✔
746
{
747
  // Print warning and write lost particle file
748
  warning(message);
6,268✔
749
  if (settings::max_write_lost_particles < 0 ||
6,268✔
750
      simulation::n_lost_particles < settings::max_write_lost_particles) {
6,000✔
751
    write_restart();
353✔
752
  }
753
  // Increment number of lost particles
754
  wgt() = 0.0;
6,268✔
755
#pragma omp atomic
3,124✔
756
  simulation::n_lost_particles += 1;
3,144✔
757

758
  // Count the total number of simulated particles (on this processor)
759
  auto n = simulation::current_batch * settings::gen_per_batch *
6,268✔
760
           simulation::work_per_rank;
761

762
  // Abort the simulation if the maximum number of lost particles has been
763
  // reached
764
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
6,268✔
765
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10✔
766
    fatal_error("Maximum number of lost particles has been reached.");
10✔
767
  }
768
}
6,258✔
769

770
void Particle::write_restart() const
353✔
771
{
772
  // Dont write another restart file if in particle restart mode
773
  if (settings::run_mode == RunMode::PARTICLE)
353✔
774
    return;
24✔
775

776
  // Set up file name
777
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
778
    simulation::current_batch, id());
619✔
779

780
#pragma omp critical(WriteParticleRestart)
314✔
781
  {
782
    // Create file
783
    hid_t file_id = file_open(filename, 'w');
329✔
784

785
    // Write filetype and version info
786
    write_attribute(file_id, "filetype", "particle restart");
329✔
787
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
329✔
788
    write_attribute(file_id, "openmc_version", VERSION);
329✔
789
#ifdef GIT_SHA1
790
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
329✔
791
#endif
792

793
    // Write data to file
794
    write_dataset(file_id, "current_batch", simulation::current_batch);
329✔
795
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
329✔
796
    write_dataset(file_id, "current_generation", simulation::current_gen);
329✔
797
    write_dataset(file_id, "n_particles", settings::n_particles);
329✔
798
    switch (settings::run_mode) {
329✔
799
    case RunMode::FIXED_SOURCE:
245✔
800
      write_dataset(file_id, "run_mode", "fixed source");
245✔
801
      break;
245✔
802
    case RunMode::EIGENVALUE:
84✔
803
      write_dataset(file_id, "run_mode", "eigenvalue");
84✔
804
      break;
84✔
UNCOV
805
    case RunMode::PARTICLE:
×
UNCOV
806
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
807
      break;
×
UNCOV
808
    default:
×
UNCOV
809
      break;
×
810
    }
811
    write_dataset(file_id, "id", id());
329✔
812
    write_dataset(file_id, "type", static_cast<int>(type()));
329✔
813

814
    int64_t i = current_work();
329✔
815
    if (settings::run_mode == RunMode::EIGENVALUE) {
329✔
816
      // take source data from primary bank for eigenvalue simulation
817
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
84✔
818
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
84✔
819
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
84✔
820
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
84✔
821
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
84✔
822
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
245✔
823
      // re-sample using rng random number seed used to generate source particle
824
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
245✔
825
                     settings::n_particles +
245✔
826
                   simulation::work_index[mpi::rank] + i;
245✔
827
      uint64_t seed = init_seed(id, STREAM_SOURCE);
245✔
828
      // re-sample source site
829
      auto site = sample_external_source(&seed);
245✔
830
      write_dataset(file_id, "weight", site.wgt);
245✔
831
      write_dataset(file_id, "energy", site.E);
245✔
832
      write_dataset(file_id, "xyz", site.r);
245✔
833
      write_dataset(file_id, "uvw", site.u);
245✔
834
      write_dataset(file_id, "time", site.time);
245✔
835
    }
836

837
    // Close file
838
    file_close(file_id);
329✔
839
  } // #pragma omp critical
840
}
329✔
841

842
void Particle::update_neutron_xs(
2,147,483,647✔
843
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
844
{
845
  // Get microscopic cross section cache
846
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
847

848
  // If the cache doesn't match, recalculate micro xs
849
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
850
      i_sab != micro.index_sab || sab_frac != micro.sab_frac) {
2,147,483,647✔
851
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
852

853
    // If NCrystal is being used, update micro cross section cache
854
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
855
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
1,001,722✔
856
      ncrystal_update_micro(ncrystal_xs, micro);
1,001,722✔
857
    }
858
  }
859
}
2,147,483,647✔
860

861
//==============================================================================
862
// Non-method functions
863
//==============================================================================
864

865
std::string particle_type_to_str(ParticleType type)
3,247,320✔
866
{
867
  switch (type) {
3,247,320✔
868
  case ParticleType::neutron:
2,450,772✔
869
    return "neutron";
2,450,772✔
870
  case ParticleType::photon:
796,308✔
871
    return "photon";
796,308✔
872
  case ParticleType::electron:
120✔
873
    return "electron";
120✔
874
  case ParticleType::positron:
120✔
875
    return "positron";
120✔
876
  }
UNCOV
877
  UNREACHABLE();
×
878
}
879

880
ParticleType str_to_particle_type(std::string str)
3,409,242✔
881
{
882
  if (str == "neutron") {
3,409,242✔
883
    return ParticleType::neutron;
785,831✔
884
  } else if (str == "photon") {
2,623,411✔
885
    return ParticleType::photon;
2,623,343✔
886
  } else if (str == "electron") {
68✔
887
    return ParticleType::electron;
34✔
888
  } else if (str == "positron") {
34✔
889
    return ParticleType::positron;
34✔
890
  } else {
UNCOV
891
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
892
  }
893
}
894

895
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,463,437,446✔
896
{
897
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
898
      simulation::surf_source_bank.full()) {
1,154,116,031✔
899
    return;
1,463,320,848✔
900
  }
901

902
  // If a cell/cellfrom/cellto parameter is defined
903
  if (settings::ssw_cell_id != C_NONE) {
349,631✔
904

905
    // Retrieve cell index and storage type
906
    int cell_idx = model::cell_map[settings::ssw_cell_id];
283,436✔
907

908
    if (surf.bc_) {
283,436✔
909
      // Leave if cellto with vacuum boundary condition
910
      if (surf.bc_->type() == "vacuum" &&
202,454✔
911
          settings::ssw_cell_type == SSWCellType::To) {
35,216✔
912
        return;
13,071✔
913
      }
914

915
      // Leave if other boundary condition than vacuum
916
      if (surf.bc_->type() != "vacuum") {
154,167✔
917
        return;
132,022✔
918
      }
919
    }
920

921
    // Check if the cell of interest has been exited
922
    bool exited = false;
138,343✔
923
    for (int i = 0; i < p.n_coord_last(); ++i) {
366,533✔
924
      if (p.cell_last(i) == cell_idx) {
228,190✔
925
        exited = true;
81,192✔
926
      }
927
    }
928

929
    // Check if the cell of interest has been entered
930
    bool entered = false;
138,343✔
931
    for (int i = 0; i < p.n_coord(); ++i) {
328,932✔
932
      if (p.coord(i).cell == cell_idx) {
190,589✔
933
        entered = true;
64,717✔
934
      }
935
    }
936

937
    // Vacuum boundary conditions: return if cell is not exited
938
    if (surf.bc_) {
138,343✔
939
      if (surf.bc_->type() == "vacuum" && !exited) {
22,145✔
940
        return;
15,245✔
941
      }
942
    } else {
943

944
      // If we both enter and exit the cell of interest
945
      if (entered && exited) {
116,198✔
946
        return;
31,409✔
947
      }
948

949
      // If we did not enter nor exit the cell of interest
950
      if (!entered && !exited) {
84,789✔
951
        return;
15,498✔
952
      }
953

954
      // If cellfrom and the cell before crossing is not the cell of
955
      // interest
956
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
69,291✔
957
        return;
12,665✔
958
      }
959

960
      // If cellto and the cell after crossing is not the cell of interest
961
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
56,626✔
962
        return;
13,123✔
963
      }
964
    }
965
  }
966

967
  SourceSite site;
116,598✔
968
  site.r = p.r();
116,598✔
969
  site.u = p.u();
116,598✔
970
  site.E = p.E();
116,598✔
971
  site.time = p.time();
116,598✔
972
  site.wgt = p.wgt();
116,598✔
973
  site.delayed_group = p.delayed_group();
116,598✔
974
  site.surf_id = surf.id_;
116,598✔
975
  site.particle = p.type();
116,598✔
976
  site.parent_id = p.id();
116,598✔
977
  site.progeny_id = p.n_progeny();
116,598✔
978
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
116,598✔
979
}
980

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