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

openmc-dev / openmc / 32417058765

20 Aug 2026 08:59PM UTC coverage: 81.311% (-0.02%) from 81.333%
32417058765

Pull #3734

github

web-flow
Merge 5d3104af4 into 86ceaad3c
Pull Request #3734: Specify temperature from a field (structured mesh only)

18708 of 27215 branches covered (68.74%)

Branch coverage included in aggregate %.

262 of 316 new or added lines in 16 files covered. (82.91%)

1 existing line in 1 file now uncovered.

60539 of 70247 relevant lines covered (86.18%)

50688755.49 hits per line

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

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

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

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

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

43
#include <fmt/format.h>
44

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

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

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

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

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

70
  int err = 0;
71
  while (status == 0 && err == 0) {
156,451✔
72
    err = openmc_next_batch(&status);
149,435✔
73
  }
74

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

80
int openmc_simulation_init()
8,245✔
81
{
82
  using namespace openmc;
8,245✔
83

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

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

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

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

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

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

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

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

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

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

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

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

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

175
int openmc_simulation_finalize()
8,210✔
176
{
177
  using namespace openmc;
8,210✔
178

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

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

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

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

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

200
#ifdef OPENMC_MPI
201
  broadcast_results();
3,690✔
202
#endif
203

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

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

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

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

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

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

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

255
int openmc_next_batch(int* status)
153,560✔
256
{
257
  using namespace openmc;
153,560✔
258
  using openmc::simulation::current_gen;
153,560✔
259

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

266
  initialize_batch();
153,549✔
267

268
  // =======================================================================
269
  // LOOP OVER GENERATIONS
270
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
307,295✔
271

272
    initialize_generation();
153,759✔
273

274
    // Start timer for transport
275
    simulation::time_transport.start();
153,759✔
276

277
    // Transport loop
278
    if (settings::event_based) {
153,759✔
279
      if (settings::use_shared_secondary_bank) {
3,482✔
280
        transport_event_based_shared_secondary();
21✔
281
      } else {
282
        transport_event_based();
3,461✔
283
      }
284
    } else {
285
      if (settings::use_shared_secondary_bank) {
150,277✔
286
        transport_history_based_shared_secondary();
3,062✔
287
      } else {
288
        transport_history_based();
147,215✔
289
      }
290
    }
291

292
    // Accumulate time for transport
293
    simulation::time_transport.stop();
153,746✔
294

295
    finalize_generation();
153,746✔
296
  }
297

298
  finalize_batch();
153,536✔
299

300
  // Check simulation ending criteria
301
  if (status) {
153,536!
302
    if (simulation::current_batch >= settings::n_max_batches) {
153,536✔
303
      *status = STATUS_EXIT_MAX_BATCH;
7,209✔
304
    } else if (simulation::satisfy_triggers) {
146,327✔
305
      *status = STATUS_EXIT_ON_TRIGGER;
93✔
306
    } else {
307
      *status = STATUS_EXIT_NORMAL;
146,234✔
308
    }
309
  }
310
  return 0;
311
}
312

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

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

324
namespace openmc {
325

326
//==============================================================================
327
// Global variables
328
//==============================================================================
329

330
namespace simulation {
331

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

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

354
TemperatureField temperature_field;
355

356
vector<double> k_generation;
357
vector<int64_t> work_index;
358

359
int64_t simulation_tracks_completed {0};
360

361
} // namespace simulation
362

363
namespace {
364

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

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

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

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

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

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

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

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

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

449
} // namespace
450

451
//==============================================================================
452
// Non-member functions
453
//==============================================================================
454

455
void allocate_banks()
8,223✔
456
{
457
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,223✔
458
      settings::solver_type == SolverType::MONTE_CARLO) {
4,691✔
459
    // Allocate source bank
460
    simulation::source_bank.resize(simulation::work_per_rank);
4,320✔
461

462
    // Allocate fission bank
463
    init_fission_bank(3 * simulation::work_per_rank);
4,320✔
464

465
    // Allocate IFP bank
466
    if (settings::ifp_on) {
4,320✔
467
      resize_simulation_ifp_banks();
74✔
468
    }
469
  }
470

471
  if (settings::surf_source_write) {
8,223✔
472
    // Allocate surface source bank
473
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,176✔
474
  }
475

476
  if (settings::collision_track) {
8,223✔
477
    // Allocate collision track bank
478
    collision_track_reserve_bank();
160✔
479
  }
480
}
8,223✔
481

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

496
  // Reset total starting particle weight used for normalizing tallies
497
  simulation::total_weight = 0.0;
175,391✔
498

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

510
  // Manage active/inactive timers and activate tallies if necessary.
511
  if (first_inactive) {
175,280✔
512
    simulation::time_inactive.start();
3,909✔
513
  } else if (first_active) {
171,482✔
514
    simulation::time_inactive.stop();
8,176✔
515
    simulation::time_active.start();
8,176✔
516
    for (auto& t : model::tallies) {
36,316✔
517
      t->active_ = true;
28,140✔
518
    }
519
  }
520

521
  // Add user tallies to active tallies list
522
  setup_active_tallies();
175,391✔
523
}
175,391✔
524

