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

openmc-dev / openmc / 29870010623

21 Jul 2026 09:27PM UTC coverage: 81.397% (+0.09%) from 81.305%
29870010623

Pull #3971

github

web-flow
Merge ab665380e into 852f92780
Pull Request #3971: Delta tracking

18715 of 27082 branches covered (69.1%)

Branch coverage included in aggregate %.

612 of 660 new or added lines in 20 files covered. (92.73%)

534 existing lines in 12 files now uncovered.

60444 of 70168 relevant lines covered (86.14%)

48950546.16 hits per line

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

92.74
/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/majorant.h"
13
#include "openmc/material.h"
14
#include "openmc/message_passing.h"
15
#include "openmc/nuclide.h"
16
#include "openmc/openmp_interface.h"
17
#include "openmc/output.h"
18
#include "openmc/particle.h"
19
#include "openmc/photon.h"
20
#include "openmc/random_lcg.h"
21
#include "openmc/random_ray/flat_source_domain.h"
22
#include "openmc/settings.h"
23
#include "openmc/source.h"
24
#include "openmc/state_point.h"
25
#include "openmc/tallies/derivative.h"
26
#include "openmc/tallies/filter.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,851 ✔
58
{
59
  openmc::simulation::time_total.start();
6,851 ✔
60
  openmc_simulation_init();
6,851 ✔
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,851 ✔
65
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
6,851 ✔
66
    status = openmc::STATUS_EXIT_MAX_BATCH;
11 ✔
67
  }
68

69
  int err = 0;
70
  while (status == 0 && err == 0) {
149,074 ✔
71
    err = openmc_next_batch(&status);
142,236 ✔
72
  }
73

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

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

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

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

92
  // Create the majorant cross sections for delta tracking.
93
  if (settings::delta_tracking) {
8,001 ✔
94
    create_majorants();
150 ✔
95
  }
96

97
  // Determine how much work each process should do
98
  calculate_work(settings::n_particles);
8,001 ✔
99

100
  // Allocate source, fission and surface source banks.
101
  allocate_banks();
8,001 ✔
102

103
  // Create track file if needed
104
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
8,001 ✔
105
    open_track_file();
90 ✔
106
  }
107

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

116
  // Allocate tally results arrays if they're not allocated yet
117
  for (auto& t : model::tallies) {
35,810 ✔
118
    t->set_strides();
27,809 ✔
119
    t->init_results();
27,809 ✔
120
  }
121

122
  // Set up material nuclide index mapping
123
  for (auto& mat : model::materials) {
28,077 ✔
124
    mat->init_nuclide_index();
20,076 ✔
125
  }
126

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

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

150
  // Display header
151
  if (mpi::master) {
8,001 ✔
152
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,949 ✔
153
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,052 ✔
154
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,676 ✔
155
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
376 !
156
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
376 ✔
157
      }
158
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,897 !
159
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,897 ✔
160
        header("K EIGENVALUE SIMULATION", 3);
3,622 ✔
161
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
275 !
162
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
275 ✔
163
      }
164
      if (settings::verbosity >= 7)
3,897 ✔
165
        print_columns();
3,517 ✔
166
    }
167
  }
168

169
  // load weight windows from file
170
  if (!settings::weight_windows_file.empty()) {
8,001 !
UNCOV
171
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
×
172
  }
173

174
  // Set flag indicating initialization is done
175
  simulation::initialized = true;
8,001 ✔
176
  return 0;
8,001 ✔
177
}
178

179
int openmc_simulation_finalize()
7,988 ✔
180
{
181
  using namespace openmc;
7,988 ✔
182

183
  // Skip if simulation was never run
184
  if (!simulation::initialized)
7,988 !
185
    return 0;
186

187
  // Stop active batch timer and start finalization timer
188
  simulation::time_active.stop();
7,988 ✔
189
  simulation::time_finalize.start();
7,988 ✔
190

191
  // Clear material nuclide mapping
192
  for (auto& mat : model::materials) {
28,051 ✔
193
    mat->mat_nuclide_index_.clear();
40,126 !
194
  }
195

196
  // Close track file if open
197
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,988 ✔
198
    close_track_file();
90 ✔
199
  }
200

201
  // Increment total number of generations
202
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
7,988 ✔
203

204
#ifdef OPENMC_MPI
205
  broadcast_results();
3,594 ✔
206
#endif
207

208
  // Write tally results to tallies.out
209
  if (settings::output_tallies && mpi::master)
7,988 !
210
    write_tallies();
6,590 ✔
211

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

221
  // Deactivate all tallies
222
  for (auto& t : model::tallies) {
35,797 ✔
223
    t->active_ = false;
27,809 ✔
224
  }
225

226
  // Stop timers and show timing statistics
227
  simulation::time_finalize.stop();
7,988 ✔
228
  simulation::time_total.stop();
7,988 ✔
229

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

243
  if (mpi::master) {
7,988 ✔
244
    if (settings::solver_type != SolverType::RANDOM_RAY) {
6,936 ✔
245
      if (settings::verbosity >= 6)
6,285 ✔
246
        print_runtime();
5,905 ✔
247
      if (settings::verbosity >= 4)
6,285 ✔
248
        print_results();
5,905 ✔
249
    }
250
  }
251
  if (settings::check_overlaps)
7,988 !
NEW
252
    print_overlap_check();
×
253

254
  // Clear majorants as they could change if OpenMC is run again.
255
  reset_majorants();
7,988 ✔
256

257
  // Reset flags
258
  simulation::initialized = false;
7,988 ✔
259
  return 0;
7,988 ✔
260
}
261

