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

openmc-dev / openmc / 21883244533

10 Feb 2026 09:34PM UTC coverage: 81.91% (+0.005%) from 81.905%
21883244533

Pull #3790

github

web-flow
Merge f540c8373 into 3f20a5e22
Pull Request #3790: Subcritical Multiplication Run Mode

17414 of 24353 branches covered (71.51%)

Branch coverage included in aggregate %.

74 of 85 new or added lines in 14 files covered. (87.06%)

56216 of 65538 relevant lines covered (85.78%)

47169664.29 hits per line

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

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

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

30
#ifdef _OPENMP
31
#include <omp.h>
32
#endif
33
#include "xtensor/xview.hpp"
34

35
#ifdef OPENMC_MPI
36
#include <mpi.h>
37
#endif
38

39
#include <fmt/format.h>
40

41
#include <algorithm>
42
#include <cmath>
43
#include <string>
44

45
//==============================================================================
46
// C API functions
47
//==============================================================================
48

49
// OPENMC_RUN encompasses all the main logic where iterations are performed
50
// over the batches, generations, and histories in a fixed source or
51
// k-eigenvalue calculation.
52

53
int openmc_run()
6,166✔
54
{
55
  openmc::simulation::time_total.start();
6,166✔
56
  openmc_simulation_init();
6,166✔
57

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

65
  int err = 0;
6,166✔
66
  while (status == 0 && err == 0) {
140,234!
67
    err = openmc_next_batch(&status);
134,080✔
68
  }
69

70
  openmc_simulation_finalize();
6,154✔
71
  openmc::simulation::time_total.stop();
6,154✔
72
  return err;
6,154✔
73
}
74

75
int openmc_simulation_init()
7,332✔
76
{
77
  using namespace openmc;
78

79
  // Skip if simulation has already been initialized
80
  if (simulation::initialized)
7,332✔
81
    return 0;
22✔
82

83
  // Initialize nuclear data (energy limits, log grid)
84
  if (settings::run_CE) {
7,310✔
85
    initialize_data();
5,899✔
86
  }
87

88
  // Determine how much work each process should do
89
  calculate_work();
7,310✔
90

91
  // Allocate source, fission and surface source banks.
92
  allocate_banks();
7,310✔
93

94
  // Create track file if needed
95
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,310✔
96
    open_track_file();
96✔
97
  }
98

99
  // If doing an event-based simulation, intialize the particle buffer
100
  // and event queues
101
  if (settings::event_based) {
7,310✔
102
    int64_t event_buffer_length =
103
      std::min(simulation::work_per_rank, settings::max_particles_in_flight);
205✔
104
    init_event_queues(event_buffer_length);
205✔
105
  }
106

107
  // Allocate tally results arrays if they're not allocated yet
108
  for (auto& t : model::tallies) {
35,002✔
109
    t->set_strides();
27,692✔
110
    t->init_results();
27,692✔
111
  }
112

113
  // Set up material nuclide index mapping
114
  for (auto& mat : model::materials) {
26,063✔
115
    mat->init_nuclide_index();
18,753✔
116
  }
117

118
  // Reset global variables -- this is done before loading state point (as that
119
  // will potentially populate k_generation and entropy)
120
  simulation::current_batch = 0;
7,310✔
121
  simulation::ct_current_file = 1;
7,310✔
122
  simulation::ssw_current_file = 1;
7,310✔
123
  simulation::k_generation.clear();
7,310✔
124
  simulation::entropy.clear();
7,310✔
125
  openmc_reset();
7,310✔
126

127
  // If this is a restart run, load the state point data and binary source
128
  // file
129
  if (settings::restart_run) {
7,310✔
130
    load_state_point();
65✔
131
    write_message("Resuming simulation...", 6);
65✔
132
  } else {
133
    // Only initialize primary source bank for eigenvalue-like simulations
134
    if (settings::eigenvalue_like() &&
11,620✔
135
        settings::solver_type == SolverType::MONTE_CARLO) {
4,375✔
136
      initialize_source();
3,980✔
137
    }
138
  }
139

140
  // Display header
141
  if (mpi::master) {
7,310✔
142
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,150✔
143
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,566✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,234✔
145
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
332!
146
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
332✔
147
      }
