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

openmc-dev / openmc / 29547392572

17 Jul 2026 01:25AM UTC coverage: 81.332% (-0.02%) from 81.348%
29547392572

push

github

web-flow
Performance optimizations for shared secondary bank (#4011)

18348 of 26613 branches covered (68.94%)

Branch coverage included in aggregate %.

58 of 63 new or added lines in 2 files covered. (92.06%)

2 existing lines in 2 files now uncovered.

59867 of 69555 relevant lines covered (86.07%)

47891676.57 hits per line

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

93.62
/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/container_util.h"
7
#include "openmc/eigenvalue.h"
8
#include "openmc/error.h"
9
#include "openmc/event.h"
10
#include "openmc/geometry_aux.h"
11
#include "openmc/ifp.h"
12
#include "openmc/material.h"
13
#include "openmc/message_passing.h"
14
#include "openmc/nuclide.h"
15
#include "openmc/openmp_interface.h"
16
#include "openmc/output.h"
17
#include "openmc/particle.h"
18
#include "openmc/photon.h"
19
#include "openmc/random_lcg.h"
20
#include "openmc/random_ray/flat_source_domain.h"
21
#include "openmc/settings.h"
22
#include "openmc/source.h"
23
#include "openmc/state_point.h"
24
#include "openmc/tallies/derivative.h"
25
#include "openmc/tallies/filter.h"
26
#include "openmc/tallies/tally.h"
27
#include "openmc/tallies/trigger.h"
28
#include "openmc/timer.h"
29
#include "openmc/track_output.h"
30
#include "openmc/weight_windows.h"
31

32
#ifdef _OPENMP
33
#include <omp.h>
34
#endif
35
#include "openmc/tensor.h"
36

37
#ifdef OPENMC_MPI
38
#include <mpi.h>
39
#endif
40

41
#include <fmt/format.h>
42

43
#include <algorithm>
44
#include <cmath>
45
#include <numeric>
46
#include <string>
47

48
//==============================================================================
49
// C API functions
50
//==============================================================================
51

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

56
int openmc_run()
6,690✔
57
{
58
  openmc::simulation::time_total.start();
6,690✔
59
  openmc_simulation_init();
6,690✔
60

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

68
  int err = 0;
69
  while (status == 0 && err == 0) {
147,402✔
70
    err = openmc_next_batch(&status);
140,725✔
71
  }
72

73
  openmc_simulation_finalize();
6,677✔
74
  openmc::simulation::time_total.stop();
6,677✔
75
  return err;
6,677✔
76
}
77

78
int openmc_simulation_init()
7,862✔
79
{
80
  using namespace openmc;
7,862✔
81

82
  // Skip if simulation has already been initialized
83
  if (simulation::initialized)
7,862✔
84
    return 0;
85

86
  // Initialize nuclear data (energy limits, log grid)
87
  if (settings::run_CE) {
7,840✔
88
    initialize_data();
6,429✔
89
  }
90

91
  // Determine how much work each process should do
92
  calculate_work(settings::n_particles);
7,840✔
93

94
  // Allocate source, fission and surface source banks.
95
  allocate_banks();
7,840✔
96

97
  // Create track file if needed
98
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,840✔
99
    open_track_file();
90✔
100
  }
101

102
  // If doing an event-based simulation, intialize the particle buffer
103
  // and event queues
104
  if (settings::event_based) {
7,840✔
105
    int64_t event_buffer_length =
222!
106
      std::min(simulation::work_per_rank, settings::max_particles_in_flight);
222✔
107
    init_event_queues(event_buffer_length);
222✔
108
  }
109

110
  // Allocate tally results arrays if they're not allocated yet
111
  for (auto& t : model::tallies) {
35,432✔
112
    t->set_strides();
27,592✔
113
    t->init_results();
27,592✔
114
  }
115

116
  // Set up material nuclide index mapping
117
  for (auto& mat : model::materials) {
27,605✔
118
    mat->init_nuclide_index();
19,765✔
119
  }
120

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

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

144
  // Display header
145
  if (mpi::master) {
7,840✔
146
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,828✔
147
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,041✔
148
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,665✔
149
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
376!
150
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
376✔
151
      }
152
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,787!
153
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,787✔
154
        header("K EIGENVALUE SIMULATION", 3);
3,512✔
155
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
275!
156
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
275✔
157
      }
158
      if (settings::verbosity >= 7)
3,787✔
159
        print_columns();
3,407✔
160
    }
161
  }
162

163
  // load weight windows from file
164
  if (!settings::weight_windows_file.empty()) {
7,840!
165
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
×
166
  }
167

168
  // Set flag indicating initialization is done
169
  simulation::initialized = true;
7,840✔
170
  return 0;
7,840✔
171
}
172

173
int openmc_simulation_finalize()
7,827✔
174
{
175
  using namespace openmc;
7,827✔
176

177
  // Skip if simulation was never run
178
  if (!simulation::initialized)
7,827!
179
    return 0;
180

181
  // Stop active batch timer and start finalization timer
182
  simulation::time_active.stop();
7,827✔
183
  simulation::time_finalize.start();
7,827✔
184

185
  // Clear material nuclide mapping
186
  for (auto& mat : model::materials) {
27,579✔
187
    mat->mat_nuclide_index_.clear();
39,504!
188
  }
189

190
  // Close track file if open
191
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,827✔
192
    close_track_file();
90✔
193
  }
194

195
  // Increment total number of generations
196
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
7,827✔
197

198
#ifdef OPENMC_MPI
199
  broadcast_results();
3,510✔
200
#endif
201

202
  // Write tally results to tallies.out
