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

openmc-dev / openmc / 33021035974

26 Aug 2026 10:49PM UTC coverage: 81.374% (+0.04%) from 81.333%
33021035974

Pull #3944

github

web-flow
Merge 5f481a929 into 7ecd3a961
Pull Request #3944: DNP drift (regular mesh only)

19081 of 27653 branches covered (69.0%)

Branch coverage included in aggregate %.

718 of 828 new or added lines in 20 files covered. (86.71%)

9 existing lines in 1 file now uncovered.

61001 of 70759 relevant lines covered (86.21%)

50433828.6 hits per line

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

93.31
/src/simulation.cpp
1
#include "openmc/simulation.h"
2

3
#include "openmc/bank.h"
4
#include "openmc/capi.h"
5
#include "openmc/collision_track.h"
6
#include "openmc/constants.h"
7
#include "openmc/container_util.h"
8
#include "openmc/eigenvalue.h"
9
#include "openmc/error.h"
10
#include "openmc/event.h"
11
#include "openmc/field.h"
12
#include "openmc/geometry_aux.h"
13
#include "openmc/ifp.h"
14
#include "openmc/material.h"
15
#include "openmc/message_passing.h"
16
#include "openmc/nuclide.h"
17
#include "openmc/openmp_interface.h"
18
#include "openmc/output.h"
19
#include "openmc/particle.h"
20
#include "openmc/photon.h"
21
#include "openmc/random_lcg.h"
22
#include "openmc/random_ray/flat_source_domain.h"
23
#include "openmc/settings.h"
24
#include "openmc/source.h"
25
#include "openmc/state_point.h"
26
#include "openmc/streamline_integrator.h"
27
#include "openmc/tallies/derivative.h"
28
#include "openmc/tallies/filter.h"
29
#include "openmc/tallies/tally.h"
30
#include "openmc/tallies/trigger.h"
31
#include "openmc/timer.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

35
#ifdef _OPENMP
36
#include <omp.h>
37
#endif
38
#include "openmc/tensor.h"
39

40
#ifdef OPENMC_MPI
41
#include <mpi.h>
42
#endif
43

44
#include <fmt/format.h>
45

46
#include <algorithm>
47
#include <cmath>
48
#include <numeric>
49
#include <string>
50

51
//==============================================================================
52
// C API functions
53
//==============================================================================
54

55
// OPENMC_RUN encompasses all the main logic where iterations are performed
56
// over the batches, generations, and histories in a fixed source or
57
// k-eigenvalue calculation.
58

59
int openmc_run()
7,059 ✔
60
{
61
  openmc::simulation::time_total.start();
7,059 ✔
62
  openmc_simulation_init();
7,059 ✔
63

64
  // Ensure that a batch isn't executed in the case that the maximum number of
65
  // batches has already been run in a restart statepoint file
66
  int status = 0;
7,059 ✔
67
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
7,059 ✔
68
    status = openmc::STATUS_EXIT_MAX_BATCH;
11 ✔
69
  }
70

71
  int err = 0;
72
  while (status == 0 && err == 0) {
157,081 ✔
73
    err = openmc_next_batch(&status);
150,035 ✔
74
  }
75

76
  openmc_simulation_finalize();
7,046 ✔
77
  openmc::simulation::time_total.stop();
7,046 ✔
78
  return err;
7,046 ✔
79
}
80

81
int openmc_simulation_init()
8,275 ✔
82
{
83
  using namespace openmc;
8,275 ✔
84

85
  // Skip if simulation has already been initialized
86
  if (simulation::initialized)
8,275 ✔
87
    return 0;
88

89
  // Initialize nuclear data (energy limits, log grid)
90
  if (settings::run_CE) {
8,253 ✔
91
    initialize_data();
6,798 ✔
92
  }
93

94
  // Determine how much work each process should do
95
  calculate_work(settings::n_particles);
8,253 ✔
96

97
  // Allocate source, fission and surface source banks.
98
  allocate_banks();
8,253 ✔
99

100
  // Create track file if needed
101
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
8,253 ✔
102
    open_track_file();
90 ✔
103
  }
104

105
  // If doing an event-based simulation, intialize the particle buffer
106
  // and event queues
107
  if (settings::event_based) {
8,253 ✔
108
    int64_t event_buffer_length =
238 !
109
      std::min(simulation::work_per_rank, settings::max_particles_in_flight);
238 ✔
110
    init_event_queues(event_buffer_length);
238 ✔
111
  }
112

113
  // Allocate tally results arrays if they're not allocated yet
114
  for (auto& t : model::tallies) {
36,415 ✔
115
    t->set_strides();
28,162 ✔
116
    t->init_results();
28,162 ✔
117
  }
118

119
  // Set up material nuclide index mapping
120
  for (auto& mat : model::materials) {
28,582 ✔
121
    mat->init_nuclide_index();
20,329 ✔
122
  }
123

124
  // Reset global variables -- this is done before loading state point (as that
125
  // will potentially populate k_generation and entropy)
126
  simulation::current_batch = 0;
8,253 ✔
127
  simulation::ct_current_file = 1;
8,253 ✔
128
  simulation::ssw_current_file = 1;
8,253 ✔
129
  simulation::k_generation.clear();
8,253 ✔
130
  simulation::entropy.clear();
8,253 ✔
131
  reset_source_rejection_counters();
8,253 ✔
132
  openmc_reset();
8,253 ✔
133

134
  // If this is a restart run, load the state point data and binary source
135
  // file
136
  if (settings::restart_run) {
8,253 ✔
137
    load_state_point();
63 ✔
138
    write_message("Resuming simulation...", 6);
126 ✔
139
  } else {
140
    // Only initialize primary source bank for eigenvalue simulations
141
    if (settings::run_mode == RunMode::EIGENVALUE &&
8,190 ✔
142
        settings::solver_type == SolverType::MONTE_CARLO) {
4,658 ✔
143
      initialize_source();
4,287 ✔
144
    }
145
  }
146

147
  // Display header
148
  if (mpi::master) {
8,253 ✔
149
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,173 ✔
150
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,206 ✔
151
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,786 ✔
152
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
420 !
153
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
420 ✔
154
      }
155
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,967 !
156
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,967 ✔
157
        header("K EIGENVALUE SIMULATION", 3);
3,692 ✔
158
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
275 !
159
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
275 ✔
160
      }
161
      if (settings::verbosity >= 7)
3,967 ✔
162
        print_columns();
3,587 ✔
163
    }
164
  }
165

166
  // load weight windows from file
167
  if (!settings::weight_windows_file.empty()) {
8,253 ✔
168
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
26 ✔
169
  }
