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

openmc-dev / openmc / 38076061502

10 Oct 2026 06:30PM UTC coverage: 81.475% (+0.04%) from 81.44%
38076061502

Pull #3971

github

web-flow
Merge e0c053e4e into aa4afc41e
Pull Request #3971: Delta tracking

20445 of 29679 branches covered (68.89%)

Branch coverage included in aggregate %.

598 of 644 new or added lines in 20 files covered. (92.86%)

5 existing lines in 2 files now uncovered.

63213 of 73000 relevant lines covered (86.59%)

43177832.23 hits per line

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

92.69
/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()
5,022 ✔
58
{
59
  openmc::simulation::time_total.start();
5,022 ✔
60
  openmc_simulation_init();
5,022 ✔
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;
5,022 ✔
65
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
5,022 ✔
66
    status = openmc::STATUS_EXIT_MAX_BATCH;
8 ✔
67
  }
68

69
  int err = 0;
70
  while (status == 0 && err == 0) {
111,586 ✔
71
    err = openmc_next_batch(&status);
106,574 ✔
72
  }
73

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

79
int openmc_simulation_init()
6,092 ✔
80
{
81
  using namespace openmc;
6,092 ✔
82

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

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

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

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

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

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

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

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

122
  // Set up material nuclide index mapping
123
  for (auto& mat : model::materials) {
21,466 ✔
124
    mat->init_nuclide_index();
15,390 ✔
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;
6,076 ✔
130
  simulation::ct_current_file = 1;
6,076 ✔
131
  simulation::ssw_current_file = 1;
6,076 ✔
132
  simulation::k_generation.clear();
6,076 ✔
133
  simulation::entropy.clear();
6,076 ✔
134
  reset_source_rejection_counters();
6,076 ✔
135
  openmc_reset();
6,076 ✔
136

137
  // If this is a restart run, load the state point data and binary source
138
  // file
139
  if (settings::restart_run) {
6,076 ✔
140
    load_state_point();
54 ✔
141
    write_message("Resuming simulation...", 6);
108 ✔
142
  } else {
143
    // Only initialize primary source bank for eigenvalue simulations
144
    if (settings::run_mode == RunMode::EIGENVALUE &&
6,022 ✔
145
        settings::solver_type == SolverType::MONTE_CARLO) {
3,281 ✔
146
      initialize_source();
2,983 ✔
147
    }
148
  }
149

150
  // Display header
151
  if (mpi::master) {
6,076 ✔
152
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,516 ✔
153
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,559 ✔
154
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,125 ✔
155
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
434 !
156
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
434 ✔
157
      }
158
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
2,957 !
159
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,957 ✔
160
        header("K EIGENVALUE SIMULATION", 3);
2,717 ✔
161
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
240 !
162
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
240 ✔
163
      }
164
      if (settings::verbosity >= 7)
2,957 ✔
165
        print_columns();
2,677 ✔
166
    }
167
  }
168

169
  // load weight windows from file
170
  if (!settings::weight_windows_file.empty()) {
6,076 ✔
171
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
18 ✔
172
  }
173

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

179
int openmc_simulation_finalize()
6,066 ✔
180
{
181
  using namespace openmc;
6,066 ✔
182

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

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

191
  // Clear material nuclide mapping
192
  for (auto& mat : model::materials) {
21,446 ✔
193
    mat->mat_nuclide_index_.clear();
30,760 !
194
  }
195

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

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

204
#ifdef OPENMC_MPI
205
  broadcast_results();
1,912 ✔
206
#endif
207

208
  // Write tally results to tallies.out
209
  if (settings::output_tallies && mpi::master)
6,066 !
210
    write_tallies();
5,229 ✔
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 &&
6,066 ✔
217
      FlatSourceDomain::solve_ != RandomRaySolve::FORWARD_FOR_ADJOINT) {
166 ✔
218
    openmc_weight_windows_export();
99 ✔
219
  }
220

221
  // Deactivate all tallies
222
  for (auto& t : model::tallies) {
26,011 ✔
223
    t->active_ = false;
19,945 ✔
224
  }
225

226
  // Stop timers and show timing statistics
227
  simulation::time_finalize.stop();
6,066 ✔
228
  simulation::time_total.stop();
6,066 ✔
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) {
1,912 ✔
235
    int64_t total_tracks;
46 ✔
236
    MPI_Reduce(&simulation::simulation_tracks_completed, &total_tracks, 1,
46 ✔
237
      MPI_INT64_T, MPI_SUM, 0, mpi::intracomm);
238
    if (mpi::master)
46 ✔
239
      simulation::simulation_tracks_completed = total_tracks;
38 ✔
240
  }
241
#endif
242