203
  if (settings::output_tallies && mpi::master)
7,827!
204
    write_tallies();
6,469✔
205

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

215
  // Deactivate all tallies
216
  for (auto& t : model::tallies) {
35,419✔
217
    t->active_ = false;
27,592✔
218
  }
219

220
  // Stop timers and show timing statistics
221
  simulation::time_finalize.stop();
7,827✔
222
  simulation::time_total.stop();
7,827✔
223

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

237
  if (mpi::master) {
7,827✔
238
    if (settings::solver_type != SolverType::RANDOM_RAY) {
6,815✔
239
      if (settings::verbosity >= 6)
6,164✔
240
        print_runtime();
5,784✔
241
      if (settings::verbosity >= 4)
6,164✔
242
        print_results();
5,784✔
243
    }
244
  }
245
  if (settings::check_overlaps)
7,827!
246
    print_overlap_check();
×
247

248
  // Reset flags
249
  simulation::initialized = false;
7,827✔
250
  return 0;
7,827✔
251
}
252

253
int openmc_next_batch(int* status)
144,850✔
254
{
255
  using namespace openmc;
144,850✔
256
  using openmc::simulation::current_gen;
144,850✔
257

258
  // Make sure simulation has been initialized
259
  if (!simulation::initialized) {
144,850✔
260
    set_errmsg("Simulation has not been initialized yet.");
11✔
261
    return OPENMC_E_ALLOCATE;
11✔
262
  }
263

264
  initialize_batch();
144,839✔
265

266
  // =======================================================================
267
  // LOOP OVER GENERATIONS
268
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
289,875✔
269

270
    initialize_generation();
145,049✔
271

272
    // Start timer for transport
273
    simulation::time_transport.start();
145,049✔
274

275
    // Transport loop
276
    if (settings::event_based) {
145,049✔
277
      if (settings::use_shared_secondary_bank) {
3,231✔
278
        transport_event_based_shared_secondary();
11✔
279
      } else {
280
        transport_event_based();
3,220✔
281
      }
282
    } else {
283
      if (settings::use_shared_secondary_bank) {
141,818✔
284
        transport_history_based_shared_secondary();
667✔
285
      } else {
286
        transport_history_based();
141,151✔
287
      }
288
    }
289

290
    // Accumulate time for transport
291
    simulation::time_transport.stop();
145,036✔
292

293
    finalize_generation();
145,036✔
294
  }
295

296
  finalize_batch();
144,826✔
297

298
  // Check simulation ending criteria
299
  if (status) {
144,826!
300
    if (simulation::current_batch >= settings::n_max_batches) {
144,826✔
301
      *status = STATUS_EXIT_MAX_BATCH;
6,870✔
302
    } else if (simulation::satisfy_triggers) {
137,956✔
303
      *status = STATUS_EXIT_ON_TRIGGER;
93✔
304
    } else {
305
      *status = STATUS_EXIT_NORMAL;
137,863✔
306
    }
307
  }
308
  return 0;
309
}
310