170

171
  // Set flag indicating initialization is done
172
  simulation::initialized = true;
8,253 ✔
173
  return 0;
8,253 ✔
174
}
175

176
int openmc_simulation_finalize()
8,240 ✔
177
{
178
  using namespace openmc;
8,240 ✔
179

180
  // Skip if simulation was never run
181
  if (!simulation::initialized)
8,240 !
182
    return 0;
183

184
  // Stop active batch timer and start finalization timer
185
  simulation::time_active.stop();
8,240 ✔
186
  simulation::time_finalize.start();
8,240 ✔
187

188
  // Clear material nuclide mapping
189
  for (auto& mat : model::materials) {
28,556 ✔
190
    mat->mat_nuclide_index_.clear();
40,632 !
191
  }
192

193
  // Close track file if open
194
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
8,240 ✔
195
    close_track_file();
90 ✔
196
  }
197

198
  // Increment total number of generations
199
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
8,240 ✔
200

201
#ifdef OPENMC_MPI
202
  broadcast_results();
3,706 ✔
203
#endif
204

205
  // Write tally results to tallies.out
206
  if (settings::output_tallies && mpi::master)
8,240 !
207
    write_tallies();
6,792 ✔
208

209
  // If weight window generators are present in this simulation, write a
210
  // weight windows file. This is skipped during the forward solve of an
211
  // adjoint (FW-CADIS) run, where only the adjoint-derived weight windows
212
  // are meaningful.
213
  if (variance_reduction::weight_windows_generators.size() > 0 &&
8,240 ✔
214
      FlatSourceDomain::solve_ != RandomRaySolve::FORWARD_FOR_ADJOINT) {
210 ✔
215
    openmc_weight_windows_export();
127 ✔
216
  }
217

218
  // Deactivate all tallies
219
  for (auto& t : model::tallies) {
36,402 ✔
220
    t->active_ = false;
28,162 ✔
221
  }
222

223
  // Stop timers and show timing statistics
224
  simulation::time_finalize.stop();
8,240 ✔
225
  simulation::time_total.stop();
8,240 ✔
226

227
#ifdef OPENMC_MPI
228
  // Reduce track count across ranks for correct reporting. In shared secondary
229
  // bank mode, all ranks already have the global count; in non-shared mode,
230
  // each rank only has its own count.
231
  if (settings::weight_windows_on && !settings::use_shared_secondary_bank) {
3,706 ✔
232
    int64_t total_tracks;
92 ✔
233
    MPI_Reduce(&simulation::simulation_tracks_completed, &total_tracks, 1,
92 ✔
234
      MPI_INT64_T, MPI_SUM, 0, mpi::intracomm);
235
    if (mpi::master)
92 ✔
236
      simulation::simulation_tracks_completed = total_tracks;
76 ✔
237
  }
238
#endif
239

240
  if (mpi::master) {
8,240 ✔
241
    if (settings::solver_type != SolverType::RANDOM_RAY) {
7,160 ✔
242
      if (settings::verbosity >= 6)
6,465 ✔
243
        print_runtime();
6,085 ✔
244
      if (settings::verbosity >= 4)
6,465 ✔
245
        print_results();
6,085 ✔
246
    }
247
  }
248
  if (settings::check_overlaps)
8,240 !
249
    print_overlap_check();
×
250

251
  // Reset flags
252
  simulation::initialized = false;
8,240 ✔
253
  return 0;
8,240 ✔
254
}
255

256
int openmc_next_batch(int* status)
154,160 ✔
257
{
258
  using namespace openmc;
154,160 ✔
259
  using openmc::simulation::current_gen;
154,160 ✔
260

261
  // Make sure simulation has been initialized
262
  if (!simulation::initialized) {
154,160 ✔
263
    set_errmsg("Simulation has not been initialized yet.");
11 ✔
264
    return OPENMC_E_ALLOCATE;
11 ✔
265
  }
266

267
  initialize_batch();
154,149 ✔
268

269
  // =======================================================================
270
  // LOOP OVER GENERATIONS
271
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
308,495 ✔
272

273
    initialize_generation();
154,359 ✔
274

275
    // Start timer for transport
276
    simulation::time_transport.start();
154,359 ✔
277

278
    // Transport loop
279
    if (settings::event_based) {
154,359 ✔
280
      if (settings::use_shared_secondary_bank) {
3,522 ✔
281
        transport_event_based_shared_secondary();
21 ✔
282
      } else {
283
        transport_event_based();
3,501 ✔
284
      }
285
    } else {
286
      if (settings::use_shared_secondary_bank) {
150,837 ✔
287
        transport_history_based_shared_secondary();
3,062 ✔
288
      } else {
289
        transport_history_based();
147,775 ✔
290
      }
291
    }
292

293
    // Accumulate time for transport
294
    simulation::time_transport.stop();
154,346 ✔
295

296
    finalize_generation();
154,346 ✔
297
  }
298

299
  finalize_batch();
154,136 ✔
300

301
  // Check simulation ending criteria
302
  if (status) {
154,136 !
303
    if (simulation::current_batch >= settings::n_max_batches) {
154,136 ✔
304
      *status = STATUS_EXIT_MAX_BATCH;
7,239 ✔
305
    } else if (simulation::satisfy_triggers) {
146,897 ✔
306
      *status = STATUS_EXIT_ON_TRIGGER;
93 ✔
307
    } else {
308
      *status = STATUS_EXIT_NORMAL;
146,804 ✔
309
    }
310
  }
311
  return 0;
312
}
313

314
bool openmc_is_statepoint_batch()
3,135 ✔
315
{
316
  using namespace openmc;
3,135 ✔
317
  using openmc::simulation::current_gen;
3,135 ✔
318

319
  if (!simulation::initialized)
3,135 !
320
    return false;
321
  else
322
    return contains(settings::statepoint_batch, simulation::current_batch);
6,270 ✔
323
}
324

