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

openmc-dev / openmc / 23084721708

14 Mar 2026 08:56AM UTC coverage: 81.599% (-0.5%) from 82.058%
23084721708

Pull #2693

github

web-flow
Merge 0ed23ee59 into bc9c31e0f
Pull Request #2693: Add reactivity control to coupled transport-depletion analyses

17575 of 25275 branches covered (69.54%)

Branch coverage included in aggregate %.

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

3755 existing lines in 99 files now uncovered.

58074 of 67433 relevant lines covered (86.12%)

47252067.37 hits per line

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

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

65
  int err = 0;
66
  while (status == 0 && err == 0) {
145,540✔
67
    err = openmc_next_batch(&status);
139,296✔
68
  }
69

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

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

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

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

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

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

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

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

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

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

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

141
  // Display header
142
  if (mpi::master) {
7,362✔
143
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,418✔
144
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,643✔
145
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,300✔
146
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
343!
147
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
343✔
148
      }
149
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,775!
150
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,775✔
151
        header("K EIGENVALUE SIMULATION", 3);
3,500✔
152
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
275!
153
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
275✔
154
      }
155
      if (settings::verbosity >= 7)
3,775✔
156
        print_columns();
3,395✔
157
    }
158
  }
159

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

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

170
int openmc_simulation_finalize()
7,349✔
171
{
172
  using namespace openmc;
7,349✔
173

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

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

182
  // Clear material nuclide mapping
183
  for (auto& mat : model::materials) {
26,470✔
184
    mat->mat_nuclide_index_.clear();
38,242!
185
  }
186

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

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

195
#ifdef OPENMC_MPI
196
  broadcast_results();
3,293✔
197
#endif
198

199
  // Write tally results to tallies.out
200
  if (settings::output_tallies && mpi::master)
7,349!
201
    write_tallies();
6,059✔
202

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

209
  // Deactivate all tallies
210
  for (auto& t : model::tallies) {
33,974✔
211
    t->active_ = false;
26,625✔
212
  }
213

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

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

233
int openmc_next_batch(int* status)
143,421✔
234
{
235
  using namespace openmc;
143,421✔
236
  using openmc::simulation::current_gen;
143,421✔
237

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

244
  initialize_batch();
143,410✔
245

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

250
    initialize_generation();
143,620✔
251

252
    // Start timer for transport
253
    simulation::time_transport.start();
143,620✔
254

255
    // Transport loop
256
    if (settings::event_based) {
143,620✔
257
      transport_event_based();
3,183✔
258
    } else {
259
      transport_history_based();
140,437✔
260
    }
261

262
    // Accumulate time for transport
263
    simulation::time_transport.stop();
143,607✔
264

265
    finalize_generation();
143,607✔
266
  }
267

268
  finalize_batch();
143,397✔
269

270
  // Check simulation ending criteria
271
  if (status) {
143,397!
272
    if (simulation::current_batch >= settings::n_max_batches) {
143,397✔
273
      *status = STATUS_EXIT_MAX_BATCH;
6,437✔
274
    } else if (simulation::satisfy_triggers) {
136,960✔
275
      *status = STATUS_EXIT_ON_TRIGGER;
93✔
276
    } else {
277
      *status = STATUS_EXIT_NORMAL;
136,867✔
278
    }
279
  }
280
  return 0;
281
}
282

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

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

294
namespace openmc {
295

296
//==============================================================================
297
// Global variables
298
//==============================================================================
299

300
namespace simulation {
301

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

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

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

327
} // namespace simulation
328

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

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

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

343
    // Allocate IFP bank
344
    if (settings::ifp_on) {
4,090✔
345
      resize_simulation_ifp_banks();
74✔
346
    }
347
  }
348

349
  if (settings::surf_source_write) {
7,362✔
350
    // Allocate surface source bank
351
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
1,154✔
352
  }
353