525
void finalize_batch()
175,378✔
526
{
527
  // Reduce tallies onto master process and accumulate
528
  simulation::time_tallies.start();
175,378✔
529
  accumulate_tallies();
175,378✔
530
  simulation::time_tallies.stop();
175,378✔
531

532
  // update weight windows if needed
533
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
178,890✔
534
    wwg->update();
3,512✔
535
  }
536

537
  // Reset global tally results
538
  if (simulation::current_batch <= settings::n_inactive) {
175,378✔
539
    simulation::global_tallies.fill(0.0);
33,263✔
540
    simulation::n_realizations = 0;
33,263✔
541
  }
542

543
  // Check_triggers
544
  if (mpi::master)
175,378✔
545
    check_triggers();
155,335✔
546
#ifdef OPENMC_MPI
547
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
76,904✔
548
#endif
549
  if (simulation::satisfy_triggers ||
175,378✔
550
      (settings::trigger_on &&
2,567✔
551
        simulation::current_batch == settings::n_max_batches)) {
2,567✔
552
    settings::statepoint_batch.insert(simulation::current_batch);
141✔
553
  }
554

555
  // Write out state point if it's been specified for this batch and is not
556
  // a CMFD run instance
557
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
350,756✔
558
      !settings::cmfd_run) {
8,478✔
559
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
16,326✔
560
        settings::source_write && !settings::source_separate) {
15,399✔
561
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
7,026✔
562
      openmc_statepoint_write(nullptr, &b);
7,026✔
563
    } else {
564
      bool b = false;
1,276✔
565
      openmc_statepoint_write(nullptr, &b);
1,276✔
566
    }
567
  }
568

569
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,378✔
570
    // Write out a separate source point if it's been specified for this batch
571
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
109,640✔
572
        settings::source_write && settings::source_separate) {
109,269✔
573

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

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

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

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

611
      // Write surface source file
612
      write_source_point(
1,209✔
613
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
614

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

629
void initialize_generation()
175,601✔
630
{
631
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,601✔
632
    // Clear out the fission bank
633
    simulation::fission_bank.resize(0);
105,133✔
634

635
    // Count source sites if using uniform fission source weighting
636
    if (settings::ufs_on)
105,133✔
637
      ufs_count_sites();
150✔
638

639
    // Store current value of tracklength k
640
    simulation::keff_generation = simulation::global_tallies(
105,133✔
641
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
642
  }
643
}
175,601✔
644

645
void finalize_generation()
175,588✔
646
{
647
  auto& gt = simulation::global_tallies;
175,588✔
648

649
  // Update global tallies with the accumulation variables
650
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,588✔
651
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
105,133✔
652
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
105,133✔
653
      global_tally_absorption;
654
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
105,133✔
655
      global_tally_tracklength;
656
  }
657
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
175,588✔
658

659
  // reset tallies
660
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,588✔
661
    global_tally_collision = 0.0;
105,133✔
662
    global_tally_absorption = 0.0;
105,133✔
663
    global_tally_tracklength = 0.0;
105,133✔
664
  }
665
  global_tally_leakage = 0.0;
175,588✔
666

667
  if (settings::run_mode == RunMode::EIGENVALUE &&
175,588✔
668
      settings::solver_type == SolverType::MONTE_CARLO) {
105,133✔
669
    // If using shared memory, stable sort the fission bank (by parent IDs)
670
    // so as to allow for reproducibility regardless of which order particles
671
    // are run in.
672
    sort_bank(simulation::fission_bank, true);
98,283✔
673

674
    // Distribute fission bank across processors evenly
675
    synchronize_bank();
98,283✔
676
  }
677

678
  if (settings::run_mode == RunMode::EIGENVALUE) {
175,588✔
679

680
    // Calculate shannon entropy
681
    if (settings::entropy_on &&
105,133✔
682
        settings::solver_type == SolverType::MONTE_CARLO)
14,535✔
683
      shannon_entropy();
7,685✔
684

685
    // Collect results and statistics
686
    calculate_generation_keff();
105,133✔
687
    calculate_average_keff();
105,133✔
688

689
    // Write generation output
690
    if (mpi::master && settings::verbosity >= 7) {
105,133✔
691
      print_generation();
79,028✔
692
    }
693
  }
694
}
175,588✔
695

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

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

721
  p.current_work() = index_source - 1;
