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

openmc-dev / openmc / 30830380864

03 Aug 2026 04:03PM UTC coverage: 81.48% (+0.05%) from 81.429%
30830380864

Pull #3971

github

web-flow
Merge 13d0297e2 into 5982acdf8
Pull Request #3971: Delta tracking

18827 of 27241 branches covered (69.11%)

Branch coverage included in aggregate %.

597 of 645 new or added lines in 20 files covered. (92.56%)

60852 of 70549 relevant lines covered (86.25%)

50385682.17 hits per line

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

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

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

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

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

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

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

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

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

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

103
  // Create track file if needed
104
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
8,185✔
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,185✔
111
    int64_t event_buffer_length =
262!
112
      std::min(simulation::work_per_rank, settings::max_particles_in_flight);
262✔
113
    init_event_queues(event_buffer_length);
262✔
114
  }
115

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

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

137
  // If this is a restart run, load the state point data and binary source
138
  // file
139
  if (settings::restart_run) {
8,185✔
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 &&
8,122✔
145
        settings::solver_type == SolverType::MONTE_CARLO) {
4,590✔
146
      initialize_source();
4,219✔
147
    }
148
  }
149

150
  // Display header
151
  if (mpi::master) {
8,185✔
152
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,125✔
153
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,206✔
154
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,786✔
155
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
420!
156
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
420✔
157
      }
158
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,919!
159
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,919✔
160
        header("K EIGENVALUE SIMULATION", 3);
3,644✔
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,919✔
165
        print_columns();
3,539✔
166
    }
167
  }
168

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

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

179
int openmc_simulation_finalize()
8,172✔
180
{
181
  using namespace openmc;
8,172✔
182

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

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

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

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

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

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

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

221
  // Deactivate all tallies
222
  for (auto& t : model::tallies) {
36,330✔
223
    t->active_ = false;
28,158✔
224
  }
225

226
  // Stop timers and show timing statistics
227
  simulation::time_finalize.stop();
8,172✔
228
  simulation::time_total.stop();
8,172✔
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,666✔
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) {
8,172✔
244
    if (settings::solver_type != SolverType::RANDOM_RAY) {
7,112✔
245
      if (settings::verbosity >= 6)
6,417✔
246
        print_runtime();
6,037✔
247
      if (settings::verbosity >= 4)
6,417✔
248
        print_results();
6,037✔
249
    }
250
  }
251
  if (settings::check_overlaps)
8,172!
252
    print_overlap_check();
×
253

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

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

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

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

273
  initialize_batch();
151,289✔
274

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

279
    initialize_generation();
151,499✔
280

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

284
    // Transport loop
285
    if (settings::event_based) {
151,499✔
286
      if (settings::use_shared_secondary_bank) {
3,622✔
287
        transport_event_based_shared_secondary();
21✔
288
      } else {
289
        transport_event_based();
3,601✔
290
      }
291
    } else {
292
      if (settings::use_shared_secondary_bank) {
147,877✔
293
        transport_history_based_shared_secondary();
3,062✔
294
      } else {
295
        transport_history_based();
144,815✔
296
      }
297
    }
298

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

302
    finalize_generation();
151,486✔
303
  }
304

305
  finalize_batch();
151,276✔
306

307
  // Check simulation ending criteria