354
  if (settings::collision_track) {
7,362✔
355
    // Allocate collision track bank
356
    collision_track_reserve_bank();
148✔
357
  }
358
}
7,362✔
359

360
void initialize_batch()
163,922✔
361
{
362
  // Increment current batch
363
  ++simulation::current_batch;
163,922✔
364
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
163,922✔
365
    if (settings::solver_type == SolverType::RANDOM_RAY &&
63,229✔
366
        simulation::current_batch < settings::n_inactive + 1) {
13,662✔
367
      write_message(
16,362✔
368
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
369
    } else {
370
      write_message(6, "Simulating batch {}", simulation::current_batch);
110,096✔
371
    }
372
  }
373

374
  // Reset total starting particle weight used for normalizing tallies
375
  simulation::total_weight = 0.0;
163,922✔
376

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

388
  // Manage active/inactive timers and activate tallies if necessary.
389
  if (first_inactive) {
163,811✔
390
    simulation::time_inactive.start();
3,800✔
391
  } else if (first_active) {
160,122✔
392
    simulation::time_inactive.stop();
7,315✔
393
    simulation::time_active.start();
7,315✔
394
    for (auto& t : model::tallies) {
33,918✔
395
      t->active_ = true;
26,603✔
396
    }
397
  }
398

399
  // Add user tallies to active tallies list
400
  setup_active_tallies();
163,922✔
401
}
163,922✔
402

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

410
  // update weight windows if needed
411
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
166,186✔
412
    wwg->update();
2,277✔
413
  }
414

415
  // Reset global tally results
416
  if (simulation::current_batch <= settings::n_inactive) {
163,909✔
417
    simulation::global_tallies.fill(0.0);
31,923✔
418
    simulation::n_realizations = 0;
31,923✔
419
  }
420

421
  // Check_triggers
422
  if (mpi::master)
163,909✔
423
    check_triggers();
145,390✔
424
#ifdef OPENMC_MPI
425
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
71,714✔
426
#endif
427
  if (simulation::satisfy_triggers ||
163,909✔
428
      (settings::trigger_on &&
2,567✔
429
        simulation::current_batch == settings::n_max_batches)) {
2,567✔
430
    settings::statepoint_batch.insert(simulation::current_batch);
141✔
431
  }
432

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