262
int openmc_next_batch(int* status)
146,361 ✔
263
{
264
  using namespace openmc;
146,361 ✔
265
  using openmc::simulation::current_gen;
146,361 ✔
266

267
  // Make sure simulation has been initialized
268
  if (!simulation::initialized) {
146,361 ✔
269
    set_errmsg("Simulation has not been initialized yet.");
11 ✔
270
    return OPENMC_E_ALLOCATE;
11 ✔
271
  }
272

273
  initialize_batch();
146,350 ✔
274

275
  // =======================================================================
276
  // LOOP OVER GENERATIONS
277
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
292,897 ✔
278

279
    initialize_generation();
146,560 ✔
280

281
    // Start timer for transport
282
    simulation::time_transport.start();
146,560 ✔
283

284
    // Transport loop
285
    if (settings::event_based) {
146,560 ✔
286
      if (settings::use_shared_secondary_bank) {
3,611 ✔
287
        transport_event_based_shared_secondary();
11 ✔
288
      } else {
289
        transport_event_based();
3,600 ✔
290
      }
291
    } else {
292
      if (settings::use_shared_secondary_bank) {
142,949 ✔
293
        transport_history_based_shared_secondary();
667 ✔
294
      } else {
295
        transport_history_based();
142,282 ✔
296
      }
297
    }
298

299
    // Accumulate time for transport
300
    simulation::time_transport.stop();
146,547 ✔
301

302
    finalize_generation();
146,547 ✔
303
  }
304

305
  finalize_batch();
146,337 ✔
306

307
  // Check simulation ending criteria
308
  if (status) {
146,337 !
309
    if (simulation::current_batch >= settings::n_max_batches) {
146,337 ✔
310
      *status = STATUS_EXIT_MAX_BATCH;
7,031 ✔
311
    } else if (simulation::satisfy_triggers) {
139,306 ✔
312
      *status = STATUS_EXIT_ON_TRIGGER;
93 ✔
313
    } else {
314
      *status = STATUS_EXIT_NORMAL;
139,213 ✔
315
    }
316
  }
317
  return 0;
318
}
319

320
bool openmc_is_statepoint_batch()
3,135 ✔
321
{
322
  using namespace openmc;
3,135 ✔
323
  using openmc::simulation::current_gen;
3,135 ✔
324

325
  if (!simulation::initialized)
3,135 !
326
    return false;
327
  else
328
    return contains(settings::statepoint_batch, simulation::current_batch);
6,270 ✔
329
}
330

331
namespace openmc {
332

333
//==============================================================================
334
// Global variables
335
//==============================================================================
336

337
namespace simulation {
338

339
int ct_current_file;
340
int current_batch;
341
int current_gen;
342
bool initialized {false};
343
double keff {1.0};
344
double keff_std;
345
double k_col_abs {0.0};
346
double k_col_tra {0.0};
347
double k_abs_tra {0.0};
348
double log_spacing;
349
int n_lost_particles {0};
350
bool need_depletion_rx {false};
351
int restart_batch;
352
bool satisfy_triggers {false};
353
int ssw_current_file;
354
int total_gen {0};
355
double total_weight;
356
int64_t work_per_rank;
357

358
const RegularMesh* entropy_mesh {nullptr};
359
const RegularMesh* ufs_mesh {nullptr};
360

361
vector<double> k_generation;
362
vector<int64_t> work_index;
363

364
int64_t simulation_tracks_completed {0};
365

366
} // namespace simulation
367

368
namespace {
369

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

383
  // Count the expected number of progeny from per-parent progeny counts
384
  int64_t n_progeny = 0;
8,905 ✔
385
  for (int64_t count : simulation::progeny_per_particle) {
21,951,449 ✔
386
    n_progeny += count;
21,942,544 ✔
387
  }
388

389
  if (n_collected != n_progeny) {
8,905 !
UNCOV
390
    fatal_error("Mismatch detected between sum of all particle progeny and "
×
391
                "secondary bank size during collection.");
392
  }
393

394
  // Convert per-parent progeny counts to offsets into the sorted bank
395
  std::exclusive_scan(simulation::progeny_per_particle.begin(),
8,905 ✔
396
    simulation::progeny_per_particle.end(),
397
    simulation::progeny_per_particle.begin(), 0);
398

399
  // Allocate the shared bank once for the complete generation
400
  simulation::shared_secondary_bank_write.resize(0);
8,905 ✔
401
  simulation::shared_secondary_bank_write.extend_uninitialized(n_progeny);
8,905 ✔
402

403
  // Place each secondary according to its parent and progeny identifiers
404
  for (const auto& bank : thread_banks) {
22,839 ✔
405
    for (const auto& site : bank) {
21,173,643 ✔
406
      if (site.parent_id < 0 ||
21,159,709 !
407
          site.parent_id >=
21,159,709 !
408
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
21,159,709 !
UNCOV
409
        fatal_error(fmt::format("Invalid parent_id {} for banked site "
×
410
                                "(expected range [0, {})).",
UNCOV
411
          site.parent_id, simulation::progeny_per_particle.size()));
×
412
      }
413
      int64_t idx =
21,159,709 ✔
414
        simulation::progeny_per_particle[site.parent_id] + site.progeny_id;
21,159,709 !
415
      if (idx < 0 || idx >= n_progeny) {
21,159,709 !
UNCOV
416
        fatal_error("Mismatch detected between sum of all particle progeny and "
×
417
                    "secondary bank size during collection.");
418
      }
419
      simulation::shared_secondary_bank_write[idx] = site;
21,159,709 ✔
420
    }
421
  }
422
}
8,905 ✔
423

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

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

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

454
} // namespace
455

456
//==============================================================================
457
// Non-member functions
458
//==============================================================================
459