308
  if (status) {
151,276!
309
    if (simulation::current_batch >= settings::n_max_batches) {
151,276✔
310
      *status = STATUS_EXIT_MAX_BATCH;
7,171✔
311
    } else if (simulation::satisfy_triggers) {
144,105✔
312
      *status = STATUS_EXIT_ON_TRIGGER;
93✔
313
    } else {
314
      *status = STATUS_EXIT_NORMAL;
144,012✔
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(
39,633✔
375
  vector<vector<SourceSite>>& thread_banks)
376
{
377
  // Count the total number of all secondary sites produced
378
  int64_t n_collected = 0;
39,633✔
379
  for (const auto& bank : thread_banks) {
101,189✔
380
    n_collected += bank.size();
61,556✔
381
  }
382

383
  // Count the expected number of progeny from per-parent progeny counts
384
  int64_t n_progeny = 0;
39,633✔
385
  for (int64_t count : simulation::progeny_per_particle) {
16,060,476✔
386
    n_progeny += count;
16,020,843✔
387
  }
388

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

403
  // Place each secondary according to its parent and progeny identifiers
404
  for (const auto& bank : thread_banks) {
101,189✔
405
    for (const auto& site : bank) {
15,185,419✔
406
      if (site.parent_id < 0 ||
15,123,863!
407
          site.parent_id >=
15,123,863!
408
            static_cast<int64_t>(simulation::progeny_per_particle.size())) {
15,123,863!
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 =
15,123,863✔
414
        simulation::progeny_per_particle[site.parent_id] + site.progeny_id;
15,123,863!
415
      if (idx < 0 || idx >= n_progeny) {
15,123,863!
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;
15,123,863✔
420
    }
421
  }
422
}
39,633✔
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()
8,185✔
461
{
462
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,185✔
463
      settings::solver_type == SolverType::MONTE_CARLO) {
4,653✔
464
    // Allocate source bank
465
    simulation::source_bank.resize(simulation::work_per_rank);
4,282✔
466

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

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

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

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

487
void initialize_batch()
173,131✔
488
{
489
  // Increment current batch
490
  ++simulation::current_batch;
173,131✔
491
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
173,131✔
492
    if (settings::solver_type == SolverType::RANDOM_RAY &&
70,468✔
493
        simulation::current_batch < settings::n_inactive + 1) {
14,992✔
494
      write_message(
18,132✔
495
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
496
    } else {
497
      write_message(6, "Simulating batch {}", simulation::current_batch);
122,804✔
498
    }
499
  }
500

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

504
  // Determine if this batch is the first inactive or active batch.
505
  bool first_inactive = false;
173,131✔
506
  bool first_active = false;
173,131✔
507
  if (!settings::restart_run) {
173,131✔
508
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
172,968✔
509
    first_active = simulation::current_batch == settings::n_inactive + 1;
172,968✔
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) {
173,020✔
517
    simulation::time_inactive.start();
4,059✔
518
  } else if (first_active) {
169,072✔
519
    simulation::time_inactive.stop();
8,138✔
520
    simulation::time_active.start();
8,138✔
521
    for (auto& t : model::tallies) {
36,274✔
522
      t->active_ = true;
28,136✔
523
    }
524
  }
525

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

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

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

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

548
  // Check_triggers
549
  if (mpi::master)
173,118✔
550
    check_triggers();
153,715✔
551
#ifdef OPENMC_MPI
552
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
75,624✔
553
#endif
554
  if (simulation::satisfy_triggers ||
173,118✔
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) &&
346,236✔
563
      !settings::cmfd_run) {
8,440✔
564
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
16,250✔
565
        settings::source_write && !settings::source_separate) {
15,323✔
566
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
6,988✔
567
      openmc_statepoint_write(nullptr, &b);
6,988✔
568
    } else {
569
      bool b = false;
1,276✔
570
      openmc_statepoint_write(nullptr, &b);
1,276✔
571
    }
572
  }
573

574
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,118✔
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,342✔
577
        settings::source_write && settings::source_separate) {
106,971✔
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,663✔
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 &&
173,118✔
599
      simulation::ssw_current_file <= settings::ssw_max_files) {
17,889✔
600
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,998✔
601
    if (simulation::surf_source_bank.full() || last_batch) {
1,998✔
602
      // Determine appropriate filename
603
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
1,209✔
604
        simulation::current_batch);
1,209✔
605
      if (settings::ssw_max_files == 1 ||
1,209✔
606
          (simulation::ssw_current_file == 1 && last_batch)) {
55!
607
        filename = settings::path_output + "surface_source";
1,154✔
608
      }
609

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

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

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

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

644
    // Store current value of tracklength k
645
    if (settings::delta_tracking) {
102,873✔
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,373✔
650
        GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
651
    }
652
  }
653
}
173,341✔
654

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

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

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

677
  if (settings::run_mode == RunMode::EIGENVALUE &&
173,328✔
678
      settings::solver_type == SolverType::MONTE_CARLO) {
102,873✔
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);
96,023✔
683

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

688
  if (settings::run_mode == RunMode::EIGENVALUE) {
173,328✔
689

690
    // Calculate shannon entropy
691
    if (settings::entropy_on &&
102,873✔
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,873✔
697
    calculate_average_keff();
102,873✔
698

699
    // Write generation output
700
    if (mpi::master && settings::verbosity >= 7) {
102,873✔
701
      print_generation();
77,408✔
702
    }
703
  }
704
}
173,328✔
705

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

721
void initialize_particle_track(
194,532,911✔
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) {
194,532,911✔
728
    sample_source_particle(p, index_source);
179,081,198✔
729
  }
730

731
  p.current_work() = index_source - 1;
194,532,907✔
732

733
  // set identifier for particle
734
  p.id() = compute_particle_id(index_source);
194,532,907✔
735

736
  // set progeny count to zero
737
  p.n_progeny() = 0;
194,532,907✔
738

739
  // Reset particle event counter
740
  p.n_event() = 0;
194,532,907✔
741

742
  // Initialize track counter (1 for this primary/secondary track)
743
  p.n_tracks() = 1;
194,532,907✔
744

745
  // Reset split counter
746
  p.n_split() = 0;
194,532,907✔
747

748
  // Reset weight window ratio
749
  p.ww_factor() = 0.0;
194,532,907✔
750

751
  // set particle history start weight
752
  p.wgt_born() = p.wgt();
194,532,907✔
753

754
  // Reset pulse_height_storage
755
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
194,532,907✔
756

757
  // set random number seed
758
  int64_t particle_seed = compute_transport_seed(p.id());
194,532,907✔
759
  init_particle_seeds(particle_seed, p.seeds());
194,532,907✔
760

761
  // set particle trace
762
  p.trace() = false;
194,532,907✔
763
  if (simulation::current_batch == settings::trace_batch &&
194,543,907✔
764
      simulation::current_gen == settings::trace_gen &&
194,532,907!
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);
194,532,907✔
770

771
  // Set the particle's initial weight window value.
772
  if (!is_secondary) {
194,532,907✔
773
    p.wgt_ww_born() = -1.0;
179,081,194✔
774
    apply_weight_windows(p);
179,081,194✔
775
  }
776

777
  // Display message if high verbosity or trace is on
778
  if (settings::verbosity >= 9 || p.trace()) {
194,532,907!
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) {
194,532,907✔
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) {
194,532,907✔
790
#pragma omp atomic
99,258,134✔
791
    simulation::total_weight += p.wgt();
179,081,194✔
792
  }
793

794
  // Force calculation of cross-sections by setting last energy to zero
795
  if (settings::run_CE) {
194,532,907✔
796
    p.invalidate_neutron_xs();
79,984,363✔
797
  }
798

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

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

810
int64_t compute_particle_id(int64_t index_source)
222,577,380✔
811
{
812
  if (settings::use_shared_secondary_bank) {
222,577,380✔
813
    return simulation::work_index[mpi::rank] + index_source +
17,249,428✔
814
           simulation::simulation_tracks_completed;
17,249,428✔
815
  } else {
816
    return simulation::work_index[mpi::rank] + index_source;
205,327,952✔
817
  }
818
}
819

820
int64_t compute_transport_seed(int64_t particle_id)
222,577,424✔
821
{
822
  if (settings::use_shared_secondary_bank) {
222,577,424✔
823
    return particle_id;
824
  } else {
825
    return (simulation::total_gen + overall_generation() - 1) *
205,327,985✔
826
             settings::n_particles +
827
           particle_id;
205,327,985✔
828
  }
829
}
830

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

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

839
  int64_t i_bank = 0;
48,544✔
840
  simulation::work_index.resize(mpi::n_procs + 1);
48,544✔
841
  simulation::work_index[0] = 0;
48,544✔
842
  for (int i = 0; i < mpi::n_procs; ++i) {
105,207✔
843
    // Number of particles for rank i
844
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
56,663✔
845

846
    // Set number of particles
847
    if (mpi::rank == i)
56,663✔
848
      simulation::work_per_rank = work_i;
48,544✔
849

850
    // Set index into source bank for rank i
851
    i_bank += work_i;
56,663✔
852
    simulation::work_index[i + 1] = i_bank;
56,663✔
853
  }
854
}
48,544✔
855

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

866
  for (const auto& nuc : data::nuclides) {
41,288✔
867
    if (nuc->grid_.size() >= 1) {
34,514!
868
      data::energy_min[neutron] =
34,514✔
869
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
40,723✔
870
      data::energy_max[neutron] =
34,514✔
871
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
42,357✔
872
    }
873
  }
874

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

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

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

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

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

907
  // Show which nuclide results in lowest energy for neutron transport
908
  for (const auto& nuc : data::nuclides) {
8,527✔
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,962!
912
      double max_E = nuc->grid_[0].energy.back();
7,962✔
913
      if (max_E == data::energy_max[neutron]) {
7,962✔
914
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
6,209✔
915
          data::energy_max[neutron], nuc->name_);
6,209✔
916
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
6,209!
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) {
41,288✔
927
    nuc->init_grid();
34,514✔
928
  }
929
  simulation::log_spacing =
13,548✔
930
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,774✔
931
    settings::n_log_bins;
932
}
6,774✔
933