447
  if (settings::run_mode == RunMode::EIGENVALUE) {
163,909✔
448
    // Write out a separate source point if it's been specified for this batch
449
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
105,180✔
450
        settings::source_write && settings::source_separate) {
104,809✔
451

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

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

470
  // Write out surface source if requested.
471
  if (settings::surf_source_write &&
163,909✔
472
      simulation::ssw_current_file <= settings::ssw_max_files) {
17,669✔
473
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,976✔
474
    if (simulation::surf_source_bank.full() || last_batch) {
1,976✔
475
      // Determine appropriate filename
476
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
1,187✔
477
        simulation::current_batch);
1,187✔
478
      if (settings::ssw_max_files == 1 ||
1,187✔
479
          (simulation::ssw_current_file == 1 && last_batch)) {
55!
480
        filename = settings::path_output + "surface_source";
1,132✔
481
      }
482

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

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

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

507
void initialize_generation()
164,132✔
508
{
509
  if (settings::run_mode == RunMode::EIGENVALUE) {
164,132✔
510
    // Clear out the fission bank
511
    simulation::fission_bank.resize(0);
100,903✔
512

513
    // Count source sites if using uniform fission source weighting
514
    if (settings::ufs_on)
100,903✔
515
      ufs_count_sites();
150✔
516

517
    // Store current value of tracklength k
518
    simulation::keff_generation = simulation::global_tallies(
100,903✔
519
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
520
  }
521
}
164,132✔
522

523
void finalize_generation()
164,119✔
524
{
525
  auto& gt = simulation::global_tallies;
164,119✔
526

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

537
  // reset tallies
538
  if (settings::run_mode == RunMode::EIGENVALUE) {
164,119✔
539
    global_tally_collision = 0.0;
100,903✔
540
    global_tally_absorption = 0.0;
100,903✔
541
    global_tally_tracklength = 0.0;
100,903✔
542
  }
543
  global_tally_leakage = 0.0;
164,119✔
544

545
  if (settings::run_mode == RunMode::EIGENVALUE &&
164,119✔
546
      settings::solver_type == SolverType::MONTE_CARLO) {
100,903✔
547
    // If using shared memory, stable sort the fission bank (by parent IDs)
548
    // so as to allow for reproducibility regardless of which order particles
549
    // are run in.
550
    sort_fission_bank();
94,053✔
551

552
    // Distribute fission bank across processors evenly
553
    synchronize_bank();
94,053✔
554
  }
555

556
  if (settings::run_mode == RunMode::EIGENVALUE) {
164,119✔
557

558
    // Calculate shannon entropy
559
    if (settings::entropy_on &&
100,903✔
560
        settings::solver_type == SolverType::MONTE_CARLO)
14,535✔
561
      shannon_entropy();
7,685✔
562

563
    // Collect results and statistics
564
    calculate_generation_keff();
100,903✔
565
    calculate_average_keff();
100,903✔
566

567
    // Write generation output
568
    if (mpi::master && settings::verbosity >= 7) {
100,903✔
569
      print_generation();
75,918✔
570
    }
571
  }
572
}
164,119✔
573

574
void initialize_history(Particle& p, int64_t index_source)
177,272,951✔
575
{
576
  // set defaults
577
  if (settings::run_mode == RunMode::EIGENVALUE) {
177,272,951✔
578
    // set defaults for eigenvalue simulations from primary bank
579
    p.from_source(&simulation::source_bank[index_source - 1]);
149,894,700✔
580
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
27,378,251!
581
    // initialize random number seed
582
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
27,378,251✔
583
                   settings::n_particles +
27,378,251✔
584
                 simulation::work_index[mpi::rank] + index_source;
27,378,251✔
585
    uint64_t seed = init_seed(id, STREAM_SOURCE);
27,378,251✔
586
    // sample from external source distribution or custom library then set
587
    auto site = sample_external_source(&seed);
27,378,251✔
588
    p.from_source(&site);
27,378,247✔
589
  }
590
  p.current_work() = index_source;
177,272,947✔
591

592
  // set identifier for particle
593
  p.id() = simulation::work_index[mpi::rank] + index_source;
177,272,947✔
594

595
  // set progeny count to zero
596
  p.n_progeny() = 0;
177,272,947✔
597

598
  // Reset particle event counter
599
  p.n_event() = 0;
177,272,947✔
600

601
  // Reset split counter
602
  p.n_split() = 0;
177,272,947✔
603

604
  // Reset weight window ratio
605
  p.ww_factor() = 0.0;
177,272,947✔
606

607
  // set particle history start weight
608
  p.wgt_born() = p.wgt();
177,272,947✔
609

610
  // Reset pulse_height_storage
611
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
177,272,947✔
612

613
  // set random number seed
614
  int64_t particle_seed =
177,272,947✔
615
    (simulation::total_gen + overall_generation() - 1) * settings::n_particles +
177,272,947✔
616
    p.id();
177,272,947✔
617
  init_particle_seeds(particle_seed, p.seeds());
177,272,947✔
618

619
  // set particle trace
620
  p.trace() = false;
177,272,947✔
621
  if (simulation::current_batch == settings::trace_batch &&
177,283,947✔
622
      simulation::current_gen == settings::trace_gen &&
177,272,947!
623
      p.id() == settings::trace_particle)
11,000✔
624
    p.trace() = true;
11✔
625

626
  // Set particle track.
627
  p.write_track() = check_track_criteria(p);
177,272,947✔
628

629
  // Set the particle's initial weight window value.
630
  p.wgt_ww_born() = -1.0;
177,272,947✔
631
  apply_weight_windows(p);
177,272,947✔
632

633
  // Display message if high verbosity or trace is on
634
  if (settings::verbosity >= 9 || p.trace()) {
177,272,947!
635
    write_message("Simulating Particle {}", p.id());
22✔
636
  }
637

638
// Add particle's starting weight to count for normalizing tallies later
639
#pragma omp atomic
96,922,744✔
640
  simulation::total_weight += p.wgt();
177,272,947✔
641

642
  // Force calculation of cross-sections by setting last energy to zero
643
  if (settings::run_CE) {
177,272,947✔
644
    p.invalidate_neutron_xs();
65,248,947✔
645
  }
646

647
  // Prepare to write out particle track.
648
  if (p.write_track())
177,272,947✔
649
    add_particle_track(p);
999✔
650
}
177,272,947✔
651

652
int overall_generation()
204,922,325✔
653
{
654
  using namespace simulation;
204,922,325✔
655
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
204,922,325✔
656
}
657

658
void calculate_work()
7,362✔
659
{
660
  // Determine minimum amount of particles to simulate on each processor
661
  int64_t min_work = settings::n_particles / mpi::n_procs;
7,362✔
662

663
  // Determine number of processors that have one extra particle
664
  int64_t remainder = settings::n_particles % mpi::n_procs;
7,362✔
665

666
  int64_t i_bank = 0;
7,362✔
667
  simulation::work_index.resize(mpi::n_procs + 1);
7,362✔
668
  simulation::work_index[0] = 0;
7,362✔
669
  for (int i = 0; i < mpi::n_procs; ++i) {
16,611✔
670
    // Number of particles for rank i
671
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
9,249!
672

673
    // Set number of particles
674
    if (mpi::rank == i)
9,249✔
675
      simulation::work_per_rank = work_i;
7,362✔
676

677
    // Set index into source bank for rank i
678
    i_bank += work_i;
9,249✔
679
    simulation::work_index[i + 1] = i_bank;
9,249✔
680
  }
681
}
7,362✔
682

683
void initialize_data()
6,070✔
684
{
685
  // Determine minimum/maximum energy for incident neutron/photon data
686
  data::energy_max = {INFTY, INFTY, INFTY, INFTY};
6,070✔
687
  data::energy_min = {0.0, 0.0, 0.0, 0.0};
6,070✔
688

689
  for (const auto& nuc : data::nuclides) {
37,518✔
690
    if (nuc->grid_.size() >= 1) {
31,448!
691
      int neutron = ParticleType::neutron().transport_index();
31,448✔
692
      data::energy_min[neutron] =
31,448✔
693
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
36,999✔
694
      data::energy_max[neutron] =
31,448✔
695
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
38,558✔
696
    }
697
  }
698

699
  if (settings::photon_transport) {
6,070✔
700
    for (const auto& elem : data::elements) {
917✔
701
      if (elem->energy_.size() >= 1) {
616!
702
        int photon = ParticleType::photon().transport_index();
616✔
703
        int n = elem->energy_.size();
616✔
704
        data::energy_min[photon] =
1,232✔
705
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
1,054✔
706
        data::energy_max[photon] =
616✔
707
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
917✔
708
      }
709
    }
710

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

720
        const std::vector<int> charged = {electron, positron};
264✔
721
        for (auto t : charged) {
792✔
722
          data::energy_min[t] = std::exp(data::ttb_e_grid(1));
528✔
723
          data::energy_max[t] = std::exp(data::ttb_e_grid(n_e - 1));
528✔
724
        }
725

726
        data::energy_min[photon] =
528✔
727
          std::max(data::energy_min[photon], data::energy_min[electron]);
528!
728

729
        data::energy_max[photon] =
528✔
730
          std::min(data::energy_max[photon], data::energy_max[electron]);
528!
731
      }
264✔
732
    }
733
  }
734

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

754
  // Set up logarithmic grid for nuclides
755
  for (auto& nuc : data::nuclides) {
37,518✔
756
    nuc->init_grid();
31,448✔
757
  }
758
  int neutron = ParticleType::neutron().transport_index();
6,070✔
759
  simulation::log_spacing =
12,140✔
760
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
6,070✔
761
    settings::n_log_bins;
762
}
6,070✔
763

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

774
    auto shape = results.shape();
13,224✔
775
    int count_per_filter = shape[1] * shape[2];
13,224✔
776
    MPI_Datatype result_block;
13,224✔
777
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
13,224✔
778
    MPI_Type_commit(&result_block);
13,224✔
779
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
13,224✔
780
    MPI_Type_free(&result_block);
13,224✔
781
  }