311
bool openmc_is_statepoint_batch()
3,135✔
312
{
313
  using namespace openmc;
3,135✔
314
  using openmc::simulation::current_gen;
3,135✔
315

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

322
namespace openmc {
323

324
//==============================================================================
325
// Global variables
326
//==============================================================================
327

328
namespace simulation {
329

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

349
const RegularMesh* entropy_mesh {nullptr};
350
const RegularMesh* ufs_mesh {nullptr};
351

352
vector<double> k_generation;
353
vector<int64_t> work_index;
354

355
int64_t simulation_tracks_completed {0};
356

357
} // namespace simulation
358

359
namespace {
360

361
//! Collect thread-local secondary banks into the shared secondary bank in
362
//! sorted order.
363
//!
364
//! \param thread_banks  Secondary banks produced by each OpenMP thread
365
void collect_sorted_history_secondary_banks(
8,918✔
366
  vector<vector<SourceSite>>& thread_banks)
367
{
368
  // Count the total number of all secondary sites produced
369
  int64_t n_collected = 0;
8,918✔
370
  for (const auto& bank : thread_banks) {
22,878✔
371
    n_collected += bank.size();
13,960✔
372
  }
373

374
  // Count the expected number of progeny from per-parent progeny counts
375
  int64_t n_progeny = 0;
8,918✔
376
  for (int64_t count : simulation::progeny_per_particle) {
21,941,812✔
377
    n_progeny += count;
21,932,894✔
378
  }
379

380
  if (n_collected != n_progeny) {
8,918!
NEW
381
    fatal_error("Mismatch detected between sum of all particle progeny and "
×
382
                "secondary bank size during collection.");
383
  }
384

385
  // Convert per-parent progeny counts to offsets into the sorted bank
386
  std::exclusive_scan(simulation::progeny_per_particle.begin(),
8,918✔
387
    simulation::progeny_per_particle.end(),
388
    simulation::progeny_per_particle.begin(), 0);
389

390
  // Allocate the shared bank once for the complete generation
391
  simulation::shared_secondary_bank_write.resize(0);
8,918✔
392
  simulation::shared_secondary_bank_write.extend_uninitialized(n_progeny);
8,918✔
393

394
  // Place each secondary according to its parent and progeny identifiers
395
  for (const auto& bank : thread_banks) {
22,878✔
396
    for (const auto& site : bank) {
21,164,019✔
397
      if (site.parent_id < 0 ||
21,150,059!
398
          site.parent_id >=
21,150,059!
399
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
21,150,059!
NEW
400
        fatal_error(fmt::format("Invalid parent_id {} for banked site "
×
401
                                "(expected range [0, {})).",
NEW
402
          site.parent_id, simulation::progeny_per_particle.size()));
×
403
      }
404
      int64_t idx =
21,150,059✔
405
        simulation::progeny_per_particle[site.parent_id] + site.progeny_id;
21,150,059!
406
      if (idx < 0 || idx >= n_progeny) {
21,150,059!
NEW
407
        fatal_error("Mismatch detected between sum of all particle progeny and "
×
408
                    "secondary bank size during collection.");
409
      }
410
      simulation::shared_secondary_bank_write[idx] = site;
21,150,059✔
411
    }
412
  }
413
}
8,918✔
414

415
//! Collect particle-local secondary banks into the shared secondary bank.
416
//!
417
//! \param n_particles  Number of particles in the active event-based buffer
418
void collect_event_secondary_banks(int64_t n_particles)
406✔
419
{
420
  // Compute offsets for each particle's local secondary bank.
421
  vector<int64_t> offsets(n_particles);
406✔
422
  int64_t total = 0;
406✔
423
  for (int64_t i = 0; i < n_particles; ++i) {
181,666✔
424
    offsets[i] = total;
181,260✔
425
    total += simulation::particles[i].local_secondary_bank().size();
181,260✔
426
  }
427

428
  // Extend the shared bank once for all collected secondaries
429
  int64_t bank_offset =
406✔
430
    simulation::shared_secondary_bank_write.extend_uninitialized(total);
406!
431

432
  // Copy each local bank into its assigned range and clear the local storage
433
#pragma omp parallel for schedule(static)
406✔
434
  for (int64_t i = 0; i < n_particles; ++i) {
×
435
    auto& local_bank = simulation::particles[i].local_secondary_bank();
×
436
    if (!local_bank.empty()) {
×
437
      std::copy(local_bank.cbegin(), local_bank.cend(),
438
        simulation::shared_secondary_bank_write.data() + bank_offset +
439
          offsets[i]);
440
      local_bank.clear();
×
441
    }
442
  }
443
}
406✔
444

445
} // namespace
446

447
//==============================================================================
448
// Non-member functions
449
//==============================================================================
450

451
void allocate_banks()
7,840✔
452
{
453
  if (settings::run_mode == RunMode::EIGENVALUE &&
7,840✔
454
      settings::solver_type == SolverType::MONTE_CARLO) {
4,481✔
455
    // Allocate source bank
456
    simulation::source_bank.resize(simulation::work_per_rank);
4,110✔
457

458
    // Allocate fission bank
459
    init_fission_bank(3 * simulation::work_per_rank);
4,110✔
460

461
    // Allocate IFP bank
462
    if (settings::ifp_on) {
4,110✔
463
      resize_simulation_ifp_banks();
74✔
464
    }
465
  }
466

467
  if (settings::surf_source_write) {
7,840✔
468
    // Allocate surface source bank
469
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,154✔
470
  }
471

472
  if (settings::collision_track) {
7,840✔
473
    // Allocate collision track bank
474
    collision_track_reserve_bank();
160✔
475
  }
476
}
7,840✔
477

478
void initialize_batch()
165,801✔
479
{
480
  // Increment current batch
481
  ++simulation::current_batch;
165,801✔
482
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
165,801✔
483
    if (settings::solver_type == SolverType::RANDOM_RAY &&
64,858✔
484
        simulation::current_batch < settings::n_inactive + 1) {
14,112✔
485
      write_message(
16,812✔
486
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
487
    } else {
488
      write_message(6, "Simulating batch {}", simulation::current_batch);
112,904✔
489
    }
490
  }
491

492
  // Reset total starting particle weight used for normalizing tallies
493
  simulation::total_weight = 0.0;
165,801✔
494

495
  // Determine if this batch is the first inactive or active batch.
496
  bool first_inactive = false;
165,801✔
497
  bool first_active = false;
165,801✔
498
  if (!settings::restart_run) {
165,801✔
499
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
165,638✔
500
    first_active = simulation::current_batch == settings::n_inactive + 1;
165,638✔
501
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
163✔
502
    first_inactive = simulation::restart_batch < settings::n_inactive;
52✔
503
    first_active = !first_inactive;
52✔
504
  }
505

506
  // Manage active/inactive timers and activate tallies if necessary.
507
  if (first_inactive) {
165,690✔
508
    simulation::time_inactive.start();
3,865✔
509
  } else if (first_active) {
161,936✔
510
    simulation::time_inactive.stop();
7,793✔
511
    simulation::time_active.start();
7,793✔
512
    for (auto& t : model::tallies) {
35,363✔
513
      t->active_ = true;
27,570✔
514
    }
515
  }
516

517
  // Add user tallies to active tallies list
518
  setup_active_tallies();
165,801✔
519
}
165,801✔
520

521
void finalize_batch()
165,788✔
522
{
523
  // Reduce tallies onto master process and accumulate
524
  simulation::time_tallies.start();
165,788✔
525
  accumulate_tallies();
165,788✔
526
  simulation::time_tallies.stop();
165,788✔
527

528
  // update weight windows if needed
529
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
168,420✔
530
    wwg->update();
2,632✔
531
  }
532

533
  // Reset global tally results
534
  if (simulation::current_batch <= settings::n_inactive) {
165,788✔
535
    simulation::global_tallies.fill(0.0);
32,603✔
536
    simulation::n_realizations = 0;
32,603✔
537
  }
538

539
  // Check_triggers
540
  if (mpi::master)
165,788✔
541
    check_triggers();
146,829✔
542
#ifdef OPENMC_MPI
543
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
72,676✔
544
#endif
545
  if (simulation::satisfy_triggers ||
165,788✔
546
      (settings::trigger_on &&
2,567✔
547
        simulation::current_batch == settings::n_max_batches)) {
2,567✔
548
    settings::statepoint_batch.insert(simulation::current_batch);
141✔
549
  }
550

551
  // Write out state point if it's been specified for this batch and is not
552
  // a CMFD run instance
553
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
331,576✔
554
      !settings::cmfd_run) {
8,095✔
555
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
15,560✔
556
        settings::source_write && !settings::source_separate) {
14,677✔
557
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
6,687✔
558
      openmc_statepoint_write(nullptr, &b);
6,687✔
559
    } else {
560
      bool b = false;
1,232✔
561
      openmc_statepoint_write(nullptr, &b);
1,232✔
562
    }
563
  }
