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

openmc-dev / openmc / 20733102133

06 Jan 2026 12:03AM UTC coverage: 81.932% (-0.2%) from 82.174%
20733102133

Pull #3702

github

web-flow
Merge b36a045c7 into 60ddafa9b
Pull Request #3702: Random Ray Kinetic Simulation Mode

17551 of 24380 branches covered (71.99%)

Branch coverage included in aggregate %.

869 of 1117 new or added lines in 21 files covered. (77.8%)

483 existing lines in 19 files now uncovered.

55915 of 65287 relevant lines covered (85.64%)

50695599.69 hits per line

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

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

65
  int err = 0;
5,929✔
66
  while (status == 0 && err == 0) {
125,545!
67
    err = openmc_next_batch(&status);
119,628✔
68
  }
69

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

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

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

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

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

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

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

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

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

127
  // If this is a restart run, load the state point data and binary source
128
  // file
129
  if (settings::restart_run) {
7,702✔
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,637✔
135
        settings::solver_type == SolverType::MONTE_CARLO) {
4,890✔
136
      initialize_source();
3,850✔
137
    }
138
  }
139

140
  // Display header
141
  if (mpi::master) {
7,702✔
142
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,367✔
143
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,453✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,132✔
145
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
321!
146
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
321✔
147
      }
148
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,914!
149
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,914✔
150
        header("K EIGENVALUE SIMULATION", 3);
3,199✔
151
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
715!
152
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
715✔
153
      }
154
      if (settings::verbosity >= 7)
3,914✔
155
        print_columns();
3,714✔
156
    }
157
  }
158

159
  // load weight windows from file
160
  if (!settings::weight_windows_file.empty()) {
7,702!
UNCOV
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,702✔
166
  return 0;
7,702✔
167
}
168

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

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

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

181
  // Clear material nuclide mapping
182
  for (auto& mat : model::materials) {
27,770✔
183
    mat->mat_nuclide_index_.clear();
20,080✔
184
  }
185

186
  // Close track file if open
187
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
7,690✔
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,690✔
193

194
#ifdef OPENMC_MPI
195
  broadcast_results();
4,239✔
196
#endif
197

198
  // Write tally results to tallies.out
199
  if (settings::output_tallies && mpi::master)
7,690!
200
    write_tallies();
6,109✔
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,690✔
205
    openmc_weight_windows_export();
131✔
206
  }
207

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

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

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

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

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

243
  initialize_batch();
123,742✔
244

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

249
    initialize_generation();
123,966✔
250

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

254
    // Transport loop
255
    if (settings::event_based) {
123,966✔
256
      transport_event_based();
3,150✔
257
    } else {
258
      transport_history_based();
120,816✔
259
    }
260

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

264
    finalize_generation();
123,954✔
265
  }
266

267
  finalize_batch();
123,730✔
268

269
  // Check simulation ending criteria
270
  if (status) {
123,730!
271
    if (simulation::current_batch >= settings::n_max_batches) {
123,730✔
272
      *status = STATUS_EXIT_MAX_BATCH;
6,106✔
273
    } else if (simulation::satisfy_triggers) {
117,624✔
274
      *status = STATUS_EXIT_ON_TRIGGER;
97✔
275
    } else {
276
      *status = STATUS_EXIT_NORMAL;
117,527✔
277
    }
278
  }
279
  return 0;
123,730✔
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!
UNCOV
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
bool is_initial_condition {false};
327
int current_timestep;
328
double current_time;
329
bool k_eff_correction {false};
330

331
} // namespace simulation
332

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

337
void allocate_banks()
7,702✔
338
{
339
  if (settings::run_mode == RunMode::EIGENVALUE &&
7,702✔
340
      settings::solver_type == SolverType::MONTE_CARLO) {
4,955✔
341
    // Allocate source bank
342
    simulation::source_bank.resize(simulation::work_per_rank);
3,915✔
343

344
    // Allocate fission bank
345
    init_fission_bank(3 * simulation::work_per_rank);
3,915✔
346

347
    // Allocate IFP bank
348
    if (settings::ifp_on) {
3,915✔
349
      resize_simulation_ifp_banks();
76✔
350
    }
351
  }
352

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

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

364
void initialize_batch()
281,354✔
365
{
366
  // Increment current batch
367
  ++simulation::current_batch;
281,354✔
368
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
281,354✔
369
    if (settings::solver_type == SolverType::RANDOM_RAY &&
52,187✔
370
        simulation::current_batch < settings::n_inactive + 1) {
13,932✔
371
      write_message(
8,486✔
372
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
373
    } else {
374
      write_message(6, "Simulating batch {}", simulation::current_batch);
43,701✔
375
    }
376
  }
377

378
  // Reset total starting particle weight used for normalizing tallies
379
  simulation::total_weight = 0.0;
281,354✔
380

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

392
  // Manage active/inactive timers and activate tallies if necessary.
393
  if (first_inactive) {
281,354✔
394
    simulation::time_inactive.start();
4,325✔
395
  } else if (first_active) {
277,029✔
396
    simulation::time_inactive.stop();
7,655✔
397
    simulation::time_active.start();
7,655✔
398
    for (auto& t : model::tallies) {
35,596✔
399
      t->active_ = true;
27,941✔
400
    }
401
  }
402

403
  // Add user tallies to active tallies list
404
  setup_active_tallies();
281,354✔
405
}
281,354✔
406

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

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

419
  // Reset global tally results
420
  if (simulation::current_batch <= settings::n_inactive) {
281,342✔
421
    xt::view(simulation::global_tallies, xt::all()) = 0.0;
99,080✔
422
    simulation::n_realizations = 0;
99,080✔
423
  }
424

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

437
  // Write out state point if it's been specified for this batch and is not
438
  // a CMFD run instance
439
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
289,266✔
440
      !settings::cmfd_run) {
7,924✔
441
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
15,275✔
442
        settings::source_write && !settings::source_separate) {
15,275✔
443
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
5,946✔
444
      openmc_statepoint_write(nullptr, &b);
5,946✔
445
    } else {
446
      bool b = false;
1,802✔
447
      openmc_statepoint_write(nullptr, &b);
1,802✔
448
    }
