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

openmc-dev / openmc / 21686031975

04 Feb 2026 07:50PM UTC coverage: 81.024% (-0.7%) from 81.763%
21686031975

Pull #3755

github

web-flow
Merge 27d6053a4 into b41e22f68
Pull Request #3755: Warn users that tally heating score with photon bin but without electron and positron bins.

16378 of 22828 branches covered (71.75%)

Branch coverage included in aggregate %.

22 of 23 new or added lines in 1 file covered. (95.65%)

862 existing lines in 51 files now uncovered.

54491 of 64639 relevant lines covered (84.3%)

8259986.93 hits per line

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

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

65
  int err = 0;
636✔
66
  while (status == 0 && err == 0) {
13,148!
67
    err = openmc_next_batch(&status);
12,513✔
68
  }
69

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

75
int openmc_simulation_init()
761✔
76
{
77
  using namespace openmc;
78

79
  // Skip if simulation has already been initialized
80
  if (simulation::initialized)
761✔
81
    return 0;
1✔
82

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

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

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

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

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

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

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

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

140
  // Display header
141
  if (mpi::master) {
760✔
142
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
537✔
143
      if (settings::solver_type == SolverType::MONTE_CARLO) {
221✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
191✔
145
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
30!
146
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
30✔
147
      }
148
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
316!
149
      if (settings::solver_type == SolverType::MONTE_CARLO) {
316✔
150
        header("K EIGENVALUE SIMULATION", 3);
296✔
151
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
20!
152
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
20✔
153
      }
154
      if (settings::verbosity >= 7)
316✔
155
        print_columns();
300✔
156
    }
157
  }
158

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

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

169
int openmc_simulation_finalize()
759✔
170
{
171
  using namespace openmc;
172

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

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

181
  // Clear material nuclide mapping
182
  for (auto& mat : model::materials) {
2,518✔
183
    mat->mat_nuclide_index_.clear();
1,759✔
184
  }
185

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

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

194
#ifdef OPENMC_MPI
195
  broadcast_results();
759✔
196
#endif
197

198
  // Write tally results to tallies.out
199
  if (settings::output_tallies && mpi::master)
759✔
200
    write_tallies();
515✔
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) {
759✔
205
    openmc_weight_windows_export();
15✔
206
  }
207

208
  // Deactivate all tallies
209
  for (auto& t : model::tallies) {
3,958✔
210
    t->active_ = false;
3,199✔
211
  }
212

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

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

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

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

243
  initialize_batch();
12,887✔
244

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

249
    initialize_generation();
12,915✔
250

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

254
    // Transport loop
255
    if (settings::event_based) {
12,915!
UNCOV
256
      transport_event_based();
×
257
    } else {
258
      transport_history_based();
12,915✔
259
    }
260

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

264
    finalize_generation();
12,914✔
265
  }
266

267
  finalize_batch();
12,886✔
268

269
  // Check simulation ending criteria
270
  if (status) {
12,886!
271
    if (simulation::current_batch >= settings::n_max_batches) {
12,886✔
272
      *status = STATUS_EXIT_MAX_BATCH;
650✔
273
    } else if (simulation::satisfy_triggers) {
12,236✔
274
      *status = STATUS_EXIT_ON_TRIGGER;
11✔
275
    } else {
276
      *status = STATUS_EXIT_NORMAL;
12,225✔
277
    }
278
  }
279
  return 0;
12,886✔
280
}
281

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

287
  if (!simulation::initialized)
285!
288
    return false;
×
289
  else
290
    return contains(settings::statepoint_batch, simulation::current_batch);
285✔
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()
760✔
333
{
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
760✔
335
      settings::solver_type == SolverType::MONTE_CARLO) {
481✔
336
    // Allocate source bank
337
    simulation::source_bank.resize(simulation::work_per_rank);
441✔
338

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

342
    // Allocate IFP bank
343
    if (settings::ifp_on) {
441✔
344
      resize_simulation_ifp_banks();
8✔
345
    }
346
  }
347

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

353
  if (settings::collision_track) {
760✔
354
    // Allocate collision track bank
355
    collision_track_reserve_bank();
18✔
356
  }
