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

openmc-dev / openmc / 34257174977

08 Sep 2026 05:27PM UTC coverage: 81.398% (+0.04%) from 81.359%
34257174977

Pull #4089

github

web-flow
Merge 1643bd7ea into 438b05db7
Pull Request #4089: Support pulse-height tallies in shared secondary mode

18821 of 27320 branches covered (68.89%)

Branch coverage included in aggregate %.

180 of 185 new or added lines in 11 files covered. (97.3%)

804 existing lines in 19 files now uncovered.

60740 of 70423 relevant lines covered (86.25%)

49868212.06 hits per line

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

93.7
/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/pulse_height.h"
27
#include "openmc/tallies/tally.h"
28
#include "openmc/tallies/trigger.h"
29
#include "openmc/timer.h"
30
#include "openmc/track_output.h"
31
#include "openmc/weight_windows.h"
32

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

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

42
#include <fmt/format.h>
43

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

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

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

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

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

69
  int err = 0;
70
  while (status == 0 && err == 0) {
154,490 ✔
71
    err = openmc_next_batch(&status);
147,515 ✔
72
  }
73

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

79
int openmc_simulation_init()
8,248 ✔
80
{
81
  using namespace openmc;
8,248 ✔
82

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

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

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

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

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

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

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

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

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

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

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

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

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

174
int openmc_simulation_finalize()
8,213 ✔
175
{
176
  using namespace openmc;
8,213 ✔
177

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

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

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

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

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

199
#ifdef OPENMC_MPI
200
  broadcast_results();
3,658 ✔
201
#endif
202

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

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

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

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

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

238
  if (mpi::master) {
8,213 ✔
239
    if (settings::solver_type != SolverType::RANDOM_RAY) {
7,189 ✔
240
      if (settings::verbosity >= 6)
6,494 ✔
241
        print_runtime();
6,114 ✔
242
      if (settings::verbosity >= 4)
6,494 ✔
243
        print_results();
6,114 ✔
244
    }
245
  }
246
  if (settings::check_overlaps)
8,213 !
247
    print_overlap_check();
×
248

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

254
int openmc_next_batch(int* status)
151,640 ✔
255
{
256
  using namespace openmc;
151,640 ✔
257
  using openmc::simulation::current_gen;
151,640 ✔
258

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

265
  initialize_batch();
151,629 ✔
266

267
  // =======================================================================
268
  // LOOP OVER GENERATIONS
269
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
303,455 ✔
270

271
    initialize_generation();
151,839 ✔
272

273
    // Start timer for transport
274
    simulation::time_transport.start();
151,839 ✔
275

276
    // Transport loop
277
    if (settings::event_based) {
151,839 ✔
278
      if (settings::use_shared_secondary_bank) {
3,262 ✔
279
        transport_event_based_shared_secondary();
36 ✔
280
      } else {
281
        transport_event_based();
3,226 ✔
282
      }
283
    } else {
284
      if (settings::use_shared_secondary_bank) {
148,577 ✔
285
        transport_history_based_shared_secondary();
3,822 ✔
286
      } else {
287
        transport_history_based();
144,755 ✔
288
      }
289
    }
290

291
    // Accumulate time for transport
292
    simulation::time_transport.stop();
151,826 ✔
293

294
    finalize_generation();
151,826 ✔
295
  }
296

297
  finalize_batch();
151,616 ✔
298

299
  // Check simulation ending criteria
300
  if (status) {
151,616 !
301
    if (simulation::current_batch >= settings::n_max_batches) {
151,616 ✔
302
      *status = STATUS_EXIT_MAX_BATCH;
7,168 ✔
303
    } else if (simulation::satisfy_triggers) {
144,448 ✔
304
      *status = STATUS_EXIT_ON_TRIGGER;
93 ✔
305
    } else {
306
      *status = STATUS_EXIT_NORMAL;
144,355 ✔
307
    }
308
  }
309
  return 0;
310
}
311

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

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

323
namespace openmc {
324

325
//==============================================================================
326
// Global variables
327
//==============================================================================
328

329
namespace simulation {
330

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

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

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

356
int64_t simulation_tracks_completed {0};
357

358
} // namespace simulation
359

360
namespace {
361

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

375
  // Count the expected number of progeny from per-parent progeny counts
376
  int64_t n_progeny = 0;
43,044 ✔
377
  for (int64_t count : simulation::progeny_per_particle) {
17,102,171 ✔
378
    n_progeny += count;
17,059,127 ✔
379
  }
380

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

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

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

395
  // Place each secondary according to its parent and progeny identifiers
396
  for (const auto& bank : thread_banks) {
109,893 ✔
397
    for (const auto& site : bank) {
15,443,996 ✔
398
      if (site.parent_slot() < 0 ||
15,377,147 !
399
          site.parent_slot() >=
15,377,147 !
400
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
15,377,147 !
NEW
401
        fatal_error(fmt::format("Invalid parent slot {} for banked site "
×
402
                                "(expected range [0, {})).",
NEW
403
          site.parent_slot(), simulation::progeny_per_particle.size()));
×
404
      }
405
      int64_t idx =
15,377,147 ✔
406
        simulation::progeny_per_particle[site.parent_slot()] + site.progeny_id;
15,377,147 !
407
      if (idx < 0 || idx >= n_progeny) {
15,377,147 !
408
        fatal_error("Mismatch detected between sum of all particle progeny and "
×
409
                    "secondary bank size during collection.");
410
      }
411
      simulation::shared_secondary_bank_write[idx] = site;
15,377,147 ✔
412
    }
413
  }
414
}
43,044 ✔
415

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

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

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

446
} // namespace
447

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

452
void allocate_banks()
8,226 ✔
453
{
454
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,226 ✔
455
      settings::solver_type == SolverType::MONTE_CARLO) {
4,540 ✔
456
    // Allocate source bank
457
    simulation::source_bank.resize(simulation::work_per_rank);
4,169 ✔
458

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

462
    // Allocate IFP bank
463
    if (settings::ifp_on()) {
4,169 ✔
464
      resize_simulation_ifp_banks();
85 ✔
465
    }
466
  }
467

468
  if (settings::surf_source_write) {
8,226 ✔
469
    // Allocate surface source bank
470
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,220 ✔
471
  }
472

473
  if (settings::collision_track) {
8,226 ✔
474
    // Allocate collision track bank
475
    collision_track_reserve_bank();
160 ✔
476
  }
477
}
8,226 ✔
478