934
#ifdef OPENMC_MPI
935
void broadcast_results()
3,666✔
936
{
937
  // Broadcast tally results so that each process has access to results
938
  for (auto& t : model::tallies) {
17,603✔
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,937✔
943

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

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

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

967
#endif
968

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

975
void transport_history_based_single_particle(Particle& p)
180,928,701✔
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();
180,928,692✔
992
}
180,928,692✔
993

994
void transport_delta_history_based_single_particle(Particle& p)
800,000✔
995
{
996
  while (p.alive()) {
74,458,730✔
997
    p.event_delta_advance();
73,658,730✔
998

999
    if (p.alive() && p.collision_distance() < p.boundary().distance()) {
73,658,730!
1000
      // Collided before hitting an external boundary. Rejection sample the
1001
      // majorant.
1002
      p.event_calculate_xs();
64,263,300✔
1003
      if (p.kill_invalid_maj()) {
64,263,300!
1004
        break;
1005
      }
1006
      if (p.alive() &&
64,263,300!
1007
          (prn(p.current_seed()) < (p.macro_xs().total / p.majorant()))) {
64,263,300✔
1008
        p.event_collide();
22,566,620✔
1009
      }
1010
    } else if (p.alive()) {
9,395,430!
1011
      // Crossed an external boundary before colliding.
1012
      p.event_cross_surface();
9,395,430✔
1013
    }
1014

1015
    p.event_check_limit_and_revive();
73,658,730✔
1016
  }
1017
  p.event_death();
800,000✔
1018
}
800,000✔
1019

1020
void transport_history_based()
144,815✔
1021
{
1022
#pragma omp parallel
80,679✔
1023
  {
64,136✔
1024
    Particle p;
64,136✔
1025
#pragma omp for schedule(runtime)
1026
    for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,875,541✔
1027
      initialize_particle_track(p, i_work, false);
80,811,414✔
1028
      if (settings::delta_tracking) {
80,811,410✔
1029
        transport_delta_history_based_single_particle(p);
400,000✔
1030
      } else {
1031
        transport_history_based_single_particle(p);
80,411,410✔
1032
      }
1033
    }
1034
  }
64,127✔
1035
}
144,806✔
1036

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