357
}
760✔
358

359
void initialize_batch()
15,187✔
360
{
361
  // Increment current batch
362
  ++simulation::current_batch;
15,187✔
363
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
15,187✔
364
    if (settings::solver_type == SolverType::RANDOM_RAY &&
5,302✔
365
        simulation::current_batch < settings::n_inactive + 1) {
1,760✔
366
      write_message(
1,070✔
367
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
368
    } else {
369
      write_message(6, "Simulating batch {}", simulation::current_batch);
4,232✔
370
    }
371
  }
372

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

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

387
  // Manage active/inactive timers and activate tallies if necessary.
388
  if (first_inactive) {
15,187✔
389
    simulation::time_inactive.start();
421✔
390
  } else if (first_active) {
14,766✔
391
    simulation::time_inactive.stop();
756✔
392
    simulation::time_active.start();
756✔
393
    for (auto& t : model::tallies) {
3,953✔
394
      t->active_ = true;
3,197✔
395
    }
396
  }
397

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

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

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

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

420
  // Check_triggers
421
  if (mpi::master)
15,186✔
422
    check_triggers();
10,681✔
423
#ifdef OPENMC_MPI
424
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
15,186✔
425
#endif
426
  if (simulation::satisfy_triggers ||
15,186✔
427
      (settings::trigger_on &&
283✔
428
        simulation::current_batch == settings::n_max_batches)) {
283✔
429
    settings::statepoint_batch.insert(simulation::current_batch);
16✔
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) &&
15,972✔
435
      !settings::cmfd_run) {
786✔
436
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
1,515✔
437
        settings::source_write && !settings::source_separate) {
1,515✔
438
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
636✔
439
      openmc_statepoint_write(nullptr, &b);
636✔
440
    } else {
441
      bool b = false;
134✔
442
      openmc_statepoint_write(nullptr, &b);
134✔
443
    }
444
  }
445

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

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

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

469
  // Write out surface source if requested.
470
  if (settings::surf_source_write &&
15,186✔
471
      simulation::ssw_current_file <= settings::ssw_max_files) {
824✔
472
    bool last_batch = (simulation::current_batch == settings::n_batches);
164✔
473
    if (simulation::surf_source_bank.full() || last_batch) {
164✔
474
      // Determine appropriate filename
475
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
476
        simulation::current_batch);
90✔
477
      if (settings::ssw_max_files == 1 ||
90✔
478
          (simulation::ssw_current_file == 1 && last_batch)) {
5!
479
        filename = settings::path_output + "surface_source";
85✔
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());
90✔
485
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
486
        simulation::surf_source_bank.size());
90✔
487

488
      // Write surface source file
489
      write_source_point(
90✔
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();
90✔
494
      if (!last_batch && settings::ssw_max_files >= 1) {
90!
495
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
73✔
496
      }
497
      ++simulation::ssw_current_file;
90✔
498
    }
90✔
499
  }
500
  // Write collision track file if requested
501
  if (settings::collision_track) {
15,186✔
502
    collision_track_flush_bank();
78✔
503
  }
504
}
15,186✔
505

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

512
    // Count source sites if using uniform fission source weighting
513
    if (settings::ufs_on)
9,913✔
514
      ufs_count_sites();
20✔
515

516
    // Store current value of tracklength k
517
    simulation::keff_generation = simulation::global_tallies(
9,913✔
518
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
519
  }
520
}
15,215✔
521

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

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

536
  // reset tallies
537
  if (settings::run_mode == RunMode::EIGENVALUE) {
15,214✔
538
    global_tally_collision = 0.0;
9,913✔
539
    global_tally_absorption = 0.0;
9,913✔
540
    global_tally_tracklength = 0.0;
9,913✔
541
  }
542
  global_tally_leakage = 0.0;
15,214✔
543