460
void allocate_banks()
8,001 ✔
461
{
462
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,001 ✔
463
      settings::solver_type == SolverType::MONTE_CARLO) {
4,631 ✔
464
    // Allocate source bank
465
    simulation::source_bank.resize(simulation::work_per_rank);
4,260 ✔
466

467
    // Allocate fission bank
468
    init_fission_bank(3 * simulation::work_per_rank);
4,260 ✔
469

470
    // Allocate IFP bank
471
    if (settings::ifp_on) {
4,260 ✔
472
      resize_simulation_ifp_banks();
74 ✔
473
    }
474
  }
475

476
  if (settings::surf_source_write) {
8,001 ✔
477
    // Allocate surface source bank
478
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,154 ✔
479
  }
480

481
  if (settings::collision_track) {
8,001 ✔
482
    // Allocate collision track bank
483
    collision_track_reserve_bank();
160 ✔
484
  }
485
}
8,001 ✔
486

487
void initialize_batch()
167,312 ✔
488
{
489
  // Increment current batch
490
  ++simulation::current_batch;
167,312 ✔
491
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
167,312 ✔
492
    if (settings::solver_type == SolverType::RANDOM_RAY &&
64,869 ✔
493
        simulation::current_batch < settings::n_inactive + 1) {
14,112 ✔
494
      write_message(
16,812 ✔
495
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
496
    } else {
497
      write_message(6, "Simulating batch {}", simulation::current_batch);
112,926 ✔
498
    }
499
  }
500

501
  // Reset total starting particle weight used for normalizing tallies
502
  simulation::total_weight = 0.0;
167,312 ✔
503

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

515
  // Manage active/inactive timers and activate tallies if necessary.
516
  if (first_inactive) {
167,201 ✔
517
    simulation::time_inactive.start();
4,015 ✔
518
  } else if (first_active) {
163,297 ✔
519
    simulation::time_inactive.stop();
7,954 ✔
520
    simulation::time_active.start();
7,954 ✔
521
    for (auto& t : model::tallies) {
35,741 ✔
522
      t->active_ = true;
27,787 ✔
523
    }
524
  }
525

526
  // Add user tallies to active tallies list
527
  setup_active_tallies();
167,312 ✔
528
}
167,312 ✔
529

530
void finalize_batch()
167,299 ✔
531
{
532
  // Reduce tallies onto master process and accumulate
533
  simulation::time_tallies.start();
167,299 ✔
534
  accumulate_tallies();
167,299 ✔
535
  simulation::time_tallies.stop();
167,299 ✔
536

537
  // update weight windows if needed
538
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
169,931 ✔
539
    wwg->update();
2,632 ✔
540
  }
541

542
  // Reset global tally results
543
  if (simulation::current_batch <= settings::n_inactive) {
167,299 ✔
544
    simulation::global_tallies.fill(0.0);
33,353 ✔
545
    simulation::n_realizations = 0;
33,353 ✔
546
  }
547

548
  // Check_triggers
549
  if (mpi::master)
167,299 ✔
550
    check_triggers();
147,940 ✔
551
#ifdef OPENMC_MPI
552
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
73,480 ✔
553
#endif
554
  if (simulation::satisfy_triggers ||
167,299 ✔
555
      (settings::trigger_on &&
2,567 ✔
556
        simulation::current_batch == settings::n_max_batches)) {
2,567 ✔
557
    settings::statepoint_batch.insert(simulation::current_batch);
141 ✔
558
  }
559

560
  // Write out state point if it's been specified for this batch and is not
561
  // a CMFD run instance
562
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
334,598 ✔
563
      !settings::cmfd_run) {
8,256 ✔
564
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
15,882 ✔
565
        settings::source_write && !settings::source_separate) {
14,999 ✔
566
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
6,848 ✔
567
      openmc_statepoint_write(nullptr, &b);
6,848 ✔
568
    } else {
569
      bool b = false;
1,232 ✔
570
      openmc_statepoint_write(nullptr, &b);
1,232 ✔
571
    }
572
  }
573

574
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,299 ✔
575
    // Write out a separate source point if it's been specified for this batch
576
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
107,100 ✔
577
        settings::source_write && settings::source_separate) {
106,729 ✔
578

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

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

597
  // Write out surface source if requested.
598
  if (settings::surf_source_write &&
167,299 ✔
599
      simulation::ssw_current_file <= settings::ssw_max_files) {
17,669 ✔
600
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,976 ✔
601
    if (simulation::surf_source_bank.full() || last_batch) {
1,976 ✔
602
      // Determine appropriate filename
603
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
1,187 ✔
604
        simulation::current_batch);
1,187 ✔
605
      if (settings::ssw_max_files == 1 ||
1,187 ✔
606
          (simulation::ssw_current_file == 1 && last_batch)) {
55 !
607
        filename = settings::path_output + "surface_source";
1,132 ✔
608
      }
609

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

616
      // Write surface source file
617
      write_source_point(
1,187 ✔
618
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
619

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

634
void initialize_generation()
167,522 ✔
635
{
636
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,522 ✔
637
    // Clear out the fission bank
638
    simulation::fission_bank.resize(0);
102,653 ✔
639

640
    // Count source sites if using uniform fission source weighting
641
    if (settings::ufs_on)
102,653 ✔
642
      ufs_count_sites();
150 ✔
643

644
    // Store current value of tracklength k
645
    if (settings::delta_tracking) {
102,653 ✔
646
      simulation::keff_generation = simulation::global_tallies(
1,500 ✔
647
        GlobalTally::K_COLLISION, TallyResult::VALUE);
648
    } else {
649
      simulation::keff_generation = simulation::global_tallies(
101,153 ✔
650
        GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
651
    }
652
  }
653
}
167,522 ✔
654

655
void finalize_generation()
167,509 ✔
656
{
657
  auto& gt = simulation::global_tallies;
167,509 ✔
658

659
  // Update global tallies with the accumulation variables
660
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,509 ✔
661
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
102,653 ✔
662
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
102,653 ✔
663
      global_tally_absorption;
664
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
102,653 ✔
665
      global_tally_tracklength;
666
  }
667
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
167,509 ✔
668

669
  // reset tallies
670
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,509 ✔
671
    global_tally_collision = 0.0;
102,653 ✔
672
    global_tally_absorption = 0.0;
102,653 ✔
673
    global_tally_tracklength = 0.0;
102,653 ✔
674
  }
675
  global_tally_leakage = 0.0;
167,509 ✔
676

677
  if (settings::run_mode == RunMode::EIGENVALUE &&
167,509 ✔
678
      settings::solver_type == SolverType::MONTE_CARLO) {
102,653 ✔
679
    // If using shared memory, stable sort the fission bank (by parent IDs)
680
    // so as to allow for reproducibility regardless of which order particles
681
    // are run in.
682
    sort_bank(simulation::fission_bank, true);
95,803 ✔
683

684
    // Distribute fission bank across processors evenly
685
    synchronize_bank();
95,803 ✔
686
  }
687

688
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,509 ✔
689

690
    // Calculate shannon entropy
691
    if (settings::entropy_on &&
102,653 ✔
692
        settings::solver_type == SolverType::MONTE_CARLO)
14,535 ✔
693
      shannon_entropy();
7,685 ✔
694

695
    // Collect results and statistics
696
    calculate_generation_keff();
102,653 ✔
697
    calculate_average_keff();
102,653 ✔
698

699
    // Write generation output
700
    if (mpi::master && settings::verbosity >= 7) {
102,653 ✔
701
      print_generation();
77,188 ✔
702
    }
703
  }
704
}
167,509 ✔
705