1051
  if (mpi::master) {
3,062✔
1052
    write_message(fmt::format(" Primary source          particles: {}",
5,860✔
1053
                    settings::n_particles),
1054
      6);
1055
  }
1056

1057
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
3,062✔
1058
  std::fill(simulation::progeny_per_particle.begin(),
6,124✔
1059
    simulation::progeny_per_particle.end(), 0);
3,062✔
1060

1061
  vector<vector<SourceSite>> thread_banks(num_threads());
3,062✔
1062

1063
  // Phase 1: Transport primary particles and deposit first generation of
1064
  // secondaries in the shared secondary bank
1065
#pragma omp parallel
1,694✔
1066
  {
1,368✔
1067
    auto& thread_bank = thread_banks[thread_num()];
1,368✔
1068
    Particle p;
1,368✔
1069

1070
#pragma omp for schedule(runtime)
1071
    for (int64_t i = 1; i <= simulation::work_per_rank; i++) {
409,118✔
1072
      initialize_particle_track(p, i, false);
407,750✔
1073
      if (settings::delta_tracking) {
407,750!
1074
        transport_delta_history_based_single_particle(p);
×
1075
      } else {
1076
        transport_history_based_single_particle(p);
407,750✔
1077
      }
1078
      for (auto& site : p.local_secondary_bank()) {
1,127,695✔
1079
        thread_bank.push_back(site);
719,945✔
1080
      }
1081
      p.local_secondary_bank().clear();
503,710✔
1082
    }
1083
  }