243
  if (mpi::master) {
6,066 ✔
244
    if (settings::solver_type != SolverType::RANDOM_RAY) {
5,506 ✔
245
      if (settings::verbosity >= 6)
4,832 ✔
246
        print_runtime();
4,552 ✔
247
      if (settings::verbosity >= 4)
4,832 ✔
248
        print_results();
4,552 ✔
249
    }
250
  }
251
  if (settings::check_overlaps)
6,066 !
252
    print_overlap_check();
×
253

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

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

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

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

273
  initialize_batch();
109,566 ✔
274

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

279
    initialize_generation();
109,706 ✔
280

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

284
    // Transport loop
285
    if (settings::event_based) {
109,706 ✔
286
      if (settings::use_shared_secondary_bank) {
3,542 ✔
287
        transport_event_based_shared_secondary();
21 ✔
288
      } else {
289
        transport_event_based();
3,521 ✔
290
      }
291
    } else {
292
      if (settings::use_shared_secondary_bank) {
106,164 ✔
293
        transport_history_based_shared_secondary();
2,197 ✔
294
      } else {
295
        transport_history_based();
103,967 ✔
296
      }
297
    }
298

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

302
    finalize_generation();
109,696 ✔
303
  }
304

305
  finalize_batch();
109,556 ✔
306

307
  // Check simulation ending criteria
308
  if (status) {
109,556 !
309
    if (simulation::current_batch >= settings::n_max_batches) {
109,556 ✔
310
      *status = STATUS_EXIT_MAX_BATCH;
5,148 ✔
311
    } else if (simulation::satisfy_triggers) {
104,408 ✔
312
      *status = STATUS_EXIT_ON_TRIGGER;
72 ✔
313
    } else {
314
      *status = STATUS_EXIT_NORMAL;
104,336 ✔
315
    }
316
  }
317
  return 0;
318
}
319

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

325
  if (!simulation::initialized)
2,280 !
326
    return false;
327
  else
328
    return contains(settings::statepoint_batch, simulation::current_batch);
4,560 ✔
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(
27,961 ✔
375
  vector<vector<SourceSite>>& thread_banks)
376
{
377
  // Count the total number of all secondary sites produced
378
  int64_t n_collected = 0;
27,961 ✔
379
  for (const auto& bank : thread_banks) {
66,122 ✔
380
    n_collected += bank.size();
38,161 ✔
381
  }
382

383
  // Count the expected number of progeny from per-parent progeny counts
384
  int64_t n_progeny = 0;
27,961 ✔
385
  for (int64_t count : simulation::progeny_per_particle) {
11,592,105 ✔
386
    n_progeny += count;
11,564,144 ✔
387
  }
388

389
  if (n_collected != n_progeny) {
27,961 !
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(),
27,961 ✔
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);
27,961 ✔
401
  simulation::shared_secondary_bank_write.extend_uninitialized(n_progeny);
27,961 ✔
402

403
  // Place each secondary according to its parent and progeny identifiers
404
  for (const auto& bank : thread_banks) {
66,122 ✔
405
    for (const auto& site : bank) {
10,949,775 ✔
406
      if (site.parent_id < 0 ||
10,911,614 !
407
          site.parent_id >=
10,911,614 !
408
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
10,911,614 !
409
        fatal_error(fmt::format("Invalid parent_id {} for banked site "
×
410
                                "(expected range [0, {})).",
411
          site.parent_id, simulation::progeny_per_particle.size()));
×
412
      }
413
      int64_t idx =
10,911,614 ✔
414
        simulation::progeny_per_particle[site.parent_id] + site.progeny_id;
10,911,614 !
415
      if (idx < 0 || idx >= n_progeny) {
10,911,614 !
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;
10,911,614 ✔
420
    }
421
  }
422
}
27,961 ✔
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)
705 ✔
428
{
429
  // Compute offsets for each particle's local secondary bank.
430
  vector<int64_t> offsets(n_particles);
705 ✔
431
  int64_t total = 0;
705 ✔
432
  for (int64_t i = 0; i < n_particles; ++i) {
330,405 ✔
433
    offsets[i] = total;
329,700 ✔
434
    total += simulation::particles[i].local_secondary_bank().size();
329,700 ✔
435
  }
436

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

441
  // Copy each local bank into its assigned range and clear the local storage
442
#pragma omp parallel for schedule(static)
705 ✔
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
}
705 ✔
453

454
} // namespace
455

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

460
void allocate_banks()
6,076 ✔
461
{
462
  if (settings::run_mode == RunMode::EIGENVALUE &&
6,076 ✔
463
      settings::solver_type == SolverType::MONTE_CARLO) {
3,335 ✔
464
    // Allocate source bank
465
    simulation::source_bank.resize(simulation::work_per_rank);
3,037 ✔
466

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

470
    // Allocate IFP bank
471
    if (settings::ifp_on()) {
3,037 ✔
472
      resize_simulation_ifp_banks();
60 ✔
473
    }
474
  }
475

476
  if (settings::surf_source_write) {
6,076 ✔
477
    // Allocate surface source bank
478
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
256 ✔
479
  }
480

481
  if (settings::collision_track) {
6,076 ✔
482
    // Allocate collision track bank
483
    collision_track_reserve_bank();
110 ✔
484
  }
485
}
6,076 ✔
486