706
void sample_source_particle(Particle& p, int64_t index_source)
178,591,577 ✔
707
{
708
  // Sample a particle from the source bank
709
  if (settings::run_mode == RunMode::EIGENVALUE) {
178,591,577 ✔
710
    p.from_source(&simulation::source_bank[index_source - 1]);
151,004,000 ✔
711
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
27,587,577 !
712
    // initialize random number seed
713
    int64_t id = compute_transport_seed(compute_particle_id(index_source));
27,587,577 ✔
714
    uint64_t seed = init_seed(id, STREAM_SOURCE);
27,587,577 ✔
715
    // sample from external source distribution or custom library then set
716
    auto site = sample_external_source(&seed);
27,587,577 ✔
717
    p.from_source(&site);
27,587,573 ✔
718
  }
719
}
178,591,573 ✔
720

721
void initialize_particle_track(
199,930,896 ✔
722
  Particle& p, int64_t index_source, bool is_secondary)
723
{
724
  // Note: index_source is 1-based (first particle = 1), but current_work() is
725
  // stored as 0-based for direct use as an array index into
726
  // progeny_per_particle, source_bank, ifp banks, etc.
727
  if (!is_secondary) {
199,930,896 ✔
728
    sample_source_particle(p, index_source);
178,591,577 ✔
729
  }
730

731
  p.current_work() = index_source - 1;
199,930,892 ✔
732

733
  // set identifier for particle
734
  p.id() = compute_particle_id(index_source);
199,930,892 ✔
735

736
  // set progeny count to zero
737
  p.n_progeny() = 0;
199,930,892 ✔
738

739
  // Reset particle event counter
740
  p.n_event() = 0;
199,930,892 ✔
741

742
  // Initialize track counter (1 for this primary/secondary track)
743
  p.n_tracks() = 1;
199,930,892 ✔
744

745
  // Reset split counter
746
  p.n_split() = 0;
199,930,892 ✔
747

748
  // Reset weight window ratio
749
  p.ww_factor() = 0.0;
199,930,892 ✔
750

751
  // set particle history start weight
752
  p.wgt_born() = p.wgt();
199,930,892 ✔
753

754
  // Reset pulse_height_storage
755
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
199,930,892 ✔
756

757
  // set random number seed
758
  int64_t particle_seed = compute_transport_seed(p.id());
199,930,892 ✔
759
  init_particle_seeds(particle_seed, p.seeds());
199,930,892 ✔
760

761
  // set particle trace
762
  p.trace() = false;
199,930,892 ✔
763
  if (simulation::current_batch == settings::trace_batch &&
199,941,892 ✔
764
      simulation::current_gen == settings::trace_gen &&
199,930,892 !
765
      p.id() == settings::trace_particle)
11,000 ✔
766
    p.trace() = true;
11 ✔
767

768
  // Set particle track.
769
  p.write_track() = check_track_criteria(p);
199,930,892 ✔
770

771
  // Set the particle's initial weight window value.
772
  if (!is_secondary) {
199,930,892 ✔
773
    p.wgt_ww_born() = -1.0;
178,591,573 ✔
774
    apply_weight_windows(p);
178,591,573 ✔
775
  }
776

777
  // Display message if high verbosity or trace is on
778
  if (settings::verbosity >= 9 || p.trace()) {
199,930,892 !
779
    write_message("Simulating Particle {}", p.id());
22 ✔
780
  }
781

782
  // Compute the majorant and set the delta tracking flag.
783
  if (settings::delta_tracking) {
199,930,892 ✔
784
    p.delta_tracking() = true;
1,100,000 ✔
785
    p.update_majorant();
1,100,000 ✔
786
  }
787

788
  // Add particle's starting weight to count for normalizing tallies later
789
  if (!is_secondary) {
199,930,892 ✔
790
#pragma omp atomic
99,179,083 ✔
791
    simulation::total_weight += p.wgt();
178,591,573 ✔
792
  }
793

794
  // Force calculation of cross-sections by setting last energy to zero
795
  if (settings::run_CE) {
199,930,892 ✔
796
    p.invalidate_neutron_xs();
85,382,348 ✔
797
  }
798

799
  // Prepare to write out particle track.
800
  if (p.write_track())
199,930,892 ✔
801
    add_particle_track(p);
999 ✔
802
}
199,930,892 ✔
803

