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

openmc-dev / openmc / 15648508499

14 Jun 2025 04:41AM UTC coverage: 85.162% (+0.04%) from 85.126%
15648508499

Pull #3346

github

web-flow
Merge 95507c5a3 into b11eb0265
Pull Request #3346: Allow specifying number of equiprobable angles for thermal scattering data generation

52373 of 61498 relevant lines covered (85.16%)

36636961.06 hits per line

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

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

3
#include "openmc/bank.h"
4
#include "openmc/capi.h"
5
#include "openmc/container_util.h"
6
#include "openmc/eigenvalue.h"
7
#include "openmc/error.h"
8
#include "openmc/event.h"
9
#include "openmc/geometry_aux.h"
10
#include "openmc/ifp.h"
11
#include "openmc/material.h"
12
#include "openmc/mcpl_interface.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,157✔
54
{
55
  openmc::simulation::time_total.start();
5,157✔
56
  openmc_simulation_init();
5,157✔
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,157✔
61
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
5,157✔
62
    status = openmc::STATUS_EXIT_MAX_BATCH;
11✔
63
  }
64

65
  int err = 0;
5,157✔
66
  while (status == 0 && err == 0) {
94,265✔
67
    err = openmc_next_batch(&status);
89,120✔
68
  }
69

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

75
int openmc_simulation_init()
6,101✔
76
{
77
  using namespace openmc;
78

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

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

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

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

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

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

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

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

139
  // Display header
140
  if (mpi::master) {
6,090✔
141
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,110✔
142
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,139✔
143
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
1,831✔
144
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
308✔
145
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
308✔
146
      }
147
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
2,971✔
148
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,971✔
149
        header("K EIGENVALUE SIMULATION", 3);
2,839✔
150
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
132✔
151
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
132✔
152
      }
153
      if (settings::verbosity >= 7)
2,971✔
154
        print_columns();
2,751✔
155
    }
156
  }
157

158
  // load weight windows from file
159
  if (!settings::weight_windows_file.empty()) {
6,090✔
160
    openmc_weight_windows_import(settings::weight_windows_file.c_str());
×
161
  }
162

163
  // Set flag indicating initialization is done
164
  simulation::initialized = true;
6,090✔
165
  return 0;
6,090✔
166
}
167

168
int openmc_simulation_finalize()
6,078✔
169
{
170
  using namespace openmc;
171

172
  // Skip if simulation was never run
173
  if (!simulation::initialized)
6,078✔
174
    return 0;
×
175

176
  // Stop active batch timer and start finalization timer
177
  simulation::time_active.stop();
6,078✔
178
  simulation::time_finalize.start();
6,078✔
179

180
  // Clear material nuclide mapping
181
  for (auto& mat : model::materials) {
24,128✔
182
    mat->mat_nuclide_index_.clear();
18,050✔
183
  }
184

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

190
  // Increment total number of generations
191
  simulation::total_gen += simulation::current_batch * settings::gen_per_batch;
6,078✔
192

193
#ifdef OPENMC_MPI
194
  broadcast_results();
3,328✔
195
#endif
196

197
  // Write tally results to tallies.out
198
  if (settings::output_tallies && mpi::master)
6,078✔
199
    write_tallies();
5,021✔
200

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

207
  // Deactivate all tallies
208
  for (auto& t : model::tallies) {
31,867✔
209
    t->active_ = false;
25,789✔
210
  }
211

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

226
  // Reset flags
227
  simulation::initialized = false;
6,078✔
228
  return 0;
6,078✔
229
}
230

231
int openmc_next_batch(int* status)
93,530✔
232
{
233
  using namespace openmc;
234
  using openmc::simulation::current_gen;
235

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

242
  initialize_batch();
93,519✔
243

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

248
    initialize_generation();
93,743✔
249

250
    // Start timer for transport
251
    simulation::time_transport.start();
93,743✔
252

253
    // Transport loop
254
    if (settings::event_based) {
93,743✔
255
      transport_event_based();
3,061✔
256
    } else {
257
      transport_history_based();
90,682✔
258
    }
259

260
    // Accumulate time for transport
261
    simulation::time_transport.stop();
93,731✔
262

263
    finalize_generation();
93,731✔
264
  }
265

266
  finalize_batch();
93,507✔
267

268
  // Check simulation ending criteria