325
namespace openmc {
326

327
//==============================================================================
328
// Global variables
329
//==============================================================================
330

331
namespace simulation {
332

333
int ct_current_file;
334
int current_batch;
335
int current_gen;
336
bool initialized {false};
337
double keff {1.0};
338
double keff_std;
339
double k_col_abs {0.0};
340
double k_col_tra {0.0};
341
double k_abs_tra {0.0};
342
double log_spacing;
343
int n_lost_particles {0};
344
bool need_depletion_rx {false};
345
int restart_batch;
346
bool satisfy_triggers {false};
347
int ssw_current_file;
348
int total_gen {0};
349
double total_weight;
350
int64_t work_per_rank;
351

352
const RegularMesh* entropy_mesh {nullptr};
353
const RegularMesh* ufs_mesh {nullptr};
354

355
TemperatureField temperature_field;
356
VelocityField velocity_field;
357
std::unique_ptr<StreamlineIntegrator> streamline_integrator;
358

359
vector<double> k_generation;
360
vector<int64_t> work_index;
361

362
int64_t simulation_tracks_completed {0};
363

364
} // namespace simulation
365

366
namespace {
367

368
//! Collect thread-local secondary banks into the shared secondary bank in
369
//! sorted order.
370
//!
371
//! \param thread_banks  Secondary banks produced by each OpenMP thread
372
void collect_sorted_history_secondary_banks(
39,633 ✔
373
  vector<vector<SourceSite>>& thread_banks)
374
{
375
  // Count the total number of all secondary sites produced
376
  int64_t n_collected = 0;
39,633 ✔
377
  for (const auto& bank : thread_banks) {
101,189 ✔
378
    n_collected += bank.size();
61,556 ✔
379
  }
380

381
  // Count the expected number of progeny from per-parent progeny counts
382
  int64_t n_progeny = 0;
39,633 ✔
383
  for (int64_t count : simulation::progeny_per_particle) {
16,060,476 ✔
384
    n_progeny += count;
16,020,843 ✔
385
  }
386

387
  if (n_collected != n_progeny) {
39,633 !
388
    fatal_error("Mismatch detected between sum of all particle progeny and "
×
389
                "secondary bank size during collection.");
390
  }
391

392
  // Convert per-parent progeny counts to offsets into the sorted bank
393
  std::exclusive_scan(simulation::progeny_per_particle.begin(),
39,633 ✔
394
    simulation::progeny_per_particle.end(),
395
    simulation::progeny_per_particle.begin(), 0);
396

397
  // Allocate the shared bank once for the complete generation
398
  simulation::shared_secondary_bank_write.resize(0);
39,633 ✔
399
  simulation::shared_secondary_bank_write.extend_uninitialized(n_progeny);
39,633 ✔
400

401
  // Place each secondary according to its parent and progeny identifiers
402
  for (const auto& bank : thread_banks) {
101,189 ✔
403
    for (const auto& site : bank) {
15,185,419 ✔
404
      if (site.parent_id < 0 ||
15,123,863 !
405
          site.parent_id >=
15,123,863 !
406
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
15,123,863 !
407
        fatal_error(fmt::format("Invalid parent_id {} for banked site "
×
408
                                "(expected range [0, {})).",
409
          site.parent_id, simulation::progeny_per_particle.size()));
×
410
      }
411
      int64_t idx =
15,123,863 ✔
412
        simulation::progeny_per_particle[site.parent_id] + site.progeny_id;
15,123,863 !
413
      if (idx < 0 || idx >= n_progeny) {
15,123,863 !
414
        fatal_error("Mismatch detected between sum of all particle progeny and "
×
415
                    "secondary bank size during collection.");
416
      }
417
      simulation::shared_secondary_bank_write[idx] = site;
15,123,863 ✔
418
    }
419
  }
420
}
39,633 ✔
421

422
//! Collect particle-local secondary banks into the shared secondary bank.
423
//!
424
//! \param n_particles  Number of particles in the active event-based buffer
425
void collect_event_secondary_banks(int64_t n_particles)
705 ✔
426
{
427
  // Compute offsets for each particle's local secondary bank.
428
  vector<int64_t> offsets(n_particles);
705 ✔
429
  int64_t total = 0;
705 ✔
430
  for (int64_t i = 0; i < n_particles; ++i) {
330,405 ✔
431
    offsets[i] = total;
329,700 ✔
432
    total += simulation::particles[i].local_secondary_bank().size();
329,700 ✔
433
  }
434

435
  // Extend the shared bank once for all collected secondaries
436
  int64_t bank_offset =
705 ✔
437
    simulation::shared_secondary_bank_write.extend_uninitialized(total);
705 !
438

439
  // Copy each local bank into its assigned range and clear the local storage
440
#pragma omp parallel for schedule(static)
705 ✔
441
  for (int64_t i = 0; i < n_particles; ++i) {
×
442
    auto& local_bank = simulation::particles[i].local_secondary_bank();
×
443
    if (!local_bank.empty()) {
×
444
      std::copy(local_bank.cbegin(), local_bank.cend(),
445
        simulation::shared_secondary_bank_write.data() + bank_offset +
446
          offsets[i]);
447
      local_bank.clear();
×
448
    }
449
  }
450
}
705 ✔
451

452
} // namespace
453

454
//==============================================================================
455
// Non-member functions
456
//==============================================================================
457

458
void allocate_banks()
8,253 ✔
459
{
460
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,253 ✔
461
      settings::solver_type == SolverType::MONTE_CARLO) {
4,721 ✔
462
    // Allocate source bank
463
    simulation::source_bank.resize(simulation::work_per_rank);
4,350 ✔
464

465
    // Allocate fission bank
466
    init_fission_bank(3 * simulation::work_per_rank);
4,350 ✔
467

468
    // Allocate IFP bank
469
    if (settings::ifp_on) {
4,350 ✔
470
      resize_simulation_ifp_banks();
74 ✔
471
    }
472
  }
473

474
  if (settings::surf_source_write) {
8,253 ✔
475
    // Allocate surface source bank
476
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,176 ✔
477
  }
478

479
  if (settings::collision_track) {
8,253 ✔
480
    // Allocate collision track bank
481
    collision_track_reserve_bank();
160 ✔
482
  }
483
}
8,253 ✔
484

485
void initialize_batch()
175,991 ✔
486
{
487
  // Increment current batch
488
  ++simulation::current_batch;
175,991 ✔
489
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
175,991 ✔
490
    if (settings::solver_type == SolverType::RANDOM_RAY &&
70,468 ✔
491
        simulation::current_batch < settings::n_inactive + 1) {
14,992 ✔
492
      write_message(
18,132 ✔
493
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
494
    } else {
495
      write_message(6, "Simulating batch {}", simulation::current_batch);
122,804 ✔
496
    }
497
  }
498

499
  // Reset total starting particle weight used for normalizing tallies
500
  simulation::total_weight = 0.0;
175,991 ✔
501

502
  // Determine if this batch is the first inactive or active batch.
503
  bool first_inactive = false;
175,991 ✔
504
  bool first_active = false;
175,991 ✔
505
  if (!settings::restart_run) {
175,991 ✔
506
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
175,828 ✔
507
    first_active = simulation::current_batch == settings::n_inactive + 1;
175,828 ✔
508
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
163 ✔
509
    first_inactive = simulation::restart_batch < settings::n_inactive;
52 ✔
510
    first_active = !first_inactive;
52 ✔
511
  }
512

513
  // Manage active/inactive timers and activate tallies if necessary.
514
  if (first_inactive) {
175,880 ✔
515
    simulation::time_inactive.start();
3,939 ✔
516
  } else if (first_active) {
172,052 ✔
517
    simulation::time_inactive.stop();
8,206 ✔
518
    simulation::time_active.start();
8,206 ✔
519
    for (auto& t : model::tallies) {
36,346 ✔
520
      t->active_ = true;
28,140 ✔
521
    }
522
  }
523

524
  // Add user tallies to active tallies list
525
  setup_active_tallies();
175,991 ✔
526
}
175,991 ✔
527