564

565
  if (settings::run_mode == RunMode::EIGENVALUE) {
165,788✔
566
    // Write out a separate source point if it's been specified for this batch
567
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
105,450✔
568
        settings::source_write && settings::source_separate) {
105,079✔
569

570
      // Determine width for zero padding
571
      int w = std::to_string(settings::n_max_batches).size();
71✔
572
      std::string source_point_filename = fmt::format("{0}source.{1:0{2}}",
71✔
573
        settings::path_output, simulation::current_batch, w);
71✔
574
      span<SourceSite> bankspan(simulation::source_bank);
71✔
575
      write_source_point(source_point_filename, bankspan,
142✔
576
        simulation::work_index, settings::source_mcpl_write);
577
    }
71✔
578

579
    // Write a continously-overwritten source point if requested.
580
    if (settings::source_latest) {
100,943✔
581
      auto filename = settings::path_output + "source";
150✔
582
      span<SourceSite> bankspan(simulation::source_bank);
150✔
583
      write_source_point(filename, bankspan, simulation::work_index,
300✔
584
        settings::source_mcpl_write);
585
    }
150✔
586
  }
587

588
  // Write out surface source if requested.
589
  if (settings::surf_source_write &&
165,788✔
590
      simulation::ssw_current_file <= settings::ssw_max_files) {
17,669✔
591
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,976✔
592
    if (simulation::surf_source_bank.full() || last_batch) {
1,976✔
593
      // Determine appropriate filename
594
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
1,187✔
595
        simulation::current_batch);
1,187✔
596
      if (settings::ssw_max_files == 1 ||
1,187✔
597
          (simulation::ssw_current_file == 1 && last_batch)) {
55!
598
        filename = settings::path_output + "surface_source";
1,132✔
599
      }
600

601
      // Get span of source bank and calculate parallel index vector
602
      auto surf_work_index = mpi::calculate_parallel_index_vector(
1,187✔
603
        simulation::surf_source_bank.size());
1,187✔
604
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
1,187✔
605
        simulation::surf_source_bank.size());
1,187✔
606

607
      // Write surface source file
608
      write_source_point(
1,187✔
609
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
610

611
      // Reset surface source bank and increment counter
612
      simulation::surf_source_bank.clear();
1,187✔
613
      if (!last_batch && settings::ssw_max_files >= 1) {
1,187!
614
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,005✔
615
      }
616
      ++simulation::ssw_current_file;
1,187✔
617
    }
1,187✔
618
  }
619
  // Write collision track file if requested
620
  if (settings::collision_track) {
165,788✔
621
    collision_track_flush_bank();
580✔
622
  }
623
}
165,788✔
624