148
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,584✔
149
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,573✔
150
        header("K EIGENVALUE SIMULATION", 3);
3,298✔
151
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
275!
152
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
275✔
NEW
153
      } else if (settings::run_mode == RunMode::SUBCRITICAL_MULTIPLICATION) {
×
NEW
154
        header(
×
155
          "FIXED SOURCE (SUBCRITICAL MULTIPLICATION) TRANSPORT SIMULATION", 3);
156
      }
157
      if (settings::verbosity >= 7)
3,573✔
158
        print_columns();
3,373✔
159
    }
160
  }
161

162
  // load weight windows from file
163
  if (!settings::weight_windows_file.empty()) {
7,310!
164
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
×
165
  }
166

167
  // Set flag indicating initialization is done
168
  simulation::initialized = true;
7,310✔
169
  return 0;
7,310✔
170
}
171

172
int openmc_simulation_finalize()
7,298✔
173
{
174
  using namespace openmc;
175

176
  // Skip if simulation was never run
177
  if (!simulation::initialized)
7,298!
178
    return 0;
×
179

180
  // Stop active batch timer and start finalization timer
181
  simulation::time_active.stop();
7,298✔
182
  simulation::time_finalize.start();
7,298✔
183

184
  // Clear material nuclide mapping
185
  for (auto& mat : model::materials) {
26,039✔
186
    mat->mat_nuclide_index_.clear();
18,741✔
187
  }
188

189
  // Close track file if open
190
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,298✔
191
    close_track_file();
96✔
192
  }
193

194
  // Increment total number of generations
195
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
7,298✔
196

197
#ifdef OPENMC_MPI
198
  broadcast_results();
3,964✔
199
#endif
200

201
  // Write tally results to tallies.out
202
  if (settings::output_tallies && mpi::master)
7,298!
203
    write_tallies();
5,793✔
204

205
  // If weight window generators are present in this simulation,
206
  // write a weight windows file
207
  if (variance_reduction::weight_windows_generators.size() > 0) {
7,298✔
208
    openmc_weight_windows_export();
131✔
209
  }
210

211
  // Deactivate all tallies
212
  for (auto& t : model::tallies) {
34,990✔
213
    t->active_ = false;
27,692✔
214
  }
215

216
  // Stop timers and show timing statistics
217
  simulation::time_finalize.stop();
7,298✔
218
  simulation::time_total.stop();
7,298✔
219
  if (mpi::master) {
7,298✔
220
    if (settings::solver_type != SolverType::RANDOM_RAY) {
6,138✔
221
      if (settings::verbosity >= 6)
5,531✔
222
        print_runtime();
5,331✔
223
      if (settings::verbosity >= 4)
5,531✔
224
        print_results();
5,331✔
225
    }
226
  }
227
  if (settings::check_overlaps)
7,298!
228
    print_overlap_check();
×
229

230
  // Reset flags
231
  simulation::initialized = false;
7,298✔
232
  return 0;
7,298✔
233
}
234

235
int openmc_next_batch(int* status)
138,205✔
236
{
237
  using namespace openmc;
238
  using openmc::simulation::current_gen;
239

240
  // Make sure simulation has been initialized
241
  if (!simulation::initialized) {
138,205✔
242
    set_errmsg("Simulation has not been initialized yet.");
11✔
243
    return OPENMC_E_ALLOCATE;
11✔
244
  }
245

246
  initialize_batch();
138,194✔
247

248
  // =======================================================================
249
  // LOOP OVER GENERATIONS
250
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
276,600✔
251

252
    initialize_generation();
138,418✔
253

254
    // Start timer for transport
255
    simulation::time_transport.start();
138,418✔
256

257
    // Transport loop
258
    if (settings::event_based) {
138,418✔
259
      transport_event_based();
3,192✔
260
    } else {
261
      transport_history_based();
135,226✔
262
    }
263

264
    // Accumulate time for transport
265
    simulation::time_transport.stop();
138,406✔
266

267
    finalize_generation();
138,406✔
268
  }
269

270
  finalize_batch();
138,182✔
271

272
  // Check simulation ending criteria