1084
  collect_sorted_history_secondary_banks(thread_banks);
3,062✔
1085
  thread_banks.clear();
3,062✔
1086

1087
  simulation::simulation_tracks_completed += settings::n_particles;
3,062✔
1088

1089
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1090
  // all secondary generations
1091
  int n_generation_depth = 1;
3,062✔
1092
  int64_t alive_secondary = 1;
3,062✔
1093
  while (alive_secondary) {
39,633✔
1094

1095
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1096
    // that each MPI rank has an approximately equal number of secondary
1097
    // tracks. Also reports the total number of secondaries alive across
1098
    // all MPI ranks.
1099
    alive_secondary = synchronize_global_secondary_bank(
36,571✔
1100
      simulation::shared_secondary_bank_write);
1101

1102
    // Recalculate work for each MPI rank based on number of alive secondary
1103
    // tracks
1104
    calculate_work(alive_secondary);
36,571✔
1105

1106
    // Display the number of secondary tracks in this generation. This
1107
    // is useful for user monitoring so as to see if the secondary population is
1108
    // exploding and to determine how many generations of secondaries are being
1109
    // transported.
1110
    if (mpi::master) {
36,571✔
1111
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
67,406✔
1112
                      n_generation_depth, alive_secondary),
1113
        6);
1114
    }
1115

1116
    simulation::shared_secondary_bank_read =
36,571✔
1117
      std::move(simulation::shared_secondary_bank_write);
36,571✔
1118
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
36,571!
1119
    simulation::progeny_per_particle.resize(
36,571✔
1120
      simulation::shared_secondary_bank_read.size());
36,571✔
1121
    std::fill(simulation::progeny_per_particle.begin(),
73,142✔
1122
      simulation::progeny_per_particle.end(), 0);
36,571✔
1123
    thread_banks.resize(num_threads());
36,571✔
1124

1125
    // Transport all secondary tracks from the shared secondary bank