487
void initialize_batch()
131,754 ✔
488
{
489
  // Increment current batch
490
  ++simulation::current_batch;
131,754 ✔
491
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
131,754 ✔
492
    if (settings::solver_type == SolverType::RANDOM_RAY &&
57,148 ✔
493
        simulation::current_batch < settings::n_inactive + 1) {
16,648 ✔
494
      write_message(
18,768 ✔
495
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
496
    } else {
497
      write_message(6, "Simulating batch {}", simulation::current_batch);
95,528 ✔
498
    }
499
  }
500

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

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

515
  // Manage active/inactive timers and activate tallies if necessary.
516
  if (first_inactive) {
131,666 ✔
517
    simulation::time_inactive.start();
3,048 ✔
518
  } else if (first_active) {
128,706 ✔
519
    simulation::time_inactive.stop();
6,008 ✔
520
    simulation::time_active.start();
6,008 ✔
521
    for (auto& t : model::tallies) {
25,937 ✔
522
      t->active_ = true;
19,929 ✔
523
    }
524
  }
525

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

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

537
  // update weight windows if needed
538
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
134,956 ✔
539
    wwg->update();
3,212 ✔
540
  }
541

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

548
  // Check_triggers
549
  if (mpi::master)
131,744 ✔
550
    check_triggers();
120,618 ✔
551
#ifdef OPENMC_MPI
552
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
40,994 ✔
553
#endif
554
  if (simulation::satisfy_triggers ||
131,744 ✔
555
      (settings::trigger_on &&
1,988 ✔
556
        simulation::current_batch == settings::n_max_batches)) {
1,988 ✔
557
    settings::statepoint_batch.insert(simulation::current_batch);
114 ✔
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) &&
263,488 ✔
563
      !settings::cmfd_run) {
6,226 ✔
564
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
11,994 ✔
565
        settings::source_write && !settings::source_separate) {
11,168 ✔
566
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
5,022 ✔
567
      openmc_statepoint_write(nullptr, &b);
5,022 ✔
568
    } else {
569
      bool b = false;
1,076 ✔
570
      openmc_statepoint_write(nullptr, &b);
1,076 ✔
571
    }
572
  }
573

574
  if (settings::run_mode == RunMode::EIGENVALUE) {
131,744 ✔
575
    // Write out a separate source point if it's been specified for this batch
576
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
77,959 ✔
577
        settings::source_write && settings::source_separate) {
77,661 ✔
578

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

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

597
  // Write out surface source if requested.
598
  if (settings::surf_source_write &&
131,744 ✔
599
      simulation::ssw_current_file <= settings::ssw_max_files) {
1,152 ✔
600
    bool last_batch = (simulation::current_batch == settings::n_batches);
844 ✔
601
    if (simulation::surf_source_bank.full() || last_batch) {
844 ✔
602
      // Determine appropriate filename
603
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
280 ✔
604
        simulation::current_batch);
280 ✔
605
      if (settings::ssw_max_files == 1 ||
280 ✔
606
          (simulation::ssw_current_file == 1 && last_batch)) {
40 !
607
        filename = settings::path_output + "surface_source";
240 ✔
608
      }
609

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

616
      // Write surface source file
617
      write_source_point(
280 ✔
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();
280 ✔
622
      if (!last_batch && settings::ssw_max_files >= 1) {
280 !
623
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
149 ✔
624
      }
625
      ++simulation::ssw_current_file;
280 ✔
626
    }
280 ✔
627
  }
628
  // Write collision track file if requested
629
  if (settings::collision_track) {
131,744 ✔
630
    collision_track_flush_bank();
390 ✔
631
  }
632
}
131,744 ✔
633

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

640
    // Count source sites if using uniform fission source weighting
641
    if (settings::ufs_on)
74,746 ✔
642
      ufs_count_sites();
100 ✔
643

644
    // Store current value of tracklength k
645
    if (settings::delta_tracking) {
74,746 ✔
646
      simulation::keff_generation = simulation::global_tallies(
1,000 ✔
647
        GlobalTally::K_COLLISION, TallyResult::VALUE);
648
    } else {
649
      simulation::keff_generation = simulation::global_tallies(
73,746 ✔
650
        GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
651
    }
652
  }
653
}
131,894 ✔
654

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

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

669
  // reset tallies