13,224✔
782

783
  // Also broadcast global tally results
784
  auto& gt = simulation::global_tallies;
3,293✔
785
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,293✔
786

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

797
#endif
798

799
void free_memory_simulation()
8,342✔
800
{
801
  simulation::k_generation.clear();
8,342✔
802
  simulation::entropy.clear();
8,342✔
803
}
8,342✔
804

805
void transport_history_based_single_particle(Particle& p)
165,120,430✔
806
{
807
  while (p.alive()) {
2,147,483,647✔
808
    p.event_calculate_xs();
2,147,483,647✔
809
    if (p.alive()) {
2,147,483,647!
810
      p.event_advance();
2,147,483,647✔
811
    }
812
    if (p.alive()) {
2,147,483,647✔
813
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
814
        p.event_cross_surface();
2,147,483,647✔
815
      } else if (p.alive()) {
2,147,483,647✔
816
        p.event_collide();
2,147,483,647✔
817
      }
818
    }
819
    p.event_revive_from_secondary();
2,147,483,647✔
820
  }
821
  p.event_death();
165,120,421✔
822
}
165,120,421✔
823

824
void transport_history_based()
140,437✔
825
{
826
#pragma omp parallel for schedule(runtime)
78,234✔
827
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
80,559,673✔
828
    Particle p;
80,497,479✔
829
    initialize_history(p, i_work);
80,497,479✔
830
    transport_history_based_single_particle(p);
80,497,475✔
831
  }