528
void finalize_batch()
175,978 ✔
529
{
530
  // Reduce tallies onto master process and accumulate
531
  simulation::time_tallies.start();
175,978 ✔
532
  accumulate_tallies();
175,978 ✔
533
  simulation::time_tallies.stop();
175,978 ✔
534

535
  // update weight windows if needed
536
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
179,490 ✔
537
    wwg->update();
3,512 ✔
538
  }
539

540
  // Reset global tally results
541
  if (simulation::current_batch <= settings::n_inactive) {
175,978 ✔
542
    simulation::global_tallies.fill(0.0);
33,323 ✔
543
    simulation::n_realizations = 0;
33,323 ✔
544
  }
545

546
  // Check_triggers
547
  if (mpi::master)
175,978 ✔
548
    check_triggers();
155,775 ✔
549
#ifdef OPENMC_MPI
550
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
77,224 ✔
551
#endif
552
  if (simulation::satisfy_triggers ||
175,978 ✔
553
      (settings::trigger_on &&
2,567 ✔
554
        simulation::current_batch == settings::n_max_batches)) {
2,567 ✔
555
    settings::statepoint_batch.insert(simulation::current_batch);
141 ✔
556
  }
557

558
  // Write out state point if it's been specified for this batch and is not
559
  // a CMFD run instance
560
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
351,956 ✔
561
      !settings::cmfd_run) {
8,508 ✔
562
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
16,386 ✔
563
        settings::source_write && !settings::source_separate) {
15,459 ✔
564
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
7,056 ✔
565
      openmc_statepoint_write(nullptr, &b);
7,056 ✔
566
    } else {
567
      bool b = false;
1,276 ✔
568
      openmc_statepoint_write(nullptr, &b);
1,276 ✔
569
    }
570
  }
571

572
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,978 ✔
573
    // Write out a separate source point if it's been specified for this batch
574
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
110,270 ✔
575
        settings::source_write && settings::source_separate) {
109,899 ✔
576

577
      // Determine width for zero padding
578
      int w = std::to_string(settings::n_max_batches).size();
71 ✔
579
      std::string source_point_filename = fmt::format("{0}source.{1:0{2}}",
71 ✔
580
        settings::path_output, simulation::current_batch, w);
71 ✔
581
      span<SourceSite> bankspan(simulation::source_bank);
71 ✔
582
      write_source_point(source_point_filename, bankspan,
142 ✔
583
        simulation::work_index, settings::source_mcpl_write);
584
    }
71 ✔
585

586
    // Write a continously-overwritten source point if requested.
587
    if (settings::source_latest) {
105,523 ✔
588
      auto filename = settings::path_output + "source";
150 ✔
589
      span<SourceSite> bankspan(simulation::source_bank);
150 ✔
590
      write_source_point(filename, bankspan, simulation::work_index,
300 ✔
591
        settings::source_mcpl_write);
592
    }
150 ✔
593
  }
594

595
  // Write out surface source if requested.
596
  if (settings::surf_source_write &&
175,978 ✔
597
      simulation::ssw_current_file <= settings::ssw_max_files) {
17,889 ✔
598
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,998 ✔
599
    if (simulation::surf_source_bank.full() || last_batch) {
1,998 ✔
600
      // Determine appropriate filename
601
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
1,209 ✔
602
        simulation::current_batch);
1,209 ✔
603
      if (settings::ssw_max_files == 1 ||
1,209 ✔
604
          (simulation::ssw_current_file == 1 && last_batch)) {
55 !
605
        filename = settings::path_output + "surface_source";
1,154 ✔
606
      }
607

608
      // Get span of source bank and calculate parallel index vector
609
      auto surf_work_index = mpi::calculate_parallel_index_vector(
1,209 ✔
610
        simulation::surf_source_bank.size());
1,209 ✔
611
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
1,209 ✔
612
        simulation::surf_source_bank.size());
1,209 ✔
613

614
      // Write surface source file
615
      write_source_point(
1,209 ✔
616
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
617

618
      // Reset surface source bank and increment counter
619
      simulation::surf_source_bank.clear();
1,209 ✔
620
      if (!last_batch && settings::ssw_max_files >= 1) {
1,209 !
621
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,027 ✔
622
      }
623
      ++simulation::ssw_current_file;
1,209 ✔
624
    }
1,209 ✔
625
  }
626
  // Write collision track file if requested
627
  if (settings::collision_track) {
175,978 ✔
628
    collision_track_flush_bank();
580 ✔
629
  }
630
}
175,978 ✔
631