544
  if (settings::run_mode == RunMode::EIGENVALUE &&
15,214✔
545
      settings::solver_type == SolverType::MONTE_CARLO) {
9,913✔
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();
9,373✔
550

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

555
  if (settings::run_mode == RunMode::EIGENVALUE) {
15,214✔
556

557
    // Calculate shannon entropy
558
    if (settings::entropy_on &&
9,913✔
559
        settings::solver_type == SolverType::MONTE_CARLO)
1,245✔
560
      shannon_entropy();
705✔
561

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

566
    // Write generation output
567
    if (mpi::master && settings::verbosity >= 7) {
9,913✔
568
      print_generation();
6,248✔
569
    }
570
  }
571
}
15,214✔
572

573
void initialize_history(Particle& p, int64_t index_source)
15,169,133✔
574
{
575
  // set defaults
576
  if (settings::run_mode == RunMode::EIGENVALUE) {
15,169,133✔
577
    // set defaults for eigenvalue simulations from primary bank
578
    p.from_source(&simulation::source_bank[index_source - 1]);
12,809,200✔
579
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
2,359,933!
580
    // initialize random number seed
581
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
2,359,933✔
582
                   settings::n_particles +
2,359,933✔
583
                 simulation::work_index[mpi::rank] + index_source;
2,359,933✔
584
    uint64_t seed = init_seed(id, STREAM_SOURCE);
2,359,933✔
585
    // sample from external source distribution or custom library then set
586
    auto site = sample_external_source(&seed);
2,359,933✔
587
    p.from_source(&site);
2,359,933✔
588
  }
589
  p.current_work() = index_source;
15,169,133✔
590

591
  // set identifier for particle
592
  p.id() = simulation::work_index[mpi::rank] + index_source;
15,169,133✔
593

594
  // set progeny count to zero
595
  p.n_progeny() = 0;
15,169,133✔
596

597
  // Reset particle event counter
598
  p.n_event() = 0;
15,169,133✔
599

600
  // Reset split counter
601
  p.n_split() = 0;
15,169,133✔
602

603
  // Reset weight window ratio
604
  p.ww_factor() = 0.0;
15,169,133✔
605

606
  // set particle history start weight
607
  p.wgt_born() = p.wgt();
15,169,133✔
608

609
  // Reset pulse_height_storage
610
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
15,169,133✔
611

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

618
  // set particle trace
619
  p.trace() = false;
15,169,133✔
620
  if (simulation::current_batch == settings::trace_batch &&
30,339,266✔
621
      simulation::current_gen == settings::trace_gen &&
15,170,133!
622
      p.id() == settings::trace_particle)
1,000✔
623
    p.trace() = true;
1✔
624

625
  // Set particle track.
626
  p.write_track() = check_track_criteria(p);
15,169,133✔
627

628
  // Set the particle's initial weight window value.
629
  p.wgt_ww_born() = -1.0;
15,169,133✔
630
  apply_weight_windows(p);
15,169,133✔
631

632
  // Display message if high verbosity or trace is on
633
  if (settings::verbosity >= 9 || p.trace()) {
15,169,133!
634
    write_message("Simulating Particle {}", p.id());
1✔
635
  }
636

637
// Add particle's starting weight to count for normalizing tallies later
638
#pragma omp atomic
639
  simulation::total_weight += p.wgt();
15,169,133✔
640

641
  // Force calculation of cross-sections by setting last energy to zero
642
  if (settings::run_CE) {
15,169,133✔
643
    p.invalidate_neutron_xs();
4,985,133✔
644
  }
645

646
  // Prepare to write out particle track.
647
  if (p.write_track())
15,169,133✔
648
    add_particle_track(p);
129✔
649
}
15,169,133✔
650

651
int overall_generation()
17,554,628✔
652
{
653
  using namespace simulation;
654
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
17,554,628✔
655
}
656

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

662
  // Determine number of processors that have one extra particle
663
  int64_t remainder = settings::n_particles % mpi::n_procs;
760✔
664

665
  int64_t i_bank = 0;
760✔
666
  simulation::work_index.resize(mpi::n_procs + 1);
760✔
667
  simulation::work_index[0] = 0;
760✔
668
  for (int i = 0; i < mpi::n_procs; ++i) {
1,966✔
669
    // Number of particles for rank i
670
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
1,206!
671

672
    // Set number of particles
673
    if (mpi::rank == i)
1,206✔
674
      simulation::work_per_rank = work_i;
760✔
675

676
    // Set index into source bank for rank i
677
    i_bank += work_i;
1,206✔
678
    simulation::work_index[i + 1] = i_bank;
1,206✔
679
  }