273
  if (status) {
138,182!
274
    if (simulation::current_batch >= settings::n_max_batches) {
138,182✔
275
      *status = STATUS_EXIT_MAX_BATCH;
6,343✔
276
    } else if (simulation::satisfy_triggers) {
131,839✔
277
      *status = STATUS_EXIT_ON_TRIGGER;
97✔
278
    } else {
279
      *status = STATUS_EXIT_NORMAL;
131,742✔
280
    }
281
  }
282
  return 0;
138,182✔
283
}
284

285
bool openmc_is_statepoint_batch()
3,135✔
286
{
287
  using namespace openmc;
288
  using openmc::simulation::current_gen;
289

290
  if (!simulation::initialized)
3,135!
291
    return false;
×
292
  else
293
    return contains(settings::statepoint_batch, simulation::current_batch);
3,135✔
294
}
295

296
namespace openmc {
297

298
//==============================================================================
299
// Global variables
300
//==============================================================================
301

302
namespace simulation {
303

304
int ct_current_file;
305
int current_batch;
306
int current_gen;
307
bool initialized {false};
308
double keff {1.0};
309
double kold {1.0};
310
double keff_std;
311
double k_col_abs {0.0};
312
double k_col_tra {0.0};
313
double k_abs_tra {0.0};
314
double log_spacing;
315
int n_lost_particles {0};
316
bool need_depletion_rx {false};
317
int restart_batch;
318
bool satisfy_triggers {false};
319
int ssw_current_file;
320
int total_gen {0};
321
double total_weight;
322
int64_t work_per_rank;
323

324
const RegularMesh* entropy_mesh {nullptr};
325
const RegularMesh* ufs_mesh {nullptr};
326

327
vector<double> k_generation;
328
vector<int64_t> work_index;
329

330
} // namespace simulation
331

332
//==============================================================================
333
// Non-member functions
334
//==============================================================================
335

336
void allocate_banks()
7,310✔
337
{
338
  if (settings::eigenvalue_like() &&
11,750✔
339
      settings::solver_type == SolverType::MONTE_CARLO) {
4,440✔
340
    // Allocate source bank
341
    simulation::source_bank.resize(simulation::work_per_rank);
4,045✔
342

343
    // Allocate fission bank
344
    init_fission_bank(3 * simulation::work_per_rank);
4,045✔
345

346
    // Allocate IFP bank
347
    if (settings::ifp_on) {
4,045✔
348
      resize_simulation_ifp_banks();
76✔
349
    }
350
  }
351

352
  if (settings::surf_source_write) {
7,310✔
353
    // Allocate surface source bank
354
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
974✔
355
  }
356

357
  if (settings::collision_track) {
7,310✔
358
    // Allocate collision track bank
359
    collision_track_reserve_bank();
155✔
360
  }
361
}
7,310✔
362

363
void initialize_batch()
159,446✔
364
{
365
  // Increment current batch
366
  ++simulation::current_batch;
159,446✔
367
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
159,446✔
368
    if (settings::solver_type == SolverType::RANDOM_RAY &&
63,537✔
369
        simulation::current_batch < settings::n_inactive + 1) {
14,092✔
370
      write_message(
8,566✔
371
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
372
    } else {
373
      write_message(6, "Simulating batch {}", simulation::current_batch);
54,971✔
374
    }
375
  }
376

377
  // Reset total starting particle weight used for normalizing tallies
378
  simulation::total_weight = 0.0;
159,446✔
379

380
  // Determine if this batch is the first inactive or active batch.
381
  bool first_inactive = false;
159,446✔
382
  bool first_active = false;
159,446✔
383
  if (!settings::restart_run) {
159,446✔
384
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
159,278✔
385
    first_active = simulation::current_batch == settings::n_inactive + 1;
159,278✔
386
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
168✔
387
    first_inactive = simulation::restart_batch < settings::n_inactive;
54✔
388
    first_active = !first_inactive;
54✔
389
  }
390

391
  // Manage active/inactive timers and activate tallies if necessary.
392
  if (first_inactive) {
159,446✔
393
    simulation::time_inactive.start();
3,778✔
394
  } else if (first_active) {
155,668✔
395
    simulation::time_inactive.stop();
7,263✔
396
    simulation::time_active.start();
7,263✔
397
    for (auto& t : model::tallies) {
34,933✔
398
      t->active_ = true;
27,670✔
399
    }
400
  }
401

402
  // Add user tallies to active tallies list
403
  setup_active_tallies();
159,446✔
404
}
159,446✔
405

406
void finalize_batch()
159,434✔
407
{
408
  // Reduce tallies onto master process and accumulate
409
  simulation::time_tallies.start();
159,434✔
410
  accumulate_tallies();
159,434✔
411
  simulation::time_tallies.stop();
159,434✔
412

413
  // update weight windows if needed
414
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
161,851✔
415
    wwg->update();
2,417✔
416
  }
417

418
  // Reset global tally results
419
  if (simulation::current_batch <= settings::n_inactive) {
159,434✔
420
    xt::view(simulation::global_tallies, xt::all()) = 0.0;
31,325✔
421
    simulation::n_realizations = 0;
31,325✔
422
  }
423

424
  // Check_triggers
425
  if (mpi::master)
159,434✔
426
    check_triggers();
136,434✔
427
#ifdef OPENMC_MPI
428
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
85,156✔
429
#endif
430
  if (simulation::satisfy_triggers ||
159,434✔
431
      (settings::trigger_on &&
2,645✔
432
        simulation::current_batch == settings::n_max_batches)) {
2,645✔
433
    settings::statepoint_batch.insert(simulation::current_batch);
146✔
434
  }
435

436
  // Write out state point if it's been specified for this batch and is not
437
  // a CMFD run instance
438
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
166,966✔
439
      !settings::cmfd_run) {
7,532✔
440
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
14,491✔
441
        settings::source_write && !settings::source_separate) {
14,491✔
442
      bool b = (settings::eigenvalue_like());
6,183✔
443
      openmc_statepoint_write(nullptr, &b);
6,183✔
444
    } else {
445
      bool b = false;
1,173✔
446
      openmc_statepoint_write(nullptr, &b);
1,173✔
447
    }