632
void initialize_generation()
176,201 ✔
633
{
634
  if (settings::run_mode == RunMode::EIGENVALUE) {
176,201 ✔
635
    // Clear out the fission bank
636
    simulation::fission_bank.resize(0);
105,733 ✔
637

638
    // Count source sites if using uniform fission source weighting
639
    if (settings::ufs_on)
105,733 ✔
640
      ufs_count_sites();
150 ✔
641

642
    // Store current value of tracklength k
643
    simulation::keff_generation = simulation::global_tallies(
105,733 ✔
644
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
645
  }
646
}
176,201 ✔
647

648
void finalize_generation()
176,188 ✔
649
{
650
  auto& gt = simulation::global_tallies;
176,188 ✔
651

652
  // Update global tallies with the accumulation variables
653
  if (settings::run_mode == RunMode::EIGENVALUE) {
176,188 ✔
654
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
105,733 ✔
655
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
105,733 ✔
656
      global_tally_absorption;
657
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
105,733 ✔
658
      global_tally_tracklength;
659
  }
660
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
176,188 ✔
661

662
  // reset tallies
663
  if (settings::run_mode == RunMode::EIGENVALUE) {
176,188 ✔
664
    global_tally_collision = 0.0;
105,733 ✔
665
    global_tally_absorption = 0.0;
105,733 ✔
666
    global_tally_tracklength = 0.0;
105,733 ✔
667
  }
668
  global_tally_leakage = 0.0;
176,188 ✔
669

670
  if (settings::run_mode == RunMode::EIGENVALUE &&
176,188 ✔
671
      settings::solver_type == SolverType::MONTE_CARLO) {
105,733 ✔
672
    // If using shared memory, stable sort the fission bank (by parent IDs)
673
    // so as to allow for reproducibility regardless of which order particles
674
    // are run in.
675
    sort_bank(simulation::fission_bank, true);
98,883 ✔
676

677
    // Distribute fission bank across processors evenly
678
    synchronize_bank();
98,883 ✔
679
  }
680

681
  if (settings::run_mode == RunMode::EIGENVALUE) {
176,188 ✔
682

683
    // Calculate shannon entropy
684
    if (settings::entropy_on &&
105,733 ✔
685
        settings::solver_type == SolverType::MONTE_CARLO)
14,535 ✔
686
      shannon_entropy();
7,685 ✔
687

688
    // Collect results and statistics
689
    calculate_generation_keff();
105,733 ✔
690
    calculate_average_keff();
105,733 ✔
691

692
    // Write generation output
693
    if (mpi::master && settings::verbosity >= 7) {
105,733 ✔
694
      print_generation();
79,468 ✔
695
    }
696
  }
697
}
176,188 ✔
698

699
void sample_source_particle(Particle& p, int64_t index_source)
180,285,198 ✔
700
{
701
  // Sample a particle from the source bank
702
  if (settings::run_mode == RunMode::EIGENVALUE) {
180,285,198 ✔
703
    p.from_source(&simulation::source_bank[index_source - 1]);
152,241,000 ✔
704
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
28,044,198 !
705
    // initialize random number seed
706
    int64_t id = compute_transport_seed(compute_particle_id(index_source));
28,044,198 ✔
707
    uint64_t seed = init_seed(id, STREAM_SOURCE);
28,044,198 ✔
708
    // sample from external source distribution or custom library then set
709
    auto site = sample_external_source(&seed);
28,044,198 ✔
710
    p.from_source(&site);
28,044,194 ✔
711
  }
712
}
180,285,194 ✔
713

714
void initialize_particle_track(
195,736,911 ✔
715
  Particle& p, int64_t index_source, bool is_secondary)
716
{
717
  // Note: index_source is 1-based (first particle = 1), but current_work() is
718
  // stored as 0-based for direct use as an array index into
719
  // progeny_per_particle, source_bank, ifp banks, etc.
720
  if (!is_secondary) {
195,736,911 ✔
721
    sample_source_particle(p, index_source);
180,285,198 ✔
722
  }
723

724
  p.current_work() = index_source - 1;
195,736,907 ✔
725

726
  // set identifier for particle
727
  p.id() = compute_particle_id(index_source);
195,736,907 ✔
728

729
  // set progeny count to zero
730
  p.n_progeny() = 0;
195,736,907 ✔
731

732
  // Reset particle event counter
733
  p.n_event() = 0;
195,736,907 ✔
734

735
  // Initialize track counter (1 for this primary/secondary track)
736
  p.n_tracks() = 1;
195,736,907 ✔
737

738
  // Reset split counter
739
  p.n_split() = 0;
195,736,907 ✔
740

741
  // Reset weight window ratio
742
  p.ww_factor() = 0.0;
195,736,907 ✔
743

744
  // set particle history start weight
745
  p.wgt_born() = p.wgt();
195,736,907 ✔
746

747
  // Reset pulse_height_storage
748
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
195,736,907 ✔
749

750
  // set random number seed
751
  int64_t particle_seed = compute_transport_seed(p.id());
195,736,907 ✔
752
  init_particle_seeds(particle_seed, p.seeds());
195,736,907 ✔
753

754
  // set particle trace
755
  p.trace() = false;
195,736,907 ✔
756
  if (simulation::current_batch == settings::trace_batch &&
195,747,907 ✔
757
      simulation::current_gen == settings::trace_gen &&
195,736,907 !
758
      p.id() == settings::trace_particle)
11,000 ✔
759
    p.trace() = true;
11 ✔
760

761
  // Set particle track.
762
  p.write_track() = check_track_criteria(p);
195,736,907 ✔
763

764
  // Set the particle's initial weight window value.
765
  if (!is_secondary) {
195,736,907 ✔
766
    p.wgt_ww_born() = -1.0;
180,285,194 ✔
767
    apply_weight_windows(p);
180,285,194 ✔
768
  }
769

770
  // Display message if high verbosity or trace is on
771
  if (settings::verbosity >= 9 || p.trace()) {
195,736,907 !
772
    write_message("Simulating Particle {}", p.id());
22 ✔
773
  }
774

775
  // Add particle's starting weight to count for normalizing tallies later
776
  if (!is_secondary) {
195,736,907 ✔
777
#pragma omp atomic
100,082,150 ✔
778
    simulation::total_weight += p.wgt();
180,285,194 ✔
779
  }
780

781
  // Force calculation of cross-sections by setting last energy to zero
782
  if (settings::run_CE) {
195,736,907 ✔
783
    p.invalidate_neutron_xs();
81,188,363 ✔
784
  }
785

786
  // Prepare to write out particle track.
787
  if (p.write_track())
195,736,907 ✔
788
    add_particle_track(p);
999 ✔
789
}
195,736,907 ✔
790

791
int overall_generation()
206,816,069 ✔
792
{
793
  using namespace simulation;
206,816,069 ✔
794
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
206,816,069 ✔
795
}
796

797
int64_t compute_particle_id(int64_t index_source)
223,781,380 ✔
798
{
799
  if (settings::use_shared_secondary_bank) {
223,781,380 ✔
800
    return simulation::work_index[mpi::rank] + index_source +
17,249,428 ✔
801
           simulation::simulation_tracks_completed;
17,249,428 ✔
802
  } else {
803
    return simulation::work_index[mpi::rank] + index_source;
206,531,952 ✔
804
  }
805
}
806

807
int64_t compute_transport_seed(int64_t particle_id)
223,781,424 ✔
808
{
809
  if (settings::use_shared_secondary_bank) {
223,781,424 ✔
810
    return particle_id;
811
  } else {
812
    return (simulation::total_gen + overall_generation() - 1) *
206,531,985 ✔
813
             settings::n_particles +
814
           particle_id;
206,531,985 ✔
815
  }
816
}
817

818
void calculate_work(int64_t n_particles)
48,612 ✔
819
{
820
  // Determine minimum amount of particles to simulate on each processor
821
  int64_t min_work = n_particles / mpi::n_procs;
48,612 ✔
822

823
  // Determine number of processors that have one extra particle
824
  int64_t remainder = n_particles % mpi::n_procs;
48,612 ✔
825

826
  int64_t i_bank = 0;
48,612 ✔
827
  simulation::work_index.resize(mpi::n_procs + 1);
48,612 ✔
828
  simulation::work_index[0] = 0;
48,612 ✔
829
  for (int i = 0; i < mpi::n_procs; ++i) {
105,383 ✔
830
    // Number of particles for rank i
831
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
56,771 ✔
832

833
    // Set number of particles
834
    if (mpi::rank == i)
56,771 ✔
835
      simulation::work_per_rank = work_i;
48,612 ✔
836

837
    // Set index into source bank for rank i
838
    i_bank += work_i;
56,771 ✔
839
    simulation::work_index[i + 1] = i_bank;
56,771 ✔
840
  }
841
}
48,612 ✔
842

843
void initialize_data()
6,842 ✔
844
{
845
  // Determine minimum/maximum energy for incident neutron/photon data
846
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
6,842 ✔
847
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
6,842 ✔
848

849
  for (const auto& nuc : data::nuclides) {
42,154 ✔
850
    if (nuc->grid_.size() >= 1) {
35,312 !
851
      int neutron = ParticleType::neutron().transport_index();
35,312 ✔
852
      data::energy_min[neutron] =
35,312 ✔
853
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
41,589 ✔
854
      data::energy_max[neutron] =
35,312 ✔
855
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
43,223 ✔
856
    }
857
  }
858

859
  if (settings::photon_transport) {
6,842 ✔
860
    for (const auto& elem : data::elements) {
2,084 ✔
861
      if (elem->energy_.size() >= 1) {
1,513 !
862
        int photon = ParticleType::photon().transport_index();
1,513 ✔
863
        int n = elem->energy_.size();
1,513 ✔
864
        data::energy_min[photon] =
3,026 ✔
865
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
2,486 ✔
866
        data::energy_max[photon] =
1,513 ✔
867
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
2,084 ✔
868
      }
869
    }
870

871
    if (settings::electron_treatment == ElectronTreatment::TTB) {
571 ✔
872
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
873
      // than the current minimum/maximum
874
      if (data::ttb_e_grid.size() >= 1) {
497 !
875
        int photon = ParticleType::photon().transport_index();
497 ✔
876
        int electron = ParticleType::electron().transport_index();
497 ✔
877
        int positron = ParticleType::positron().transport_index();
497 ✔
878
        int n_e = data::ttb_e_grid.size();
497 ✔
879

880
        const std::vector<int> charged = {electron, positron};
497 ✔
881
        for (auto t : charged) {
1,491 ✔
882
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
994 ✔
883
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
994 ✔
884
        }
885

886
        data::energy_min[photon] =
994 ✔
887
          std::max(data::energy_min[photon], data::energy_min[electron]);
994 !
888

889
        data::energy_max[photon] =
994 ✔
890
          std::min(data::energy_max[photon], data::energy_max[electron]);
994 !
891
      }
497 ✔
892
    }
893
  }
894

895
  // Show which nuclide results in lowest energy for neutron transport
896
  for (const auto& nuc : data::nuclides) {
8,595 ✔
897
    // If a nuclide is present in a material that's not used in the model, its
898
    // grid has not been allocated
899
    if (nuc->grid_.size() > 0) {
8,030 !
900
      double max_E = nuc->grid_[0].energy.back();
8,030 ✔
901
      int neutron = ParticleType::neutron().transport_index();
8,030 ✔
902
      if (max_E == data::energy_max[neutron]) {
8,030 ✔
903
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
6,277 ✔
904
          data::energy_max[neutron], nuc->name_);
6,277 ✔
905
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
6,277 !
906
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
907
                  "the results.");
908
        }
909
        break;
910
      }
911
    }