804
int overall_generation()
204,886,077 ✔
805
{
806
  using namespace simulation;
204,886,077 ✔
807
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
204,886,077 ✔
808
}
809

810
int64_t compute_particle_id(int64_t index_source)
227,518,744 ✔
811
{
812
  if (settings::use_shared_secondary_bank) {
227,518,744 ✔
813
    return simulation::work_index[mpi::rank] + index_source +
22,908,344 ✔
814
           simulation::simulation_tracks_completed;
22,908,344 ✔
815
  } else {
816
    return simulation::work_index[mpi::rank] + index_source;
204,610,400 ✔
817
  }
818
}
819

820
int64_t compute_transport_seed(int64_t particle_id)
227,518,788 ✔
821
{
822
  if (settings::use_shared_secondary_bank) {
227,518,788 ✔
823
    return particle_id;
824
  } else {
825
    return (simulation::total_gen + overall_generation() - 1) *
204,610,433 ✔
826
             settings::n_particles +
827
           particle_id;
204,610,433 ✔
828
  }
829
}
830

831
void calculate_work(int64_t n_particles)
17,323 ✔
832
{
833
  // Determine minimum amount of particles to simulate on each processor
834
  int64_t min_work = n_particles / mpi::n_procs;
17,323 ✔
835

836
  // Determine number of processors that have one extra particle
837
  int64_t remainder = n_particles % mpi::n_procs;
17,323 ✔
838

839
  int64_t i_bank = 0;
17,323 ✔
840
  simulation::work_index.resize(mpi::n_procs + 1);
17,323 ✔
841
  simulation::work_index[0] = 0;
17,323 ✔
842
  for (int i = 0; i < mpi::n_procs; ++i) {
40,277 ✔
843
    // Number of particles for rank i
844
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
22,954 ✔
845

846
    // Set number of particles
847
    if (mpi::rank == i)
22,954 ✔
848
      simulation::work_per_rank = work_i;
17,323 ✔
849

850
    // Set index into source bank for rank i
851
    i_bank += work_i;
22,954 ✔
852
    simulation::work_index[i + 1] = i_bank;
22,954 ✔
853
  }
854
}
17,323 ✔
855

856
void initialize_data()
6,634 ✔
857
{
858
  // Determine minimum/maximum energy for incident neutron/photon data
859
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
6,634 ✔
860
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
6,634 ✔
861
  int neutron = ParticleType::neutron().transport_index();
6,634 ✔
862
  int photon = ParticleType::photon().transport_index();
6,634 ✔
863
  int electron = ParticleType::electron().transport_index();
6,634 ✔
864
  int positron = ParticleType::positron().transport_index();
6,634 ✔
865

866
  for (const auto& nuc : data::nuclides) {
40,412 ✔
867
    if (nuc->grid_.size() >= 1) {
33,778 !
868
      data::energy_min[neutron] =
33,778 ✔
869
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
39,880 ✔
870
      data::energy_max[neutron] =
33,778 ✔
871
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
41,444 ✔
872
    }
873
  }
874

875
  if (settings::photon_transport) {
6,634 ✔
876
    for (const auto& elem : data::elements) {
2,212 ✔
877
      if (elem->energy_.size() >= 1) {
1,622 !
878
        int n = elem->energy_.size();
1,622 ✔
879
        data::energy_min[photon] =
3,244 ✔
880
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
2,659 ✔
881
        data::energy_max[photon] =
1,622 ✔
882
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
2,212 ✔
883
      }
884
    }
885

886
    if (settings::electron_treatment == ElectronTreatment::TTB) {
590 ✔
887
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
888
      // than the current minimum/maximum
889
      if (data::ttb_e_grid.size() >= 1) {
531 !
890
        int n_e = data::ttb_e_grid.size();
531 ✔
891

892
        const std::vector<int> charged = {electron, positron};
531 ✔
893
        for (auto t : charged) {
1,593 ✔
894
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
1,062 ✔
895
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
1,062 ✔
896
        }
897

898
        data::energy_min[photon] =
1,062 ✔
899
          std::max(data::energy_min[photon], data::energy_min[electron]);
1,062 !
900

901
        data::energy_max[photon] =
1,062 ✔
902
          std::min(data::energy_max[photon], data::energy_max[electron]);
1,062 !
903
      }
531 ✔
904
    }
905
  }
906

907
  // Show which nuclide results in lowest energy for neutron transport
908
  for (const auto& nuc : data::nuclides) {
8,258 ✔
909
    // If a nuclide is present in a material that's not used in the model, its
910
    // grid has not been allocated
911
    if (nuc->grid_.size() > 0) {
7,726 !
912
      double max_E = nuc->grid_[0].energy.back();
7,726 ✔
913
      if (max_E == data::energy_max[neutron]) {
7,726 ✔
914
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
6,102 ✔
915
          data::energy_max[neutron], nuc->name_);
6,102 ✔
916
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
6,102 !
NEW
917
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
918
                  "the results.");
919
        }
920
        break;
921
      }
922
    }
923
  }
924

925
  // Set up logarithmic grid for nuclides
926
  for (auto& nuc : data::nuclides) {
40,412 ✔
927
    nuc->init_grid();
33,778 ✔
928
  }
929
  simulation::log_spacing =
13,268 ✔
930
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,634 ✔
931
    settings::n_log_bins;
932
}
6,634 ✔
933