479
void initialize_batch()
173,471 ✔
480
{
481
  // Increment current batch
482
  ++simulation::current_batch;
173,471 ✔
483
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
173,471 ✔
484
    if (settings::solver_type == SolverType::RANDOM_RAY &&
71,568 ✔
485
        simulation::current_batch < settings::n_inactive + 1) {
14,992 ✔
486
      write_message(
18,132 ✔
487
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
488
    } else {
489
      write_message(6, "Simulating batch {}", simulation::current_batch);
125,004 ✔
490
    }
491
  }
492

493
  // Reset total starting particle weight used for normalizing tallies
494
  simulation::total_weight = 0.0;
173,471 ✔
495

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

507
  // Manage active/inactive timers and activate tallies if necessary.
508
  if (first_inactive) {
173,360 ✔
509
    simulation::time_inactive.start();
3,946 ✔
510
  } else if (first_active) {
169,525 ✔
511
    simulation::time_inactive.stop();
8,135 ✔
512
    simulation::time_active.start();
8,135 ✔
513
    for (auto& t : model::tallies) {
36,330 ✔
514
      t->active_ = true;
28,195 ✔
515
    }
516
  }
517

518
  // Add user tallies to active tallies list
519
  setup_active_tallies();
173,471 ✔
520
}
173,471 ✔
521

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

529
  // update weight windows if needed
530
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
176,970 ✔
531
    wwg->update();
3,512 ✔
532
  }
533

534
  // Reset global tally results
535
  if (simulation::current_batch <= settings::n_inactive) {
173,458 ✔
536
    simulation::global_tallies.fill(0.0);
33,448 ✔
537
    simulation::n_realizations = 0;
33,448 ✔
538
  }
539

540
  // Check_triggers
541
  if (mpi::master)
173,458 ✔
542
    check_triggers();
154,375 ✔
543
#ifdef OPENMC_MPI
544
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
75,544 ✔
545
#endif
546
  if (simulation::satisfy_triggers ||
173,458 ✔
547
      (settings::trigger_on &&
2,567 ✔
548
        simulation::current_batch == settings::n_max_batches)) {
2,567 ✔
549
    settings::statepoint_batch.insert(simulation::current_batch);
141 ✔
550
  }
551

552
  // Write out state point if it's been specified for this batch and is not
553
  // a CMFD run instance
554
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
346,916 ✔
555
      !settings::cmfd_run) {
8,437 ✔
556
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
16,244 ✔
557
        settings::source_write && !settings::source_separate) {
15,317 ✔
558
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
6,985 ✔
559
      openmc_statepoint_write(nullptr, &b);
6,985 ✔
560
    } else {
561
      bool b = false;
1,276 ✔
562
      openmc_statepoint_write(nullptr, &b);
1,276 ✔
563
    }
564
  }
565

566
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,458 ✔
567
    // Write out a separate source point if it's been specified for this batch
568
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
106,469 ✔
569
        settings::source_write && settings::source_separate) {
106,098 ✔
570

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

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

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

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

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

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

626
void initialize_generation()
173,681 ✔
627
{
628
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,681 ✔
629
    // Clear out the fission bank
630
    simulation::fission_bank.resize(0);
102,113 ✔
631

632
    // Count source sites if using uniform fission source weighting
633
    if (settings::ufs_on)
102,113 ✔
634
      ufs_count_sites();
150 ✔
635

636
    // Store current value of tracklength k
637
    simulation::keff_generation = simulation::global_tallies(
102,113 ✔
638
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
639
  }
640
}
173,681 ✔
641

642
void finalize_generation()
173,668 ✔
643
{
644
  auto& gt = simulation::global_tallies;
173,668 ✔
645

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

656
  // reset tallies
657
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,668 ✔
658
    global_tally_collision = 0.0;
102,113 ✔
659
    global_tally_absorption = 0.0;
102,113 ✔
660
    global_tally_tracklength = 0.0;
102,113 ✔
661
  }
662
  global_tally_leakage = 0.0;
173,668 ✔
663

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

671
    // Distribute fission bank across processors evenly
672
    synchronize_bank();
95,263 ✔
673
  }
674

675
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,668 ✔
676

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

682
    // Collect results and statistics
683
    calculate_generation_keff();
102,113 ✔
684
    calculate_average_keff();
102,113 ✔
685

686
    // Write generation output
687
    if (mpi::master && settings::verbosity >= 7) {
102,113 ✔
688
      print_generation();
76,968 ✔
689
    }
690
  }
691
}
173,668 ✔
692

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

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

718
  p.current_work() = index_source - 1;
197,646,347 ✔
719

720
  // set identifier for particle
721
  p.id() = compute_particle_id(index_source);
197,646,347 ✔
722

723
  // set progeny count to zero
724
  p.n_progeny() = 0;
197,646,347 ✔
725

726
  // Reset particle event counter
727
  p.n_event() = 0;
197,646,347 ✔
728

729
  // Initialize track counter (1 for this primary/secondary track)
730
  p.n_tracks() = 1;
197,646,347 ✔
731

732
  // Reset split counter
733
  p.n_split() = 0;
197,646,347 ✔
734

735
  // Reset weight window ratio
736
  p.ww_factor() = 0.0;
197,646,347 ✔
737

738
  // set particle history start weight
739
  p.wgt_born() = p.wgt();
197,646,347 ✔
740

741
  // Reset pulse_height_storage
742
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
197,646,347 ✔
743

744
  // A primary is the root of its own tree. Secondaries overwrite this in
745
  // Particle::event_revive_from_secondary() using the value carried on the
746
  // bank site. Only meaningful in shared-secondary mode, where a history is
747
  // spread over several Particle objects; harmless otherwise.
748
  if (!is_secondary) {
197,646,347 ✔
749
    p.root_index() = phase1_first_root(mpi::rank) + index_source - 1;
181,941,194 ✔
750
  }
751

752
  // set random number seed
753
  int64_t particle_seed = compute_transport_seed(p.id());
197,646,347 ✔
754
  init_particle_seeds(particle_seed, p.seeds());
197,646,347 ✔
755

756
  // set particle trace
757
  p.trace() = false;
197,646,347 ✔
758
  if (simulation::current_batch == settings::trace_batch &&
197,657,347 ✔
759
      simulation::current_gen == settings::trace_gen &&
197,646,347 !
760
      p.id() == settings::trace_particle)
11,000 ✔
761
    p.trace() = true;
11 ✔
762

763
  // Set particle track.
764
  p.write_track() = check_track_criteria(p);
197,646,347 ✔
765

766
  // Set the particle's initial weight window value.
767
  if (!is_secondary) {
197,646,347 ✔
768
    p.wgt_ww_born() = -1.0;
181,941,194 ✔
769
    apply_weight_windows(p);
181,941,194 ✔
770
  }
771

772
  // Display message if high verbosity or trace is on
773
  if (settings::verbosity >= 9 || p.trace()) {
197,646,347 !
774
    write_message("Simulating Particle {}", p.id());
22 ✔
775
  }
776

777
  // Add particle's starting weight to count for normalizing tallies later
778
  if (!is_secondary) {
197,646,347 ✔
779
#pragma omp atomic
100,654,075 ✔
780
    simulation::total_weight += p.wgt();
181,941,194 ✔
781
  }
782

783
  // Force calculation of cross-sections by setting last energy to zero
784
  if (settings::run_CE) {
197,646,347 ✔
785
    p.invalidate_neutron_xs();
83,097,803 ✔
786
  }
787

788
  // Prepare to write out particle track.
789
  if (p.write_track())
197,646,347 ✔
790
    add_particle_track(p);
999 ✔
791
}
197,646,347 ✔
792

793
int overall_generation()
208,429,329 ✔
794
{
795
  using namespace simulation;
208,429,329 ✔
796
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
208,429,329 ✔
797
}
798

799
int64_t compute_particle_id(int64_t index_source)
227,230,820 ✔
800
{
801
  if (settings::use_shared_secondary_bank) {
227,230,820 ✔
802
    return simulation::work_index[mpi::rank] + index_source +
19,075,868 ✔
803
           simulation::simulation_tracks_completed;
19,075,868 ✔
804
  } else {
805
    return simulation::work_index[mpi::rank] + index_source;
208,154,952 ✔
806
  }
807
}
808

809
int64_t compute_transport_seed(int64_t particle_id)
227,230,864 ✔
810
{
811
  if (settings::use_shared_secondary_bank) {
227,230,864 ✔
812
    return particle_id;
813
  } else {
814
    return (simulation::total_gen + overall_generation() - 1) *
208,154,985 ✔
815
             settings::n_particles +
816
           particle_id;
208,154,985 ✔
817
  }
818
}
819

820
int64_t phase1_first_root(int rank)
181,986,537 ✔
821
{
822
  // Reproduces the partition calculate_work(settings::n_particles) produces,
823
  // without depending on the current contents of simulation::work_index, which
824
  // is overwritten for every secondary generation. The partition is a pure
825
  // function of the primary count and the number of ranks, so it can be
826
  // recomputed wherever it is needed instead of being snapshotted.
827
  int64_t min_work = settings::n_particles / mpi::n_procs;
181,986,537 ✔
828
  int64_t remainder = settings::n_particles % mpi::n_procs;
181,986,537 ✔
829
  return rank < remainder
181,986,537 ✔
830
           ? static_cast<int64_t>(rank) * (min_work + 1)
181,986,537 !
831
           : remainder * (min_work + 1) +
181,986,537 ✔
832
               (static_cast<int64_t>(rank) - remainder) * min_work;
181,986,537 ✔
833
}
834

835
int phase1_owner_of_root(int64_t root)
418,924 ✔
836
{
837
  int64_t min_work = settings::n_particles / mpi::n_procs;
418,924 ✔
838
  int64_t remainder = settings::n_particles % mpi::n_procs;
418,924 ✔
839

840
  // Ranks below the remainder carry one extra primary each. Roots below the
841
  // boundary fall in that region; the rest divide evenly. When min_work is
842
  // zero the boundary equals n_particles, so the second branch, which would
843
  // divide by zero, is unreachable.
844
  int64_t boundary = remainder * (min_work + 1);
418,924 ✔
845
  if (root < boundary) {
418,924 !
NEW
846
    return static_cast<int>(root / (min_work + 1));
×
847
  }
848
  return static_cast<int>(remainder + (root - boundary) / min_work);
418,924 ✔
849
}
850

851
void resolve_root_indices(
43,793 ✔
852
  SharedArray<SourceSite>& sites, const SharedArray<SourceSite>* parents)
853
{
854
  // Every site has now been placed, so its placement key has been consumed and
855
  // the field can be overwritten with the root of its history. A site's parent
856
  // is a primary when parents is null, and an entry of the generation just
857
  // transported otherwise; in the latter case that entry already carries its
858
  // own root, so the value simply propagates down the tree.
859
  int64_t n = sites.size();
43,793 ✔
860
  int64_t n_parents = parents ? parents->size() : 0;
43,793 ✔
861
  int64_t first_root = phase1_first_root(mpi::rank);
43,793 ✔
862

863
#pragma omp parallel for schedule(static)
24,554 ✔
864
  for (int64_t i = 0; i < n; ++i) {
7,154,854 ✔
865
    int64_t slot = sites[i].parent_slot();
7,135,615 ✔
866
    if (parents) {
7,135,615 ✔
867
      if (slot < 0 || slot >= n_parents) {
6,315,745 !
868
        // fatal_error aborts the process, so it is safe to call from inside a
869
        // parallel region
870
        fatal_error(fmt::format("Invalid parent slot {} while resolving root "
×
871
                                "index (expected range [0, {})).",
872
          slot, n_parents));
873
      }
874
      sites[i].root_index() = (*parents)[slot].root_index();
6,315,745 ✔
875
    } else {
876
      sites[i].root_index() = first_root + slot;
819,870 ✔
877
    }
878
  }
879
}
43,793 ✔
880

881
void calculate_work(int64_t n_particles)
52,055 ✔
882
{
883
  // Determine minimum amount of particles to simulate on each processor
884
  int64_t min_work = n_particles / mpi::n_procs;
52,055 ✔
885

886
  // Determine number of processors that have one extra particle
887
  int64_t remainder = n_particles % mpi::n_procs;
52,055 ✔
888

889
  int64_t i_bank = 0;
52,055 ✔
890
  simulation::work_index.resize(mpi::n_procs + 1);
52,055 ✔
891
  simulation::work_index[0] = 0;
52,055 ✔
892
  for (int i = 0; i < mpi::n_procs; ++i) {
112,629 ✔
893
    // Number of particles for rank i
894
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
60,574 ✔
895

896
    // Set number of particles
897
    if (mpi::rank == i)
60,574 ✔
898
      simulation::work_per_rank = work_i;
52,055 ✔
899

900
    // Set index into source bank for rank i
901
    i_bank += work_i;
60,574 ✔
902
    simulation::work_index[i + 1] = i_bank;
60,574 ✔
903
  }
904
}
52,055 ✔
905

906
void initialize_data()
6,815 ✔
907
{
908
  // Determine minimum/maximum energy for incident neutron/photon data
909
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
6,815 ✔
910
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
6,815 ✔
911

912
  for (const auto& nuc : data::nuclides) {
41,224 ✔
913
    if (nuc->grid_.size() >= 1) {
34,409 !
914
      int neutron = ParticleType::neutron().transport_index();
34,409 ✔
915
      data::energy_min[neutron] =
34,409 ✔
916
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
40,659 ✔
917
      data::energy_max[neutron] =
34,409 ✔
918
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
42,293 ✔
919
    }
920
  }
921

922
  if (settings::photon_transport) {
6,815 ✔
923
    for (const auto& elem : data::elements) {
2,546 ✔
924
      if (elem->energy_.size() >= 1) {
1,821 !
925
        int photon = ParticleType::photon().transport_index();
1,821 ✔
926
        int n = elem->energy_.size();
1,821 ✔
927
        data::energy_min[photon] =
3,642 ✔
928
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
2,948 ✔
929
        data::energy_max[photon] =
1,821 ✔
930
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
2,546 ✔
931
      }
932
    }
933

934
    if (settings::electron_treatment == ElectronTreatment::TTB) {
725 ✔
935
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
936
      // than the current minimum/maximum
937
      if (data::ttb_e_grid.size() >= 1) {
607 !
938
        int photon = ParticleType::photon().transport_index();
607 ✔
939
        int electron = ParticleType::electron().transport_index();
607 ✔
940
        int positron = ParticleType::positron().transport_index();
607 ✔
941
        int n_e = data::ttb_e_grid.size();
607 ✔
942

943
        const std::vector<int> charged = {electron, positron};
607 ✔
944
        for (auto t : charged) {
1,821 ✔
945
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
1,214 ✔
946
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
1,214 ✔
947
        }
948

949
        data::energy_min[photon] =
1,214 ✔
950
          std::max(data::energy_min[photon], data::energy_min[electron]);
1,214 !
951

952
        data::energy_max[photon] =
1,214 ✔
953
          std::min(data::energy_max[photon], data::energy_max[electron]);
1,214 !
954
      }
607 ✔
955
    }
956
  }
957

958
  // Show which nuclide results in lowest energy for neutron transport
959
  for (const auto& nuc : data::nuclides) {
8,568 ✔
960
    // If a nuclide is present in a material that's not used in the model, its
961
    // grid has not been allocated
962
    if (nuc->grid_.size() > 0) {
8,003 !
963
      double max_E = nuc->grid_[0].energy.back();
8,003 ✔
964
      int neutron = ParticleType::neutron().transport_index();
8,003 ✔
965
      if (max_E == data::energy_max[neutron]) {
8,003 ✔
966
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
6,250 ✔
967
          data::energy_max[neutron], nuc->name_);
6,250 ✔
968
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
6,250 !
969
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
970
                  "the results.");
971
        }
972
        break;
973
      }
974
    }
975
  }
976

977
  // Set up logarithmic grid for nuclides
978
  for (auto& nuc : data::nuclides) {
41,224 ✔
979
    nuc->init_grid();
34,409 ✔
980
  }
981
  int neutron = ParticleType::neutron().transport_index();
6,815 ✔
982
  simulation::log_spacing =
13,630 ✔
983
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,815 ✔
984
    settings::n_log_bins;
985
}
6,815 ✔
986

987
#ifdef OPENMC_MPI
988
void broadcast_results()
3,658 ✔
989
{
990
  // Broadcast tally results so that each process has access to results
991
  for (auto& t : model::tallies) {
17,591 ✔
992
    // Create a new datatype that consists of all values for a given filter
993
    // bin and then use that to broadcast. This is done to minimize the
994
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
995
    auto& results = t->results_;
13,933 ✔
996

997
    auto shape = results.shape();
13,933 ✔
998
    int count_per_filter = shape[1] * shape[2];
13,933 ✔
999
    MPI_Datatype result_block;
13,933 ✔
1000
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
13,933 ✔
1001
    MPI_Type_commit(&result_block);
13,933 ✔
1002
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
13,933 ✔
1003
    MPI_Type_free(&result_block);
13,933 ✔
1004
  }
13,933 ✔
1005

1006
  // Also broadcast global tally results
1007
  auto& gt = simulation::global_tallies;
3,658 ✔
1008
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,658 ✔
1009

1010
  // These guys are needed so that non-master processes can calculate the
1011
  // combined estimate of k-effective
1012
  double temp[] {
3,658 ✔
1013
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,658 ✔
1014
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,658 ✔
1015
  simulation::k_col_abs = temp[0];
3,658 ✔
1016
  simulation::k_col_tra = temp[1];
3,658 ✔
1017
  simulation::k_abs_tra = temp[2];
3,658 ✔
1018
}
3,658 ✔
1019

1020
#endif
1021

1022
void free_memory_simulation()
9,515 ✔
1023
{
1024
  simulation::k_generation.clear();
9,515 ✔
1025
  simulation::entropy.clear();
9,515 ✔
1026
}
9,515 ✔
1027

1028
void transport_history_based_single_particle(Particle& p)
185,121,985 ✔
1029
{
1030
  while (p.alive()) {
2,147,483,647 ✔
1031
    p.event_calculate_xs();
2,147,483,647 ✔
1032
    if (p.alive()) {
2,147,483,647 !
1033
      p.event_advance();
2,147,483,647 ✔
1034
    }
1035
    if (p.alive()) {
2,147,483,647 ✔
1036
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647 ✔
1037
        p.event_cross_surface();
2,147,483,647 ✔
1038
      } else if (p.alive()) {
2,147,483,647 ✔
1039
        p.event_collide();
2,147,483,647 ✔
1040
      }
1041
    }
1042
    p.event_check_limit_and_revive();
2,147,483,647 ✔
1043
  }
1044
  p.event_death();
185,121,976 ✔
1045
}
185,121,976 ✔
1046

1047
void transport_history_based()
144,755 ✔
1048
{
1049
#pragma omp parallel
80,619 ✔
1050
  {
64,136 ✔
1051
    Particle p;
64,136 ✔
1052
#pragma omp for schedule(runtime)
1053
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
81,918,041 ✔
1054
      initialize_particle_track(p, i_work, false);
81,853,914 ✔
1055
      transport_history_based_single_particle(p);
81,853,910 ✔
1056
    }
1057
  }
64,127 ✔
1058
}
144,746 ✔
1059

1060
// The shared secondary bank transport algorithm works in two phases. In the
1061
// first phase, all primary particles are sampled then transported, and their
1062
// secondary particles are deposited into a shared secondary bank. The second
1063
// phase occurs in a loop, where all secondary tracks in the shared secondary
1064
// bank are transported. Any secondary particles generated during this phase are
1065
// deposited back into the shared secondary bank. The shared secondary bank is
1066
// sorted for consistent ordering and load balanced across MPI ranks. This loop
1067
// continues until there are no more secondary tracks left to transport.
1068
void transport_history_based_shared_secondary()
3,822 ✔
1069
{
1070
  // Clear shared secondary banks from any prior use
1071
  simulation::shared_secondary_bank_read.clear();
3,822 ✔
1072
  simulation::shared_secondary_bank_write.clear();
3,822 ✔
1073

1074
  if (!model::active_pulse_height_tallies.empty()) {
3,822 ✔
1075
    init_pulse_height_buffers();
760 ✔
1076
  }
1077

1078
  if (mpi::master) {
3,822 ✔
1079
    write_message(fmt::format(" Primary source          particles: {}",
7,260 ✔
1080
                    settings::n_particles),
1081
      6);
1082
  }
1083

1084
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
3,822 ✔
1085
  std::fill(simulation::progeny_per_particle.begin(),
7,644 ✔
1086
    simulation::progeny_per_particle.end(), 0);
3,822 ✔
1087

1088
  vector<vector<SourceSite>> thread_banks(num_threads());
3,822 ✔
1089

1090
  // Phase 1: Transport primary particles and deposit first generation of
1091
  // secondaries in the shared secondary bank
1092
#pragma omp parallel
2,114 ✔
1093
  {
1,708 ✔
1094
    auto& thread_bank = thread_banks[thread_num()];
1,708 ✔
1095
    Particle p;
1,708 ✔
1096

1097
#pragma omp for schedule(runtime)
1098
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
766,958 ✔
1099
      initialize_particle_track(p, i, false);
765,250 ✔
1100
      transport_history_based_single_particle(p);
765,250 ✔
1101
      for (auto& site : p.local_secondary_bank()) {
1,585,120 ✔
1102
        thread_bank.push_back(site);
819,870 ✔
1103
      }
1104
      p.local_secondary_bank().clear();
925,400 ✔
1105
    }
1106
  }
1107
  collect_sorted_history_secondary_banks(thread_banks);
3,822 ✔
1108
  resolve_root_indices(simulation::shared_secondary_bank_write, nullptr);
3,822 ✔
1109
  thread_banks.clear();
3,822 ✔
1110

1111
  simulation::simulation_tracks_completed += settings::n_particles;
3,822 ✔
1112

1113
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1114
  // all secondary generations
1115
  int n_generation_depth = 1;
3,822 ✔
1116
  int64_t alive_secondary = 1;
3,822 ✔
1117
  while (alive_secondary) {
43,044 ✔
1118

1119
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1120
    // that each MPI rank has an approximately equal number of secondary
1121
    // tracks. Also reports the total number of secondaries alive across
1122
    // all MPI ranks.
1123
    alive_secondary = synchronize_global_secondary_bank(
39,222 ✔
1124
      simulation::shared_secondary_bank_write);
1125

1126
    // Recalculate work for each MPI rank based on number of alive secondary
1127
    // tracks
1128
    calculate_work(alive_secondary);
39,222 ✔
1129

1130
    // Display the number of secondary tracks in this generation. This
1131
    // is useful for user monitoring so as to see if the secondary population is
1132
    // exploding and to determine how many generations of secondaries are being
1133
    // transported.
1134
    if (mpi::master) {
39,222 ✔
1135
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
72,356 ✔
1136
                      n_generation_depth, alive_secondary),
1137
        6);
1138
    }
1139

1140
    simulation::shared_secondary_bank_read =
39,222 ✔
1141
      std::move(simulation::shared_secondary_bank_write);
39,222 ✔
1142
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
39,222 !
1143
    simulation::progeny_per_particle.resize(
39,222 ✔
1144
      simulation::shared_secondary_bank_read.size());
39,222 ✔
1145
    std::fill(simulation::progeny_per_particle.begin(),
78,444 ✔
1146
      simulation::progeny_per_particle.end(), 0);
39,222 ✔
1147
    thread_banks.resize(num_threads());
39,222 ✔
1148

1149
    // Transport all secondary tracks from the shared secondary bank
1150
#pragma omp parallel
21,691 ✔
1151
    {
17,531 ✔
1152
      auto& thread_bank = thread_banks[thread_num()];
17,531 ✔
1153
      Particle p;
17,531 ✔
1154

1155
#pragma omp for schedule(runtime)
1156
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
7,153,146 ✔
1157
           i++) {
1158
        initialize_particle_track(p, i, true);
7,135,615 ✔
1159
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
7,135,615 ✔
1160
        p.event_revive_from_secondary(site);
7,135,615 ✔
1161
        transport_history_based_single_particle(p);
7,135,615 ✔
1162
        for (auto& secondary_site : p.local_secondary_bank()) {
13,451,360 ✔
1163
          thread_bank.push_back(secondary_site);
6,315,745 ✔
1164
        }
1165
        p.local_secondary_bank().clear();
9,633,480 ✔
1166
      }
1167
    } // End of transport loop over tracks in shared secondary bank
1168
    // The bank just transported is needed to resolve the roots of the sites it
1169
    // produced, so it is released after collection rather than recycled into
1170
    // the write bank beforehand.
1171
    collect_sorted_history_secondary_banks(thread_banks);
39,222 ✔
1172
    resolve_root_indices(simulation::shared_secondary_bank_write,
39,222 ✔
1173
      &simulation::shared_secondary_bank_read);
1174
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
39,222 !
1175
    thread_banks.clear();
39,222 ✔
1176
    n_generation_depth++;
39,222 ✔
1177
    simulation::simulation_tracks_completed += alive_secondary;
39,222 ✔
1178
  } // End of loop over secondary generations
1179

1180
  // The full particle tree of every history is now complete, so per-history
1181
  // pulse-height results can be reassembled and scored.
1182
  if (!model::active_pulse_height_tallies.empty()) {
3,822 ✔
1183
    finalize_pulse_height_tallies();
760 ✔
1184
  }
1185

1186
  // Reset work so that fission bank etc works correctly
1187
  calculate_work(settings::n_particles);
3,822 ✔
1188
}
3,822 ✔
1189

1190
void transport_event_based()
3,226 ✔
1191
{
1192
  int64_t remaining_work = simulation::work_per_rank;
3,226 ✔
1193
  int64_t source_offset = 0;
3,226 ✔
1194

1195
  // To cap the total amount of memory used to store particle object data, the
1196
  // number of particles in flight at any point in time can bet set. In the case
1197
  // that the maximum in flight particle count is lower than the total number
1198
  // of particles that need to be run this iteration, the event-based transport
1199
  // loop is executed multiple times until all particles have been completed.
1200
  while (remaining_work > 0) {
6,452 ✔
1201
    // Figure out # of particles to run for this subiteration
1202
    int64_t n_particles =
3,226 !
1203
      std::min(remaining_work, settings::max_particles_in_flight);
3,226 ✔
1204

1205
    // Initialize all particle histories for this subiteration
1206
    process_init_events(n_particles, source_offset);
3,226 ✔
1207
    process_transport_events();
3,226 ✔
1208
    process_death_events(n_particles);
3,226 ✔
1209

1210
    // Adjust remaining work and source offset variables
1211
    remaining_work -= n_particles;
3,226 ✔
1212
    source_offset += n_particles;
3,226 ✔
1213
  }
1214
}
3,226 ✔
1215

1216
void transport_event_based_shared_secondary()
36 ✔
1217
{
1218
  // Clear shared secondary banks from any prior use
1219
  simulation::shared_secondary_bank_read.clear();
36 ✔
1220
  simulation::shared_secondary_bank_write.clear();
36 ✔
1221

1222
  if (!model::active_pulse_height_tallies.empty()) {
36 ✔
1223
    init_pulse_height_buffers();
15 ✔
1224
  }
1225

1226
  if (mpi::master) {
36 !
1227
    write_message(fmt::format(" Primary source          particles: {}",
72 !
1228
                    settings::n_particles),
1229
      6);
1230
  }
1231

1232
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
36 ✔
1233
  std::fill(simulation::progeny_per_particle.begin(),
72 ✔
1234
    simulation::progeny_per_particle.end(), 0);
36 ✔
1235

1236
  // Phase 1: Transport primary particles using event-based processing and
1237
  // deposit first generation of secondaries in the shared secondary bank
1238
  int64_t remaining_work = simulation::work_per_rank;
36 ✔
1239
  int64_t source_offset = 0;
36 ✔
1240

1241
  while (remaining_work > 0) {
72 ✔
1242
    int64_t n_particles =
36 !
1243
      std::min(remaining_work, settings::max_particles_in_flight);
36 ✔
1244

1245
    process_init_events(n_particles, source_offset);
36 ✔
1246
    process_transport_events();
36 ✔
1247
    process_death_events(n_particles);
36 ✔
1248

1249
    collect_event_secondary_banks(n_particles);
36 ✔
1250

1251
    remaining_work -= n_particles;
36 ✔
1252
    source_offset += n_particles;
36 ✔
1253
  }
1254

1255
  simulation::simulation_tracks_completed += settings::n_particles;
36 ✔
1256

1257
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1258
  // all secondary generations
1259
  int n_generation_depth = 1;
36 ✔
1260
  int64_t alive_secondary = 1;
36 ✔
1261
  while (alive_secondary) {
785 ✔
1262

1263
    // Sort the shared secondary bank by parent ID then progeny ID to
1264
    // ensure reproducibility.
1265
    sort_bank(simulation::shared_secondary_bank_write, false);
749 ✔
1266

1267
    // Roots are resolved after the sort, which consumes the placement key, and
1268
    // before the migration below, which invalidates the parent slots by moving
1269
    // sites away from the rank whose bank they index. On the first pass the
1270
    // read bank is empty because the parents were the primaries.
1271
    resolve_root_indices(simulation::shared_secondary_bank_write,
785 ✔
1272
      simulation::shared_secondary_bank_read.size() > 0
749 ✔
1273
        ? &simulation::shared_secondary_bank_read
1274
        : nullptr);
1275

1276
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1277
    // that each MPI rank has an approximately equal number of secondary
1278
    // tracks.
1279
    alive_secondary = synchronize_global_secondary_bank(
749 ✔
1280
      simulation::shared_secondary_bank_write);
1281

1282
    // Recalculate work for each MPI rank based on number of alive secondary
1283
    // tracks
1284
    calculate_work(alive_secondary);
749 ✔
1285

1286
    if (mpi::master) {
749 !
1287
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
1,498 !
1288
                      n_generation_depth, alive_secondary),
1289
        6);
1290
    }
1291

1292
    simulation::shared_secondary_bank_read =
749 ✔
1293
      std::move(simulation::shared_secondary_bank_write);
749 ✔
1294
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
749 !
1295
    simulation::progeny_per_particle.resize(
749 ✔
1296
      simulation::shared_secondary_bank_read.size());
749 ✔
1297
    std::fill(simulation::progeny_per_particle.begin(),
1,498 ✔
1298
      simulation::progeny_per_particle.end(), 0);
749 ✔
1299

1300
    // Ensure particle buffer is large enough for this secondary generation
1301
    int64_t sec_buffer_length = std::min(
749 !
1302
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
749 !
1303
      settings::max_particles_in_flight);
749 ✔
1304
    if (sec_buffer_length >
749 ✔
1305
        static_cast<int64_t>(simulation::particles.size())) {
749 ✔
1306
      init_event_queues(sec_buffer_length);
53 ✔
1307
    }
1308

1309
    // Transport secondary tracks using event-based processing
1310
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
749 ✔
1311
    int64_t sec_offset = 0;
749 ✔
1312

1313
    while (sec_remaining > 0) {
1,462 ✔
1314
      int64_t n_particles =
713 !
1315
        std::min(sec_remaining, settings::max_particles_in_flight);
713 ✔
1316

1317
      process_init_secondary_events(
713 ✔
1318
        n_particles, sec_offset, simulation::shared_secondary_bank_read);
1319
      process_transport_events();
713 ✔
1320
      process_death_events(n_particles);
713 ✔
1321

1322
      collect_event_secondary_banks(n_particles);
713 ✔
1323

1324
      sec_remaining -= n_particles;
713 ✔
1325
      sec_offset += n_particles;
713 ✔
1326
    } // End of subiteration loop over secondary tracks
1327
    n_generation_depth++;
749 ✔
1328
    simulation::simulation_tracks_completed += alive_secondary;
749 ✔
1329
  } // End of loop over secondary generations
1330

1331
  // The full particle tree of every history is now complete, so per-history
1332
  // pulse-height results can be reassembled and scored.
1333
  if (!model::active_pulse_height_tallies.empty()) {
36 ✔
1334
    finalize_pulse_height_tallies();
15 ✔
1335
  }
1336

1337
  // Reset work so that fission bank etc works correctly
1338
  calculate_work(settings::n_particles);
36 ✔
1339
}
36 ✔
1340

1341
extern "C" int openmc_get_current_batch()
11,253 ✔
1342
{
1343
  return simulation::current_batch;
11,253 ✔
1344
}
1345

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