912
  }
913

914
  // Set up logarithmic grid for nuclides
915
  for (auto& nuc : data::nuclides) {
42,154 ✔
916
    nuc->init_grid();
35,312 ✔
917
  }
918
  int neutron = ParticleType::neutron().transport_index();
6,842 ✔
919
  simulation::log_spacing =
13,684 ✔
920
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,842 ✔
921
    settings::n_log_bins;
922
}
6,842 ✔
923

924
#ifdef OPENMC_MPI
925
void broadcast_results()
3,706 ✔
926
{
927
  // Broadcast tally results so that each process has access to results
928
  for (auto& t : model::tallies) {
17,647 ✔
929
    // Create a new datatype that consists of all values for a given filter
930
    // bin and then use that to broadcast. This is done to minimize the
931
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
932
    auto& results = t->results_;
13,941 ✔
933

934
    auto shape = results.shape();
13,941 ✔
935
    int count_per_filter = shape[1] * shape[2];
13,941 ✔
936
    MPI_Datatype result_block;
13,941 ✔
937
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
13,941 ✔
938
    MPI_Type_commit(&result_block);
13,941 ✔
939
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
13,941 ✔
940
    MPI_Type_free(&result_block);
13,941 ✔
941
  }
13,941 ✔
942

943
  // Also broadcast global tally results
944
  auto& gt = simulation::global_tallies;
3,706 ✔
945
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,706 ✔
946

947
  // These guys are needed so that non-master processes can calculate the
948
  // combined estimate of k-effective
949
  double temp[] {
3,706 ✔
950
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,706 ✔
951
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,706 ✔
952
  simulation::k_col_abs = temp[0];
3,706 ✔
953
  simulation::k_col_tra = temp[1];
3,706 ✔
954
  simulation::k_abs_tra = temp[2];
3,706 ✔
955
}
3,706 ✔
956

957
#endif
958

959
void free_memory_simulation()
9,442 ✔
960
{
961
  simulation::k_generation.clear();
9,442 ✔
962
  simulation::entropy.clear();
9,442 ✔
963
}
9,442 ✔
964

965
void transport_history_based_single_particle(Particle& p)
183,024,701 ✔
966
{
967
  while (p.alive()) {
2,147,483,647 ✔
968
    p.event_calculate_xs();
2,147,483,647 ✔
969
    if (p.alive()) {
2,147,483,647 !
970
      p.event_advance();
2,147,483,647 ✔
971
    }
972
    if (p.alive()) {
2,147,483,647 !
973
      switch (p.next_event().event_type) {
2,147,483,647 !
974
      case EVENT_CROSS_SURFACE:
2,147,483,647 ✔
975
        p.event_cross_surface();
2,147,483,647 ✔
976
        break;
2,147,483,647 ✔
977
      case EVENT_COLLIDE:
2,147,483,647 ✔
978
        p.event_collide();
2,147,483,647 ✔
979
        break;
2,147,483,647 ✔
980
      case EVENT_TIME_CUTOFF:
223,928 ✔
981
        p.wgt() = 0.0;
223,928 ✔
982
        break;
223,928 ✔
NEW
983
      default:
×
NEW
984
        fatal_error(
×
NEW
985
          fmt::format("Unknown event '{}' in history-based transport!",
×
NEW
986
            p.next_event().event_type));
×
987
        break;
988
      }
989
    }
990
    p.event_check_limit_and_revive();
2,147,483,647 ✔
991
  }
992
  p.event_death();
183,024,692 ✔
993
}
183,024,692 ✔
994

995
void transport_history_based()
147,775 ✔
996
{
997
#pragma omp parallel
82,439 ✔
998
  {
65,336 ✔
999
    Particle p;
65,336 ✔
1000
#pragma omp for schedule(runtime)
1001
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
81,516,741 ✔
1002
      initialize_particle_track(p, i_work, false);
81,451,414 ✔
1003
      transport_history_based_single_particle(p);
81,451,410 ✔
1004
    }
1005
  }
65,327 ✔
1006
}
147,766 ✔
1007