670
  if (settings::run_mode == RunMode::EIGENVALUE) {
131,884 ✔
671
    global_tally_collision = 0.0;
74,746 ✔
672
    global_tally_absorption = 0.0;
74,746 ✔
673
    global_tally_tracklength = 0.0;
74,746 ✔
674
  }
675
  global_tally_leakage = 0.0;
131,884 ✔
676

677
  if (settings::run_mode == RunMode::EIGENVALUE &&
131,884 ✔
678
      settings::solver_type == SolverType::MONTE_CARLO) {
74,746 ✔
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);
69,206 ✔
683

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

688
  if (settings::run_mode == RunMode::EIGENVALUE) {
131,884 ✔
689

690
    // Calculate shannon entropy
691
    if (settings::entropy_on &&
74,746 ✔
692
        settings::solver_type == SolverType::MONTE_CARLO)
11,120 ✔
693
      shannon_entropy();
5,580 ✔
694

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

699
    // Write generation output
700
    if (mpi::master && settings::verbosity >= 7) {
74,746 ✔
701
      print_generation();
59,294 ✔
702
    }
703
  }
704
}
131,884 ✔
705

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

721
void initialize_particle_track(
143,689,054 ✔
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) {
143,689,054 ✔
728
    sample_source_particle(p, index_source);
132,449,590 ✔
729
  }
730

731
  p.current_work() = index_source - 1;
143,689,051 ✔
732

733
  // set identifier for particle
734
  p.id() = compute_particle_id(index_source);
143,689,051 ✔
735

736
  // set progeny count to zero
737
  p.n_progeny() = 0;
143,689,051 ✔
738

739
  // Reset particle event counter
740
  p.n_event() = 0;
143,689,051 ✔
741

742
  // Initialize track counter (1 for this primary/secondary track)
743
  p.n_tracks() = 1;
143,689,051 ✔
744

745
  // Reset split counter
746
  p.n_split() = 0;
143,689,051 ✔
747

748
  // Reset weight window ratio
749
  p.ww_factor() = 0.0;
143,689,051 ✔
750

751
  // set particle history start weight
752
  p.wgt_born() = p.wgt();
143,689,051 ✔
753

754
  // Reset pulse_height_storage
755
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
143,689,051 ✔
756

757
  // set random number seed
758
  int64_t particle_seed = compute_transport_seed(p.id());
143,689,051 ✔
759
  init_particle_seeds(particle_seed, p.seeds());
143,689,051 ✔
760

761
  // set particle trace
762
  p.trace() = false;
143,689,051 ✔
763
  if (simulation::current_batch == settings::trace_batch &&
143,697,051 ✔
764
      simulation::current_gen == settings::trace_gen &&
143,689,051 !
765
      p.id() == settings::trace_particle)
8,000 ✔
766
    p.trace() = true;
8 ✔
767

768
  // Set particle track.
769
  p.write_track() = check_track_criteria(p);
143,689,051 ✔
770

771
  // Set the particle's initial weight window value.
772
  if (!is_secondary) {
143,689,051 ✔
773
    p.wgt_ww_born() = -1.0;
132,449,587 ✔
774
    apply_weight_windows(p);
132,449,587 ✔
775
  }
776

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

782
  // Compute the majorant and set the delta tracking flag.
783
  if (settings::delta_tracking) {
143,689,051 ✔
784
    p.delta_tracking() = true;
800,000 ✔
785
    p.update_majorant();
800,000 ✔
786
  }
787

788
  // Add particle's starting weight to count for normalizing tallies later
789
  if (!is_secondary) {
143,689,051 ✔
790
#pragma omp atomic
52,181,286 ✔
791
    simulation::total_weight += p.wgt();
132,449,587 ✔
792
  }
793

794
  // Force calculation of cross-sections by setting last energy to zero
795
  if (settings::run_CE) {
143,689,051 ✔
796
    p.invalidate_neutron_xs();
60,381,019 ✔
797
  }
798

799
  // Prepare to write out particle track.
800
  if (p.write_track())
143,689,051 ✔
801
    add_particle_track(p);
672 ✔
802
}
143,689,051 ✔
803

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

810
int64_t compute_particle_id(int64_t index_source)
164,412,241 ✔
811
{
812
  if (settings::use_shared_secondary_bank) {
164,412,241 ✔
813
    return simulation::work_index[mpi::rank] + index_source +
12,548,264 ✔
814
           simulation::simulation_tracks_completed;
12,548,264 ✔
815
  } else {
816
    return simulation::work_index[mpi::rank] + index_source;
151,863,977 ✔
817
  }
818
}
819

820
int64_t compute_transport_seed(int64_t particle_id)
164,412,273 ✔
821
{
822
  if (settings::use_shared_secondary_bank) {
164,412,273 ✔
823
    return particle_id;
824
  } else {
825
    return (simulation::total_gen + overall_generation() - 1) *
151,864,001 ✔
826
             settings::n_particles +
827
           particle_id;
151,864,001 ✔
828
  }
829
}
830

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

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