625
void initialize_generation()
166,011✔
626
{
627
  if (settings::run_mode == RunMode::EIGENVALUE) {
166,011✔
628
    // Clear out the fission bank
629
    simulation::fission_bank.resize(0);
101,153✔
630

631
    // Count source sites if using uniform fission source weighting
632
    if (settings::ufs_on)
101,153✔
633
      ufs_count_sites();
150✔
634

635
    // Store current value of tracklength k
636
    simulation::keff_generation = simulation::global_tallies(
101,153✔
637
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
638
  }
639
}
166,011✔
640

641
void finalize_generation()
165,998✔
642
{
643
  auto& gt = simulation::global_tallies;
165,998✔
644

645
  // Update global tallies with the accumulation variables
646
  if (settings::run_mode == RunMode::EIGENVALUE) {
165,998✔
647
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
101,153✔
648
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
101,153✔
649
      global_tally_absorption;
650
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
101,153✔
651
      global_tally_tracklength;
652
  }
653
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
165,998✔
654

655
  // reset tallies
656
  if (settings::run_mode == RunMode::EIGENVALUE) {
165,998✔
657
    global_tally_collision = 0.0;
101,153✔
658
    global_tally_absorption = 0.0;
101,153✔
659
    global_tally_tracklength = 0.0;
101,153✔
660
  }
661
  global_tally_leakage = 0.0;
165,998✔
662

663
  if (settings::run_mode == RunMode::EIGENVALUE &&
165,998✔
664
      settings::solver_type == SolverType::MONTE_CARLO) {
101,153✔
665
    // If using shared memory, stable sort the fission bank (by parent IDs)
666
    // so as to allow for reproducibility regardless of which order particles
667
    // are run in.
668
    sort_bank(simulation::fission_bank, true);
94,303✔
669

670
    // Distribute fission bank across processors evenly
671
    synchronize_bank();
94,303✔
672
  }
673

674
  if (settings::run_mode == RunMode::EIGENVALUE) {
165,998✔
675

676
    // Calculate shannon entropy
677
    if (settings::entropy_on &&
101,153✔
678
        settings::solver_type == SolverType::MONTE_CARLO)
14,535✔
679
      shannon_entropy();
7,685✔
680

681
    // Collect results and statistics
682
    calculate_generation_keff();
101,153✔
683
    calculate_average_keff();
101,153✔
684

685
    // Write generation output
686
    if (mpi::master && settings::verbosity >= 7) {
101,153✔
687
      print_generation();
76,088✔
688
    }
689
  }
690
}
165,998✔
691

692
void sample_source_particle(Particle& p, int64_t index_source)
177,381,577✔
693
{
694
  // Sample a particle from the source bank
695
  if (settings::run_mode == RunMode::EIGENVALUE) {
177,381,577✔
696
    p.from_source(&simulation::source_bank[index_source - 1]);
149,904,000✔
697
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
27,477,577!
698
    // initialize random number seed
699
    int64_t id = compute_transport_seed(compute_particle_id(index_source));
27,477,577✔
700
    uint64_t seed = init_seed(id, STREAM_SOURCE);
27,477,577✔
701
    // sample from external source distribution or custom library then set
702
    auto site = sample_external_source(&seed);
27,477,577✔
703
    p.from_source(&site);
27,477,573✔
704
  }
705
}
177,381,573✔
706

707
void initialize_particle_track(
198,711,246✔
708
  Particle& p, int64_t index_source, bool is_secondary)
709
{
710
  // Note: index_source is 1-based (first particle = 1), but current_work() is
711
  // stored as 0-based for direct use as an array index into
712
  // progeny_per_particle, source_bank, ifp banks, etc.
713
  if (!is_secondary) {
198,711,246✔
714
    sample_source_particle(p, index_source);
177,381,577✔
715
  }
716

717
  p.current_work() = index_source - 1;
198,711,242✔
718

719
  // set identifier for particle
720
  p.id() = compute_particle_id(index_source);
198,711,242✔
721

722
  // set progeny count to zero
723
  p.n_progeny() = 0;
198,711,242✔
724

725
  // Reset particle event counter
726
  p.n_event() = 0;
198,711,242✔
727

728
  // Initialize track counter (1 for this primary/secondary track)
729
  p.n_tracks() = 1;
198,711,242✔
730

731
  // Reset split counter
732
  p.n_split() = 0;
198,711,242✔
733

734
  // Reset weight window ratio
735
  p.ww_factor() = 0.0;
198,711,242✔
736

737
  // set particle history start weight
738
  p.wgt_born() = p.wgt();
198,711,242✔
739

740
  // Reset pulse_height_storage
741
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
198,711,242✔
742

743
  // set random number seed
744
  int64_t particle_seed = compute_transport_seed(p.id());
198,711,242✔
745
  init_particle_seeds(particle_seed, p.seeds());
198,711,242✔
746

747
  // set particle trace
748
  p.trace() = false;
198,711,242✔
749
  if (simulation::current_batch == settings::trace_batch &&
198,722,242✔
750
      simulation::current_gen == settings::trace_gen &&
198,711,242!
751
      p.id() == settings::trace_particle)
11,000✔
752
    p.trace() = true;
11✔
753

754
  // Set particle track.
755
  p.write_track() = check_track_criteria(p);
198,711,242✔
756

757
  // Set the particle's initial weight window value.
758
  if (!is_secondary) {
198,711,242✔
759
    p.wgt_ww_born() = -1.0;
177,381,573✔
760
    apply_weight_windows(p);
177,381,573✔
761
  }
762

763
  // Display message if high verbosity or trace is on
764
  if (settings::verbosity >= 9 || p.trace()) {
198,711,242!
765
    write_message("Simulating Particle {}", p.id());
22✔
766
  }
767

768
  // Add particle's starting weight to count for normalizing tallies later
769
  if (!is_secondary) {
198,711,242✔
770
#pragma omp atomic
97,911,123✔
771
    simulation::total_weight += p.wgt();
177,381,573✔
772
  }
773

774
  // Force calculation of cross-sections by setting last energy to zero
775
  if (settings::run_CE) {
198,711,242✔
776
    p.invalidate_neutron_xs();
84,162,698✔
777
  }
778

779
  // Prepare to write out particle track.
780
  if (p.write_track())
198,711,242✔
781
    add_particle_track(p);
999✔
782
}
198,711,242✔
783

784
int overall_generation()
203,561,977✔
785
{
786
  using namespace simulation;
203,561,977✔
787
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
203,561,977✔
788
}
789

790
int64_t compute_particle_id(int64_t index_source)
226,189,094✔
791
{
792
  if (settings::use_shared_secondary_bank) {
226,189,094✔
793
    return simulation::work_index[mpi::rank] + index_source +
22,898,694✔
794
           simulation::simulation_tracks_completed;
22,898,694✔
795
  } else {
796
    return simulation::work_index[mpi::rank] + index_source;
203,290,400✔
797
  }
798
}
799

800
int64_t compute_transport_seed(int64_t particle_id)
226,189,138✔
801
{
802
  if (settings::use_shared_secondary_bank) {
226,189,138✔
803
    return particle_id;
804
  } else {
805
    return (simulation::total_gen + overall_generation() - 1) *
203,290,433✔
806
             settings::n_particles +
807
           particle_id;
203,290,433✔
808
  }
809
}
810

811
void calculate_work(int64_t n_particles)
17,175✔
812
{
813
  // Determine minimum amount of particles to simulate on each processor
814
  int64_t min_work = n_particles / mpi::n_procs;
17,175✔
815

816
  // Determine number of processors that have one extra particle
817
  int64_t remainder = n_particles % mpi::n_procs;
17,175✔
818

819
  int64_t i_bank = 0;
17,175✔
820
  simulation::work_index.resize(mpi::n_procs + 1);
17,175✔
821
  simulation::work_index[0] = 0;
17,175✔
822
  for (int i = 0; i < mpi::n_procs; ++i) {
39,901✔
823
    // Number of particles for rank i
824
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
22,726✔
825

826
    // Set number of particles
827
    if (mpi::rank == i)
22,726✔
828
      simulation::work_per_rank = work_i;
17,175✔
829

830
    // Set index into source bank for rank i
831
    i_bank += work_i;
22,726✔
832
    simulation::work_index[i + 1] = i_bank;
22,726✔
833
  }
834
}
17,175✔
835

836
void initialize_data()
6,473✔
837
{
838
  // Determine minimum/maximum energy for incident neutron/photon data
839
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
6,473✔
840
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
6,473✔
841

842
  for (const auto& nuc : data::nuclides) {
39,779✔
843
    if (nuc->grid_.size() >= 1) {
33,306!
844
      int neutron = ParticleType::neutron().transport_index();
33,306✔
845
      data::energy_min[neutron] =
33,306✔
846
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
39,247✔
847
      data::energy_max[neutron] =
33,306✔
848
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
40,811✔
849
    }
850
  }
851

852
  if (settings::photon_transport) {
6,473✔
853
    for (const auto& elem : data::elements) {
1,999✔
854
      if (elem->energy_.size() >= 1) {
1,465!
855
        int photon = ParticleType::photon().transport_index();
1,465✔
856
        int n = elem->energy_.size();
1,465✔
857
        data::energy_min[photon] =
2,930✔
858
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
2,401✔
859
        data::energy_max[photon] =
1,465✔
860
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
1,999✔
861
      }
862
    }
863

864
    if (settings::electron_treatment == ElectronTreatment::TTB) {
534✔
865
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
866
      // than the current minimum/maximum
867
      if (data::ttb_e_grid.size() >= 1) {
475!
868
        int photon = ParticleType::photon().transport_index();
475✔
869
        int electron = ParticleType::electron().transport_index();
475✔
870
        int positron = ParticleType::positron().transport_index();
475✔
871
        int n_e = data::ttb_e_grid.size();
475✔
872

873
        const std::vector<int> charged = {electron, positron};
475✔
874
        for (auto t : charged) {
1,425✔
875
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
950✔
876
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
950✔
877
        }
878

879
        data::energy_min[photon] =
950✔
880
          std::max(data::energy_min[photon], data::energy_min[electron]);
950!
881

882
        data::energy_max[photon] =
950✔
883
          std::min(data::energy_max[photon], data::energy_max[electron]);
950!
884
      }
475✔
885
    }
886
  }
887

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

907
  // Set up logarithmic grid for nuclides
908
  for (auto& nuc : data::nuclides) {
39,779✔
909
    nuc->init_grid();
33,306✔
910
  }
911
  int neutron = ParticleType::neutron().transport_index();
6,473✔
912
  simulation::log_spacing =
12,946✔
913
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,473✔
914
    settings::n_log_bins;
915
}
6,473✔
916

917
#ifdef OPENMC_MPI
918
void broadcast_results()
3,510✔
919
{
920
  // Broadcast tally results so that each process has access to results
921
  for (auto& t : model::tallies) {
17,203✔
922
    // Create a new datatype that consists of all values for a given filter
923
    // bin and then use that to broadcast. This is done to minimize the
924
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
925
    auto& results = t->results_;
13,693✔
926

927
    auto shape = results.shape();
13,693✔
928
    int count_per_filter = shape[1] * shape[2];
13,693✔
929
    MPI_Datatype result_block;
13,693✔
930
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
13,693✔
931
    MPI_Type_commit(&result_block);
13,693✔
932
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
13,693✔
933
    MPI_Type_free(&result_block);
13,693✔
934
  }
13,693✔
935

936
  // Also broadcast global tally results
937
  auto& gt = simulation::global_tallies;
3,510✔
938
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,510✔
939

940
  // These guys are needed so that non-master processes can calculate the
941
  // combined estimate of k-effective
942
  double temp[] {
3,510✔
943
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,510✔
944
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,510✔
945
  simulation::k_col_abs = temp[0];
3,510✔
946
  simulation::k_col_tra = temp[1];
3,510✔
947
  simulation::k_abs_tra = temp[2];
3,510✔
948
}
3,510✔
949

950
#endif
951

952
void free_memory_simulation()
9,056✔
953
{
954
  simulation::k_generation.clear();
9,056✔
955
  simulation::entropy.clear();
9,056✔
956
}
9,056✔
957

958
void transport_history_based_single_particle(Particle& p)
186,365,476✔
959
{
960
  while (p.alive()) {
2,147,483,647✔
961
    p.event_calculate_xs();
2,147,483,647✔
962
    if (p.alive()) {
2,147,483,647!
963
      p.event_advance();
2,147,483,647✔
964
    }
965
    if (p.alive()) {
2,147,483,647✔
966
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
967
        p.event_cross_surface();
2,147,483,647✔
968
      } else if (p.alive()) {
2,147,483,647✔
969
        p.event_collide();
2,147,483,647✔
970
      }
971
    }
972
    p.event_check_limit_and_revive();
2,147,483,647✔
973
  }
974
  p.event_death();
186,365,467✔
975
}
186,365,467✔
976

977
void transport_history_based()
141,151✔
978
{
979
#pragma omp parallel
78,651✔
980
  {
62,500✔
981
    Particle p;
62,500✔
982
#pragma omp for schedule(runtime)
983
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,253,325✔
984
      initialize_particle_track(p, i_work, false);
80,190,834✔
985
      transport_history_based_single_particle(p);
80,190,830✔
986
    }
987
  }
62,491✔
988
}
141,142✔
989