449
  }
450

451
  if (settings::run_mode == RunMode::EIGENVALUE) {
281,342✔
452
    // Write out a separate source point if it's been specified for this batch
453
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
234,171✔
454
        settings::source_write && settings::source_separate) {
234,171✔
455

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

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

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

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

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

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

511
void initialize_generation()
281,578✔
512
{
513
  if (settings::run_mode == RunMode::EIGENVALUE) {
281,578✔
514
    // Clear out the fission bank
515
    simulation::fission_bank.resize(0);
229,391✔
516

517
    // Count source sites if using uniform fission source weighting
518
    if (settings::ufs_on)
229,391✔
519
      ufs_count_sites();
160✔
520

521
    // Store current value of tracklength k
522
    simulation::keff_generation = simulation::global_tallies(
229,391✔
523
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
524
  }
525
}
281,578✔
526

527
void finalize_generation()
281,566✔
528
{
529
  auto& gt = simulation::global_tallies;
281,566✔
530

531
  // Update global tallies with the accumulation variables
532
  if (settings::run_mode == RunMode::EIGENVALUE) {
281,566✔
533
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
229,391✔
534
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
229,391✔
535
      global_tally_absorption;
536
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
229,391✔
537
      global_tally_tracklength;
538
  }
539
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
281,566✔
540

541
  // reset tallies
542
  if (settings::run_mode == RunMode::EIGENVALUE) {
281,566✔
543
    global_tally_collision = 0.0;
229,391✔
544
    global_tally_absorption = 0.0;
229,391✔
545
    global_tally_tracklength = 0.0;
229,391✔
546
  }
547
  global_tally_leakage = 0.0;
281,566✔
548

549
  if (settings::run_mode == RunMode::EIGENVALUE &&
281,566✔
550
      settings::solver_type == SolverType::MONTE_CARLO) {
229,391✔
551
    // If using shared memory, stable sort the fission bank (by parent IDs)
552
    // so as to allow for reproducibility regardless of which order particles
553
    // are run in.
554
    sort_fission_bank();
85,711✔
555

556
    // Distribute fission bank across processors evenly
557
    synchronize_bank();
85,711✔
558
  }
559

560
  if (settings::run_mode == RunMode::EIGENVALUE) {
281,566✔
561

562
    // Calculate shannon entropy
563
    if (settings::entropy_on &&
229,391✔
564
        settings::solver_type == SolverType::MONTE_CARLO)
151,375✔
565
      shannon_entropy();
7,695✔
566

567
    // Collect results and statistics
568
    calculate_generation_keff();
229,391✔
569
    calculate_average_keff();
229,391✔
570

571
    // Write generation output
572
    if (mpi::master && settings::verbosity >= 7) {
229,391✔
573
      print_generation();
166,041✔
574
    }
575
  }
576
}
281,566✔
577

578
void initialize_history(Particle& p, int64_t index_source)
165,812,060✔
579
{
580
  // set defaults
581
  if (settings::run_mode == RunMode::EIGENVALUE) {
165,812,060✔
582
    // set defaults for eigenvalue simulations from primary bank
583
    p.from_source(&simulation::source_bank[index_source - 1]);
140,155,700✔
584
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
25,656,360!
585
    // initialize random number seed
586
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
25,656,360✔
587
                   settings::n_particles +
25,656,360✔
588
                 simulation::work_index[mpi::rank] + index_source;
25,656,360✔
589
    uint64_t seed = init_seed(id, STREAM_SOURCE);
25,656,360✔
590
    // sample from external source distribution or custom library then set
591
    auto site = sample_external_source(&seed);
25,656,360✔
592
    p.from_source(&site);
25,656,357✔
593
  }
594
  p.current_work() = index_source;
165,812,057✔
595

596
  // set identifier for particle
597
  p.id() = simulation::work_index[mpi::rank] + index_source;
165,812,057✔
598

599
  // set progeny count to zero
600
  p.n_progeny() = 0;
165,812,057✔
601

602
  // Reset particle event counter
603
  p.n_event() = 0;
165,812,057✔
604

605
  // Reset split counter
606
  p.n_split() = 0;
165,812,057✔
607

608
  // Reset weight window ratio
609
  p.ww_factor() = 0.0;
165,812,057✔
610

611
  // set particle history start weight
612
  p.wgt_born() = p.wgt();
165,812,057✔
613

614
  // Reset pulse_height_storage
615
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
165,812,057✔
616

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

623
  // set particle trace
624
  p.trace() = false;
165,812,057✔
625
  if (simulation::current_batch == settings::trace_batch &&
331,635,114✔
626
      simulation::current_gen == settings::trace_gen &&
165,823,057!
627
      p.id() == settings::trace_particle)
11,000✔
628
    p.trace() = true;
11✔
629

630
  // Set particle track.
631
  p.write_track() = check_track_criteria(p);
165,812,057✔
632

633
  // Set the particle's initial weight window value.
634
  p.wgt_ww_born() = -1.0;
165,812,057✔
635
  apply_weight_windows(p);
165,812,057✔
636

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

642
// Add particle's starting weight to count for normalizing tallies later
643
#pragma omp atomic
90,711,139✔
644
  simulation::total_weight += p.wgt();
165,812,057✔
645

646
  // Force calculation of cross-sections by setting last energy to zero
647
  if (settings::run_CE) {
165,812,057✔
648
    p.invalidate_neutron_xs();
53,788,057✔
649
  }
650

651
  // Prepare to write out particle track.
652
  if (p.write_track())
165,812,057✔
653
    add_particle_track(p);
1,059✔
654
}
165,812,057✔
655

656
int overall_generation()
191,949,818✔
657
{
658
  using namespace simulation;
659
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
191,949,818✔
660
}
661

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

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

670
  int64_t i_bank = 0;
7,702✔
671
  simulation::work_index.resize(mpi::n_procs + 1);
7,702✔
672
  simulation::work_index[0] = 0;
7,702✔
673
  for (int i = 0; i < mpi::n_procs; ++i) {
18,073✔
674
    // Number of particles for rank i
675
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
10,371!
676

677
    // Set number of particles
678
    if (mpi::rank == i)
10,371✔
679
      simulation::work_per_rank = work_i;
7,702✔
680

681
    // Set index into source bank for rank i
682
    i_bank += work_i;
10,371✔
683
    simulation::work_index[i + 1] = i_bank;
10,371✔
684
  }
685
}
7,702✔
686

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

693
  for (const auto& nuc : data::nuclides) {
34,210✔
694
    if (nuc->grid_.size() >= 1) {
28,499!
695
      int neutron = static_cast<int>(ParticleType::neutron);
28,499✔
696
      data::energy_min[neutron] =
56,998✔
697
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
28,499✔
698
      data::energy_max[neutron] =
28,499✔
699
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
28,499✔
700
    }
701
  }
702

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

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

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

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

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

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

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

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

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

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

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

801
#endif
802

803
void free_memory_simulation()
7,901✔
804
{
805
  simulation::k_generation.clear();
7,901✔
806
  simulation::entropy.clear();
7,901✔
807
}
7,901✔
808

809
void transport_history_based_single_particle(Particle& p)
153,697,390✔
810
{
811
  while (p.alive()) {
2,147,483,647✔
812
    p.event_calculate_xs();
2,147,483,647✔
813
    if (p.alive()) {
2,147,483,647!
814
      p.event_advance();
2,147,483,647✔
815
    }
816
    if (p.alive()) {
2,147,483,647✔
817
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
818
        p.event_cross_surface();
1,364,150,771✔
819
      } else if (p.alive()) {
2,147,483,647!
820
        p.event_collide();
2,147,483,647✔
821
      }
822
    }
823
    p.event_revive_from_secondary();
2,147,483,647✔
824
  }
825
  p.event_death();
153,697,381✔
826
}
153,697,381✔
827

828
void transport_history_based()
120,816✔
829
{
830
#pragma omp parallel for schedule(runtime)
831
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
75,341,270✔
832
    Particle p;
75,286,088✔
833
    initialize_history(p, i_work);
75,286,088✔
834
    transport_history_based_single_particle(p);
75,286,085✔
835
  }
75,286,080✔
836
}
120,808✔
837

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

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

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

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

865
      // Execute event with the longest queue
866
      if (max == 0) {
2,362,131✔
867
        break;
3,150✔
868
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,358,981✔
869
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
425,180!
870
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,933,801✔
871
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
358,547!
872
      } else if (max == simulation::advance_particle_queue.size()) {
1,575,254✔
873
        process_advance_particle_events();
778,487!
874
      } else if (max == simulation::surface_crossing_queue.size()) {
796,767✔
875
        process_surface_crossing_events();
258,589!
876
      } else if (max == simulation::collision_queue.size()) {
538,178!
877
        process_collision_events();
538,178!
878
      }
879
    }
2,358,981✔
880

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

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

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