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

openmc-dev / openmc / 13860705201

14 Mar 2025 04:10PM UTC coverage: 84.925% (-0.1%) from 85.042%
13860705201

Pull #3305

github

web-flow
Merge f02782e46 into 906548db2
Pull Request #3305: New Feature Development: The Implementation of chord length sampling (CLS) method for stochastic media( #3286 )

20 of 161 new or added lines in 8 files covered. (12.42%)

1010 existing lines in 44 files now uncovered.

51574 of 60729 relevant lines covered (84.92%)

36935786.37 hits per line

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

87.4
/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/stochastic_media.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 DAGMC
37
#include "DagMC.hpp"
38
#endif
39

40
namespace openmc {
41

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

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

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

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

79
bool Particle::create_secondary(
102,198,971✔
80
  double wgt, Direction u, double E, ParticleType type)
81
{
82
  // If energy is below cutoff for this particle, don't create secondary
83
  // particle
84
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
102,198,971✔
85
    return false;
48,745,828✔
86
  }
87

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

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

110
void Particle::from_source(const SourceSite* src)
219,068,214✔
111
{
112
  // Reset some attributes
113
  clear();
219,068,214✔
114
  surface() = SURFACE_NONE;
219,068,214✔
115
  cell_born() = C_NONE;
219,068,214✔
116
  material() = C_NONE;
219,068,214✔
117
  n_collision() = 0;
219,068,214✔
118
  fission() = false;
219,068,214✔
119
  zero_flux_derivs();
219,068,214✔
120

121
  // Copy attributes from source bank site
122
  type() = src->particle;
219,068,214✔
123
  wgt() = src->wgt;
219,068,214✔
124
  wgt_last() = src->wgt;
219,068,214✔
125
  r() = src->r;
219,068,214✔
126
  u() = src->u;
219,068,214✔
127
  r_born() = src->r;
219,068,214✔
128
  r_last_current() = src->r;
219,068,214✔
129
  r_last() = src->r;
219,068,214✔
130
  u_last() = src->u;
219,068,214✔
131
  if (settings::run_CE) {
219,068,214✔
132
    E() = src->E;
100,519,421✔
133
    g() = 0;
100,519,421✔
134
  } else {
135
    g() = static_cast<int>(src->E);
118,548,793✔
136
    g_last() = static_cast<int>(src->E);
118,548,793✔
137
    E() = data::mg.energy_bin_avg_[g()];
118,548,793✔
138
  }
139
  E_last() = E();
219,068,214✔
140
  time() = src->time;
219,068,214✔
141
  time_last() = src->time;
219,068,214✔
142
  parent_nuclide() = src->parent_nuclide;
219,068,214✔
143
}
219,068,214✔
144

145
void Particle::event_calculate_xs()
2,147,483,647✔
146
{
147
  // Set the random number stream
148
  stream() = STREAM_TRACKING;
2,147,483,647✔
149

150
  // Store pre-collision particle properties
151
  wgt_last() = wgt();
2,147,483,647✔
152
  E_last() = E();
2,147,483,647✔
153
  u_last() = u();
2,147,483,647✔
154
  r_last() = r();
2,147,483,647✔
155
  time_last() = time();
2,147,483,647✔
156

157
  // Reset event variables
158
  event() = TallyEvent::KILL;
2,147,483,647✔
159
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
160
  event_mt() = REACTION_NONE;
2,147,483,647✔
161

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

172
    // Set birth cell attribute
173
    if (cell_born() == C_NONE)
216,389,373✔
174
      cell_born() = lowest_coord().cell;
216,389,373✔
175

176
    // Initialize last cells from current cell
177
    for (int j = 0; j < n_coord(); ++j) {
454,471,017✔
178
      cell_last(j) = coord(j).cell;
238,081,644✔
179
    }
180
    n_coord_last() = n_coord();
216,389,373✔
181
  }
182

183
  // Write particle track.
184
  if (write_track())
2,147,483,647✔
185
    write_particle_track(*this);
10,835✔
186

187
  if (settings::check_overlaps)
2,147,483,647✔
188
    check_cell_overlap(*this);
×
189

190
  // Calculate microscopic and macroscopic cross sections
191
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
192
    if (settings::run_CE) {
2,147,483,647✔
193
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,587,531,567✔
194
        // If the material is the same as the last material and the
195
        // temperature hasn't changed, we don't need to lookup cross
196
        // sections again.
197
        model::materials[material()]->calculate_xs(*this);
1,268,580,446✔
198
      }
199
    } else {
200
      // Get the MG data; unlike the CE case above, we have to re-calculate
201
      // cross sections for every collision since the cross sections may
202
      // be angle-dependent
203
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,079,768,108✔
204

205
      // Update the particle's group while we know we are multi-group
206
      g_last() = g();
2,079,768,108✔
207
    }