934
#ifdef OPENMC_MPI
935
void broadcast_results()
3,594 ✔
936
{
937
  // Broadcast tally results so that each process has access to results
938
  for (auto& t : model::tallies) {
17,399 ✔
939
    // Create a new datatype that consists of all values for a given filter
940
    // bin and then use that to broadcast. This is done to minimize the
941
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
942
    auto& results = t->results_;
13,805 ✔
943

944
    auto shape = results.shape();
13,805 ✔
945
    int count_per_filter = shape[1] * shape[2];
13,805 ✔
946
    MPI_Datatype result_block;
13,805 ✔
947
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
13,805 ✔
948
    MPI_Type_commit(&result_block);
13,805 ✔
949
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
13,805 ✔
950
    MPI_Type_free(&result_block);
13,805 ✔
951
  }
13,805 ✔
952

953
  // Also broadcast global tally results
954
  auto& gt = simulation::global_tallies;
3,594 ✔
955
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,594 ✔
956

957
  // These guys are needed so that non-master processes can calculate the
958
  // combined estimate of k-effective
959
  double temp[] {
3,594 ✔
960
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,594 ✔
961
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,594 ✔
962
  simulation::k_col_abs = temp[0];
3,594 ✔
963
  simulation::k_col_tra = temp[1];
3,594 ✔
964
  simulation::k_abs_tra = temp[2];
3,594 ✔
965
}
3,594 ✔
966

967
#endif
968

969
void free_memory_simulation()
9,217 ✔
970
{
971
  simulation::k_generation.clear();
9,217 ✔
972
  simulation::entropy.clear();
9,217 ✔
973
}
9,217 ✔
974

975
void transport_history_based_single_particle(Particle& p)
186,485,126 ✔
976
{
977
  while (p.alive()) {
2,147,483,647 ✔
978
    p.event_calculate_xs();
2,147,483,647 ✔
979
    if (p.alive()) {
2,147,483,647 !
980
      p.event_advance();
2,147,483,647 ✔
981
    }
982
    if (p.alive()) {
2,147,483,647 ✔
983
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647 ✔
984
        p.event_cross_surface();
2,147,483,647 ✔
985
      } else if (p.alive()) {
2,147,483,647 ✔
986
        p.event_collide();
2,147,483,647 ✔
987
      }
988
    }
989
    p.event_check_limit_and_revive();
2,147,483,647 ✔
990
  }
991
  p.event_death();
186,485,117 ✔
992
}
186,485,117 ✔
993

994
void transport_delta_history_based_single_particle(Particle& p)
800,000 ✔
995
{
996
  while (p.alive()) {
166,141,730 ✔
997
    p.event_delta_advance();
165,341,730 ✔
998

999
    if (p.alive()) {
165,341,730 !
1000
      // Electrons and positrons collide in-place, no need to rejection sample.
1001
      if (p.type() == ParticleType::electron() ||
165,341,730 ✔
1002
          p.type() == ParticleType::positron()) {
72,988,700 ✔
1003
        p.event_collide();
92,436,050 ✔
1004
      }
1005

1006
      if (p.alive() && p.collision_distance() < p.boundary().distance()) {
165,341,730 ✔
1007
        // Collided before hitting an external boundary. Rejection sample the
1008
        // majorant.
1009
        p.event_calculate_xs();
63,537,450 ✔
1010
        if (p.kill_invalid_maj()) {
63,537,450 !
1011
          break;
1012
        }
1013
        if (p.alive() &&
63,537,450 !
1014
            (prn(p.current_seed()) < (p.macro_xs().total / p.majorant()))) {
63,537,450 ✔
1015
          p.event_collide();
22,537,730 ✔
1016
        }
1017
      } else if (p.alive()) {
101,804,280 ✔
1018
        // Crossed an external boundary before colliding.
1019
        p.event_cross_surface();
9,368,230 ✔
1020
      }
1021
    }
1022

1023
    p.event_check_limit_and_revive();
165,341,730 ✔
1024
  }
1025
  p.event_death();
800,000 ✔
1026
}
800,000 ✔
1027

1028
void transport_history_based()
142,282 ✔
1029
{
1030
#pragma omp parallel
79,297 ✔
1031
  {
62,985 ✔
1032
    Particle p;
62,985 ✔
1033
#pragma omp for schedule(runtime)
1034
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,703,810 ✔
1035
      initialize_particle_track(p, i_work, false);
80,640,834 ✔
1036
      if (settings::delta_tracking) {
80,640,830 ✔
1037
        transport_delta_history_based_single_particle(p);
400,000 ✔
1038
      } else {
1039
        transport_history_based_single_particle(p);
80,240,830 ✔
1040
      }
1041
    }
1042
  }
62,976 ✔
1043
}
142,273 ✔
1044