80,497,470✔
832
}
140,428✔
833

834
void transport_event_based()
3,183✔
835
{
836
  int64_t remaining_work = simulation::work_per_rank;
3,183✔
837
  int64_t source_offset = 0;
3,183✔
838

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

849
    // Initialize all particle histories for this subiteration
850
    process_init_events(n_particles, source_offset);
3,183✔
851

852
    // Event-based transport loop
853
    while (true) {
2,829,943✔
854
      // Determine which event kernel has the longest queue
855
      int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(),
2,829,943✔
856
        simulation::calculate_nonfuel_xs_queue.size(),
2,829,943✔
857
        simulation::advance_particle_queue.size(),
2,829,943✔
858
        simulation::surface_crossing_queue.size(),
2,829,943✔
859
        simulation::collision_queue.size()});
2,829,943✔
860

861
      // Execute event with the longest queue
862
      if (max == 0) {
2,829,943✔
863
        break;
864
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,826,760✔
865
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
425,858✔
866
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
2,400,902✔
867
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
513,742✔
868
      } else if (max == simulation::advance_particle_queue.size()) {
1,887,160✔
869
        process_advance_particle_events();
934,326✔
870
      } else if (max == simulation::surface_crossing_queue.size()) {
952,834✔
871
        process_surface_crossing_events();
262,403✔
872
      } else if (max == simulation::collision_queue.size()) {
690,431!
873
        process_collision_events();
690,431✔
874
      }
875
    }
876

877
    // Execute death event for all particles
878
    process_death_events(n_particles);
3,183✔
879

880
    // Adjust remaining work and source offset variables
881
    remaining_work -= n_particles;
3,183✔
882
    source_offset += n_particles;
3,183✔
883
  }
884
}
3,183✔
885

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