1126
#pragma omp parallel
20,229✔
1127
    {
16,342✔
1128
      auto& thread_bank = thread_banks[thread_num()];
16,342✔
1129
      Particle p;
16,342✔
1130

1131
#pragma omp for schedule(runtime)
1132
      for (int64_t i = 1; i <= simulation::shared_secondary_bank_read.size();
7,036,757✔
1133
           i++) {
1134
        initialize_particle_track(p, i, true);
7,020,415✔
1135
        SourceSite& site = simulation::shared_secondary_bank_read[i - 1];
7,020,415✔
1136
        p.event_revive_from_secondary(site);
7,020,415✔
1137
        if (settings::delta_tracking) {
7,020,415!
1138
          transport_delta_history_based_single_particle(p);
×
1139
        } else {
1140
          transport_history_based_single_particle(p);
7,020,415✔
1141
        }
1142
        for (auto& secondary_site : p.local_secondary_bank()) {
13,320,885✔
1143
          thread_bank.push_back(secondary_site);
6,300,470✔
1144
        }
1145
        p.local_secondary_bank().clear();
9,504,010✔
1146
      }
1147
    } // End of transport loop over tracks in shared secondary bank
1148
    simulation::shared_secondary_bank_write =
36,571✔
1149
      std::move(simulation::shared_secondary_bank_read);
36,571✔
1150
    simulation::shared_secondary_bank_read = SharedArray<SourceSite>();
36,571!
1151
    collect_sorted_history_secondary_banks(thread_banks);
36,571✔
1152
    thread_banks.clear();
36,571✔
1153
    n_generation_depth++;
36,571✔
1154
    simulation::simulation_tracks_completed += alive_secondary;
36,571✔
1155
  } // End of loop over secondary generations
1156

1157
  // Reset work so that fission bank etc works correctly
1158
  calculate_work(settings::n_particles);
3,062✔
1159
}
3,062✔
1160

1161
void transport_event_based()
3,601✔
1162
{
1163
  int64_t remaining_work = simulation::work_per_rank;
3,601✔
1164
  int64_t source_offset = 0;
3,601✔
1165

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

1176
    // Initialize all particle histories for this subiteration
1177
    if (settings::delta_tracking) {
3,601✔
1178
      process_delta_init_events(n_particles, source_offset);
380✔
1179
      process_delta_transport_events();
380✔
1180
    } else {
1181
      process_init_events(n_particles, source_offset);
3,221✔
1182
      process_transport_events();
3,221✔
1183
    }
1184
    process_death_events(n_particles);
3,601✔
1185

1186
    // Adjust remaining work and source offset variables
1187
    remaining_work -= n_particles;
3,601✔
1188
    source_offset += n_particles;
3,601✔
1189
  }
1190
}
3,601✔
1191