1008
// The shared secondary bank transport algorithm works in two phases. In the
1009
// first phase, all primary particles are sampled then transported, and their
1010
// secondary particles are deposited into a shared secondary bank. The second
1011
// phase occurs in a loop, where all secondary tracks in the shared secondary
1012
// bank are transported. Any secondary particles generated during this phase are
1013
// deposited back into the shared secondary bank. The shared secondary bank is
1014
// sorted for consistent ordering and load balanced across MPI ranks. This loop
1015
// continues until there are no more secondary tracks left to transport.
1016
void transport_history_based_shared_secondary()
3,062 ✔
1017
{
1018
  // Clear shared secondary banks from any prior use
1019
  simulation::shared_secondary_bank_read.clear();
3,062 ✔
1020
  simulation::shared_secondary_bank_write.clear();
3,062 ✔
1021

1022
  if (mpi::master) {
3,062 ✔
1023
    write_message(fmt::format(" Primary source          particles: {}",
5,860 ✔
1024
                    settings::n_particles),
1025
      6);
1026
  }
1027

1028
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
3,062 ✔
1029
  std::fill(simulation::progeny_per_particle.begin(),
6,124 ✔
1030
    simulation::progeny_per_particle.end(), 0);
3,062 ✔
1031

1032
  vector<vector<SourceSite>> thread_banks(num_threads());
3,062 ✔
1033

1034
  // Phase 1: Transport primary particles and deposit first generation of
1035
  // secondaries in the shared secondary bank
1036
#pragma omp parallel
1,694 ✔
1037
  {
1,368 ✔
1038
    auto& thread_bank = thread_banks[thread_num()];
1,368 ✔
1039
    Particle p;
1,368 ✔
1040

1041
#pragma omp for schedule(runtime)
1042
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
409,118 ✔
1043
      initialize_particle_track(p, i, false);
407,750 ✔
1044
      transport_history_based_single_particle(p);
407,750 ✔
1045
      for (auto& site : p.local_secondary_bank()) {
1,127,695 ✔
1046
        thread_bank.push_back(site);
719,945 ✔
1047
      }
1048
      p.local_secondary_bank().clear();
503,710 ✔
1049
    }
1050
  }
1051
  collect_sorted_history_secondary_banks(thread_banks);
3,062 ✔
1052
  thread_banks.clear();
3,062 ✔
1053

1054
  simulation::simulation_tracks_completed += settings::n_particles;
3,062 ✔
1055

1056
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1057
  // all secondary generations
1058
  int n_generation_depth = 1;
3,062 ✔
1059
  int64_t alive_secondary = 1;
3,062 ✔
1060
  while (alive_secondary) {
39,633 ✔
1061

1062
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1063
    // that each MPI rank has an approximately equal number of secondary
1064
    // tracks. Also reports the total number of secondaries alive across
1065
    // all MPI ranks.
1066
    alive_secondary = synchronize_global_secondary_bank(
36,571 ✔
1067
      simulation::shared_secondary_bank_write);
1068

1069
    // Recalculate work for each MPI rank based on number of alive secondary
1070
    // tracks
1071
    calculate_work(alive_secondary);
36,571 ✔
1072

1073
    // Display the number of secondary tracks in this generation. This
1074
    // is useful for user monitoring so as to see if the secondary population is
1075
    // exploding and to determine how many generations of secondaries are being
1076
    // transported.
1077
    if (mpi::master) {
36,571 ✔
1078
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
67,406 ✔
1079
                      n_generation_depth, alive_secondary),
1080
        6);
1081
    }
1082

1083
    simulation::shared_secondary_bank_read =
36,571 ✔
1084
      std::move(simulation::shared_secondary_bank_write);
36,571 ✔
1085
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
36,571 !
1086
    simulation::progeny_per_particle.resize(
36,571 ✔
1087
      simulation::shared_secondary_bank_read.size());
36,571 ✔
1088
    std::fill(simulation::progeny_per_particle.begin(),
73,142 ✔
1089
      simulation::progeny_per_particle.end(), 0);
36,571 ✔
1090
    thread_banks.resize(num_threads());
36,571 ✔
1091

1092
    // Transport all secondary tracks from the shared secondary bank
1093
#pragma omp parallel
20,229 ✔
1094
    {
16,342 ✔
1095
      auto& thread_bank = thread_banks[thread_num()];
16,342 ✔
1096
      Particle p;
16,342 ✔
1097

1098
#pragma omp for schedule(runtime)
1099
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
7,036,757 ✔
1100
           i++) {
1101
        initialize_particle_track(p, i, true);
7,020,415 ✔
1102
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
7,020,415 ✔
1103
        p.event_revive_from_secondary(site);
7,020,415 ✔
1104
        transport_history_based_single_particle(p);
7,020,415 ✔
1105
        for (auto& secondary_site : p.local_secondary_bank()) {
13,320,885 ✔
1106
          thread_bank.push_back(secondary_site);
6,300,470 ✔
1107
        }
1108
        p.local_secondary_bank().clear();
9,504,010 ✔
1109
      }
1110
    } // End of transport loop over tracks in shared secondary bank
1111
    simulation::shared_secondary_bank_write =