448
  }
449

450
  if (settings::eigenvalue_like()) {
159,434✔
451
    // Write out a separate source point if it's been specified for this batch
452
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
100,398✔
453
        settings::source_write && settings::source_separate) {
100,398✔
454

455
      // Determine width for zero padding
456
      int w = std::to_string(settings::n_max_batches).size();
75✔
457
      std::string source_point_filename = fmt::format("{0}source.{1:0{2}}",
458
        settings::path_output, simulation::current_batch, w);
61✔
459
      span<SourceSite> bankspan(simulation::source_bank);
75✔
460
      write_source_point(source_point_filename, bankspan,
75✔
461
        simulation::work_index, settings::source_mcpl_write);
462
    }
75✔
463

464
    // Write a continously-overwritten source point if requested.
465
    if (settings::source_latest) {
95,909✔
466
      auto filename = settings::path_output + "source";
160✔
467
      span<SourceSite> bankspan(simulation::source_bank);
160✔
468
      write_source_point(filename, bankspan, simulation::work_index,
160✔
469
        settings::source_mcpl_write);
470
    }
160✔
471
  }
472

473
  // Write out surface source if requested.
474
  if (settings::surf_source_write &&
159,434✔
475
      simulation::ssw_current_file <= settings::ssw_max_files) {
9,269✔
476
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,796✔
477
    if (simulation::surf_source_bank.full() || last_batch) {
1,796✔
478
      // Determine appropriate filename
479
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
480
        simulation::current_batch);
823✔
481
      if (settings::ssw_max_files == 1 ||
1,007✔
482
          (simulation::ssw_current_file == 1 && last_batch)) {
55!
483
        filename = settings::path_output + "surface_source";
952✔
484
      }
485

486
      // Get span of source bank and calculate parallel index vector
487
      auto surf_work_index = mpi::calculate_parallel_index_vector(
488
        simulation::surf_source_bank.size());
1,007✔
489
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
490
        simulation::surf_source_bank.size());
1,007✔
491

492
      // Write surface source file