990
// The shared secondary bank transport algorithm works in two phases. In the
991
// first phase, all primary particles are sampled then transported, and their
992
// secondary particles are deposited into a shared secondary bank. The second
993
// phase occurs in a loop, where all secondary tracks in the shared secondary
994
// bank are transported. Any secondary particles generated during this phase are
995
// deposited back into the shared secondary bank. The shared secondary bank is
996
// sorted for consistent ordering and load balanced across MPI ranks. This loop
997
// continues until there are no more secondary tracks left to transport.
998
void transport_history_based_shared_secondary()
667✔
999
{
1000
  // Clear shared secondary banks from any prior use
1001
  simulation::shared_secondary_bank_read.clear();
667✔
1002
  simulation::shared_secondary_bank_write.clear();
667✔
1003

1004
  if (mpi::master) {
667✔
1005
    write_message(fmt::format(" Primary source          particles: {}",
1,150✔
1006
                    settings::n_particles),
1007
      6);
1008
  }
1009

1010
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
667✔
1011
  std::fill(simulation::progeny_per_particle.begin(),
1,334✔
1012
    simulation::progeny_per_particle.end(), 0);
667✔
1013

1014
  vector<vector<SourceSite>> thread_banks(num_threads());
667✔
1015

1016
  // Phase 1: Transport primary particles and deposit first generation of
1017
  // secondaries in the shared secondary bank
1018
#pragma omp parallel
384✔
1019
  {
283✔
1020
    auto& thread_bank = thread_banks[thread_num()];
283✔
1021
    Particle p;
283✔
1022

1023
#pragma omp for schedule(runtime)
1024
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
356,058✔
1025
      initialize_particle_track(p, i, false);
355,775✔
1026
      transport_history_based_single_particle(p);
355,775✔
1027
      for (auto& site : p.local_secondary_bank()) {
1,087,225✔
1028
        thread_bank.push_back(site);
731,450✔
1029
      }
1030
      p.local_secondary_bank().clear();
444,500✔
1031
    }
1032
  }