269
  if (status) {
93,507✔
270
    if (simulation::current_batch >= settings::n_max_batches) {
93,507✔
271
      *status = STATUS_EXIT_MAX_BATCH;
5,381✔
272
    } else if (simulation::satisfy_triggers) {
88,126✔
273
      *status = STATUS_EXIT_ON_TRIGGER;
65✔
274
    } else {
275
      *status = STATUS_EXIT_NORMAL;
88,061✔
276
    }
277
  }
278
  return 0;
93,507✔
279
}
280

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

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

292
namespace openmc {
293

294
//==============================================================================
295
// Global variables
296
//==============================================================================
297

298
namespace simulation {
299

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

318
const RegularMesh* entropy_mesh {nullptr};
319
const RegularMesh* ufs_mesh {nullptr};
320

321
vector<double> k_generation;
322
vector<int64_t> work_index;
323

324
} // namespace simulation
325

326
//==============================================================================
327
// Non-member functions
328
//==============================================================================
329

330
void allocate_banks()
6,090✔
331
{
332
  if (settings::run_mode == RunMode::EIGENVALUE &&
6,090✔
333
      settings::solver_type == SolverType::MONTE_CARLO) {
3,682✔
334
    // Allocate source bank
335
    simulation::source_bank.resize(simulation::work_per_rank);
3,490✔
336

337
    // Allocate fission bank
338
    init_fission_bank(3 * simulation::work_per_rank);
3,490✔
339

340
    // Allocate IFP bank
341
    if (settings::ifp_on) {
3,490✔
342
      resize_simulation_ifp_banks();
16✔
343
    }
344
  }
345

346
  if (settings::surf_source_write) {
6,090✔
347
    // Allocate surface source bank
348
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
576✔
349
  }
350
}
6,090✔
351

352
void initialize_batch()
110,319✔
353
{
354
  // Increment current batch
355
  ++simulation::current_batch;
110,319✔
356
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
110,319✔
357
    if (settings::solver_type == SolverType::RANDOM_RAY &&
31,674✔
358
        simulation::current_batch < settings::n_inactive + 1) {
13,760✔
359
      write_message(
8,400✔
360
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
361
    } else {
362
      write_message(6, "Simulating batch {}", simulation::current_batch);
23,274✔
363
    }
364
  }
365

366
  // Reset total starting particle weight used for normalizing tallies
367
  simulation::total_weight = 0.0;
110,319✔
368

369
  // Determine if this batch is the first inactive or active batch.
370
  bool first_inactive = false;
110,319✔
371
  bool first_active = false;
110,319✔
372
  if (!settings::restart_run) {
110,319✔
373
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
110,082✔
374
    first_active = simulation::current_batch == settings::n_inactive + 1;
110,082✔
375
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
237✔
376
    first_inactive = simulation::restart_batch < settings::n_inactive;
55✔
377
    first_active = !first_inactive;
55✔
378
  }
379

380
  // Manage active/inactive timers and activate tallies if necessary.
381
  if (first_inactive) {
110,319✔
382
    simulation::time_inactive.start();
3,138✔
383
  } else if (first_active) {
107,181✔
384
    simulation::time_inactive.stop();
6,032✔
385
    simulation::time_active.start();
6,032✔
386
    for (auto& t : model::tallies) {
31,799✔
387
      t->active_ = true;
25,767✔
388
    }
389
  }
390

391
  // Add user tallies to active tallies list
392
  setup_active_tallies();
110,319✔
393
}
110,319✔
394

395
void finalize_batch()
110,307✔
396
{
397
  // Reduce tallies onto master process and accumulate
398
  simulation::time_tallies.start();
110,307✔
399
  accumulate_tallies();
110,307✔
400
  simulation::time_tallies.stop();
110,307✔
401

402
  // update weight windows if needed
403
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
112,712✔
404
    wwg->update();
2,405✔
405
  }
406

407
  // Reset global tally results
408
  if (simulation::current_batch <= settings::n_inactive) {
110,307✔
409
    xt::view(simulation::global_tallies, xt::all()) = 0.0;
25,725✔
410
    simulation::n_realizations = 0;
25,725✔
411
  }
412

413
  // Check_triggers
414
  if (mpi::master)
110,307✔
415
    check_triggers();
88,712✔
416
#ifdef OPENMC_MPI
417
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
62,214✔
418
#endif
419
  if (simulation::satisfy_triggers ||
110,307✔
420
      (settings::trigger_on &&
2,997✔
421
        simulation::current_batch == settings::n_max_batches)) {
2,997✔
422
    settings::statepoint_batch.insert(simulation::current_batch);
146✔
423
  }
424

425
  // Write out state point if it's been specified for this batch and is not
426
  // a CMFD run instance
427
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
116,619✔
428
      !settings::cmfd_run) {
6,312✔
429
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
12,019✔
430
        settings::source_write && !settings::source_separate) {
12,019✔
431
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
5,195✔
432
      openmc_statepoint_write(nullptr, &b);
5,195✔
433
    } else {
434
      bool b = false;
925✔
435
      openmc_statepoint_write(nullptr, &b);
925✔
436
    }