493
      write_source_point(
1,007✔
494
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
495

496
      // Reset surface source bank and increment counter
497
      simulation::surf_source_bank.clear();
1,007✔
498
      if (!last_batch && settings::ssw_max_files >= 1) {
1,007!
499
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
825✔
500
      }
501
      ++simulation::ssw_current_file;
1,007✔
502
    }
1,007✔
503
  }
504
  // Write collision track file if requested
505
  if (settings::collision_track) {
159,434✔
506
    collision_track_flush_bank();
643✔
507
  }
508
}
159,434✔
509

510
void initialize_generation()
159,670✔
511
{
512
  if (settings::eigenvalue_like()) {
159,670✔
513
    // Clear out the fission bank
514
    simulation::fission_bank.resize(0);
96,133✔
515

516
    // Count source sites if using uniform fission source weighting
517
    if (settings::ufs_on)
96,133✔
518
      ufs_count_sites();
160✔
519

520
    // Store current value of tracklength k
521
    simulation::keff_generation = simulation::global_tallies(
96,133✔
522
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
523
  }
524
}
159,670✔
525

526
void finalize_generation()
159,658✔
527
{
528
  auto& gt = simulation::global_tallies;
159,658✔
529

530
  // Update global tallies with the accumulation variables
531
  if (settings::eigenvalue_like()) {
159,658✔
532
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
96,133✔
533
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
96,133✔
534
      global_tally_absorption;
535
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
96,133✔
536
      global_tally_tracklength;
537
  }
538
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
159,658✔
539

540
  // reset tallies
541
  if (settings::eigenvalue_like()) {
159,658✔
542
    global_tally_collision = 0.0;
96,133✔
543
    global_tally_absorption = 0.0;
96,133✔
544
    global_tally_tracklength = 0.0;
96,133✔
545
  }
546
  global_tally_leakage = 0.0;
159,658✔
547

548
  if (settings::eigenvalue_like() &&
255,791✔
549
      settings::solver_type == SolverType::MONTE_CARLO) {
96,133✔
550
    // If using shared memory, stable sort the fission bank (by parent IDs)
551
    // so as to allow for reproducibility regardless of which order particles
552
    // are run in.
553
    sort_fission_bank();
88,973✔
554

555
    // Distribute fission bank across processors evenly
556
    synchronize_bank();
88,973✔
557
  }
558

559
  if (settings::eigenvalue_like()) {
159,658✔
560

561
    // Calculate shannon entropy
562
    if (settings::entropy_on &&
96,133✔
563
        settings::solver_type == SolverType::MONTE_CARLO)
14,855✔
564
      shannon_entropy();
7,695✔
565

566
    // Collect results and statistics
567
    calculate_generation_keff();
96,133✔
568
    calculate_average_keff();
96,133✔
569

570
    simulation::kold = simulation::keff;
96,133✔
571

572
    // Write generation output
573
    if (mpi::master && settings::verbosity >= 7) {
96,133✔
574
      print_generation();
75,973✔
575
    }
576
  }
577
}
159,658✔
578

579
void initialize_history(Particle& p, int64_t index_source)
190,647,060✔
580
{
581
  // set defaults
582
  if (settings::run_mode == RunMode::EIGENVALUE) {
190,647,060✔
583
    // set defaults for eigenvalue simulations from primary bank
584
    p.from_source(&simulation::source_bank[index_source - 1]);
141,365,700✔
585
  } else {
586
    // initialize random number seed
587
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
49,281,360✔
588
                   settings::n_particles +
49,281,360✔
589
                 simulation::work_index[mpi::rank] + index_source;
49,281,360✔
590
    uint64_t seed = init_seed(id, STREAM_SOURCE);
49,281,360✔
591
    if (settings::run_mode == RunMode::SUBCRITICAL_MULTIPLICATION) {
49,281,360✔
592
      double rnd = prn(&seed);
22,000,000✔
593
      double k_avg = 0.0;
22,000,000✔
594
      int n = simulation::k_generation.size();
22,000,000✔
595
      if (n >= 2) {
22,000,000✔
596
        // Average the last two values
597
        double k_last = simulation::k_generation[n - 1];
19,800,000✔
598
        double k_prev = simulation::k_generation[n - 2];
19,800,000✔
599
        k_avg = (k_last + k_prev) / 2.0;
19,800,000✔
600
      } else if (n == 1) {
2,200,000✔
601
        // Only one generation exists, use it directly
602
        k_avg = simulation::k_generation[0];
1,100,000✔
603
      }
604
      if (rnd < k_avg) {
22,000,000✔
605
        // sample from fission source bank
606
        p.from_source(&simulation::source_bank[index_source - 1]);
18,755,924✔
607
      } else {
608
        // sample from external source
609
        auto site = sample_external_source(&seed);
3,244,076✔
610
        p.from_source(&site);
3,244,076✔
611
      }
612
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
27,281,360!
613
      // sample from external source distribution or custom library then set
614
      auto site = sample_external_source(&seed);
27,281,360✔
615
      p.from_source(&site);
27,281,357✔
616
    }
617
  }
618
  p.current_work() = index_source;
190,647,057✔
619

620
  // set identifier for particle
621
  p.id() = simulation::work_index[mpi::rank] + index_source;
190,647,057✔
622

623
  // set progeny count to zero
624
  p.n_progeny() = 0;
190,647,057✔
625

626
  // Reset particle event counter
627
  p.n_event() = 0;
190,647,057✔
628

629
  // Reset split counter
630
  p.n_split() = 0;
190,647,057✔
631

632
  // Reset weight window ratio
633
  p.ww_factor() = 0.0;
190,647,057✔
634

635
  // set particle history start weight
636
  p.wgt_born() = p.wgt();
190,647,057✔
637

638
  // Reset pulse_height_storage
639
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
190,647,057✔
640

641
  // set random number seed
642
  int64_t particle_seed =
643
    (simulation::total_gen + overall_generation() - 1) * settings::n_particles +
190,647,057✔
644
    p.id();
190,647,057✔
645
  init_particle_seeds(particle_seed, p.seeds());
190,647,057✔
646

647
  // set particle trace
648
  p.trace() = false;
190,647,057✔
649
  if (simulation::current_batch == settings::trace_batch &&
381,305,114✔
650
      simulation::current_gen == settings::trace_gen &&
190,658,057!
651
      p.id() == settings::trace_particle)
11,000✔
652
    p.trace() = true;
11✔
653

654
  // Set particle track.
655
  p.write_track() = check_track_criteria(p);
190,647,057✔
656

657
  // Set the particle's initial weight window value.
658
  p.wgt_ww_born() = -1.0;
190,647,057✔
659
  apply_weight_windows(p);
190,647,057✔
660

661
  // Display message if high verbosity or trace is on
662
  if (settings::verbosity >= 9 || p.trace()) {
190,647,057!
663
    write_message("Simulating Particle {}", p.id());
11✔
664
  }
665

666
// Add particle's starting weight to count for normalizing tallies later
667
#pragma omp atomic
104,240,754✔
668
  simulation::total_weight += p.wgt();
190,647,057✔
669

670
  // Force calculation of cross-sections by setting last energy to zero
671
  if (settings::run_CE) {
190,647,057✔
672
    p.invalidate_neutron_xs();
56,623,057✔
673
  }
674

675
  // Prepare to write out particle track.
676
  if (p.write_track())
190,647,057✔
677
    add_particle_track(p);
1,059✔
678
}
190,647,057✔
679

680
int overall_generation()
240,189,754✔
681
{
682
  using namespace simulation;
683
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
240,189,754✔
684
}
685

686
void calculate_work()
7,310✔
687
{
688
  // Determine minimum amount of particles to simulate on each processor
689
  int64_t min_work = settings::n_particles / mpi::n_procs;
7,310✔
690

691
  // Determine number of processors that have one extra particle
692
  int64_t remainder = settings::n_particles % mpi::n_procs;
7,310✔
693

694
  int64_t i_bank = 0;
7,310✔
695
  simulation::work_index.resize(mpi::n_procs + 1);
7,310✔
696
  simulation::work_index[0] = 0;
7,310✔
697
  for (int i = 0; i < mpi::n_procs; ++i) {
16,939✔
698
    // Number of particles for rank i
699
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
9,629!
700

701
    // Set number of particles
702
    if (mpi::rank == i)
9,629✔
703
      simulation::work_per_rank = work_i;
7,310✔
704

705
    // Set index into source bank for rank i
706
    i_bank += work_i;
9,629✔
707
    simulation::work_index[i + 1] = i_bank;
9,629✔
708
  }
709
}
7,310✔
710

711
void initialize_data()
5,932✔
712
{
713
  // Determine minimum/maximum energy for incident neutron/photon data
714
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
5,932✔
715
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
5,932✔
716

717
  for (const auto& nuc : data::nuclides) {
35,347✔
718
    if (nuc->grid_.size() >= 1) {
29,415!
719
      int neutron = ParticleType::neutron().transport_index();
29,415✔
720
      data::energy_min[neutron] =
58,830✔
721
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
29,415✔
722
      data::energy_max[neutron] =
29,415✔
723
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
29,415✔
724
    }
725
  }
726

727
  if (settings::photon_transport) {
5,932✔
728
    for (const auto& elem : data::elements) {
919✔
729
      if (elem->energy_.size() >= 1) {
622!
730
        int photon = ParticleType::photon().transport_index();
622✔
731
        int n = elem->energy_.size();
622✔
732
        data::energy_min[photon] =
1,244✔
733
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
622✔
734
        data::energy_max[photon] =
1,244✔
735
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
622✔
736
      }
737
    }
738

739
    if (settings::electron_treatment == ElectronTreatment::TTB) {
297✔
740
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
741
      // than the current minimum/maximum
742
      if (data::ttb_e_grid.size() >= 1) {
275!
743
        int photon = ParticleType::photon().transport_index();
275✔
744
        int electron = ParticleType::electron().transport_index();
275✔
745
        int positron = ParticleType::positron().transport_index();
275✔
746
        int n_e = data::ttb_e_grid.size();
275✔
747

748
        const std::vector<int> charged = {electron, positron};
275✔
749
        for (auto t : charged) {
825✔
750
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
550✔
751
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
550✔
752
        }
753

754
        data::energy_min[photon] =
550✔
755
          std::max(data::energy_min[photon], data::energy_min[electron]);
275✔
756

757
        data::energy_max[photon] =
550✔
758
          std::min(data::energy_max[photon], data::energy_max[electron]);
275✔
759
      }
275✔
760
    }
761
  }
762

763
  // Show which nuclide results in lowest energy for neutron transport
764
  for (const auto& nuc : data::nuclides) {
7,413✔
765
    // If a nuclide is present in a material that's not used in the model, its
766
    // grid has not been allocated
767
    if (nuc->grid_.size() > 0) {
6,933!
768
      double max_E = nuc->grid_[0].energy.back();
6,933✔
769
      int neutron = ParticleType::neutron().transport_index();
6,933✔
770
      if (max_E == data::energy_max[neutron]) {
6,933✔
771
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
5,452✔
772
          data::energy_max[neutron], nuc->name_);
5,452✔
773
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
5,452!
774
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
775
                  "the results.");
776
        }
777
        break;
5,452✔
778
      }
779
    }
780
  }
781

782
  // Set up logarithmic grid for nuclides
783
  for (auto& nuc : data::nuclides) {
35,347✔
784
    nuc->init_grid();
29,415✔
785
  }
786
  int neutron = ParticleType::neutron().transport_index();
5,932✔
787
  simulation::log_spacing =
5,932✔
788
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
5,932✔
789
    settings::n_log_bins;
790
}
5,932✔
791

792
#ifdef OPENMC_MPI
793
void broadcast_results()
3,964✔
794
{
795
  // Broadcast tally results so that each process has access to results
796
  for (auto& t : model::tallies) {
20,319✔
797
    // Create a new datatype that consists of all values for a given filter
798
    // bin and then use that to broadcast. This is done to minimize the
799
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
800
    auto& results = t->results_;
16,355✔
801

802
    auto shape = results.shape();
16,355✔
803
    int count_per_filter = shape[1] * shape[2];
16,355✔
804
    MPI_Datatype result_block;
805
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
16,355✔
806
    MPI_Type_commit(&result_block);
16,355✔
807
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
16,355✔
808
    MPI_Type_free(&result_block);
16,355✔
809
  }
810

811
  // Also broadcast global tally results
812
  auto& gt = simulation::global_tallies;
3,964✔
813
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,964✔
814

815
  // These guys are needed so that non-master processes can calculate the
816
  // combined estimate of k-effective
817
  double temp[] {
818
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,964✔
819
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,964✔
820
  simulation::k_col_abs = temp[0];
3,964✔
821
  simulation::k_col_tra = temp[1];
3,964✔
822
  simulation::k_abs_tra = temp[2];
3,964✔
823
}
3,964✔
824

825
#endif
826

827
void free_memory_simulation()
8,401✔
828
{
829
  simulation::k_generation.clear();
8,401✔
830
  simulation::entropy.clear();
8,401✔
831
}
8,401✔
832

833
void transport_history_based_single_particle(Particle& p)
176,510,390✔
834
{
835
  while (p.alive()) {
2,147,483,647✔
836
    p.event_calculate_xs();
2,147,483,647✔
837
    if (p.alive()) {
2,147,483,647!
838
      p.event_advance();
2,147,483,647✔
839
    }
840
    if (p.alive()) {
2,147,483,647✔
841
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
842
        p.event_cross_surface();
1,462,590,705✔
843
      } else if (p.alive()) {
2,147,483,647!
844
        p.event_collide();
2,147,483,647✔
845
      }
846
    }
847
    p.event_revive_from_secondary();
2,147,483,647✔
848
  }
849
  p.event_death();
176,510,381✔
850
}
176,510,381✔
851

852
void transport_history_based()
135,226✔
853
{
854
#pragma omp parallel for schedule(runtime)
855
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
86,622,814✔
856
    Particle p;
86,561,088✔
857
    initialize_history(p, i_work);
86,561,088✔
858
    transport_history_based_single_particle(p);
86,561,085✔
859
  }
86,561,080✔
860
}
135,218✔
861

862
void transport_event_based()
3,192✔
863
{
864
  int64_t remaining_work = simulation::work_per_rank;
3,192✔
865
  int64_t source_offset = 0;
3,192✔
866

867
  // To cap the total amount of memory used to store particle object data, the
868
  // number of particles in flight at any point in time can bet set. In the case
869
  // that the maximum in flight particle count is lower than the total number
870
  // of particles that need to be run this iteration, the event-based transport
871
  // loop is executed multiple times until all particles have been completed.
872
  while (remaining_work > 0) {
6,384✔
873
    // Figure out # of particles to run for this subiteration
874
    int64_t n_particles =
875
      std::min(remaining_work, settings::max_particles_in_flight);
3,192✔
876

877
    // Initialize all particle histories for this subiteration
878
    process_init_events(n_particles, source_offset);
3,192!
879

880
    // Event-based transport loop
881
    while (true) {
882
      // Determine which event kernel has the longest queue
883
      int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(),
4,745,894!
884
        simulation::calculate_nonfuel_xs_queue.size(),
2,372,947✔
885
        simulation::advance_particle_queue.size(),
2,372,947✔
886
        simulation::surface_crossing_queue.size(),
2,372,947✔
887
        simulation::collision_queue.size()});
2,372,947✔
888

889
      // Execute event with the longest queue
890
      if (max == 0) {
2,372,947✔
891
        break;
3,192✔
892
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,369,755✔
893
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
425,912!
894
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,943,843✔
895
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
361,280!
896
      } else if (max == simulation::advance_particle_queue.size()) {
1,582,563✔
897
        process_advance_particle_events();
781,921!
898
      } else if (max == simulation::surface_crossing_queue.size()) {
800,642✔
899
        process_surface_crossing_events();
260,009!
900
      } else if (max == simulation::collision_queue.size()) {
540,633!
901
        process_collision_events();
540,633!
902
      }
903
    }
2,369,755✔
904

905
    // Execute death event for all particles
906
    process_death_events(n_particles);
3,192!
907

908
    // Adjust remaining work and source offset variables
909
    remaining_work -= n_particles;
3,192✔
910
    source_offset += n_particles;
3,192✔
911
  }
912
}
3,192✔
913

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

© 2026 Coveralls, Inc