839
  int64_t i_bank = 0;
34,763 ✔
840
  simulation::work_index.resize(mpi::n_procs + 1);
34,763 ✔
841
  simulation::work_index[0] = 0;
34,763 ✔
842
  for (int i = 0; i < mpi::n_procs; ++i) {
73,646 ✔
843
    // Number of particles for rank i
844
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
38,883 ✔
845

846
    // Set number of particles
847
    if (mpi::rank == i)
38,883 ✔
848
      simulation::work_per_rank = work_i;
34,763 ✔
849

850
    // Set index into source bank for rank i
851
    i_bank += work_i;
38,883 ✔
852
    simulation::work_index[i + 1] = i_bank;
38,883 ✔
853
  }
854
}
34,763 ✔
855

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

866
  for (const auto& nuc : data::nuclides) {
30,329 ✔
867
    if (nuc->grid_.size() >= 1) {
25,401 !
868
      data::energy_min[neutron] =
25,401 ✔
869
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
29,921 ✔
870
      data::energy_max[neutron] =
25,401 ✔
871
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
31,095 ✔
872
    }
873
  }
874

875
  if (settings::photon_transport) {
4,928 ✔
876
    for (const auto& elem : data::elements) {
1,710 ✔
877
      if (elem->energy_.size() >= 1) {
1,234 !
878
        int n = elem->energy_.size();
1,234 ✔
879
        data::energy_min[photon] =
2,468 ✔
880
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
2,026 ✔
881
        data::energy_max[photon] =
1,234 ✔
882
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
1,710 ✔
883
      }
884
    }
885

886
    if (settings::electron_treatment == ElectronTreatment::TTB) {
476 ✔
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) {
376 !
890
        int n_e = data::ttb_e_grid.size();
376 ✔
891

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

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

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

907
  // Show which nuclide results in lowest energy for neutron transport
908
  for (const auto& nuc : data::nuclides) {
6,184 ✔
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) {
5,776 !
912
      double max_E = nuc->grid_[0].energy.back();
5,776 ✔
913
      if (max_E == data::energy_max[neutron]) {
5,776 ✔
914
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
4,520 ✔
915
          data::energy_max[neutron], nuc->name_);
4,520 ✔
916
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
4,520 !
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) {
30,329 ✔
927
    nuc->init_grid();
25,401 ✔
928
  }
929
  simulation::log_spacing =
9,856 ✔
930
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
4,928 ✔
931
    settings::n_log_bins;
932
}
4,928 ✔
933

934
#ifdef OPENMC_MPI
935
void broadcast_results()
1,912 ✔
936
{
937
  // Broadcast tally results so that each process has access to results
938
  for (auto& t : model::tallies) {
9,090 ✔
939
    auto& results = t->results_;
7,178 ✔
940
    mpi::broadcast(results.data(), results.size(), 0, mpi::intracomm);
7,178 ✔
941
  }
942

943
  // Also broadcast global tally results
944
  auto& gt = simulation::global_tallies;
1,912 ✔
945
  mpi::broadcast(gt.data(), gt.size(), 0, mpi::intracomm);
1,912 ✔
946

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

957
#endif
958

959
void free_memory_simulation()
7,015 ✔
960
{
961
  simulation::k_generation.clear();
7,015 ✔
962
  simulation::entropy.clear();
7,015 ✔
963
}
7,015 ✔
964

965
void transport_history_based_single_particle(Particle& p)
130,364,833 ✔
966
{
967
  while (p.alive()) {
2,147,483,647 ✔
968
    p.event_calculate_xs();
2,147,483,647 ✔
969
    if (p.alive()) {
2,147,483,647 !
970
      p.event_advance();
2,147,483,647 ✔
971
    }
972
    if (p.alive()) {
2,147,483,647 ✔
973
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647 ✔
974
        p.event_cross_surface();
1,925,113,880 ✔
975
      } else if (p.alive()) {
2,147,483,647 ✔
976
        p.event_collide();
2,147,483,647 ✔
977
      }
978
    }
979
    p.event_check_limit_and_revive();
2,147,483,647 ✔
980
  }
981
  p.event_death();
130,364,826 ✔
982
}
130,364,826 ✔
983

984
void transport_delta_history_based_single_particle(Particle& p)
560,000 ✔
985
{
986
  while (p.alive()) {
52,121,111 ✔
987
    p.event_delta_advance();
51,561,111 ✔
988

989
    if (p.alive() && p.collision_distance() < p.boundary().distance()) {
51,561,111 !
990
      // Collided before hitting an external boundary. Rejection sample the
991
      // majorant.
992
      p.event_calculate_xs();
44,984,310 ✔
993
      if (p.kill_invalid_maj()) {
44,984,310 !
994
        break;
995
      }
996
      if (p.alive() &&
44,984,310 !
997
          (prn(p.current_seed()) < (p.macro_xs().total / p.majorant()))) {
44,984,310 ✔
998
        p.event_collide();
15,796,634 ✔
999
      }
1000
    } else if (p.alive()) {
6,576,801 !
1001
      // Crossed an external boundary before colliding.
1002
      p.event_cross_surface();
6,576,801 ✔
1003
    }
1004

1005
    p.event_check_limit_and_revive();
51,561,111 ✔
1006
  }
1007
  p.event_death();
560,000 ✔
1008
}
560,000 ✔
1009

1010
void transport_history_based()
103,967 ✔
1011
{
1012
#pragma omp parallel
37,364 ✔
1013
  {
66,603 ✔
1014
    Particle p;
66,603 ✔
1015
#pragma omp for schedule(runtime)
1016
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
82,521,196 ✔
1017
      initialize_particle_track(p, i_work, false);
82,454,600 ✔
1018
      if (settings::delta_tracking) {
82,454,597 ✔
1019
        transport_delta_history_based_single_particle(p);
400,000 ✔
1020
      } else {
1021
        transport_history_based_single_particle(p);
82,054,597 ✔
1022
      }
1023
    }
1024
  }
66,596 ✔
1025
}
103,960 ✔
1026