437
  }
438

439
  if (settings::run_mode == RunMode::EIGENVALUE) {
110,307✔
440
    // Write out a separate source point if it's been specified for this batch
441
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
82,387✔
442
        settings::source_write && settings::source_separate) {
82,387✔
443

444
      // Determine width for zero padding
445
      int w = std::to_string(settings::n_max_batches).size();
64✔
446
      std::string source_point_filename = fmt::format("{0}source.{1:0{2}}",
447
        settings::path_output, simulation::current_batch, w);
52✔
448
      span<SourceSite> bankspan(simulation::source_bank);
64✔
449
      write_source_point(source_point_filename, bankspan,
64✔
450
        simulation::work_index, settings::source_mcpl_write);
451
    }
64✔
452

453
    // Write a continously-overwritten source point if requested.
454
    if (settings::source_latest) {
78,645✔
455
      auto filename = settings::path_output + "source";
160✔
456
      span<SourceSite> bankspan(simulation::source_bank);
160✔
457
      write_source_point(filename, bankspan, simulation::work_index,
160✔
458
        settings::source_mcpl_write);
459
    }
160✔
460
  }
461

462
  // Write out surface source if requested.
463
  if (settings::surf_source_write &&
110,307✔
464
      simulation::ssw_current_file <= settings::ssw_max_files) {
3,804✔
465
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,400✔
466
    if (simulation::surf_source_bank.full() || last_batch) {
1,400✔
467
      // Determine appropriate filename
468
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
469
        simulation::current_batch);
497✔
470
      if (settings::ssw_max_files == 1 ||
609✔
471
          (simulation::ssw_current_file == 1 && last_batch)) {
55✔
472
        filename = settings::path_output + "surface_source";
554✔
473
      }
474

475
      // Get span of source bank and calculate parallel index vector
476
      auto surf_work_index = mpi::calculate_parallel_index_vector(
477
        simulation::surf_source_bank.size());
609✔
478
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
479
        simulation::surf_source_bank.size());
609✔
480

481
      // Write surface source file
482
      write_source_point(
609✔
483
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
484

485
      // Reset surface source bank and increment counter
486
      simulation::surf_source_bank.clear();
609✔
487
      if (!last_batch && settings::ssw_max_files >= 1) {
609✔
488
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
425✔
489
      }
490
      ++simulation::ssw_current_file;
609✔
491
    }
609✔
492
  }
493
}
110,307✔
494

495
void initialize_generation()
110,543✔
496
{
497
  if (settings::run_mode == RunMode::EIGENVALUE) {
110,543✔
498
    // Clear out the fission bank
499
    simulation::fission_bank.resize(0);
78,869✔
500

501
    // Count source sites if using uniform fission source weighting
502
    if (settings::ufs_on)
78,869✔
503
      ufs_count_sites();
160✔
504

505
    // Store current value of tracklength k
506
    simulation::keff_generation = simulation::global_tallies(
78,869✔
507
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
508
  }
509
}
110,543✔
510

511
void finalize_generation()
110,531✔
512
{
513
  auto& gt = simulation::global_tallies;
110,531✔
514

515
  // Update global tallies with the accumulation variables
516
  if (settings::run_mode == RunMode::EIGENVALUE) {
110,531✔
517
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
78,869✔
518
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
78,869✔
519
      global_tally_absorption;
520
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
78,869✔
521
      global_tally_tracklength;
522
  }
523
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
110,531✔
524

525
  // reset tallies
526
  if (settings::run_mode == RunMode::EIGENVALUE) {
110,531✔
527
    global_tally_collision = 0.0;
78,869✔
528
    global_tally_absorption = 0.0;
78,869✔
529
    global_tally_tracklength = 0.0;
78,869✔
530
  }
531
  global_tally_leakage = 0.0;
110,531✔
532

533
  if (settings::run_mode == RunMode::EIGENVALUE &&
110,531✔
534
      settings::solver_type == SolverType::MONTE_CARLO) {
78,869✔
535
    // If using shared memory, stable sort the fission bank (by parent IDs)
536
    // so as to allow for reproducibility regardless of which order particles
537
    // are run in.
538
    sort_fission_bank();
75,829✔
539

540
    // Distribute fission bank across processors evenly
541
    synchronize_bank();
75,829✔
542
  }
543

544
  if (settings::run_mode == RunMode::EIGENVALUE) {
110,531✔
545

546
    // Calculate shannon entropy
547
    if (settings::entropy_on &&
78,869✔
548
        settings::solver_type == SolverType::MONTE_CARLO)
11,020✔
549
      shannon_entropy();
7,980✔
550

551
    // Collect results and statistics
552
    calculate_generation_keff();
78,869✔
553
    calculate_average_keff();
78,869✔
554

555
    // Write generation output
556
    if (mpi::master && settings::verbosity >= 7) {
78,869✔
557
      print_generation();
59,521✔
558
    }
559
  }
560
}
110,531✔
561

562
void initialize_history(Particle& p, int64_t index_source)
156,311,597✔
563
{
564
  // set defaults
565
  if (settings::run_mode == RunMode::EIGENVALUE) {
156,311,597✔
566
    // set defaults for eigenvalue simulations from primary bank
567
    p.from_source(&simulation::source_bank[index_source - 1]);
133,397,800✔
568
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
22,913,797✔
569
    // initialize random number seed
570
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
22,913,797✔
571
                   settings::n_particles +
22,913,797✔
572
                 simulation::work_index[mpi::rank] + index_source;
22,913,797✔
573
    uint64_t seed = init_seed(id, STREAM_SOURCE);
22,913,797✔
574
    // sample from external source distribution or custom library then set
575
    auto site = sample_external_source(&seed);
22,913,797✔
576
    p.from_source(&site);
22,913,794✔
577
  }
578
  p.current_work() = index_source;
156,311,594✔
579

580
  // set identifier for particle
581
  p.id() = simulation::work_index[mpi::rank] + index_source;
156,311,594✔
582

583
  // set progeny count to zero
584
  p.n_progeny() = 0;
156,311,594✔
585

586
  // Reset particle event counter
587
  p.n_event() = 0;
156,311,594✔
588

589
  // Reset split counter
590
  p.n_split() = 0;
156,311,594✔
591

592
  // Reset weight window ratio
593
  p.ww_factor() = 0.0;
156,311,594✔
594

595
  // set particle history start weight
596
  p.wgt_born() = p.wgt();
156,311,594✔
597

598
  // Reset pulse_height_storage
599
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
156,311,594✔
600

601
  // set random number seed
602
  int64_t particle_seed =
603
    (simulation::total_gen + overall_generation() - 1) * settings::n_particles +
156,311,594✔
604
    p.id();
156,311,594✔
605
  init_particle_seeds(particle_seed, p.seeds());
156,311,594✔
606

607
  // set particle trace
608
  p.trace() = false;
156,311,594✔
609
  if (simulation::current_batch == settings::trace_batch &&
312,634,188✔
610
      simulation::current_gen == settings::trace_gen &&
156,322,594✔
611
      p.id() == settings::trace_particle)
11,000✔
612
    p.trace() = true;
11✔
613

614
  // Set particle track.
615
  p.write_track() = check_track_criteria(p);
156,311,594✔
616

617
  // Display message if high verbosity or trace is on
618
  if (settings::verbosity >= 9 || p.trace()) {
156,311,594✔
619
    write_message("Simulating Particle {}", p.id());
11✔
620
  }
621

622
// Add particle's starting weight to count for normalizing tallies later
623
#pragma omp atomic
85,260,720✔
624
  simulation::total_weight += p.wgt();
156,311,594✔
625

626
  // Force calculation of cross-sections by setting last energy to zero
627
  if (settings::run_CE) {
156,311,594✔
628
    p.invalidate_neutron_xs();
44,287,594✔
629
  }
630

631
  // Prepare to write out particle track.
632
  if (p.write_track())
156,311,594✔
633
    add_particle_track(p);
1,059✔
634
}
156,311,594✔
635

636
int overall_generation()
179,439,868✔
637
{
638
  using namespace simulation;
639
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
179,439,868✔
640
}
641

642
void calculate_work()
6,090✔
643
{
644
  // Determine minimum amount of particles to simulate on each processor
645
  int64_t min_work = settings::n_particles / mpi::n_procs;
6,090✔
646

647
  // Determine number of processors that have one extra particle
648
  int64_t remainder = settings::n_particles % mpi::n_procs;
6,090✔
649

650
  int64_t i_bank = 0;
6,090✔
651
  simulation::work_index.resize(mpi::n_procs + 1);
6,090✔
652
  simulation::work_index[0] = 0;
6,090✔
653
  for (int i = 0; i < mpi::n_procs; ++i) {
14,139✔
654
    // Number of particles for rank i
655
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
8,049✔
656

657
    // Set number of particles
658
    if (mpi::rank == i)
8,049✔
659
      simulation::work_per_rank = work_i;
6,090✔
660

661
    // Set index into source bank for rank i
662
    i_bank += work_i;
8,049✔
663
    simulation::work_index[i + 1] = i_bank;
8,049✔
664
  }
665
}
6,090✔
666

667
void initialize_data()
4,965✔
668
{
669
  // Determine minimum/maximum energy for incident neutron/photon data
670
  data::energy_max = {INFTY, INFTY};
4,965✔
671
  data::energy_min = {0.0, 0.0};
4,965✔
672
  for (const auto& nuc : data::nuclides) {
30,927✔
673
    if (nuc->grid_.size() >= 1) {
25,962✔
674
      int neutron = static_cast<int>(ParticleType::neutron);
25,962✔
675
      data::energy_min[neutron] =
51,924✔
676
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
25,962✔
677
      data::energy_max[neutron] =
25,962✔
678
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
25,962✔
679
    }
680
  }
681

682
  if (settings::photon_transport) {
4,965✔
683
    for (const auto& elem : data::elements) {
827✔
684
      if (elem->energy_.size() >= 1) {
557✔
685
        int photon = static_cast<int>(ParticleType::photon);
557✔
686
        int n = elem->energy_.size();
557✔
687
        data::energy_min[photon] =
1,114✔
688
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
557✔
689
        data::energy_max[photon] =
1,114✔
690
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
557✔
691
      }
692
    }
693

694
    if (settings::electron_treatment == ElectronTreatment::TTB) {
270✔
695
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
696
      // than the current minimum/maximum
697
      if (data::ttb_e_grid.size() >= 1) {
259✔
698
        int photon = static_cast<int>(ParticleType::photon);
259✔
699
        int n_e = data::ttb_e_grid.size();
259✔
700
        data::energy_min[photon] =
518✔
701
          std::max(data::energy_min[photon], std::exp(data::ttb_e_grid(1)));
259✔
702
        data::energy_max[photon] = std::min(
259✔
703
          data::energy_max[photon], std::exp(data::ttb_e_grid(n_e - 1)));
518✔
704
      }
705
    }
706
  }
707

708
  // Show which nuclide results in lowest energy for neutron transport
709
  for (const auto& nuc : data::nuclides) {
6,126✔
710
    // If a nuclide is present in a material that's not used in the model, its
711
    // grid has not been allocated
712
    if (nuc->grid_.size() > 0) {
5,706✔
713
      double max_E = nuc->grid_[0].energy.back();
5,706✔
714
      int neutron = static_cast<int>(ParticleType::neutron);
5,706✔
715
      if (max_E == data::energy_max[neutron]) {
5,706✔
716
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
4,545✔
717
          data::energy_max[neutron], nuc->name_);
4,545✔
718
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
4,545✔
719
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
720
                  "the results.");
721
        }
722
        break;
4,545✔
723
      }
724
    }