208
  } else {
209
    macro_xs().total = 0.0;
66,440,917✔
210
    macro_xs().absorption = 0.0;
66,440,917✔
211
    macro_xs().fission = 0.0;
66,440,917✔
212
    macro_xs().nu_fission = 0.0;
66,440,917✔
213
  }
214
}
215

216
void Particle::event_advance()
2,147,483,647✔
217
{
218
  // Find the distance to the nearest boundary
219
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
220

221
  // Sample a distance to collision
222
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
223
    collision_distance() = 0.0;
48,822,143✔
224
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
225
    collision_distance() = INFINITY;
66,440,917✔
226
  } else {
227
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
228
  }
229

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

233
  if (this->status() != ParticleStatus::OUTSIDE) {
2,147,483,647✔
NEW
234
    double stocha_media_distance = distance_to_stochamedia(*this);
×
NEW
235
    if (stocha_media_distance < distance) {
×
NEW
236
      distance = stocha_media_distance;
×
NEW
237
      boundary().if_stochastic_surface = true;
×
238
    }
239
  }
240

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

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

256
    double push_back_distance = speed() * dt;
11,000✔
257
    this->move_distance(-push_back_distance);
11,000✔
258
    hit_time_boundary = true;
11,000✔
259
  }
260

261
  // Score track-length tallies
262
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_tracklength_tally(*this, distance);
1,223,452,884✔
264
  }
265

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

272
  // Score flux derivative accumulators for differential tallies.
273
  if (!model::active_tallies.empty()) {
2,147,483,647✔
274
    score_track_derivative(*this, distance);
1,391,564,562✔
275
  }
276

277
  // Set particle weight to zero if it hit the time boundary
278
  if (hit_time_boundary) {
2,147,483,647✔
279
    wgt() = 0.0;
11,000✔
280
  }
281
}
2,147,483,647✔
282

283
void Particle::event_cross_surface()
1,988,485,353✔
284
{
285
  // Saving previous cell data
286
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
287
    cell_last(j) = coord(j).cell;
2,147,483,647✔
288
  }
289
  n_coord_last() = n_coord();
1,988,485,353✔
290

291
  // Set surface that particle is on and adjust coordinate levels
292
  surface() = boundary().surface;
1,988,485,353✔
293
  n_coord() = boundary().coord_level;
1,988,485,353✔
294

295
  if (boundary().lattice_translation[0] != 0 ||
1,988,485,353✔
296
      boundary().lattice_translation[1] != 0 ||
2,147,483,647✔
297
      boundary().lattice_translation[2] != 0) {
1,503,280,892✔
298
    // Particle crosses lattice boundary
299

300
    bool verbose = settings::verbosity >= 10 || trace();
672,460,868✔
301
    cross_lattice(*this, boundary(), verbose);
672,460,868✔
302
    event() = TallyEvent::LATTICE;
672,460,868✔
303
  } else {
304
    // Particle crosses surface
305
    const auto& surf {model::surfaces[surface_index()].get()};
1,316,024,485✔
306
    // If BC, add particle to surface source before crossing surface
307
    if (surf->surf_source_ && surf->bc_) {
1,316,024,485✔
308
      add_surf_source_to_bank(*this, *surf);
623,745,726✔
309
    }
310
    this->cross_surface(*surf);
1,316,024,485✔
311
    // If no BC, add particle to surface source after crossing surface
312
    if (surf->surf_source_ && !surf->bc_) {
1,316,024,476✔
313
      add_surf_source_to_bank(*this, *surf);
691,375,341✔
314
    }
315
    if (settings::weight_window_checkpoint_surface) {
1,316,024,476✔
316
      apply_weight_windows(*this);
×
317
    }
318
    event() = TallyEvent::SURFACE;
1,316,024,476✔
319
  }
