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

openmc-dev / openmc / 29158451936

11 Jul 2026 03:43PM UTC coverage: 81.294% (-0.007%) from 81.301%
29158451936

Pull #4011

github

web-flow
Merge 901449abe into e783e0147
Pull Request #4011: Performance optimizations for shared secondary bank

18229 of 26454 branches covered (68.91%)

Branch coverage included in aggregate %.

57 of 62 new or added lines in 2 files covered. (91.94%)

1 existing line in 1 file now uncovered.

59470 of 69124 relevant lines covered (86.03%)

48447029.94 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,930✔
70
    err = openmc_next_batch(&status);
141,253✔
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,421✔
112
    t->set_strides();
27,581✔
113
    t->init_results();
27,581✔
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,408✔
217
    t->active_ = false;
27,581✔
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)
145,378✔
254
{
255
  using namespace openmc;
145,378✔
256
  using openmc::simulation::current_gen;
145,378✔
257

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

264
  initialize_batch();
145,367✔
265

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

270
    initialize_generation();
145,577✔
271

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

275
    // Transport loop
276
    if (settings::event_based) {
145,577✔
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) {
142,346✔
284
        transport_history_based_shared_secondary();
667✔
285
      } else {
286
        transport_history_based();
141,679✔
287
      }
288
    }
289

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

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

296
  finalize_batch();
145,354✔
297

298
  // Check simulation ending criteria
299
  if (status) {
145,354!
300
    if (simulation::current_batch >= settings::n_max_batches) {
145,354✔
301
      *status = STATUS_EXIT_MAX_BATCH;
6,870✔
302
    } else if (simulation::satisfy_triggers) {
138,484✔
303
      *status = STATUS_EXIT_ON_TRIGGER;
93✔
304
    } else {
305
      *status = STATUS_EXIT_NORMAL;
138,391✔
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,908✔
366
  vector<vector<SourceSite>>& thread_banks)
367
{
368
  // Count the total number of all secondary sites produced
369
  int64_t n_collected = 0;
8,908✔
370
  for (const auto& bank : thread_banks) {
22,848✔
371
    n_collected += bank.size();
13,940✔
372
  }
373

374
  // Count the expected number of progeny from per-parent progeny counts
375
  int64_t n_progeny = 0;
8,908✔
376
  for (int64_t count : simulation::progeny_per_particle) {
21,946,642✔
377
    n_progeny += count;
21,937,734✔
378
  }
379

380
  if (n_collected != n_progeny) {
8,908!
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,908✔
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,908✔
392
  simulation::shared_secondary_bank_write.extend_uninitialized(n_progeny);
8,908✔
393

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

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

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

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

444
} // namespace
445

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

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

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

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

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

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

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

491
  // Reset total starting particle weight used for normalizing tallies
492
  simulation::total_weight = 0.0;
166,329✔
493

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

505
  // Manage active/inactive timers and activate tallies if necessary.
506
  if (first_inactive) {
166,218✔
507
    simulation::time_inactive.start();
3,865✔
508
  } else if (first_active) {
162,464✔
509
    simulation::time_inactive.stop();
7,793✔
510
    simulation::time_active.start();
7,793✔
511
    for (auto& t : model::tallies) {
35,352✔
512
      t->active_ = true;
27,559✔
513
    }
514
  }
515

516
  // Add user tallies to active tallies list
517
  setup_active_tallies();
166,329✔
518
}
166,329✔
519

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

640
void finalize_generation()
166,526✔
641
{
642
  auto& gt = simulation::global_tallies;
166,526✔
643

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

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

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

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

673
  if (settings::run_mode == RunMode::EIGENVALUE) {
166,526✔
674

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

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

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

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

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

716
  p.current_work() = index_source - 1;
199,343,082✔
717

718
  // set identifier for particle
719
  p.id() = compute_particle_id(index_source);
199,343,082✔
720

721
  // set progeny count to zero
722
  p.n_progeny() = 0;
199,343,082✔
723

724
  // Reset particle event counter
725
  p.n_event() = 0;
199,343,082✔
726

727
  // Initialize track counter (1 for this primary/secondary track)
728
  p.n_tracks() = 1;
199,343,082✔
729

730
  // Reset split counter
731
  p.n_split() = 0;
199,343,082✔
732

733
  // Reset weight window ratio
734
  p.ww_factor() = 0.0;
199,343,082✔
735

736
  // set particle history start weight
737
  p.wgt_born() = p.wgt();
199,343,082✔
738

739
  // Reset pulse_height_storage
740
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
199,343,082✔
741

742
  // set random number seed
743
  int64_t particle_seed = compute_transport_seed(p.id());
199,343,082✔
744
  init_particle_seeds(particle_seed, p.seeds());
199,343,082✔
745

746
  // set particle trace
747
  p.trace() = false;
199,343,082✔
748
  if (simulation::current_batch == settings::trace_batch &&
199,354,082✔
749
      simulation::current_gen == settings::trace_gen &&
199,343,082!
750
      p.id() == settings::trace_particle)
11,000✔
751
    p.trace() = true;
11✔
752

753
  // Set particle track.
754
  p.write_track() = check_track_criteria(p);
199,343,082✔
755

756
  // Set the particle's initial weight window value.
757
  if (!is_secondary) {
199,343,082✔
758
    p.wgt_ww_born() = -1.0;
178,008,573✔
759
    apply_weight_windows(p);
178,008,573✔
760
  }
761

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

767
  // Add particle's starting weight to count for normalizing tallies later
768
  if (!is_secondary) {
199,343,082✔
769
#pragma omp atomic
98,779,969✔
770
    simulation::total_weight += p.wgt();
178,008,573✔
771
  }
772

773
  // Force calculation of cross-sections by setting last energy to zero
774
  if (settings::run_CE) {
199,343,082✔
775
    p.invalidate_neutron_xs();
84,794,538✔
776
  }
777

778
  // Prepare to write out particle track.
779
  if (p.write_track())
199,343,082✔
780
    add_particle_track(p);
999✔
781
}
199,343,082✔
782

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

789
int64_t compute_particle_id(int64_t index_source)
227,447,934✔
790
{
791
  if (settings::use_shared_secondary_bank) {
227,447,934✔
792
    return simulation::work_index[mpi::rank] + index_source +
22,903,534✔
793
           simulation::simulation_tracks_completed;
22,903,534✔
794
  } else {
795
    return simulation::work_index[mpi::rank] + index_source;
204,544,400✔
796
  }
797
}
798

799
int64_t compute_transport_seed(int64_t particle_id)
227,447,978✔
800
{
801
  if (settings::use_shared_secondary_bank) {
227,447,978✔
802
    return particle_id;
803
  } else {
804
    return (simulation::total_gen + overall_generation() - 1) *
204,544,433✔
805
             settings::n_particles +
806
           particle_id;
204,544,433✔
807
  }
808
}
809

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

949
#endif
950

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

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

976
void transport_history_based()
141,679✔
977
{
978
#pragma omp parallel
78,939✔
979
  {
62,740✔
980
    Particle p;
62,740✔
981
#pragma omp for schedule(runtime)
982
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,538,565✔
983
      initialize_particle_track(p, i_work, false);
80,475,834✔
984
      transport_history_based_single_particle(p);
80,475,830✔
985
    }
986
  }
62,731✔
987
}
141,670✔
988

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1160
    collect_event_secondary_banks(n_particles);
11✔
1161

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

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

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

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

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

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

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

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

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

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

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

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

1224
      collect_event_secondary_banks(n_particles);
395✔
1225

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

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

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