36,571 ✔
1112
      std::move(simulation::shared_secondary_bank_read);
36,571 ✔
1113
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
36,571 !
1114
    collect_sorted_history_secondary_banks(thread_banks);
36,571 ✔
1115
    thread_banks.clear();
36,571 ✔
1116
    n_generation_depth++;
36,571 ✔
1117
    simulation::simulation_tracks_completed += alive_secondary;
36,571 ✔
1118
  } // End of loop over secondary generations
1119

1120
  // Reset work so that fission bank etc works correctly
1121
  calculate_work(settings::n_particles);
3,062 ✔
1122
}
3,062 ✔
1123

1124
void transport_event_based()
3,501 ✔
1125
{
1126
  int64_t remaining_work = simulation::work_per_rank;
3,501 ✔
1127
  int64_t source_offset = 0;
3,501 ✔
1128

1129
  // To cap the total amount of memory used to store particle object data, the
1130
  // number of particles in flight at any point in time can bet set. In the case
1131
  // that the maximum in flight particle count is lower than the total number
1132
  // of particles that need to be run this iteration, the event-based transport
1133
  // loop is executed multiple times until all particles have been completed.
1134
  while (remaining_work > 0) {
7,002 ✔
1135
    // Figure out # of particles to run for this subiteration
1136
    int64_t n_particles =
3,501 !
1137
      std::min(remaining_work, settings::max_particles_in_flight);
3,501 ✔
1138

1139
    // Initialize all particle histories for this subiteration
1140
    process_init_events(n_particles, source_offset);
3,501 ✔
1141
    process_transport_events();
3,501 ✔
1142
    process_death_events(n_particles);
3,501 ✔
1143

1144
    // Adjust remaining work and source offset variables
1145
    remaining_work -= n_particles;
3,501 ✔
1146
    source_offset += n_particles;
3,501 ✔
1147
  }
1148
}
3,501 ✔
1149

1150
void transport_event_based_shared_secondary()
21 ✔
1151
{
1152
  // Clear shared secondary banks from any prior use
1153
  simulation::shared_secondary_bank_read.clear();
21 ✔
1154
  simulation::shared_secondary_bank_write.clear();
21 ✔
1155

1156
  if (mpi::master) {
21 !
1157
    write_message(fmt::format(" Primary source          particles: {}",
42 !
1158
                    settings::n_particles),
1159
      6);
1160
  }
1161

1162
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
21 ✔
1163
  std::fill(simulation::progeny_per_particle.begin(),
42 ✔
1164
    simulation::progeny_per_particle.end(), 0);
21 ✔
1165

1166
  // Phase 1: Transport primary particles using event-based processing and
1167
  // deposit first generation of secondaries in the shared secondary bank
1168
  int64_t remaining_work = simulation::work_per_rank;
21 ✔
1169
  int64_t source_offset = 0;
21 ✔
1170

1171
  while (remaining_work > 0) {
42 ✔
1172
    int64_t n_particles =
21 !
1173
      std::min(remaining_work, settings::max_particles_in_flight);
21 ✔
1174

1175
    process_init_events(n_particles, source_offset);
21 ✔
1176
    process_transport_events();
21 ✔
1177
    process_death_events(n_particles);
21 ✔
1178

1179
    collect_event_secondary_banks(n_particles);
21 ✔
1180

1181
    remaining_work -= n_particles;
21 ✔
1182
    source_offset += n_particles;
21 ✔
1183
  }
1184

1185
  simulation::simulation_tracks_completed += settings::n_particles;
21 ✔
1186

1187
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1188
  // all secondary generations
1189
  int n_generation_depth = 1;
21 ✔
1190
  int64_t alive_secondary = 1;
21 ✔
1191
  while (alive_secondary) {
726 ✔
1192

1193
    // Sort the shared secondary bank by parent ID then progeny ID to
1194
    // ensure reproducibility.
1195
    sort_bank(simulation::shared_secondary_bank_write, false);
705 ✔
1196

1197
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1198
    // that each MPI rank has an approximately equal number of secondary
1199
    // tracks.
1200
    alive_secondary = synchronize_global_secondary_bank(
705 ✔
1201
      simulation::shared_secondary_bank_write);
1202

1203
    // Recalculate work for each MPI rank based on number of alive secondary
1204
    // tracks
1205
    calculate_work(alive_secondary);
705 ✔
1206

1207
    if (mpi::master) {
705 !
1208
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
1,410 !
1209
                      n_generation_depth, alive_secondary),
1210
        6);
1211
    }
1212

1213
    simulation::shared_secondary_bank_read =
705 ✔
1214
      std::move(simulation::shared_secondary_bank_write);
705 ✔
1215
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
705 !
1216
    simulation::progeny_per_particle.resize(
705 ✔
1217
      simulation::shared_secondary_bank_read.size());
705 ✔
1218
    std::fill(simulation::progeny_per_particle.begin(),
1,410 ✔
1219
      simulation::progeny_per_particle.end(), 0);
705 ✔
1220

1221
    // Ensure particle buffer is large enough for this secondary generation
1222
    int64_t sec_buffer_length = std::min(
705 !
1223
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
705 !
1224
      settings::max_particles_in_flight);
705 ✔
1225
    if (sec_buffer_length >
705 ✔
1226
        static_cast<int64_t>(simulation::particles.size())) {
705 ✔
1227
      init_event_queues(sec_buffer_length);
53 ✔
1228
    }
1229

1230
    // Transport secondary tracks using event-based processing
1231
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
705 ✔
1232
    int64_t sec_offset = 0;
705 ✔
1233

1234
    while (sec_remaining > 0) {
1,389 ✔
1235
      int64_t n_particles =
684 !
1236
        std::min(sec_remaining, settings::max_particles_in_flight);
684 ✔
1237

1238
      process_init_secondary_events(
684 ✔
1239
        n_particles, sec_offset, simulation::shared_secondary_bank_read);
1240
      process_transport_events();
684 ✔
1241
      process_death_events(n_particles);
684 ✔
1242

1243
      collect_event_secondary_banks(n_particles);
684 ✔
1244

1245
      sec_remaining -= n_particles;
684 ✔
1246
      sec_offset += n_particles;
684 ✔
1247
    } // End of subiteration loop over secondary tracks
1248
    n_generation_depth++;
705 ✔
1249
    simulation::simulation_tracks_completed += alive_secondary;
705 ✔
1250
  } // End of loop over secondary generations
1251

1252
  // Reset work so that fission bank etc works correctly
1253
  calculate_work(settings::n_particles);
21 ✔
1254
}
21 ✔
1255

1256
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc