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

openmc-dev / openmc / 21822677700

09 Feb 2026 11:09AM UTC coverage: 81.694% (-0.1%) from 81.817%
21822677700

Pull #3785

github

web-flow
Merge 83143abcc into d0346e94a
Pull Request #3785: Coincident source

17361 of 24416 branches covered (71.11%)

Branch coverage included in aggregate %.

137 of 197 new or added lines in 5 files covered. (69.54%)

8 existing lines in 1 file now uncovered.

56180 of 65604 relevant lines covered (85.64%)

45050359.49 hits per line

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

94.13
/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,038✔
54
{
55
  openmc::simulation::time_total.start();
6,038✔
56
  openmc_simulation_init();
6,038✔
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,038✔
61
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
6,038✔
62
    status = openmc::STATUS_EXIT_MAX_BATCH;
11✔
63
  }
64

65
  int err = 0;
6,038✔
66
  while (status == 0 && err == 0) {
124,356!
67
    err = openmc_next_batch(&status);
118,331✔
68
  }
69

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

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

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

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

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

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

94
  // Create track file if needed
95
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,118✔
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,118✔
102
    int64_t event_buffer_length =
103
      std::min(simulation::work_per_rank, settings::max_particles_in_flight);
200✔
104
    init_event_queues(event_buffer_length);
200✔
105
  }
106

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

113
  // Set up material nuclide index mapping
114
  for (auto& mat : model::materials) {
25,481✔
115
    mat->init_nuclide_index();
18,363✔
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,118✔
121
  simulation::ct_current_file = 1;
7,118✔
122
  simulation::ssw_current_file = 1;
7,118✔
123
  simulation::k_generation.clear();
7,118✔
124
  simulation::entropy.clear();
7,118✔
125
  openmc_reset();
7,118✔
126

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

140
  // Display header
141
  if (mpi::master) {
7,118✔
142
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,983✔
143
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,475✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,143✔
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,508!
149
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,508✔
150
        header("K EIGENVALUE SIMULATION", 3);
3,277✔
151
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
231!
152
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
231✔
153
      }
154
      if (settings::verbosity >= 7)
3,508✔
155
        print_columns();
3,308✔
156
    }
157
  }
158

159
  // load weight windows from file
160
  if (!settings::weight_windows_file.empty()) {
7,118!
161
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
×
162
  }
163

164
  // Set flag indicating initialization is done
165
  simulation::initialized = true;
7,118✔
166
  return 0;
7,118✔
167
}
168

169
int openmc_simulation_finalize()
7,105✔
170
{
171
  using namespace openmc;
172

173
  // Skip if simulation was never run
174
  if (!simulation::initialized)
7,105!
175
    return 0;
×
176

177
  // Stop active batch timer and start finalization timer
178
  simulation::time_active.stop();
7,105✔
179
  simulation::time_finalize.start();
7,105✔
180

181
  // Clear material nuclide mapping
182
  for (auto& mat : model::materials) {
25,453✔
183
    mat->mat_nuclide_index_.clear();
18,348✔
184
  }
185

186
  // Close track file if open
187
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,105✔
188
    close_track_file();
96✔
189
  }
190

191
  // Increment total number of generations
192
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
7,105✔
193

194
#ifdef OPENMC_MPI
195
  broadcast_results();
3,864✔
196
#endif
197

198
  // Write tally results to tallies.out
199
  if (settings::output_tallies && mpi::master)
7,105!
200
    write_tallies();
5,735✔
201

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

208
  // Deactivate all tallies
209
  for (auto& t : model::tallies) {
34,226✔
210
    t->active_ = false;
27,121✔
211
  }
212

213
  // Stop timers and show timing statistics
214
  simulation::time_finalize.stop();
7,105✔
215
  simulation::time_total.stop();
7,105✔
216
  if (mpi::master) {
7,105✔
217
    if (settings::solver_type != SolverType::RANDOM_RAY) {
5,970✔
218
      if (settings::verbosity >= 6)
5,407✔
219
        print_runtime();
5,207✔
220
      if (settings::verbosity >= 4)
5,407✔
221
        print_results();
5,207✔
222
    }
223
  }
224
  if (settings::check_overlaps)
7,105!
225
    print_overlap_check();
×
226

227
  // Reset flags
228
  simulation::initialized = false;
7,105✔
229
  return 0;
7,105✔
230
}
231

232
int openmc_next_batch(int* status)
122,456✔
233
{
234
  using namespace openmc;
235
  using openmc::simulation::current_gen;
236

237
  // Make sure simulation has been initialized
238
  if (!simulation::initialized) {
122,456✔
239
    set_errmsg("Simulation has not been initialized yet.");
11✔
240
    return OPENMC_E_ALLOCATE;
11✔
241
  }
242

243
  initialize_batch();
122,445✔
244

245
  // =======================================================================
246
  // LOOP OVER GENERATIONS
247
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
245,101✔
248

249
    initialize_generation();
122,669✔
250

251
    // Start timer for transport
252
    simulation::time_transport.start();
122,669✔
253

254
    // Transport loop
255
    if (settings::event_based) {
122,669✔
256
      transport_event_based();
3,172✔
257
    } else {
258
      transport_history_based();
119,497✔
259
    }
260

261
    // Accumulate time for transport
262
    simulation::time_transport.stop();
122,656✔
263

264
    finalize_generation();
122,656✔
265
  }
266

267
  finalize_batch();
122,432✔
268

269
  // Check simulation ending criteria
270
  if (status) {
122,432!
271
    if (simulation::current_batch >= settings::n_max_batches) {
122,432✔
272
      *status = STATUS_EXIT_MAX_BATCH;
6,214✔
273
    } else if (simulation::satisfy_triggers) {
116,218✔
274
      *status = STATUS_EXIT_ON_TRIGGER;
97✔
275
    } else {
276
      *status = STATUS_EXIT_NORMAL;
116,121✔
277
    }
278
  }
279
  return 0;
122,432✔
280
}
281

282
bool openmc_is_statepoint_batch()
3,135✔
283
{
284
  using namespace openmc;
285
  using openmc::simulation::current_gen;
286

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

293
namespace openmc {
294

295
//==============================================================================
296
// Global variables
297
//==============================================================================
298

299
namespace simulation {
300

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

320
const RegularMesh* entropy_mesh {nullptr};
321
const RegularMesh* ufs_mesh {nullptr};
322

323
vector<double> k_generation;
324
vector<int64_t> work_index;
325

326
} // namespace simulation
327

328
//==============================================================================
329
// Non-member functions
330
//==============================================================================
331

332
void allocate_banks()
7,118✔
333
{
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
7,118✔
335
      settings::solver_type == SolverType::MONTE_CARLO) {
4,339✔
336
    // Allocate source bank
337
    simulation::source_bank.resize(simulation::work_per_rank);
4,008✔
338

339
    // Allocate fission bank
340
    init_fission_bank(3 * simulation::work_per_rank);
4,008✔
341

342
    // Allocate IFP bank
343
    if (settings::ifp_on) {
4,008✔
344
      resize_simulation_ifp_banks();
76✔
345
    }
346
  }
347

348
  if (settings::surf_source_write) {
7,118✔
349
    // Allocate surface source bank
350
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
974✔
351
  }
352

353
  if (settings::collision_track) {
7,118✔
354
    // Allocate collision track bank
355
    collision_track_reserve_bank();
155✔
356
  }
357
}
7,118✔
358

359
void initialize_batch()
143,057✔
360
{
361
  // Increment current batch
362
  ++simulation::current_batch;
143,057✔
363
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
143,057✔
364
    if (settings::solver_type == SolverType::RANDOM_RAY &&
52,507✔
365
        simulation::current_batch < settings::n_inactive + 1) {
14,092✔
366
      write_message(
8,566✔
367
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
368
    } else {
369
      write_message(6, "Simulating batch {}", simulation::current_batch);
43,941✔
370
    }
371
  }
372

373
  // Reset total starting particle weight used for normalizing tallies
374
  simulation::total_weight = 0.0;
143,057✔
375

376
  // Determine if this batch is the first inactive or active batch.
377
  bool first_inactive = false;
143,057✔
378
  bool first_active = false;
143,057✔
379
  if (!settings::restart_run) {
143,057✔
380
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
142,889✔
381
    first_active = simulation::current_batch == settings::n_inactive + 1;
142,889✔
382
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
168✔
383
    first_inactive = simulation::restart_batch < settings::n_inactive;
54✔
384
    first_active = !first_inactive;
54✔
385
  }
386

387
  // Manage active/inactive timers and activate tallies if necessary.
388
  if (first_inactive) {
143,057✔
389
    simulation::time_inactive.start();
3,677✔
390
  } else if (first_active) {
139,380✔
391
    simulation::time_inactive.stop();
7,070✔
392
    simulation::time_active.start();
7,070✔
393
    for (auto& t : model::tallies) {
34,169✔
394
      t->active_ = true;
27,099✔
395
    }
396
  }
397

398
  // Add user tallies to active tallies list
399
  setup_active_tallies();
143,057✔
400
}
143,057✔
401

402
void finalize_batch()
143,044✔
403
{
404
  // Reduce tallies onto master process and accumulate
405
  simulation::time_tallies.start();
143,044✔
406
  accumulate_tallies();
143,044✔
407
  simulation::time_tallies.stop();
143,044✔
408

409
  // update weight windows if needed
410
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
145,461✔
411
    wwg->update();
2,417✔
412
  }
413

414
  // Reset global tally results
415
  if (simulation::current_batch <= settings::n_inactive) {
143,044✔
416
    xt::view(simulation::global_tallies, xt::all()) = 0.0;
28,645✔
417
    simulation::n_realizations = 0;
28,645✔
418
  }
419

420
  // Check_triggers
421
  if (mpi::master)
143,044✔
422
    check_triggers();
120,344✔
423
#ifdef OPENMC_MPI
424
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
77,556✔
425
#endif
426
  if (simulation::satisfy_triggers ||
143,044✔
427
      (settings::trigger_on &&
2,645✔
428
        simulation::current_batch == settings::n_max_batches)) {
2,645✔
429
    settings::statepoint_batch.insert(simulation::current_batch);
146✔
430
  }
431

432
  // Write out state point if it's been specified for this batch and is not
433
  // a CMFD run instance
434
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
150,383✔
435
      !settings::cmfd_run) {
7,339✔
436
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
14,105✔
437
        settings::source_write && !settings::source_separate) {
14,105✔
438
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
6,054✔
439
      openmc_statepoint_write(nullptr, &b);
6,054✔
440
    } else {
441
      bool b = false;
1,109✔
442
      openmc_statepoint_write(nullptr, &b);
1,109✔
443
    }
444
  }
445

446
  if (settings::run_mode == RunMode::EIGENVALUE) {
143,044✔
447
    // Write out a separate source point if it's been specified for this batch
448
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
94,936✔
449
        settings::source_write && settings::source_separate) {
94,936✔
450

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

460
    // Write a continously-overwritten source point if requested.
461
    if (settings::source_latest) {
90,549✔
462
      auto filename = settings::path_output + "source";
160✔
463
      span<SourceSite> bankspan(simulation::source_bank);
160✔
464
      write_source_point(filename, bankspan, simulation::work_index,
160✔
465
        settings::source_mcpl_write);
466
    }
160✔
467
  }
468

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

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

488
      // Write surface source file
489
      write_source_point(
1,007✔
490
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
491

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

506
void initialize_generation()
143,281✔
507
{
508
  if (settings::run_mode == RunMode::EIGENVALUE) {
143,281✔
509
    // Clear out the fission bank
510
    simulation::fission_bank.resize(0);
90,774✔
511

512
    // Count source sites if using uniform fission source weighting
513
    if (settings::ufs_on)
90,774✔
514
      ufs_count_sites();
160✔
515

516
    // Store current value of tracklength k
517
    simulation::keff_generation = simulation::global_tallies(
90,774✔
518
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
519
  }
520
}
143,281✔
521

522
void finalize_generation()
143,268✔
523
{
524
  auto& gt = simulation::global_tallies;
143,268✔
525

526
  // Update global tallies with the accumulation variables
527
  if (settings::run_mode == RunMode::EIGENVALUE) {
143,268✔
528
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
90,773✔
529
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
90,773✔
530
      global_tally_absorption;
531
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
90,773✔
532
      global_tally_tracklength;
533
  }
534
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
143,268✔
535

536
  // reset tallies
537
  if (settings::run_mode == RunMode::EIGENVALUE) {
143,268✔
538
    global_tally_collision = 0.0;
90,773✔
539
    global_tally_absorption = 0.0;
90,773✔
540
    global_tally_tracklength = 0.0;
90,773✔
541
  }
542
  global_tally_leakage = 0.0;
143,268✔
543

544
  if (settings::run_mode == RunMode::EIGENVALUE &&
143,268✔
545
      settings::solver_type == SolverType::MONTE_CARLO) {
90,773✔
546
    // If using shared memory, stable sort the fission bank (by parent IDs)
547
    // so as to allow for reproducibility regardless of which order particles
548
    // are run in.
549
    sort_fission_bank();
84,253✔
550

551
    // Distribute fission bank across processors evenly
552
    synchronize_bank();
84,253✔
553
  }
554

555
  if (settings::run_mode == RunMode::EIGENVALUE) {
143,268✔
556

557
    // Calculate shannon entropy
558
    if (settings::entropy_on &&
90,773✔
559
        settings::solver_type == SolverType::MONTE_CARLO)
14,215✔
560
      shannon_entropy();
7,695✔
561

562
    // Collect results and statistics
563
    calculate_generation_keff();
90,773✔
564
    calculate_average_keff();
90,773✔
565

566
    // Write generation output
567
    if (mpi::master && settings::verbosity >= 7) {
90,773✔
568
      print_generation();
70,913✔
569
    }
570
  }
571
}
143,268✔
572

573
void initialize_history(Particle& p, int64_t index_source)
167,077,082✔
574
{
575
  // set defaults
576
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,077,082✔
577
    // set defaults for eigenvalue simulations from primary bank
578
    p.from_source(&simulation::source_bank[index_source - 1]);
140,925,722✔
579
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
26,151,360!
580
    // initialize random number seed
581
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
26,151,360✔
582
                   settings::n_particles +
26,151,360✔
583
                 simulation::work_index[mpi::rank] + index_source;
26,151,360✔
584
    uint64_t seed = init_seed(id, STREAM_SOURCE);
26,151,360✔
585
    // sample from external source distribution or custom library then set
586
    auto sites = sample_external_source(&seed);
26,151,360✔
587
    p.from_source(&sites[0]);
26,151,357✔
588
    // For correlated sources, add extra particles to secondary bank
589
    for (size_t i = 1; i < sites.size(); ++i) {
26,151,357!
NEW
590
      p.secondary_bank().push_back(sites[i]);
×
591
    }
592
  }
26,151,357✔
593
  p.current_work() = index_source;
167,077,079✔
594

595
  // set identifier for particle
596
  p.id() = simulation::work_index[mpi::rank] + index_source;
167,077,079✔
597

598
  // set progeny count to zero
599
  p.n_progeny() = 0;
167,077,079✔
600

601
  // Reset particle event counter
602
  p.n_event() = 0;
167,077,079✔
603

604
  // Reset split counter
605
  p.n_split() = 0;
167,077,079✔
606

607
  // Reset weight window ratio
608
  p.ww_factor() = 0.0;
167,077,079✔
609

610
  // set particle history start weight
611
  p.wgt_born() = p.wgt();
167,077,079✔
612

613
  // Reset pulse_height_storage
614
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
167,077,079✔
615

616
  // set random number seed
617
  int64_t particle_seed =
618
    (simulation::total_gen + overall_generation() - 1) * settings::n_particles +
167,077,079✔
619
    p.id();
167,077,079✔
620
  init_particle_seeds(particle_seed, p.seeds());
167,077,079✔
621

622
  // set particle trace
623
  p.trace() = false;
167,077,079✔
624
  if (simulation::current_batch == settings::trace_batch &&
334,165,158✔
625
      simulation::current_gen == settings::trace_gen &&
167,088,079!
626
      p.id() == settings::trace_particle)
11,000✔
627
    p.trace() = true;
11✔
628

629
  // Set particle track.
630
  p.write_track() = check_track_criteria(p);
167,077,079✔
631

632
  // Set the particle's initial weight window value.
633
  p.wgt_ww_born() = -1.0;
167,077,079✔
634
  apply_weight_windows(p);
167,077,079✔
635

636
  // Display message if high verbosity or trace is on
637
  if (settings::verbosity >= 9 || p.trace()) {
167,077,079!
638
    write_message("Simulating Particle {}", p.id());
11✔
639
  }
640

641
// Add particle's starting weight to count for normalizing tallies later
642
#pragma omp atomic
91,270,053✔
643
  simulation::total_weight += p.wgt();
167,077,079✔
644

645
  // Force calculation of cross-sections by setting last energy to zero
646
  if (settings::run_CE) {
167,077,079✔
647
    p.invalidate_neutron_xs();
55,053,079✔
648
  }
649

650
  // Prepare to write out particle track.
651
  if (p.write_track())
167,077,079✔
652
    add_particle_track(p);
1,059✔
653
}
167,077,079✔
654

655
int overall_generation()
193,474,636✔
656
{
657
  using namespace simulation;
658
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
193,474,636✔
659
}
660

661
void calculate_work()
7,118✔
662
{
663
  // Determine minimum amount of particles to simulate on each processor
664
  int64_t min_work = settings::n_particles / mpi::n_procs;
7,118✔
665

666
  // Determine number of processors that have one extra particle
667
  int64_t remainder = settings::n_particles % mpi::n_procs;
7,118✔
668

669
  int64_t i_bank = 0;
7,118✔
670
  simulation::work_index.resize(mpi::n_procs + 1);
7,118✔
671
  simulation::work_index[0] = 0;
7,118✔
672
  for (int i = 0; i < mpi::n_procs; ++i) {
16,505✔
673
    // Number of particles for rank i
674
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
9,387!
675

676
    // Set number of particles
677
    if (mpi::rank == i)
9,387✔
678
      simulation::work_per_rank = work_i;
7,118✔
679

680
    // Set index into source bank for rank i
681
    i_bank += work_i;
9,387✔
682
    simulation::work_index[i + 1] = i_bank;
9,387✔
683
  }
684
}
7,118✔
685

686
void initialize_data()
5,820✔
687
{
688
  // Determine minimum/maximum energy for incident neutron/photon data
689
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
5,820✔
690
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
5,820✔
691

692
  for (const auto& nuc : data::nuclides) {
34,421✔
693
    if (nuc->grid_.size() >= 1) {
28,601!
694
      int neutron = ParticleType::neutron().transport_index();
28,601✔
695
      data::energy_min[neutron] =
57,202✔
696
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
28,601✔
697
      data::energy_max[neutron] =
28,601✔
698
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
28,601✔
699
    }
700
  }
701

702
  if (settings::photon_transport) {
5,820✔
703
    for (const auto& elem : data::elements) {
919✔
704
      if (elem->energy_.size() >= 1) {
622!
705
        int photon = ParticleType::photon().transport_index();
622✔
706
        int n = elem->energy_.size();
622✔
707
        data::energy_min[photon] =
1,244✔
708
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
622✔
709
        data::energy_max[photon] =
1,244✔
710
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
622✔
711
      }
712
    }
713

714
    if (settings::electron_treatment == ElectronTreatment::TTB) {
297✔
715
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
716
      // than the current minimum/maximum
717
      if (data::ttb_e_grid.size() >= 1) {
275!
718
        int photon = ParticleType::photon().transport_index();
275✔
719
        int electron = ParticleType::electron().transport_index();
275✔
720
        int positron = ParticleType::positron().transport_index();
275✔
721
        int n_e = data::ttb_e_grid.size();
275✔
722

723
        const std::vector<int> charged = {electron, positron};
275✔
724
        for (auto t : charged) {
825✔
725
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
550✔
726
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
550✔
727
        }
728

729
        data::energy_min[photon] =
550✔
730
          std::max(data::energy_min[photon], data::energy_min[electron]);
275✔
731

732
        data::energy_max[photon] =
550✔
733
          std::min(data::energy_max[photon], data::energy_max[electron]);
275✔
734
      }
275✔
735
    }
736
  }
737

738
  // Show which nuclide results in lowest energy for neutron transport
739
  for (const auto& nuc : data::nuclides) {
7,236✔
740
    // If a nuclide is present in a material that's not used in the model, its
741
    // grid has not been allocated
742
    if (nuc->grid_.size() > 0) {
6,756!
743
      double max_E = nuc->grid_[0].energy.back();
6,756✔
744
      int neutron = ParticleType::neutron().transport_index();
6,756✔
745
      if (max_E == data::energy_max[neutron]) {
6,756✔
746
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
5,340✔
747
          data::energy_max[neutron], nuc->name_);
5,340✔
748
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
5,340!
749
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
750
                  "the results.");
751
        }
752
        break;
5,340✔
753
      }
754
    }
755
  }
756

757
  // Set up logarithmic grid for nuclides
758
  for (auto& nuc : data::nuclides) {
34,421✔
759
    nuc->init_grid();
28,601✔
760
  }
761
  int neutron = ParticleType::neutron().transport_index();
5,820✔
762
  simulation::log_spacing =
5,820✔
763
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
5,820✔
764
    settings::n_log_bins;
765
}
5,820✔
766

767
#ifdef OPENMC_MPI
768
void broadcast_results()
3,864✔
769
{
770
  // Broadcast tally results so that each process has access to results
771
  for (auto& t : model::tallies) {
19,959✔
772
    // Create a new datatype that consists of all values for a given filter
773
    // bin and then use that to broadcast. This is done to minimize the
774
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
775
    auto& results = t->results_;
16,095✔
776

777
    auto shape = results.shape();
16,095✔
778
    int count_per_filter = shape[1] * shape[2];
16,095✔
779
    MPI_Datatype result_block;
780
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
16,095✔
781
    MPI_Type_commit(&result_block);
16,095✔
782
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
16,095✔
783
    MPI_Type_free(&result_block);
16,095✔
784
  }
785

786
  // Also broadcast global tally results
787
  auto& gt = simulation::global_tallies;
3,864✔
788
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,864✔
789

790
  // These guys are needed so that non-master processes can calculate the
791
  // combined estimate of k-effective
792
  double temp[] {
793
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,864✔
794
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,864✔
795
  simulation::k_col_abs = temp[0];
3,864✔
796
  simulation::k_col_tra = temp[1];
3,864✔
797
  simulation::k_abs_tra = temp[2];
3,864✔
798
}
3,864✔
799

800
#endif
801

802
void free_memory_simulation()
8,208✔
803
{
804
  simulation::k_generation.clear();
8,208✔
805
  simulation::entropy.clear();
8,208✔
806
}
8,208✔
807

808
void transport_history_based_single_particle(Particle& p)
154,940,412✔
809
{
810
  while (p.alive()) {
2,147,483,647✔
811
    p.event_calculate_xs();
2,147,483,647✔
812
    if (p.alive()) {
2,147,483,647!
813
      p.event_advance();
2,147,483,647✔
814
    }
815
    if (p.alive()) {
2,147,483,647✔
816
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
817
        p.event_cross_surface();
1,381,988,230✔
818
      } else if (p.alive()) {
2,147,483,647!
819
        p.event_collide();
2,147,483,647✔
820
      }
821
    }
822
    p.event_revive_from_secondary();
2,147,483,647✔
823
  }
824
  p.event_death();
154,940,401✔
825
}
154,940,401✔
826

827
void transport_history_based()
119,497✔
828
{
829
#pragma omp parallel for schedule(runtime)
830
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
75,915,674✔
831
    Particle p;
75,861,088✔
832
    initialize_history(p, i_work);
75,861,088✔
833
    transport_history_based_single_particle(p);
75,861,085✔
834
  }
75,861,080✔
835
}
119,489✔
836

837
void transport_event_based()
3,172✔
838
{
839
  int64_t remaining_work = simulation::work_per_rank;
3,172✔
840
  int64_t source_offset = 0;
3,172✔
841

842
  // To cap the total amount of memory used to store particle object data, the
843
  // number of particles in flight at any point in time can bet set. In the case
844
  // that the maximum in flight particle count is lower than the total number
845
  // of particles that need to be run this iteration, the event-based transport
846
  // loop is executed multiple times until all particles have been completed.
847
  while (remaining_work > 0) {
6,344✔
848
    // Figure out # of particles to run for this subiteration
849
    int64_t n_particles =
850
      std::min(remaining_work, settings::max_particles_in_flight);
3,172✔
851

852
    // Initialize all particle histories for this subiteration
853
    process_init_events(n_particles, source_offset);
3,172!
854

855
    // Event-based transport loop
856
    while (true) {
857
      // Determine which event kernel has the longest queue
858
      int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(),
4,743,840!
859
        simulation::calculate_nonfuel_xs_queue.size(),
2,371,920✔
860
        simulation::advance_particle_queue.size(),
2,371,920✔
861
        simulation::surface_crossing_queue.size(),
2,371,920✔
862
        simulation::collision_queue.size()});
2,371,920✔
863

864
      // Execute event with the longest queue
865
      if (max == 0) {
2,371,920✔
866
        break;
3,172✔
867
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,368,748✔
868
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
425,668!
869
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,943,080✔
870
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
361,260!
871
      } else if (max == simulation::advance_particle_queue.size()) {
1,581,820✔
872
        process_advance_particle_events();
781,657!
873
      } else if (max == simulation::surface_crossing_queue.size()) {
800,163✔
874
        process_surface_crossing_events();
259,774!
875
      } else if (max == simulation::collision_queue.size()) {
540,389!
876
        process_collision_events();
540,389!
877
      }
878
    }
2,368,748✔
879

880
    // Execute death event for all particles
881
    process_death_events(n_particles);
3,172!
882

883
    // Adjust remaining work and source offset variables
884
    remaining_work -= n_particles;
3,172✔
885
    source_offset += n_particles;
3,172✔
886
  }
887
}
3,172✔
888

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