1027
// The shared secondary bank transport algorithm works in two phases. In the
1028
// first phase, all primary particles are sampled then transported, and their
1029
// secondary particles are deposited into a shared secondary bank. The second
1030
// phase occurs in a loop, where all secondary tracks in the shared secondary
1031
// bank are transported. Any secondary particles generated during this phase are
1032
// deposited back into the shared secondary bank. The shared secondary bank is
1033
// sorted for consistent ordering and load balanced across MPI ranks. This loop
1034
// continues until there are no more secondary tracks left to transport.
1035
void transport_history_based_shared_secondary()
2,197 ✔
1036
{
1037
  // Clear shared secondary banks from any prior use
1038
  simulation::shared_secondary_bank_read.clear();
2,197 ✔
1039
  simulation::shared_secondary_bank_write.clear();
2,197 ✔
1040

1041
  if (mpi::master) {
2,197 ✔
1042
    write_message(fmt::format(" Primary source          particles: {}",
4,262 ✔
1043
                    settings::n_particles),
1044
      6);
1045
  }
1046

1047
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
2,197 ✔
1048
  std::fill(simulation::progeny_per_particle.begin(),
4,394 ✔
1049
    simulation::progeny_per_particle.end(), 0);
2,197 ✔
1050

1051
  vector<vector<SourceSite>> thread_banks(num_threads());
2,197 ✔
1052

1053
  // Phase 1: Transport primary particles and deposit first generation of
1054
  // secondaries in the shared secondary bank
1055
#pragma omp parallel
813 ✔
1056
  {
1,384 ✔
1057
    auto& thread_bank = thread_banks[thread_num()];
1,384 ✔
1058
    Particle p;
1,384 ✔
1059

1060
#pragma omp for schedule(runtime)
1061
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
411,114 ✔
1062
      initialize_particle_track(p, i, false);
409,730 ✔
1063
      if (settings::delta_tracking) {
409,730 !
1064
        transport_delta_history_based_single_particle(p);
×
1065
      } else {
1066
        transport_history_based_single_particle(p);
409,730 ✔
1067
      }
1068
      for (auto& site : p.local_secondary_bank()) {
1,132,123 ✔
1069
        thread_bank.push_back(site);
722,393 ✔
1070
      }
1071
      p.local_secondary_bank().clear();
506,686 ✔
1072
    }
1073
  }
1074
  collect_sorted_history_secondary_banks(thread_banks);
2,197 ✔
1075
  thread_banks.clear();
2,197 ✔
1076

1077
  simulation::simulation_tracks_completed += settings::n_particles;
2,197 ✔
1078

1079
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1080
  // all secondary generations
1081
  int n_generation_depth = 1;
2,197 ✔
1082
  int64_t alive_secondary = 1;
2,197 ✔
1083
  while (alive_secondary) {
27,961 ✔
1084

1085
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1086
    // that each MPI rank has an approximately equal number of secondary
1087
    // tracks. Also reports the total number of secondaries alive across
1088
    // all MPI ranks.
1089
    alive_secondary = synchronize_global_secondary_bank(
25,764 ✔
1090
      simulation::shared_secondary_bank_write);
1091

1092
    // Recalculate work for each MPI rank based on number of alive secondary
1093
    // tracks
1094
    calculate_work(alive_secondary);
25,764 ✔
1095

1096
    // Display the number of secondary tracks in this generation. This
1097
    // is useful for user monitoring so as to see if the secondary population is
1098
    // exploding and to determine how many generations of secondaries are being
1099
    // transported.
1100
    if (mpi::master) {
25,764 ✔
1101
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
48,660 ✔
1102
                      n_generation_depth, alive_secondary),
1103
        6);