725
  }
726

727
  // Set up logarithmic grid for nuclides
728
  for (auto& nuc : data::nuclides) {
30,927✔
729
    nuc->init_grid();
25,962✔
730
  }
731
  int neutron = static_cast<int>(ParticleType::neutron);
4,965✔
732
  simulation::log_spacing =
4,965✔
733
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
4,965✔
734
    settings::n_log_bins;
735
}
4,965✔
736

737
#ifdef OPENMC_MPI
738
void broadcast_results()
3,328✔
739
{
740
  // Broadcast tally results so that each process has access to results
741
  for (auto& t : model::tallies) {
18,805✔
742
    // Create a new datatype that consists of all values for a given filter
743
    // bin and then use that to broadcast. This is done to minimize the
744
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
745
    auto& results = t->results_;
15,477✔
746

747
    auto shape = results.shape();
15,477✔
748
    int count_per_filter = shape[1] * shape[2];
15,477✔
749
    MPI_Datatype result_block;
750
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
15,477✔
751
    MPI_Type_commit(&result_block);
15,477✔
752
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
15,477✔
753
    MPI_Type_free(&result_block);
15,477✔
754
  }
755

756
  // Also broadcast global tally results
757
  auto& gt = simulation::global_tallies;
3,328✔
758
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,328✔
759

760
  // These guys are needed so that non-master processes can calculate the
761
  // combined estimate of k-effective
762
  double temp[] {
763
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,328✔
764
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,328✔
765
  simulation::k_col_abs = temp[0];
3,328✔
766
  simulation::k_col_tra = temp[1];
3,328✔
767
  simulation::k_abs_tra = temp[2];
3,328✔
768
}
3,328✔
769

770
#endif
771

772
void free_memory_simulation()
6,801✔
773
{
774
  simulation::k_generation.clear();
6,801✔
775
  simulation::entropy.clear();
6,801✔
776
}
6,801✔
777

778
void transport_history_based_single_particle(Particle& p)
144,268,227✔
779
{
780
  while (p.alive()) {
2,147,483,647✔
781
    p.event_calculate_xs();
2,147,483,647✔
782
    if (p.alive()) {
2,147,483,647✔
783
      p.event_advance();
2,147,483,647✔
784
    }
785
    if (p.alive()) {
2,147,483,647✔
786
      if (p.collision_distance() > p.boundary().distance) {
2,147,483,647✔
787
        p.event_cross_surface();
1,230,589,755✔
788
      } else if (p.alive()) {
2,147,483,647✔
789
        p.event_collide();
2,147,483,647✔
790
      }
791
    }
792
    p.event_revive_from_secondary();
2,147,483,647✔
793
  }
794
  p.event_death();
144,268,218✔
795
}
144,268,218✔
796

797
void transport_history_based()
90,682✔
798
{
799
#pragma omp parallel for schedule(runtime)
800
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
71,160,632✔
801
    Particle p;
71,118,923✔
802
    initialize_history(p, i_work);
71,118,923✔
803
    transport_history_based_single_particle(p);
71,118,920✔
804
  }
71,118,915✔
805
}
90,674✔
806