193,976,907✔
722

723
  // set identifier for particle
724
  p.id() = compute_particle_id(index_source);
193,976,907✔
725

726
  // set progeny count to zero
727
  p.n_progeny() = 0;
193,976,907✔
728

729
  // Reset particle event counter
730
  p.n_event() = 0;
193,976,907✔
731

732
  // Initialize track counter (1 for this primary/secondary track)
733
  p.n_tracks() = 1;
193,976,907✔
734

735
  // Reset split counter
736
  p.n_split() = 0;
193,976,907✔
737

738
  // Reset weight window ratio
739
  p.ww_factor() = 0.0;
193,976,907✔
740

741
  // set particle history start weight
742
  p.wgt_born() = p.wgt();
193,976,907✔
743

744
  // Reset pulse_height_storage
745
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
193,976,907✔
746

747
  // set random number seed
748
  int64_t particle_seed = compute_transport_seed(p.id());
193,976,907✔
749
  init_particle_seeds(particle_seed, p.seeds());
193,976,907✔
750

751
  // set particle trace
752
  p.trace() = false;
193,976,907✔
753
  if (simulation::current_batch == settings::trace_batch &&
193,987,907✔
754
      simulation::current_gen == settings::trace_gen &&
193,976,907!
755
      p.id() == settings::trace_particle)
11,000✔
756
    p.trace() = true;
11✔
757

758
  // Set particle track.
759
  p.write_track() = check_track_criteria(p);
193,976,907✔
760

761
  // Set the particle's initial weight window value.
762
  if (!is_secondary) {
193,976,907✔
763
    p.wgt_ww_born() = -1.0;
178,525,194✔
764
    apply_weight_windows(p);
178,525,194✔
765
  }
766

767
  // Display message if high verbosity or trace is on
768
  if (settings::verbosity >= 9 || p.trace()) {
193,976,907!
769
    write_message("Simulating Particle {}", p.id());
22✔
770
  }
771

772
  // Add particle's starting weight to count for normalizing tallies later
773
  if (!is_secondary) {
193,976,907✔
774
#pragma omp atomic
102,205,986✔
775
    simulation::total_weight += p.wgt();
178,525,194✔
776
  }
777

778
  // Force calculation of cross-sections by setting last energy to zero
779
  if (settings::run_CE) {
193,976,907✔
780
    p.invalidate_neutron_xs();
79,428,363✔
781
  }
782

783
  // Prepare to write out particle track.
784
  if (p.write_track())
193,976,907✔
785
    add_particle_track(p);
999✔
786
}
193,976,907✔
787

788
int overall_generation()
205,054,429✔
789
{
790
  using namespace simulation;
205,054,429✔
791
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
205,054,429✔
792
}
793

794
int64_t compute_particle_id(int64_t index_source)
222,021,380✔
795
{
796
  if (settings::use_shared_secondary_bank) {
222,021,380✔
797
    return simulation::work_index[mpi::rank] + index_source +
17,249,428✔
798
           simulation::simulation_tracks_completed;
17,249,428✔
799
  } else {
800
    return simulation::work_index[mpi::rank] + index_source;
204,771,952✔
801
  }
802
}
803

804
int64_t compute_transport_seed(int64_t particle_id)
222,021,424✔
805
{
806
  if (settings::use_shared_secondary_bank) {
222,021,424✔
807
    return particle_id;
808
  } else {
809
    return (simulation::total_gen + overall_generation() - 1) *
204,771,985✔
810
             settings::n_particles +
811
           particle_id;
204,771,985✔
812
  }
813
}
814

815
void calculate_work(int64_t n_particles)
48,582✔
816
{
817
  // Determine minimum amount of particles to simulate on each processor
818
  int64_t min_work = n_particles / mpi::n_procs;
48,582✔
819

820
  // Determine number of processors that have one extra particle
821
  int64_t remainder = n_particles % mpi::n_procs;
48,582✔
822

823
  int64_t i_bank = 0;
48,582✔
824
  simulation::work_index.resize(mpi::n_procs + 1);
48,582✔
825
  simulation::work_index[0] = 0;
48,582✔
826
  for (int i = 0; i < mpi::n_procs; ++i) {
105,307✔
827
    // Number of particles for rank i
828
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
56,725✔
829

830
    // Set number of particles
831
    if (mpi::rank == i)
56,725✔
832
      simulation::work_per_rank = work_i;
48,582✔
833

834
    // Set index into source bank for rank i
835
    i_bank += work_i;
56,725✔
836
    simulation::work_index[i + 1] = i_bank;
56,725✔
837
  }
838
}
48,582✔
839

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

846
  for (const auto& nuc : data::nuclides) {
42,004✔
847
    if (nuc->grid_.size() >= 1) {
35,192!
848
      int neutron = ParticleType::neutron().transport_index();
35,192✔
849
      data::energy_min[neutron] =
35,192✔
850
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
41,439✔
851
      data::energy_max[neutron] =
35,192✔
852
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
43,073✔
853
    }
854
  }
855

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

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

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

883
        data::energy_min[photon] =
994✔
884
          std::max(data::energy_min[photon], data::energy_min[electron]);
994!
885

886
        data::energy_max[photon] =
994✔
887
          std::min(data::energy_max[photon], data::energy_max[electron]);
994!
888
      }
497✔
889
    }
890
  }
891

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

911
  // Set up logarithmic grid for nuclides
912
  for (auto& nuc : data::nuclides) {
42,004✔
913
    nuc->init_grid();
35,192✔
914
  }
915
  int neutron = ParticleType::neutron().transport_index();
6,812✔
916
  simulation::log_spacing =
13,624✔
917
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,812✔
918
    settings::n_log_bins;
919
}
6,812✔
920

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

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

940
  // Also broadcast global tally results
941
  auto& gt = simulation::global_tallies;
3,690✔
942
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,690✔
943

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

954
#endif
955

956
void free_memory_simulation()
9,412✔
957
{
958
  simulation::k_generation.clear();
9,412✔
959
  simulation::entropy.clear();
9,412✔
960
}
9,412✔
961

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

992
void transport_history_based()
147,215✔
993
{
994
#pragma omp parallel
82,119✔
995
  {
65,096✔
996
    Particle p;
65,096✔
997
#pragma omp for schedule(runtime)
998
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,716,501✔
999
      initialize_particle_track(p, i_work, false);
80,651,414✔
1000
      transport_history_based_single_particle(p);
80,651,410✔
1001
    }
1002
  }
65,087✔
1003
}
147,206✔
1004

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

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

1025
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
3,062✔
1026
  std::fill(simulation::progeny_per_particle.begin(),
6,124✔
1027
    simulation::progeny_per_particle.end(), 0);
3,062✔
1028

1029
  vector<vector<SourceSite>> thread_banks(num_threads());
3,062✔
1030

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

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

1051
  simulation::simulation_tracks_completed += settings::n_particles;
3,062✔
1052

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

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

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

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

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

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

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

1117
  // Reset work so that fission bank etc works correctly
1118
  calculate_work(settings::n_particles);
3,062✔
1119
}
3,062✔
1120

1121
void transport_event_based()
3,461✔
1122
{
1123
  int64_t remaining_work = simulation::work_per_rank;
3,461✔
1124
  int64_t source_offset = 0;
3,461✔
1125

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

1136
    // Initialize all particle histories for this subiteration
1137
    process_init_events(n_particles, source_offset);
3,461✔
1138
    process_transport_events();
3,461✔
1139
    process_death_events(n_particles);
3,461✔
1140

1141
    // Adjust remaining work and source offset variables
1142
    remaining_work -= n_particles;
3,461✔
1143
    source_offset += n_particles;
3,461✔
1144
  }
1145
}
3,461✔
1146

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

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

1159
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
21✔
1160
  std::fill(simulation::progeny_per_particle.begin(),
42✔
1161
    simulation::progeny_per_particle.end(), 0);
21✔
1162

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

1168
  while (remaining_work > 0) {
42✔
1169
    int64_t n_particles =
21!
1170
      std::min(remaining_work, settings::max_particles_in_flight);
21✔
1171

1172
    process_init_events(n_particles, source_offset);
21✔
1173
    process_transport_events();
21✔
1174
    process_death_events(n_particles);
21✔
1175

1176
    collect_event_secondary_banks(n_particles);
21✔
1177

1178
    remaining_work -= n_particles;
21✔
1179
    source_offset += n_particles;
21✔
1180
  }
1181

1182
  simulation::simulation_tracks_completed += settings::n_particles;
21✔
1183

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

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

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

1200
    // Recalculate work for each MPI rank based on number of alive secondary
1201
    // tracks
1202
    calculate_work(alive_secondary);
705✔
1203

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

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

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

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

1231
    while (sec_remaining > 0) {
1,389✔
1232
      int64_t n_particles =
684!
1233
        std::min(sec_remaining, settings::max_particles_in_flight);
684✔
1234

1235
      process_init_secondary_events(
684✔
1236
        n_particles, sec_offset, simulation::shared_secondary_bank_read);
1237
      process_transport_events();
684✔
1238
      process_death_events(n_particles);
684✔
1239

1240
      collect_event_secondary_banks(n_particles);
684✔
1241

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

1249
  // Reset work so that fission bank etc works correctly
1250
  calculate_work(settings::n_particles);
21✔
1251
}
21✔
1252

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

© 2026 Coveralls, Inc