1045
// The shared secondary bank transport algorithm works in two phases. In the
1046
// first phase, all primary particles are sampled then transported, and their
1047
// secondary particles are deposited into a shared secondary bank. The second
1048
// phase occurs in a loop, where all secondary tracks in the shared secondary
1049
// bank are transported. Any secondary particles generated during this phase are
1050
// deposited back into the shared secondary bank. The shared secondary bank is
1051
// sorted for consistent ordering and load balanced across MPI ranks. This loop
1052
// continues until there are no more secondary tracks left to transport.
1053
void transport_history_based_shared_secondary()
667 ✔
1054
{
1055
  // Clear shared secondary banks from any prior use
1056
  simulation::shared_secondary_bank_read.clear();
667 ✔
1057
  simulation::shared_secondary_bank_write.clear();
667 ✔
1058

1059
  if (mpi::master) {
667 ✔
1060
    write_message(fmt::format(" Primary source          particles: {}",
1,150 ✔
1061
                    settings::n_particles),
1062
      6);
1063
  }
1064

1065
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
667 ✔
1066
  std::fill(simulation::progeny_per_particle.begin(),
1,334 ✔
1067
    simulation::progeny_per_particle.end(), 0);
667 ✔
1068

1069
  vector<vector<SourceSite>> thread_banks(num_threads());
667 ✔
1070

1071
  // Phase 1: Transport primary particles and deposit first generation of
1072
  // secondaries in the shared secondary bank
1073
#pragma omp parallel
384 ✔
1074
  {
283 ✔
1075
    auto& thread_bank = thread_banks[thread_num()];
283 ✔
1076
    Particle p;
283 ✔
1077

1078
#pragma omp for schedule(runtime)
1079
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
356,058 ✔
1080
      initialize_particle_track(p, i, false);
355,775 ✔
1081
      if (settings::delta_tracking) {
355,775 !
1082
        transport_delta_history_based_single_particle(p);
×
1083
      } else {
1084
        transport_history_based_single_particle(p);
355,775 ✔
1085
      }
1086
      for (auto& site : p.local_secondary_bank()) {
1,087,225 ✔
1087
        thread_bank.push_back(site);
731,450 ✔
1088
      }
1089
      p.local_secondary_bank().clear();
444,500 ✔
1090
    }
1091
  }
1092
  collect_sorted_history_secondary_banks(thread_banks);
667 ✔
1093
  thread_banks.clear();
667 ✔
1094

1095
  simulation::simulation_tracks_completed += settings::n_particles;
667 ✔
1096

1097
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1098
  // all secondary generations
1099
  int n_generation_depth = 1;
667 ✔
1100
  int64_t alive_secondary = 1;
667 ✔
1101
  while (alive_secondary) {
8,905 ✔
1102

1103
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1104
    // that each MPI rank has an approximately equal number of secondary
1105
    // tracks. Also reports the total number of secondaries alive across
1106
    // all MPI ranks.
1107
    alive_secondary = synchronize_global_secondary_bank(
8,238 ✔
1108
      simulation::shared_secondary_bank_write);
1109

1110
    // Recalculate work for each MPI rank based on number of alive secondary
1111
    // tracks
1112
    calculate_work(alive_secondary);
8,238 ✔
1113

1114
    // Display the number of secondary tracks in this generation. This
1115
    // is useful for user monitoring so as to see if the secondary population is
1116
    // exploding and to determine how many generations of secondaries are being
1117
    // transported.
1118
    if (mpi::master) {
8,238 ✔
1119
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
13,132 ✔
1120
                      n_generation_depth, alive_secondary),
1121
        6);
1122
    }
1123

1124
    simulation::shared_secondary_bank_read =
8,238 ✔
1125
      std::move(simulation::shared_secondary_bank_write);
8,238 ✔
1126
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
8,238 !
1127
    simulation::progeny_per_particle.resize(
8,238 ✔
1128
      simulation::shared_secondary_bank_read.size());
8,238 ✔
1129
    std::fill(simulation::progeny_per_particle.begin(),
16,476 ✔
1130
      simulation::progeny_per_particle.end(), 0);
8,238 ✔
1131
    thread_banks.resize(num_threads());
8,238 ✔
1132

1133
    // Transport all secondary tracks from the shared secondary bank
1134
#pragma omp parallel
4,645 ✔
1135
    {
3,593 ✔
1136
      auto& thread_bank = thread_banks[thread_num()];
3,593 ✔
1137
      Particle p;
3,593 ✔
1138

1139
#pragma omp for schedule(runtime)
1140
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
9,727,253 ✔
1141
           i++) {
1142
        initialize_particle_track(p, i, true);
9,723,660 ✔
1143
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
9,723,660 ✔
1144
        p.event_revive_from_secondary(site);
9,723,660 ✔
1145
        if (settings::delta_tracking) {
9,723,660 !
1146
          transport_delta_history_based_single_particle(p);
×
1147
        } else {
1148
          transport_history_based_single_particle(p);
9,723,660 ✔
1149
        }
1150
        for (auto& secondary_site : p.local_secondary_bank()) {
18,715,870 ✔
1151
          thread_bank.push_back(secondary_site);
8,992,210 ✔
1152
        }
1153
        p.local_secondary_bank().clear();
11,189,190 ✔
1154
      }
1155
    } // End of transport loop over tracks in shared secondary bank
1156
    simulation::shared_secondary_bank_write =
8,238 ✔
1157
      std::move(simulation::shared_secondary_bank_read);
8,238 ✔
1158
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
8,238 !
1159
    collect_sorted_history_secondary_banks(thread_banks);
8,238 ✔
1160
    thread_banks.clear();
8,238 ✔
1161
    n_generation_depth++;
8,238 ✔
1162
    simulation::simulation_tracks_completed += alive_secondary;
8,238 ✔
1163
  } // End of loop over secondary generations
1164

1165
  // Reset work so that fission bank etc works correctly
1166
  calculate_work(settings::n_particles);
667 ✔
1167
}
667 ✔
1168

1169
void transport_event_based()
3,600 ✔
1170
{
1171
  int64_t remaining_work = simulation::work_per_rank;
3,600 ✔
1172
  int64_t source_offset = 0;
3,600 ✔
1173

1174
  // To cap the total amount of memory used to store particle object data, the
1175
  // number of particles in flight at any point in time can bet set. In the case
1176
  // that the maximum in flight particle count is lower than the total number
1177
  // of particles that need to be run this iteration, the event-based transport
1178
  // loop is executed multiple times until all particles have been completed.
1179
  while (remaining_work > 0) {
7,200 ✔
1180
    // Figure out # of particles to run for this subiteration
1181
    int64_t n_particles =
3,600 !
1182
      std::min(remaining_work, settings::max_particles_in_flight);
3,600 ✔
1183

1184
    // Initialize all particle histories for this subiteration
1185
    if (settings::delta_tracking) {
3,600 ✔
1186
      process_delta_init_events(n_particles, source_offset);
380 ✔
1187
      process_delta_transport_events();
380 ✔
1188
    } else {
1189
      process_init_events(n_particles, source_offset);
3,220 ✔
1190
      process_transport_events();
3,220 ✔
1191
    }
1192
    process_death_events(n_particles);
3,600 ✔
1193

1194
    // Adjust remaining work and source offset variables
1195
    remaining_work -= n_particles;
3,600 ✔
1196
    source_offset += n_particles;
3,600 ✔
1197
  }
1198
}
3,600 ✔
1199