1033
  collect_sorted_history_secondary_banks(thread_banks);
667✔
1034
  thread_banks.clear();
667✔
1035

1036
  simulation::simulation_tracks_completed += settings::n_particles;
667✔
1037

1038
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1039
  // all secondary generations
1040
  int n_generation_depth = 1;
667✔
1041
  int64_t alive_secondary = 1;
667✔
1042
  while (alive_secondary) {
8,918✔
1043

1044
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1045
    // that each MPI rank has an approximately equal number of secondary
1046
    // tracks. Also reports the total number of secondaries alive across
1047
    // all MPI ranks.
1048
    alive_secondary = synchronize_global_secondary_bank(
8,251✔
1049
      simulation::shared_secondary_bank_write);
1050

1051
    // Recalculate work for each MPI rank based on number of alive secondary
1052
    // tracks
1053
    calculate_work(alive_secondary);
8,251✔
1054

1055
    // Display the number of secondary tracks in this generation. This
1056
    // is useful for user monitoring so as to see if the secondary population is
1057
    // exploding and to determine how many generations of secondaries are being
1058
    // transported.
1059
    if (mpi::master) {
8,251✔
1060
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
13,158✔
1061
                      n_generation_depth, alive_secondary),
1062
        6);
1063
    }
1064

1065
    simulation::shared_secondary_bank_read =
8,251✔
1066
      std::move(simulation::shared_secondary_bank_write);
8,251✔
1067
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
8,251!
1068
    simulation::progeny_per_particle.resize(
8,251✔
1069
      simulation::shared_secondary_bank_read.size());
8,251✔
1070
    std::fill(simulation::progeny_per_particle.begin(),
16,502✔
1071
      simulation::progeny_per_particle.end(), 0);
8,251✔
1072
    thread_banks.resize(num_threads());
8,251✔
1073

1074
    // Transport all secondary tracks from the shared secondary bank
1075
#pragma omp parallel
4,658✔
1076
    {
3,593✔
1077
      auto& thread_bank = thread_banks[thread_num()];
3,593✔
1078
      Particle p;
3,593✔
1079

1080
#pragma omp for schedule(runtime)
1081
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
9,727,253✔
1082
           i++) {
1083
        initialize_particle_track(p, i, true);
9,723,660✔
1084
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
9,723,660✔
1085
        p.event_revive_from_secondary(site);
9,723,660✔
1086
        transport_history_based_single_particle(p);
9,723,660✔
1087
        for (auto& secondary_site : p.local_secondary_bank()) {
18,715,870✔
1088
          thread_bank.push_back(secondary_site);
8,992,210✔
1089
        }
1090
        p.local_secondary_bank().clear();
11,189,190✔
1091
      }
1092
    } // End of transport loop over tracks in shared secondary bank
1093
    simulation::shared_secondary_bank_write =
8,251✔
1094
      std::move(simulation::shared_secondary_bank_read);
8,251✔
1095
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
8,251!
1096
    collect_sorted_history_secondary_banks(thread_banks);
8,251✔
1097
    thread_banks.clear();
8,251✔
1098
    n_generation_depth++;
8,251✔
1099
    simulation::simulation_tracks_completed += alive_secondary;
8,251✔
1100
  } // End of loop over secondary generations
1101

1102
  // Reset work so that fission bank etc works correctly
1103
  calculate_work(settings::n_particles);
667✔
1104
}
667✔
1105