680
}
760✔
681

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

688
  for (const auto& nuc : data::nuclides) {
3,443✔
689
    if (nuc->grid_.size() >= 1) {
2,844!
690
      int neutron = ParticleType::neutron().transport_index();
2,844✔
691
      data::energy_min[neutron] =
5,688✔
692
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
2,844✔
693
      data::energy_max[neutron] =
2,844✔
694
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
2,844✔
695
    }
696
  }
697

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

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

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

725
        data::energy_min[photon] =
62✔
726
          std::max(data::energy_min[photon], data::energy_min[electron]);
31✔
727

728
        data::energy_max[photon] =
62✔
729
          std::min(data::energy_max[photon], data::energy_max[electron]);
31✔
730
      }
31✔
731
    }
732
  }
733

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

753
  // Set up logarithmic grid for nuclides
754
  for (auto& nuc : data::nuclides) {
3,443✔
755
    nuc->init_grid();
2,844✔
756
  }
757
  int neutron = ParticleType::neutron().transport_index();
599✔
758
  simulation::log_spacing =
599✔
759
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
599✔
760
    settings::n_log_bins;
761
}
599✔
762

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

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

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

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

796
#endif
797

798
void free_memory_simulation()
857✔
799
{
800
  simulation::k_generation.clear();
857✔
801
  simulation::entropy.clear();
857✔
802
}
857✔
803

804
void transport_history_based_single_particle(Particle& p)
15,169,136✔
805
{
806
  while (p.alive()) {
390,273,256✔
807
    p.event_calculate_xs();
375,104,121✔
808
    if (p.alive()) {
375,104,121!
809
      p.event_advance();
375,104,121✔
810
    }
811
    if (p.alive()) {
375,104,121✔
812
      if (p.collision_distance() > p.boundary().distance()) {
375,083,673✔
813
        p.event_cross_surface();
127,670,952✔
814
      } else if (p.alive()) {
247,412,721!
815
        p.event_collide();
247,412,721✔
816
      }
817
    }
818
    p.event_revive_from_secondary();
375,104,120✔
819
  }
820
  p.event_death();
15,169,135✔
821
}
15,169,135✔
822

823
void transport_history_based()
12,915✔
824
{
825
#pragma omp parallel for schedule(runtime)
826
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
15,182,047✔
827
    Particle p;
15,169,133✔
828
    initialize_history(p, i_work);
15,169,133✔
829
    transport_history_based_single_particle(p);
15,169,133✔
830
  }
15,169,132✔
831
}
12,914✔
832

UNCOV
833
void transport_event_based()
×
834
{
UNCOV
835
  int64_t remaining_work = simulation::work_per_rank;
×
UNCOV
836
  int64_t source_offset = 0;
×
837

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

848
    // Initialize all particle histories for this subiteration
UNCOV
849
    process_init_events(n_particles, source_offset);
×
850

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

860
      // Execute event with the longest queue
UNCOV
861
      if (max == 0) {
×
UNCOV
862
        break;
×
UNCOV
863
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
×
UNCOV
864
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
×
UNCOV
865
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
×
UNCOV
866
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
×
UNCOV
867
      } else if (max == simulation::advance_particle_queue.size()) {
×
UNCOV
868
        process_advance_particle_events();
×
UNCOV
869
      } else if (max == simulation::surface_crossing_queue.size()) {
×
UNCOV
870
        process_surface_crossing_events();
×
UNCOV
871
      } else if (max == simulation::collision_queue.size()) {
×
UNCOV
872
        process_collision_events();
×
873
      }
UNCOV
874
    }
×
875

876
    // Execute death event for all particles
UNCOV
877
    process_death_events(n_particles);
×
878

879
    // Adjust remaining work and source offset variables
UNCOV
880
    remaining_work -= n_particles;
×
UNCOV
881
    source_offset += n_particles;
×
882
  }
UNCOV
883
}
×
884

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