320
  // Score cell to cell partial currents
321
  if (!model::active_surface_tallies.empty()) {
1,988,485,344✔
322
    score_surface_tally(*this, model::active_surface_tallies);
34,896,037✔
323
  }
324
}
1,988,485,344✔
325

326
void Particle::event_collide()
2,147,483,647✔
327
{
328
  // Score collision estimate of keff
329
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
330
      type() == ParticleType::neutron) {
2,134,009,103✔
331
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,094,208,056✔
332
  }
333

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

338
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
339
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,216,648✔
340

341
  // Clear surface component
342
  surface() = SURFACE_NONE;
2,147,483,647✔
343

344
  if (settings::run_CE) {
2,147,483,647✔
345
    collision(*this);
689,298,623✔
346
  } else {
347
    collision_mg(*this);
1,785,735,523✔
348
  }
349

350
  // Score collision estimator tallies -- this is done after a collision
351
  // has occurred rather than before because we need information on the
352
  // outgoing energy for any tallies with an outgoing energy filter
353
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
354
    score_collision_tally(*this);
91,226,071✔
355
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
356
    if (settings::run_CE) {
98,802,616✔
357
      score_analog_tally_ce(*this);
97,601,405✔
358
    } else {
359
      score_analog_tally_mg(*this);
1,201,211✔
360
    }
361
  }
362

363
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
364
      type() == ParticleType::photon) {
16,918✔
365
    pht_collision_energy();
2,024✔
366
  }
367

368
  // Reset banked weight during collision
369
  n_bank() = 0;
2,147,483,647✔
370
  bank_second_E() = 0.0;
2,147,483,647✔
371
  wgt_bank() = 0.0;
2,147,483,647✔
372
  zero_delayed_bank();
2,147,483,647✔
373

374
  // Reset fission logical
375
  fission() = false;
2,147,483,647✔
376

377
  // Save coordinates for tallying purposes
378
  r_last_current() = r();
2,147,483,647✔
379

380
  // Set last material to none since cross sections will need to be
381
  // re-evaluated
382
  material_last() = C_NONE;
2,147,483,647✔
383

384
  // Set all directions to base level -- right now, after a collision, only
385
  // the base level directions are changed
386
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
387
    if (coord(j + 1).rotated) {
119,811,690✔
388
      // If next level is rotated, apply rotation matrix
389
      const auto& m {model::cells[coord(j).cell]->rotation_};
10,394,285✔
390
      const auto& u {coord(j).u};
10,394,285✔
391
      coord(j + 1).u = u.rotate(m);
10,394,285✔
392
    } else {
393
      // Otherwise, copy this level's direction
394
      coord(j + 1).u = coord(j).u;
109,417,405✔
395
    }
396
  }
397

398
  // Score flux derivative accumulators for differential tallies.
399
  if (!model::active_tallies.empty())
2,147,483,647✔
400
    score_collision_derivative(*this);
596,304,948✔
401

402
#ifdef DAGMC
403
  history().reset();
225,822,167✔
404
#endif
405
}
2,147,483,647✔
406

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

417
  // Check for secondary particles if this particle is dead
418
  if (!alive()) {
2,147,483,647✔
419
    // Write final position for this particle
420
    if (write_track()) {
216,388,969✔
421
      write_particle_track(*this);
6,674✔
422
    }
423

424
    // If no secondary particles, break out of event loop
425
    if (secondary_bank().empty())
216,388,969✔
426
      return;
155,952,911✔
427

428
    from_source(&secondary_bank().back());
60,436,058✔
429
    secondary_bank().pop_back();
60,436,058✔
430
    n_event() = 0;
60,436,058✔
431
    bank_second_E() = 0.0;
60,436,058✔
432

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

450
        // Initialize last cells from current cell
451
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
452
          cell_last(j) = coord(j).cell;
605✔
453
        }