1104
    }
1105

1106
    simulation::shared_secondary_bank_read =
25,764 ✔
1107
      std::move(simulation::shared_secondary_bank_write);
25,764 ✔
1108
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
25,764 !
1109
    simulation::progeny_per_particle.resize(
25,764 ✔
1110
      simulation::shared_secondary_bank_read.size());
25,764 ✔
1111
    std::fill(simulation::progeny_per_particle.begin(),
51,528 ✔
1112
      simulation::progeny_per_particle.end(), 0);
25,764 ✔
1113
    thread_banks.resize(num_threads());
25,764 ✔
1114

1115
    // Transport all secondary tracks from the shared secondary bank
1116
#pragma omp parallel
9,387 ✔
1117
    {
16,377 ✔
1118
      auto& thread_bank = thread_banks[thread_num()];
16,377 ✔
1119
      Particle p;
16,377 ✔
1120

1121
#pragma omp for schedule(runtime)
1122
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
7,043,592 ✔
1123
           i++) {
1124
        initialize_particle_track(p, i, true);
7,027,215 ✔
1125
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
7,027,215 ✔
1126
        p.event_revive_from_secondary(site);
7,027,215 ✔
1127
        if (settings::delta_tracking) {
7,027,215 !
1128
          transport_delta_history_based_single_particle(p);
×
1129
        } else {
1130
          transport_history_based_single_particle(p);
7,027,215 ✔
1131
        }
1132
        for (auto& secondary_site : p.local_secondary_bank()) {
13,332,037 ✔
1133
          thread_bank.push_back(secondary_site);
6,304,822 ✔
1134
        }
1135
        p.local_secondary_bank().clear();
9,513,543 ✔
1136
      }
1137
    } // End of transport loop over tracks in shared secondary bank
1138
    simulation::shared_secondary_bank_write =
25,764 ✔
1139
      std::move(simulation::shared_secondary_bank_read);
25,764 ✔
1140
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
25,764 !
1141
    collect_sorted_history_secondary_banks(thread_banks);
25,764 ✔
1142
    thread_banks.clear();
25,764 ✔
1143
    n_generation_depth++;
25,764 ✔
1144
    simulation::simulation_tracks_completed += alive_secondary;
25,764 ✔
1145
  } // End of loop over secondary generations
1146

1147
  // Reset work so that fission bank etc works correctly
1148
  calculate_work(settings::n_particles);
2,197 ✔
1149
}
2,197 ✔
1150

1151
void transport_event_based()
3,521 ✔
1152
{
1153
  int64_t remaining_work = simulation::work_per_rank;
3,521 ✔
1154
  int64_t source_offset = 0;
3,521 ✔
1155

1156
  // To cap the total amount of memory used to store particle object data, the
1157
  // number of particles in flight at any point in time can bet set. In the case
1158
  // that the maximum in flight particle count is lower than the total number
1159
  // of particles that need to be run this iteration, the event-based transport
1160
  // loop is executed multiple times until all particles have been completed.
1161
  while (remaining_work > 0) {
7,042 ✔
1162
    // Figure out # of particles to run for this subiteration
1163
    int64_t n_particles =
3,521 !
1164
      std::min(remaining_work, settings::max_particles_in_flight);
3,521 ✔
1165

1166
    // Initialize all particle histories for this subiteration
1167
    if (settings::delta_tracking) {
3,521 ✔
1168
      process_delta_init_events(n_particles, source_offset);
280 ✔
1169
      process_delta_transport_events();
280 ✔
1170
    } else {
1171
      process_init_events(n_particles, source_offset);
3,241 ✔
1172
      process_transport_events();
3,241 ✔
1173
    }
1174
    process_death_events(n_particles);
3,521 ✔
1175

1176
    // Adjust remaining work and source offset variables
1177
    remaining_work -= n_particles;
3,521 ✔
1178
    source_offset += n_particles;
3,521 ✔
1179
  }
1180
}
3,521 ✔
1181