1200
void transport_event_based_shared_secondary()
11 ✔
1201
{
1202
  // Clear shared secondary banks from any prior use
1203
  simulation::shared_secondary_bank_read.clear();
11 ✔
1204
  simulation::shared_secondary_bank_write.clear();
11 ✔
1205

1206
  if (mpi::master) {
11 !
1207
    write_message(fmt::format(" Primary source          particles: {}",
22 !
1208
                    settings::n_particles),
1209
      6);
1210
  }
1211

1212
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
11 ✔
1213
  std::fill(simulation::progeny_per_particle.begin(),
22 ✔
1214
    simulation::progeny_per_particle.end(), 0);
11 ✔
1215

1216
  // Phase 1: Transport primary particles using event-based processing and
1217
  // deposit first generation of secondaries in the shared secondary bank
1218
  int64_t remaining_work = simulation::work_per_rank;
11 ✔
1219
  int64_t source_offset = 0;
11 ✔
1220

1221
  while (remaining_work > 0) {
22 ✔
1222
    int64_t n_particles =
11 !
1223
      std::min(remaining_work, settings::max_particles_in_flight);
11 ✔
1224

1225
    if (settings::delta_tracking) {
11 !
NEW
1226
      process_delta_init_events(n_particles, source_offset);
×
NEW
1227
      process_delta_transport_events();
×
1228
    } else {
1229
      process_init_events(n_particles, source_offset);
11 ✔
1230
      process_transport_events();
11 ✔
1231
    }
1232
    process_death_events(n_particles);
11 ✔
1233

1234
    collect_event_secondary_banks(n_particles);
11 ✔
1235

1236
    remaining_work -= n_particles;
11 ✔
1237
    source_offset += n_particles;
11 ✔
1238
  }
1239

1240
  simulation::simulation_tracks_completed += settings::n_particles;
11 ✔
1241

1242
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1243
  // all secondary generations
1244
  int n_generation_depth = 1;
11 ✔
1245
  int64_t alive_secondary = 1;
11 ✔
1246
  while (alive_secondary) {
417 ✔
1247

1248
    // Sort the shared secondary bank by parent ID then progeny ID to
1249
    // ensure reproducibility.
1250
    sort_bank(simulation::shared_secondary_bank_write, false);
406 ✔
1251

1252
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1253
    // that each MPI rank has an approximately equal number of secondary
1254
    // tracks.
1255
    alive_secondary = synchronize_global_secondary_bank(
406 ✔
1256
      simulation::shared_secondary_bank_write);
1257

1258
    // Recalculate work for each MPI rank based on number of alive secondary
1259
    // tracks
1260
    calculate_work(alive_secondary);
406 ✔
1261

1262
    if (mpi::master) {
406 !
1263
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
812 !
1264
                      n_generation_depth, alive_secondary),
1265
        6);
1266
    }
1267

1268
    simulation::shared_secondary_bank_read =
406 ✔
1269
      std::move(simulation::shared_secondary_bank_write);
406 ✔
1270
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
406 !
1271
    simulation::progeny_per_particle.resize(
406 ✔
1272
      simulation::shared_secondary_bank_read.size());
406 ✔
1273
    std::fill(simulation::progeny_per_particle.begin(),
812 ✔
1274
      simulation::progeny_per_particle.end(), 0);
406 ✔
1275

1276
    // Ensure particle buffer is large enough for this secondary generation
1277
    int64_t sec_buffer_length = std::min(
406 !
1278
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
406 !
1279
      settings::max_particles_in_flight);
406 ✔
1280
    if (sec_buffer_length >
406 ✔
1281
        static_cast<int64_t>(simulation::particles.size())) {
406 ✔
1282
      init_event_queues(sec_buffer_length);
34 ✔
1283
    }
1284

1285
    // Transport secondary tracks using event-based processing
1286
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
406 ✔
1287
    int64_t sec_offset = 0;
406 ✔
1288

1289
    while (sec_remaining > 0) {
801 ✔
1290
      int64_t n_particles =
395 !
1291
        std::min(sec_remaining, settings::max_particles_in_flight);
395 ✔
1292

1293
      if (settings::delta_tracking) {
395 !
UNCOV
1294
        process_delta_init_secondary_events(
×
1295
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
UNCOV
1296
        process_delta_transport_events();
×
1297
      } else {
1298
        process_init_secondary_events(
395 ✔
1299
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
1300
        process_transport_events();
395 ✔
1301
      }
1302
      process_death_events(n_particles);
395 ✔
1303

1304
      collect_event_secondary_banks(n_particles);
395 ✔
1305

1306
      sec_remaining -= n_particles;
395 ✔
1307
      sec_offset += n_particles;
395 ✔
1308
    } // End of subiteration loop over secondary tracks
1309
    n_generation_depth++;
406 ✔
1310
    simulation::simulation_tracks_completed += alive_secondary;
406 ✔
1311
  } // End of loop over secondary generations
1312

1313
  // Reset work so that fission bank etc works correctly
1314
  calculate_work(settings::n_particles);
11 ✔
1315
}
11 ✔
1316

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