807
void transport_event_based()
3,061✔
808
{
809
  int64_t remaining_work = simulation::work_per_rank;
3,061✔
810
  int64_t source_offset = 0;
3,061✔
811

812
  // To cap the total amount of memory used to store particle object data, the
813
  // number of particles in flight at any point in time can bet set. In the case
814
  // that the maximum in flight particle count is lower than the total number
815
  // of particles that need to be run this iteration, the event-based transport
816
  // loop is executed multiple times until all particles have been completed.
817
  while (remaining_work > 0) {
6,122✔
818
    // Figure out # of particles to run for this subiteration
819
    int64_t n_particles =
820
      std::min(remaining_work, settings::max_particles_in_flight);
3,061✔
821

822
    // Initialize all particle histories for this subiteration
823
    process_init_events(n_particles, source_offset);
3,061✔
824

825
    // Event-based transport loop
826
    while (true) {
827
      // Determine which event kernel has the longest queue
828
      int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(),
4,668,760✔
829
        simulation::calculate_nonfuel_xs_queue.size(),
2,334,380✔
830
        simulation::advance_particle_queue.size(),
2,334,380✔
831
        simulation::surface_crossing_queue.size(),
2,334,380✔
832
        simulation::collision_queue.size()});
2,334,380✔
833

834
      // Execute event with the longest queue
835
      if (max == 0) {
2,334,380✔
836
        break;
3,061✔
837
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,331,319✔
838
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
422,577✔
839
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,908,742✔
840
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
351,593✔
841
      } else if (max == simulation::advance_particle_queue.size()) {
1,557,149✔
842
        process_advance_particle_events();
769,336✔
843
      } else if (max == simulation::surface_crossing_queue.size()) {
787,813✔
844
        process_surface_crossing_events();
256,219✔
845
      } else if (max == simulation::collision_queue.size()) {
531,594✔
846
        process_collision_events();
531,594✔
847
      }
848
    }
2,331,319✔
849

850
    // Execute death event for all particles
851
    process_death_events(n_particles);
3,061✔
852

853
    // Adjust remaining work and source offset variables
854
    remaining_work -= n_particles;
3,061✔
855
    source_offset += n_particles;
3,061✔
856
  }
857
}
3,061✔
858

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