1182
void transport_event_based_shared_secondary()
21 ✔
1183
{
1184
  // Clear shared secondary banks from any prior use
1185
  simulation::shared_secondary_bank_read.clear();
21 ✔
1186
  simulation::shared_secondary_bank_write.clear();
21 ✔
1187

1188
  if (mpi::master) {
21 !
1189
    write_message(fmt::format(" Primary source          particles: {}",
42 !
1190
                    settings::n_particles),
1191
      6);
1192
  }
1193

1194
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
21 ✔
1195
  std::fill(simulation::progeny_per_particle.begin(),
42 ✔
1196
    simulation::progeny_per_particle.end(), 0);
21 ✔
1197

1198
  // Phase 1: Transport primary particles using event-based processing and
1199
  // deposit first generation of secondaries in the shared secondary bank
1200
  int64_t remaining_work = simulation::work_per_rank;
21 ✔
1201
  int64_t source_offset = 0;
21 ✔
1202

1203
  while (remaining_work > 0) {
42 ✔
1204
    int64_t n_particles =
21 !
1205
      std::min(remaining_work, settings::max_particles_in_flight);
21 ✔
1206

1207
    if (settings::delta_tracking) {
21 !
UNCOV
1208
      process_delta_init_events(n_particles, source_offset);
×
NEW
1209
      process_delta_transport_events();
×
1210
    } else {
1211
      process_init_events(n_particles, source_offset);
21 ✔
1212
      process_transport_events();
21 ✔
1213
    }
1214
    process_death_events(n_particles);
21 ✔
1215

1216
    collect_event_secondary_banks(n_particles);
21 ✔
1217

1218
    remaining_work -= n_particles;
21 ✔
1219
    source_offset += n_particles;
21 ✔
1220
  }
1221

1222
  simulation::simulation_tracks_completed += settings::n_particles;
21 ✔
1223

1224
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1225
  // all secondary generations
1226
  int n_generation_depth = 1;
21 ✔
1227
  int64_t alive_secondary = 1;
21 ✔
1228
  while (alive_secondary) {
726 ✔
1229

1230
    // Sort the shared secondary bank by parent ID then progeny ID to
1231
    // ensure reproducibility.
1232
    sort_bank(simulation::shared_secondary_bank_write, false);
705 ✔
1233

1234
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1235
    // that each MPI rank has an approximately equal number of secondary
1236
    // tracks.
1237
    alive_secondary = synchronize_global_secondary_bank(
705 ✔
1238
      simulation::shared_secondary_bank_write);
1239

1240
    // Recalculate work for each MPI rank based on number of alive secondary
1241
    // tracks
1242
    calculate_work(alive_secondary);
705 ✔
1243

1244
    if (mpi::master) {
705 !
1245
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
1,410 !
1246
                      n_generation_depth, alive_secondary),
1247
        6);
1248
    }
1249

1250
    simulation::shared_secondary_bank_read =
705 ✔
1251
      std::move(simulation::shared_secondary_bank_write);
705 ✔
1252
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
705 !
1253
    simulation::progeny_per_particle.resize(
705 ✔
1254
      simulation::shared_secondary_bank_read.size());
705 ✔
1255
    std::fill(simulation::progeny_per_particle.begin(),
1,410 ✔
1256
      simulation::progeny_per_particle.end(), 0);
705 ✔
1257

1258
    // Ensure particle buffer is large enough for this secondary generation
1259
    int64_t sec_buffer_length = std::min(
705 !
1260
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
705 !
1261
      settings::max_particles_in_flight);
705 ✔
1262
    if (sec_buffer_length >
705 ✔
1263
        static_cast<int64_t>(simulation::particles.size())) {
705 ✔
1264
      init_event_queues(sec_buffer_length);
53 ✔
1265
    }
1266

1267
    // Transport secondary tracks using event-based processing
1268
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
705 ✔
1269
    int64_t sec_offset = 0;
705 ✔
1270

1271
    while (sec_remaining > 0) {
1,389 ✔
1272
      int64_t n_particles =
684 !
1273
        std::min(sec_remaining, settings::max_particles_in_flight);
684 ✔
1274

1275
      if (settings::delta_tracking) {
684 !
UNCOV
1276
        process_delta_init_secondary_events(
×
1277
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
NEW
1278
        process_delta_transport_events();
×
1279
      } else {
1280
        process_init_secondary_events(
684 ✔
1281
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
1282
        process_transport_events();
684 ✔
1283
      }
1284
      process_death_events(n_particles);
684 ✔
1285

1286
      collect_event_secondary_banks(n_particles);
684 ✔
1287

1288
      sec_remaining -= n_particles;
684 ✔
1289
      sec_offset += n_particles;
684 ✔
1290
    } // End of subiteration loop over secondary tracks
1291
    n_generation_depth++;
705 ✔
1292
    simulation::simulation_tracks_completed += alive_secondary;
705 ✔
1293
  } // End of loop over secondary generations
1294

1295
  // Reset work so that fission bank etc works correctly
1296
  calculate_work(settings::n_particles);
21 ✔
1297
}
21 ✔
1298

1299
extern "C" int openmc_get_current_batch()
8,184 ✔
1300
{
1301
  return simulation::current_batch;
8,184 ✔
1302
}
1303

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