1106
void transport_event_based()
3,220✔
1107
{
1108
  int64_t remaining_work = simulation::work_per_rank;
3,220✔
1109
  int64_t source_offset = 0;
3,220✔
1110

1111
  // To cap the total amount of memory used to store particle object data, the
1112
  // number of particles in flight at any point in time can bet set. In the case
1113
  // that the maximum in flight particle count is lower than the total number
1114
  // of particles that need to be run this iteration, the event-based transport
1115
  // loop is executed multiple times until all particles have been completed.
1116
  while (remaining_work > 0) {
6,440✔
1117
    // Figure out # of particles to run for this subiteration
1118
    int64_t n_particles =
3,220!
1119
      std::min(remaining_work, settings::max_particles_in_flight);
3,220✔
1120

1121
    // Initialize all particle histories for this subiteration
1122
    process_init_events(n_particles, source_offset);
3,220✔
1123
    process_transport_events();
3,220✔
1124
    process_death_events(n_particles);
3,220✔
1125

1126
    // Adjust remaining work and source offset variables
1127
    remaining_work -= n_particles;
3,220✔
1128
    source_offset += n_particles;
3,220✔
1129
  }
1130
}
3,220✔
1131

1132
void transport_event_based_shared_secondary()
11✔
1133
{
1134
  // Clear shared secondary banks from any prior use
1135
  simulation::shared_secondary_bank_read.clear();
11✔
1136
  simulation::shared_secondary_bank_write.clear();
11✔
1137

1138
  if (mpi::master) {
11!
1139
    write_message(fmt::format(" Primary source          particles: {}",
22!
1140
                    settings::n_particles),
1141
      6);
1142
  }
1143

1144
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
11✔
1145
  std::fill(simulation::progeny_per_particle.begin(),
22✔
1146
    simulation::progeny_per_particle.end(), 0);
11✔
1147

1148
  // Phase 1: Transport primary particles using event-based processing and
1149
  // deposit first generation of secondaries in the shared secondary bank
1150
  int64_t remaining_work = simulation::work_per_rank;
11✔
1151
  int64_t source_offset = 0;
11✔
1152

1153
  while (remaining_work > 0) {
22✔
1154
    int64_t n_particles =
11!
1155
      std::min(remaining_work, settings::max_particles_in_flight);
11✔
1156

1157
    process_init_events(n_particles, source_offset);
11✔
1158
    process_transport_events();
11✔
1159
    process_death_events(n_particles);
11✔
1160

1161
    collect_event_secondary_banks(n_particles);
11✔
1162

1163
    remaining_work -= n_particles;
11✔
1164
    source_offset += n_particles;
11✔
1165
  }
1166

1167
  simulation::simulation_tracks_completed += settings::n_particles;
11✔
1168

1169
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1170
  // all secondary generations
1171
  int n_generation_depth = 1;
11✔
1172
  int64_t alive_secondary = 1;
11✔
1173
  while (alive_secondary) {
417✔
1174

1175
    // Sort the shared secondary bank by parent ID then progeny ID to
1176
    // ensure reproducibility.
1177
    sort_bank(simulation::shared_secondary_bank_write, false);
406✔
1178

1179
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1180
    // that each MPI rank has an approximately equal number of secondary
1181
    // tracks.
1182
    alive_secondary = synchronize_global_secondary_bank(
406✔
1183
      simulation::shared_secondary_bank_write);
1184

1185
    // Recalculate work for each MPI rank based on number of alive secondary
1186
    // tracks
1187
    calculate_work(alive_secondary);
406✔
1188

1189
    if (mpi::master) {
406!
1190
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
812!
1191
                      n_generation_depth, alive_secondary),
1192
        6);
1193
    }
1194

1195
    simulation::shared_secondary_bank_read =
406✔
1196
      std::move(simulation::shared_secondary_bank_write);
406✔
1197
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
406!
1198
    simulation::progeny_per_particle.resize(
406✔
1199
      simulation::shared_secondary_bank_read.size());
406✔
1200
    std::fill(simulation::progeny_per_particle.begin(),
812✔
1201
      simulation::progeny_per_particle.end(), 0);
406✔
1202

1203
    // Ensure particle buffer is large enough for this secondary generation
1204
    int64_t sec_buffer_length = std::min(
406!
1205
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
406!
1206
      settings::max_particles_in_flight);
406✔
1207
    if (sec_buffer_length >
406✔
1208
        static_cast<int64_t>(simulation::particles.size())) {
406✔
1209
      init_event_queues(sec_buffer_length);
34✔
1210
    }
1211

1212
    // Transport secondary tracks using event-based processing
1213
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
406✔
1214
    int64_t sec_offset = 0;
406✔
1215

1216
    while (sec_remaining > 0) {
801✔
1217
      int64_t n_particles =
395!
1218
        std::min(sec_remaining, settings::max_particles_in_flight);
395✔
1219

1220
      process_init_secondary_events(
395✔
1221
        n_particles, sec_offset, simulation::shared_secondary_bank_read);
1222
      process_transport_events();
395✔
1223
      process_death_events(n_particles);
395✔
1224

1225
      collect_event_secondary_banks(n_particles);
395✔
1226

1227
      sec_remaining -= n_particles;
395✔
1228
      sec_offset += n_particles;
395✔
1229
    } // End of subiteration loop over secondary tracks
1230
    n_generation_depth++;
406✔
1231
    simulation::simulation_tracks_completed += alive_secondary;
406✔
1232
  } // End of loop over secondary generations
1233

1234
  // Reset work so that fission bank etc works correctly
1235
  calculate_work(settings::n_particles);
11✔
1236
}
11✔
1237

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

© 2026 Coveralls, Inc