454
        n_coord_last() = n_coord();
605✔
455
      }
456
      pht_secondary_particles();
605✔
457
    }
458

459
    // Enter new particle in particle track file
460
    if (write_track())
60,436,058✔
461
      add_particle_track(*this);
5,604✔
462
  }
463
}
464

465
void Particle::event_death()
155,953,911✔
466
{
467
#ifdef DAGMC
468
  history().reset();
14,202,385✔
469
#endif
470

471
  // Finish particle track output.
472
  if (write_track()) {
155,953,911✔
473
    finalize_particle_track(*this);
1,070✔
474
  }
475

476
// Contribute tally reduction variables to global accumulator
477
#pragma omp atomic
85,691,483✔
478
  global_tally_absorption += keff_tally_absorption();
155,953,911✔
479
#pragma omp atomic
85,434,975✔
480
  global_tally_collision += keff_tally_collision();
155,953,911✔
481
#pragma omp atomic
85,506,884✔
482
  global_tally_tracklength += keff_tally_tracklength();
155,953,911✔
483
#pragma omp atomic
85,289,206✔
484
  global_tally_leakage += keff_tally_leakage();
155,953,911✔
485

486
  // Reset particle tallies once accumulated
487
  keff_tally_absorption() = 0.0;
155,953,911✔
488
  keff_tally_collision() = 0.0;
155,953,911✔
489
  keff_tally_tracklength() = 0.0;
155,953,911✔
490
  keff_tally_leakage() = 0.0;
155,953,911✔
491

492
  if (!model::active_pulse_height_tallies.empty()) {
155,953,911✔
493
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
494
  }
495

496
  // Record the number of progeny created by this particle.
497
  // This data will be used to efficiently sort the fission bank.
498
  if (settings::run_mode == RunMode::EIGENVALUE) {
155,953,911✔
499
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,234,800✔
500
    simulation::progeny_per_particle[offset] = n_progeny();
133,234,800✔
501
  }
502
}
155,953,911✔
503

504
void Particle::pht_collision_energy()
2,024✔
505
{
506
  // Adds the energy particles lose in a collision to the pulse-height
507

508
  // determine index of cell in pulse_height_cells
509
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
510
    model::pulse_height_cells.end(), lowest_coord().cell);
2,024✔
511

512
  if (it != model::pulse_height_cells.end()) {
2,024✔
513
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
514
    pht_storage()[index] += E_last() - E();
2,024✔
515

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

525
void Particle::pht_secondary_particles()
605✔
526
{
527
  // Removes the energy of secondary produced particles from the pulse-height
528

529
  // determine index of cell in pulse_height_cells
530
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
531
    model::pulse_height_cells.end(), cell_born());
605✔
532

533
  if (it != model::pulse_height_cells.end()) {
605✔
534
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
535
    pht_storage()[index] -= E();
605✔
536
  }
537
}
605✔
538

539
void Particle::cross_surface(const Surface& surf)
1,316,991,781✔
540
{
541

542
  if (settings::verbosity >= 10 || trace()) {
1,316,991,781✔
543
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
544
  }
545

546
// if we're crossing a CSG surface, make sure the DAG history is reset
547
#ifdef DAGMC
548
  if (surf.geom_type() == GeometryType::CSG)
119,034,619✔
549
    history().reset();
118,999,303✔
550
#endif
551

552
  // Handle any applicable boundary conditions.
553
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,316,991,781✔
554
    surf.bc_->handle_particle(*this, surf);
623,983,343✔
555
    return;
623,983,343✔
556
  }
557

558
  // ==========================================================================
559
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
560

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

574
    cell_instance() = 0;
28,265✔
575
    if (cell->distribcell_index_ >= 0)
28,265✔
576
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
27,264✔
577

578
    material() = cell->material(cell_instance());
28,265✔
579
    sqrtkT() = cell->sqrtkT(cell_instance());
28,265✔
580
    return;
28,265✔
581
  }
582
#endif
583

584
  bool verbose = settings::verbosity >= 10 || trace();
692,980,173✔
585
  if (neighbor_list_find_cell(*this, verbose)) {
692,980,173✔
586
    return;
692,952,154✔
587
  }
588

589
  // ==========================================================================
590
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
591

592
  // Remove lower coordinate levels
593
  n_coord() = 1;
28,019✔
594
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
595

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

602
    surface() = SURFACE_NONE;
5,744✔
603
    n_coord() = 1;
5,744✔
604
    r() += TINY_BIT * u();
5,744✔
605

606
    // Couldn't find next cell anywhere! This probably means there is an actual
607
    // undefined region in the geometry.
608

609
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
610
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
611
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
612
                   " it could not be located in any cell and it did not leak.");
613
      return;
5,735✔
614
    }
615
  }
616
}
617

UNCOV
618
void Particle::cross_surface_in_stochmedia()
×
619
{
NEW
620
  surface() = SURFACE_NONE;
×
NEW
621
  bool verbose = settings::verbosity >= 10 || trace();
×
622

NEW
623
  double i_cell = this->lowest_coord().cell;
×
NEW
624
  Cell& c {*model::cells[i_cell]};
×
625

NEW
626
  this->cell_instance() = 0;
×
627
  // Find the distribcell instance number.
NEW
628
  if (c.distribcell_index_ >= 0) {
×
NEW
629
    this->cell_instance() = cell_instance_at_level(*this, this->n_coord() - 1);
×
630
  }
631

632
  // If the Particle is in a cell containing a stochastic medium, update the
633
  // status of particle based on the current stochastic medium.
NEW
634
  Stochastic_Media& media {*model::stochastic_media[c.fill_]};
×
635
  int32_t material;
NEW
636
  if (this->status() == ParticleStatus::IN_STOCHASTIC_MEDIA) {
×
637

NEW
638
    material = media.matrix_mat();
×
NEW
639
    this->status() = ParticleStatus::IN_MATRIX;
×
NEW
640
    if (verbose) {
×
NEW
641
      write_message(1,
×
642
        "    Crossing surface in stochasitic media {} from particle to matrix",
NEW
643
        media.id_);
×
644
    }
645

NEW
646
  } else if (this->status() == ParticleStatus::IN_MATRIX) {
×
647
    // short time implementation, only one particle type in matrix
NEW
648
    material = media.particle_mat(0);
×
NEW
649
    this->status() = ParticleStatus::IN_STOCHASTIC_MEDIA;
×
NEW
650
    if (verbose) {
×
NEW
651
      write_message(1,
×
652
        "    Crossing surface in stochasitic media {} from matrix to particle",
NEW
653
        media.id_);
×
654
    }
655
  }
NEW
656
  this->material_last() = this->material();
×
NEW
657
  this->material() = material;
×
NEW
658
  this->sqrtkT_last() = this->sqrtkT();
×
NEW
659
  this->sqrtkT() = c.sqrtkT(this->cell_instance());
×
660
}
661

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

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

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

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

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

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

708
  if (!model::active_meshsurf_tallies.empty()) {
593,972,598✔
709
    Position r {this->r()};
54,998,215✔
710
    this->r() -= TINY_BIT * u();
54,998,215✔
711
    score_surface_tally(*this, model::active_meshsurf_tallies);
54,998,215✔
712
    this->r() = r;
54,998,215✔
713
  }
714

715
  // Set the new particle direction
716
  u() = new_u;
593,972,598✔
717

718
  // Reassign particle's cell and surface
719
  coord(0).cell = cell_last(0);
593,972,598✔
720
  surface() = -surface();
593,972,598✔
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;
593,972,598✔
727
  if (surf.geom_type() != GeometryType::DAG &&
1,187,942,657✔
728
      !neighbor_list_find_cell(*this)) {
593,970,059✔
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();
593,972,598✔
736

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

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

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

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

775
  if (!neighbor_list_find_cell(*this)) {
666,318✔
776
    mark_as_lost("Couldn't find particle after hitting periodic "
×
777
                 "boundary on surface " +
×
778
                 std::to_string(surf.id_) +
×
779
                 ". The normal vector "
780
                 "of one periodic surface may need to be reversed.");
781
    return;
×
782
  }
783

784
  // Set previous coordinate going slightly past surface crossing
785
  r_last_current() = r() + TINY_BIT * u();
666,318✔
786

787
  // Diagnostic message
788
  if (settings::verbosity >= 10 || trace()) {
666,318✔
789
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
790
  }
791
}
792

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

806
  // Count the total number of simulated particles (on this processor)
807
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
808
           simulation::work_per_rank;
809

810
  // Abort the simulation if the maximum number of lost particles has been
811
  // reached
812
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
813
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
814
    fatal_error("Maximum number of lost particles has been reached.");
9✔
815
  }
816
}
5,735✔
817

818
void Particle::write_restart() const
324✔
819
{
820
  // Dont write another restart file if in particle restart mode
821
  if (settings::run_mode == RunMode::PARTICLE)
324✔
822
    return;
22✔
823

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

828
#pragma omp critical(WriteParticleRestart)
314✔
829
  {
830
    // Create file
831
    hid_t file_id = file_open(filename, 'w');
302✔
832

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

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

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

885
    // Close file
886
    file_close(file_id);
302✔
887
  } // #pragma omp critical
888
}
302✔
889

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

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

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

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

913
std::string particle_type_to_str(ParticleType type)
3,130,116✔
914
{
915
  switch (type) {
3,130,116✔
916
  case ParticleType::neutron:
2,399,925✔
917
    return "neutron";
2,399,925✔
918
  case ParticleType::photon:
729,971✔
919
    return "photon";
729,971✔
920
  case ParticleType::electron:
110✔
921
    return "electron";
110✔
922
  case ParticleType::positron:
110✔
923
    return "positron";
110✔
924
  }
925
  UNREACHABLE();
×
926
}
927

928
ParticleType str_to_particle_type(std::string str)
2,819,536✔
929
{
930
  if (str == "neutron") {
2,819,536✔
931
    return ParticleType::neutron;
646,276✔
932
  } else if (str == "photon") {
2,173,260✔
933
    return ParticleType::photon;
2,173,196✔
934
  } else if (str == "electron") {
64✔
935
    return ParticleType::electron;
32✔
936
  } else if (str == "positron") {
32✔
937
    return ParticleType::positron;
32✔
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)
1,315,121,067✔
944
{
945
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
946
      simulation::surf_source_bank.full()) {
1,043,279,350✔
947
    return;
1,315,014,302✔
948
  }
949

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

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

956
    if (surf.bc_) {
258,708✔
957
      // Leave if cellto with vacuum boundary condition
958
      if (surf.bc_->type() == "vacuum" &&
184,448✔
959
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
960
        return;
11,953✔
961
      }
962

963
      // Leave if other boundary condition than vacuum
964
      if (surf.bc_->type() != "vacuum") {
140,281✔
965
        return;
120,020✔
966
      }
967
    }
968

969
    // Check if the cell of interest has been exited
970
    bool exited = false;
126,735✔
971
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,347✔
972
      if (p.cell_last(i) == cell_idx) {
208,612✔
973
        exited = true;
74,235✔
974
      }
975
    }
976

977
    // Check if the cell of interest has been entered
978
    bool entered = false;
126,735✔
979
    for (int i = 0; i < p.n_coord(); ++i) {
301,043✔
980
      if (p.coord(i).cell == cell_idx) {
174,308✔
981
        entered = true;
59,100✔
982
      }
983
    }
984

985
    // Vacuum boundary conditions: return if cell is not exited
986
    if (surf.bc_) {
126,735✔
987
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
988
        return;
13,961✔
989
      }
990
    } else {
991

992
      // If we both enter and exit the cell of interest
993
      if (entered && exited) {
106,474✔
994
        return;
28,613✔
995
      }
996

997
      // If we did not enter nor exit the cell of interest
998
      if (!entered && !exited) {
77,861✔
999
        return;
14,352✔
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) {
63,509✔
1005
        return;
11,567✔
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) {
51,942✔
1010
        return;
12,038✔
1011
      }
1012
    }
1013
  }
1014

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

© 2025 Coveralls, Inc