1192
void transport_event_based_shared_secondary()
21✔
1193
{
1194
  // Clear shared secondary banks from any prior use
1195
  simulation::shared_secondary_bank_read.clear();
21✔
1196
  simulation::shared_secondary_bank_write.clear();
21✔
1197

1198
  if (mpi::master) {
21!
1199
    write_message(fmt::format(" Primary source          particles: {}",
42!
1200
                    settings::n_particles),
1201
      6);
1202
  }
1203

1204
  simulation::progeny_per_particle.resize(simulation::work_per_rank);
21✔
1205
  std::fill(simulation::progeny_per_particle.begin(),
42✔
1206
    simulation::progeny_per_particle.end(), 0);
21✔
1207

1208
  // Phase 1: Transport primary particles using event-based processing and
1209
  // deposit first generation of secondaries in the shared secondary bank
1210
  int64_t remaining_work = simulation::work_per_rank;
21✔
1211
  int64_t source_offset = 0;
21✔
1212

1213
  while (remaining_work > 0) {
42✔
1214
    int64_t n_particles =
21!
1215
      std::min(remaining_work, settings::max_particles_in_flight);
21✔
1216

1217
    if (settings::delta_tracking) {
21!
NEW
1218
      process_delta_init_events(n_particles, source_offset);
×
NEW
1219
      process_delta_transport_events();
×
1220
    } else {
1221
      process_init_events(n_particles, source_offset);
21✔
1222
      process_transport_events();
21✔
1223
    }
1224
    process_death_events(n_particles);
21✔
1225

1226
    collect_event_secondary_banks(n_particles);
21✔
1227

1228
    remaining_work -= n_particles;
21✔
1229
    source_offset += n_particles;
21✔
1230
  }
1231

1232
  simulation::simulation_tracks_completed += settings::n_particles;
21✔
1233

1234
  // Phase 2: Now that the secondary bank has been populated, enter loop over
1235
  // all secondary generations
1236
  int n_generation_depth = 1;
21✔
1237
  int64_t alive_secondary = 1;
21✔
1238
  while (alive_secondary) {
726✔
1239

1240
    // Sort the shared secondary bank by parent ID then progeny ID to
1241
    // ensure reproducibility.
1242
    sort_bank(simulation::shared_secondary_bank_write, false);
705✔
1243

1244
    // Synchronize the shared secondary bank amongst all MPI ranks, such
1245
    // that each MPI rank has an approximately equal number of secondary
1246
    // tracks.
1247
    alive_secondary = synchronize_global_secondary_bank(
705✔
1248
      simulation::shared_secondary_bank_write);
1249

1250
    // Recalculate work for each MPI rank based on number of alive secondary
1251
    // tracks
1252
    calculate_work(alive_secondary);
705✔
1253

1254
    if (mpi::master) {
705!
1255
      write_message(fmt::format(" Secondary generation {:<2}    tracks: {}",
1,410!
1256
                      n_generation_depth, alive_secondary),
1257
        6);
1258
    }
1259

1260
    simulation::shared_secondary_bank_read =
705✔
1261
      std::move(simulation::shared_secondary_bank_write);
705✔
1262
    simulation::shared_secondary_bank_write = SharedArray<SourceSite>();
705!
1263
    simulation::progeny_per_particle.resize(
705✔
1264
      simulation::shared_secondary_bank_read.size());
705✔
1265
    std::fill(simulation::progeny_per_particle.begin(),
1,410✔
1266
      simulation::progeny_per_particle.end(), 0);
705✔
1267

1268
    // Ensure particle buffer is large enough for this secondary generation
1269
    int64_t sec_buffer_length = std::min(
705!
1270
      static_cast<int64_t>(simulation::shared_secondary_bank_read.size()),
705!
1271
      settings::max_particles_in_flight);
705✔
1272
    if (sec_buffer_length >
705✔
1273
        static_cast<int64_t>(simulation::particles.size())) {
705✔
1274
      init_event_queues(sec_buffer_length);
53✔
1275
    }
1276

1277
    // Transport secondary tracks using event-based processing
1278
    int64_t sec_remaining = simulation::shared_secondary_bank_read.size();
705✔
1279
    int64_t sec_offset = 0;
705✔
1280

1281
    while (sec_remaining > 0) {
1,389✔
1282
      int64_t n_particles =
684!
1283
        std::min(sec_remaining, settings::max_particles_in_flight);
684✔
1284

1285
      if (settings::delta_tracking) {
684!
NEW
1286
        process_delta_init_secondary_events(
×
1287
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
NEW
1288
        process_delta_transport_events();
×
1289
      } else {
1290
        process_init_secondary_events(
684✔
1291
          n_particles, sec_offset, simulation::shared_secondary_bank_read);
1292
        process_transport_events();
684✔
1293
      }
1294
      process_death_events(n_particles);
684✔
1295

1296
      collect_event_secondary_banks(n_particles);
684✔
1297

1298
      sec_remaining -= n_particles;
684✔
1299
      sec_offset += n_particles;
684✔
1300
    } // End of subiteration loop over secondary tracks
1301
    n_generation_depth++;
705✔
1302
    simulation::simulation_tracks_completed += alive_secondary;
705✔
1303
  } // End of loop over secondary generations
1304

1305
  // Reset work so that fission bank etc works correctly
1306
  calculate_work(settings::n_particles);
21✔
1307
}
21✔
1308

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