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

openmc-dev / openmc / 13341039720

15 Feb 2025 02:46AM UTC coverage: 85.006% (+0.1%) from 84.867%
13341039720

Pull #2655

github

web-flow
Merge 1b7b4ad1e into be4396c12
Pull Request #2655: Raytrace plots

402 of 453 new or added lines in 5 files covered. (88.74%)

1175 existing lines in 53 files now uncovered.

50436 of 59332 relevant lines covered (85.01%)

35668719.75 hits per line

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

98.72
/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/material.h"
11
#include "openmc/mcpl_interface.h"
12
#include "openmc/message_passing.h"
13
#include "openmc/nuclide.h"
14
#include "openmc/output.h"
15
#include "openmc/particle.h"
16
#include "openmc/photon.h"
17
#include "openmc/random_lcg.h"
18
#include "openmc/settings.h"
19
#include "openmc/source.h"
20
#include "openmc/state_point.h"
21
#include "openmc/tallies/derivative.h"
22
#include "openmc/tallies/filter.h"
23
#include "openmc/tallies/tally.h"
24
#include "openmc/tallies/trigger.h"
25
#include "openmc/timer.h"
26
#include "openmc/track_output.h"
27
#include "openmc/weight_windows.h"
28

29
#ifdef _OPENMP
30
#include <omp.h>
31
#endif
32
#include "xtensor/xview.hpp"
33

34
#ifdef OPENMC_MPI
35
#include <mpi.h>
36
#endif
37

38
#include <fmt/format.h>
39

40
#include <algorithm>
41
#include <cmath>
42
#include <string>
43

44
//==============================================================================
45
// C API functions
46
//==============================================================================
47

48
// OPENMC_RUN encompasses all the main logic where iterations are performed
49
// over the batches, generations, and histories in a fixed source or
50
// k-eigenvalue calculation.
51

52
int openmc_run()
5,412 ✔
53
{
54
  openmc::simulation::time_total.start();
5,412 ✔
55
  openmc_simulation_init();
5,412 ✔
56

57
  // Ensure that a batch isn't executed in the case that the maximum number of
58
  // batches has already been run in a restart statepoint file
59
  int status = 0;
5,412 ✔
60
  if (openmc::simulation::current_batch >= openmc::settings::n_max_batches) {
5,412 ✔
61
    status = openmc::STATUS_EXIT_MAX_BATCH;
12 ✔
62
  }
63

64
  int err = 0;
5,412 ✔
65
  while (status == 0 && err == 0) {
90,087 ✔
66
    err = openmc_next_batch(&status);
84,689 ✔
67
  }
68

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

74
int openmc_simulation_init()
6,371 ✔
75
{
76
  using namespace openmc;
77

78
  // Skip if simulation has already been initialized
79
  if (simulation::initialized)
6,371 ✔
80
    return 0;
12 ✔
81

82
  // Initialize nuclear data (energy limits, log grid)
83
  if (settings::run_CE) {
6,359 ✔
84
    initialize_data();
5,383 ✔
85
  }
86

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

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

93
  // Create track file if needed
94
  if (!settings::track_identifiers.empty() || settings::write_all_tracks) {
6,359 ✔
95
    open_track_file();
102 ✔
96
  }
97

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

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

112
  // Set up material nuclide index mapping
113
  for (auto& mat : model::materials) {
27,430 ✔
114
    mat->init_nuclide_index();
21,071 ✔
115
  }
116

117
  // Reset global variables -- this is done before loading state point (as that
118
  // will potentially populate k_generation and entropy)
119
  simulation::current_batch = 0;
6,359 ✔
120
  simulation::ssw_current_file = 1;
6,359 ✔
121
  simulation::k_generation.clear();
6,359 ✔
122
  simulation::entropy.clear();
6,359 ✔
123
  openmc_reset();
6,359 ✔
124

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

138
  // Display header
139
  if (mpi::master) {
6,359 ✔
140
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,469 ✔
141
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,026 ✔
142
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
1,798 ✔
143
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
228 ✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
228 ✔
145
      }
146
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,443 ✔
147
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,443 ✔
148
        header("K EIGENVALUE SIMULATION", 3);
3,371 ✔
149
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
72 ✔
150
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
72 ✔
151
      }
152
      if (settings::verbosity >= 7)
3,443 ✔
153
        print_columns();
3,174 ✔
154
    }
155
  }
156

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

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

167
int openmc_simulation_finalize()
6,345 ✔
168
{
169
  using namespace openmc;
170

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

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

179
  // Clear material nuclide mapping
180
  for (auto& mat : model::materials) {
27,402 ✔
181
    mat->mat_nuclide_index_.clear();
21,057 ✔
182
  }
183

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

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

192
#ifdef OPENMC_MPI
193
  broadcast_results();
3,407 ✔
194
#endif
195

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

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

206
  // Deactivate all tallies
207
  for (auto& t : model::tallies) {
34,048 ✔
208
    t->active_ = false;
27,703 ✔
209
  }
210

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

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

230
int openmc_next_batch(int* status)
94,034 ✔
231
{
232
  using namespace openmc;
233
  using openmc::simulation::current_gen;
234

235
  // Make sure simulation has been initialized
236
  if (!simulation::initialized) {
94,034 ✔
237
    set_errmsg("Simulation has not been initialized yet.");
12 ✔
238
    return OPENMC_E_ALLOCATE;
12 ✔
239
  }
240

241
  initialize_batch();
94,022 ✔
242

243
  // =======================================================================
244
  // LOOP OVER GENERATIONS
245
  for (current_gen = 1; current_gen <= settings::gen_per_batch; ++current_gen) {
188,268 ✔
246

247
    initialize_generation();
94,260 ✔
248

249
    // Start timer for transport
250
    simulation::time_transport.start();
94,260 ✔
251

252
    // Transport loop
253
    if (settings::event_based) {
94,260 ✔
254
      transport_event_based();
3,021 ✔
255
    } else {
256
      transport_history_based();
91,239 ✔
257
    }
258

259
    // Accumulate time for transport
260
    simulation::time_transport.stop();
94,246 ✔
261

262
    finalize_generation();
94,246 ✔
263
  }
264

265
  finalize_batch();
94,008 ✔
266

267
  // Check simulation ending criteria
268
  if (status) {
94,008 ✔
269
    if (simulation::current_batch >= settings::n_max_batches) {
94,008 ✔
270
      *status = STATUS_EXIT_MAX_BATCH;
5,895 ✔
271
    } else if (simulation::satisfy_triggers) {
88,113 ✔
272
      *status = STATUS_EXIT_ON_TRIGGER;
70 ✔
273
    } else {
274
      *status = STATUS_EXIT_NORMAL;
88,043 ✔
275
    }
276
  }
277
  return 0;
94,008 ✔
278
}
279

280
bool openmc_is_statepoint_batch()
8,265 ✔
281
{
282
  using namespace openmc;
283
  using openmc::simulation::current_gen;
284

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

291
namespace openmc {
292

293
//==============================================================================
294
// Global variables
295
//==============================================================================
296

297
namespace simulation {
298

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

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

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

323
} // namespace simulation
324

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

329
void allocate_banks()
6,359 ✔
330
{
331
  if (settings::run_mode == RunMode::EIGENVALUE &&
6,359 ✔
332
      settings::solver_type == SolverType::MONTE_CARLO) {
4,114 ✔
333
    // Allocate source bank
334
    simulation::source_bank.resize(simulation::work_per_rank);
4,012 ✔
335

336
    // Allocate fission bank
337
    init_fission_bank(3 * simulation::work_per_rank);
4,012 ✔
338
  }
339

340
  if (settings::surf_source_write) {
6,359 ✔
341
    // Allocate surface source bank
342
    simulation::surf_source_bank.reserve(settings::ssw_max_particles);
629 ✔
343
  }
344
}
6,359 ✔
345

346
void initialize_batch()
105,752 ✔
347
{
348
  // Increment current batch
349
  ++simulation::current_batch;
105,752 ✔
350
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
105,752 ✔
351
    if (settings::solver_type == SolverType::RANDOM_RAY &&
24,867 ✔
352
        simulation::current_batch < settings::n_inactive + 1) {
9,690 ✔
353
      write_message(
6,120 ✔
354
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
355
    } else {
356
      write_message(6, "Simulating batch {}", simulation::current_batch);
18,747 ✔
357
    }
358
  }
359

360
  // Reset total starting particle weight used for normalizing tallies
361
  simulation::total_weight = 0.0;
105,752 ✔
362

363
  // Determine if this batch is the first inactive or active batch.
364
  bool first_inactive = false;
105,752 ✔
365
  bool first_active = false;
105,752 ✔
366
  if (!settings::restart_run) {
105,752 ✔
367
    first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1;
105,418 ✔
368
    first_active = simulation::current_batch == settings::n_inactive + 1;
105,418 ✔
369
  } else if (simulation::current_batch == simulation::restart_batch + 1) {
334 ✔
370
    first_inactive = simulation::restart_batch < settings::n_inactive;
75 ✔
371
    first_active = !first_inactive;
75 ✔
372
  }
373

374
  // Manage active/inactive timers and activate tallies if necessary.
375
  if (first_inactive) {
105,752 ✔
376
    simulation::time_inactive.start();
3,258 ✔
377
  } else if (first_active) {
102,494 ✔
378
    simulation::time_inactive.stop();
6,332 ✔
379
    simulation::time_active.start();
6,332 ✔
380
    for (auto& t : model::tallies) {
34,011 ✔
381
      t->active_ = true;
27,679 ✔
382
    }
383
  }
384

385
  // Add user tallies to active tallies list
386
  setup_active_tallies();
105,752 ✔
387
}
105,752 ✔
388

389
void finalize_batch()
105,738 ✔
390
{
391
  // Reduce tallies onto master process and accumulate
392
  simulation::time_tallies.start();
105,738 ✔
393
  accumulate_tallies();
105,738 ✔
394
  simulation::time_tallies.stop();
105,738 ✔
395

396
  // update weight windows if needed
397
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
106,258 ✔
398
    wwg->update();
520 ✔
399
  }
400

401
  // Reset global tally results
402
  if (simulation::current_batch <= settings::n_inactive) {
105,738 ✔
403
    xt::view(simulation::global_tallies, xt::all()) = 0.0;
22,529 ✔
404
    simulation::n_realizations = 0;
22,529 ✔
405
  }
406

407
  // Check_triggers
408
  if (mpi::master)
105,738 ✔
409
    check_triggers();
86,143 ✔
410
#ifdef OPENMC_MPI
411
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
59,154 ✔
412
#endif
413
  if (simulation::satisfy_triggers ||
105,738 ✔
414
      (settings::trigger_on &&
3,224 ✔
415
        simulation::current_batch == settings::n_max_batches)) {
3,224 ✔
416
    settings::statepoint_batch.insert(simulation::current_batch);
157 ✔
417
  }
418

419
  // Write out state point if it's been specified for this batch and is not
420
  // a CMFD run instance
421
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
112,385 ✔
422
      !settings::cmfd_run) {
6,647 ✔
423
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
12,129 ✔
424
        settings::source_write && !settings::source_separate) {
12,129 ✔
425
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
5,453 ✔
426
      openmc_statepoint_write(nullptr, &b);
5,453 ✔
427
    } else {
428
      bool b = false;
730 ✔
429
      openmc_statepoint_write(nullptr, &b);
730 ✔
430
    }
431
  }
432

433
  if (settings::run_mode == RunMode::EIGENVALUE) {
105,738 ✔
434
    // Write out a separate source point if it's been specified for this batch
435
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
85,079 ✔
436
        settings::source_write && settings::source_separate) {
85,079 ✔
437

438
      // Determine width for zero padding
439
      int w = std::to_string(settings::n_max_batches).size();
68 ✔
440
      std::string source_point_filename = fmt::format("{0}source.{1:0{2}}",
441
        settings::path_output, simulation::current_batch, w);
56 ✔
442
      gsl::span<SourceSite> bankspan(simulation::source_bank);
68 ✔
443
      write_source_point(source_point_filename, bankspan,
68 ✔
444
        simulation::work_index, settings::source_mcpl_write);
445
    }
68 ✔
446

447
    // Write a continously-overwritten source point if requested.
448
    if (settings::source_latest) {
80,885 ✔
449
      auto filename = settings::path_output + "source";
170 ✔
450
      gsl::span<SourceSite> bankspan(simulation::source_bank);
170 ✔
451
      write_source_point(filename, bankspan, simulation::work_index,
170 ✔
452
        settings::source_mcpl_write);
453
    }
170 ✔
454
  }
455

456
  // Write out surface source if requested.
457
  if (settings::surf_source_write &&
105,738 ✔
458
      simulation::ssw_current_file <= settings::ssw_max_files) {
4,153 ✔
459
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,530 ✔
460
    if (simulation::surf_source_bank.full() || last_batch) {
1,530 ✔
461
      // Determine appropriate filename
462
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
463
        simulation::current_batch);
553 ✔
464
      if (settings::ssw_max_files == 1 ||
665 ✔
465
          (simulation::ssw_current_file == 1 && last_batch)) {
60 ✔
466
        filename = settings::path_output + "surface_source";
605 ✔
467
      }
468

469
      // Get span of source bank and calculate parallel index vector
470
      auto surf_work_index = mpi::calculate_parallel_index_vector(
471
        simulation::surf_source_bank.size());
665 ✔
472
      gsl::span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
473
        simulation::surf_source_bank.size());
665 ✔
474

475
      // Write surface source file
476
      write_source_point(
665 ✔
477
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
478

479
      // Reset surface source bank and increment counter
480
      simulation::surf_source_bank.clear();
665 ✔
481
      if (!last_batch && settings::ssw_max_files >= 1) {
665 ✔
482
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
464 ✔
483
      }
484
      ++simulation::ssw_current_file;
665 ✔
485
    }
665 ✔
486
  }
487
}
105,738 ✔
488

489
void initialize_generation()
105,990 ✔
490
{
491
  if (settings::run_mode == RunMode::EIGENVALUE) {
105,990 ✔
492
    // Clear out the fission bank
493
    simulation::fission_bank.resize(0);
81,123 ✔
494

495
    // Count source sites if using uniform fission source weighting
496
    if (settings::ufs_on)
81,123 ✔
497
      ufs_count_sites();
170 ✔
498

499
    // Store current value of tracklength k
500
    simulation::keff_generation = simulation::global_tallies(
81,123 ✔
501
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
502
  }
503
}
105,990 ✔
504

505
void finalize_generation()
105,976 ✔
506
{
507
  auto& gt = simulation::global_tallies;
105,976 ✔
508

509
  // Update global tallies with the accumulation variables
510
  if (settings::run_mode == RunMode::EIGENVALUE) {
105,976 ✔
511
    gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision;
81,123 ✔
512
    gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) +=
81,123 ✔
513
      global_tally_absorption;
514
    gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) +=
81,123 ✔
515
      global_tally_tracklength;
516
  }
517
  gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage;
105,976 ✔
518

519
  // reset tallies
520
  if (settings::run_mode == RunMode::EIGENVALUE) {
105,976 ✔
521
    global_tally_collision = 0.0;
81,123 ✔
522
    global_tally_absorption = 0.0;
81,123 ✔
523
    global_tally_tracklength = 0.0;
81,123 ✔
524
  }
525
  global_tally_leakage = 0.0;
105,976 ✔
526

527
  if (settings::run_mode == RunMode::EIGENVALUE &&
105,976 ✔
528
      settings::solver_type == SolverType::MONTE_CARLO) {
81,123 ✔
529
    // If using shared memory, stable sort the fission bank (by parent IDs)
530
    // so as to allow for reproducibility regardless of which order particles
531
    // are run in.
532
    sort_fission_bank();
79,083 ✔
533

534
    // Distribute fission bank across processors evenly
535
    synchronize_bank();
79,083 ✔
536
  }
537

538
  if (settings::run_mode == RunMode::EIGENVALUE) {
105,976 ✔
539

540
    // Calculate shannon entropy
541
    if (settings::entropy_on &&
81,123 ✔
542
        settings::solver_type == SolverType::MONTE_CARLO)
15,275 ✔
543
      shannon_entropy();
13,235 ✔
544

545
    // Collect results and statistics
546
    calculate_generation_keff();
81,123 ✔
547
    calculate_average_keff();
81,123 ✔
548

549
    // Write generation output
550
    if (mpi::master && settings::verbosity >= 7) {
81,123 ✔
551
      print_generation();
61,727 ✔
552
    }
553
  }
554
}
105,976 ✔
555

556
void initialize_history(Particle& p, int64_t index_source)
163,205,994 ✔
557
{
558
  // set defaults
559
  if (settings::run_mode == RunMode::EIGENVALUE) {
163,205,994 ✔
560
    // set defaults for eigenvalue simulations from primary bank
561
    p.from_source(&simulation::source_bank[index_source - 1]);
149,450,600 ✔
562
  } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
13,755,394 ✔
563
    // initialize random number seed
564
    int64_t id = (simulation::total_gen + overall_generation() - 1) *
13,755,394 ✔
565
                   settings::n_particles +
13,755,394 ✔
566
                 simulation::work_index[mpi::rank] + index_source;
13,755,394 ✔
567
    uint64_t seed = init_seed(id, STREAM_SOURCE);
13,755,394 ✔
568
    // sample from external source distribution or custom library then set
569
    auto site = sample_external_source(&seed);
13,755,394 ✔
570
    p.from_source(&site);
13,755,390 ✔
571
  }
572
  p.current_work() = index_source;
163,205,990 ✔
573

574
  // set identifier for particle
575
  p.id() = simulation::work_index[mpi::rank] + index_source;
163,205,990 ✔
576

577
  // set progeny count to zero
578
  p.n_progeny() = 0;
163,205,990 ✔
579

580
  // Reset particle event counter
581
  p.n_event() = 0;
163,205,990 ✔
582

583
  // Reset split counter
584
  p.n_split() = 0;
163,205,990 ✔
585

586
  // Reset weight window ratio
587
  p.ww_factor() = 0.0;
163,205,990 ✔
588

589
  // Reset pulse_height_storage
590
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
163,205,990 ✔
591

592
  // set random number seed
593
  int64_t particle_seed =
594
    (simulation::total_gen + overall_generation() - 1) * settings::n_particles +
163,205,990 ✔
595
    p.id();
163,205,990 ✔
596
  init_particle_seeds(particle_seed, p.seeds());
163,205,990 ✔
597

598
  // set particle trace
599
  p.trace() = false;
163,205,990 ✔
600
  if (simulation::current_batch == settings::trace_batch &&
326,423,980 ✔
601
      simulation::current_gen == settings::trace_gen &&
163,217,990 ✔
602
      p.id() == settings::trace_particle)
12,000 ✔
603
    p.trace() = true;
12 ✔
604

605
  // Set particle track.
606
  p.write_track() = check_track_criteria(p);
163,205,990 ✔
607

608
  // Display message if high verbosity or trace is on
609
  if (settings::verbosity >= 9 || p.trace()) {
163,205,990 ✔
610
    write_message("Simulating Particle {}", p.id());
12 ✔
611
  }
612

613
// Add paricle's starting weight to count for normalizing tallies later
614
#pragma omp atomic
81,712,392 ✔
615
  simulation::total_weight += p.wgt();
163,205,990 ✔
616

617
  // Force calculation of cross-sections by setting last energy to zero
618
  if (settings::run_CE) {
163,205,990 ✔
619
    p.invalidate_neutron_xs();
40,997,990 ✔
620
  }
621

622
  // Prepare to write out particle track.
623
  if (p.write_track())
163,205,990 ✔
624
    add_particle_track(p);
1,128 ✔
625
}
163,205,990 ✔
626

627
int overall_generation()
177,183,598 ✔
628
{
629
  using namespace simulation;
630
  return settings::gen_per_batch * (current_batch - 1) + current_gen;
177,183,598 ✔
631
}
632

633
void calculate_work()
6,359 ✔
634
{
635
  // Determine minimum amount of particles to simulate on each processor
636
  int64_t min_work = settings::n_particles / mpi::n_procs;
6,359 ✔
637

638
  // Determine number of processors that have one extra particle
639
  int64_t remainder = settings::n_particles % mpi::n_procs;
6,359 ✔
640

641
  int64_t i_bank = 0;
6,359 ✔
642
  simulation::work_index.resize(mpi::n_procs + 1);
6,359 ✔
643
  simulation::work_index[0] = 0;
6,359 ✔
644
  for (int i = 0; i < mpi::n_procs; ++i) {
14,497 ✔
645
    // Number of particles for rank i
646
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
8,138 ✔
647

648
    // Set number of particles
649
    if (mpi::rank == i)
8,138 ✔
650
      simulation::work_per_rank = work_i;
6,359 ✔
651

652
    // Set index into source bank for rank i
653
    i_bank += work_i;
8,138 ✔
654
    simulation::work_index[i + 1] = i_bank;
8,138 ✔
655
  }
656
}
6,359 ✔
657

658
void initialize_data()
5,419 ✔
659
{
660
  // Determine minimum/maximum energy for incident neutron/photon data
661
  data::energy_max = {INFTY, INFTY};
5,419 ✔
662
  data::energy_min = {0.0, 0.0};
5,419 ✔
663
  for (const auto& nuc : data::nuclides) {
36,480 ✔
664
    if (nuc->grid_.size() >= 1) {
31,061 ✔
665
      int neutron = static_cast<int>(ParticleType::neutron);
31,061 ✔
666
      data::energy_min[neutron] =
62,122 ✔
667
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
31,061 ✔
668
      data::energy_max[neutron] =
31,061 ✔
669
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
31,061 ✔
670
    }
671
  }
672

673
  if (settings::photon_transport) {
5,419 ✔
674
    for (const auto& elem : data::elements) {
817 ✔
675
      if (elem->energy_.size() >= 1) {
563 ✔
676
        int photon = static_cast<int>(ParticleType::photon);
563 ✔
677
        int n = elem->energy_.size();
563 ✔
678
        data::energy_min[photon] =
1,126 ✔
679
          std::max(data::energy_min[photon], std::exp(elem->energy_(1)));
563 ✔
680
        data::energy_max[photon] =
1,126 ✔
681
          std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1)));
563 ✔
682
      }
683
    }
684

685
    if (settings::electron_treatment == ElectronTreatment::TTB) {
254 ✔
686
      // Determine if minimum/maximum energy for bremsstrahlung is greater/less
687
      // than the current minimum/maximum
688
      if (data::ttb_e_grid.size() >= 1) {
254 ✔
689
        int photon = static_cast<int>(ParticleType::photon);
254 ✔
690
        int n_e = data::ttb_e_grid.size();
254 ✔
691
        data::energy_min[photon] =
508 ✔
692
          std::max(data::energy_min[photon], std::exp(data::ttb_e_grid(1)));
254 ✔
693
        data::energy_max[photon] = std::min(
254 ✔
694
          data::energy_max[photon], std::exp(data::ttb_e_grid(n_e - 1)));
508 ✔
695
      }
696
    }
697
  }
698

699
  // Show which nuclide results in lowest energy for neutron transport
700
  for (const auto& nuc : data::nuclides) {
6,691 ✔
701
    // If a nuclide is present in a material that's not used in the model, its
702
    // grid has not been allocated
703
    if (nuc->grid_.size() > 0) {
6,246 ✔
704
      double max_E = nuc->grid_[0].energy.back();
6,246 ✔
705
      int neutron = static_cast<int>(ParticleType::neutron);
6,246 ✔
706
      if (max_E == data::energy_max[neutron]) {
6,246 ✔
707
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
4,974 ✔
708
          data::energy_max[neutron], nuc->name_);
4,974 ✔
709
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
4,974 ✔
UNCOV
710
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
711
                  "the results.");
712
        }
713
        break;
4,974 ✔
714
      }
715
    }
716
  }
717

718
  // Set up logarithmic grid for nuclides
719
  for (auto& nuc : data::nuclides) {
36,480 ✔
720
    nuc->init_grid();
31,061 ✔
721
  }
722
  int neutron = static_cast<int>(ParticleType::neutron);
5,419 ✔
723
  simulation::log_spacing =
5,419 ✔
724
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
5,419 ✔
725
    settings::n_log_bins;
726
}
5,419 ✔
727

728
#ifdef OPENMC_MPI
729
void broadcast_results()
3,407 ✔
730
{
731
  // Broadcast tally results so that each process has access to results
732
  for (auto& t : model::tallies) {
19,633 ✔
733
    // Create a new datatype that consists of all values for a given filter
734
    // bin and then use that to broadcast. This is done to minimize the
735
    // chance of the 'count' argument of MPI_BCAST exceeding 2**31
736
    auto& results = t->results_;
16,226 ✔
737

738
    auto shape = results.shape();
16,226 ✔
739
    int count_per_filter = shape[1] * shape[2];
16,226 ✔
740
    MPI_Datatype result_block;
741
    MPI_Type_contiguous(count_per_filter, MPI_DOUBLE, &result_block);
16,226 ✔
742
    MPI_Type_commit(&result_block);
16,226 ✔
743
    MPI_Bcast(results.data(), shape[0], result_block, 0, mpi::intracomm);
16,226 ✔
744
    MPI_Type_free(&result_block);
16,226 ✔
745
  }
746

747
  // Also broadcast global tally results
748
  auto& gt = simulation::global_tallies;
3,407 ✔
749
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
3,407 ✔
750

751
  // These guys are needed so that non-master processes can calculate the
752
  // combined estimate of k-effective
753
  double temp[] {
754
    simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra};
3,407 ✔
755
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
3,407 ✔
756
  simulation::k_col_abs = temp[0];
3,407 ✔
757
  simulation::k_col_tra = temp[1];
3,407 ✔
758
  simulation::k_abs_tra = temp[2];
3,407 ✔
759
}
3,407 ✔
760

761
#endif
762

763
void free_memory_simulation()
7,055 ✔
764
{
765
  simulation::k_generation.clear();
7,055 ✔
766
  simulation::entropy.clear();
7,055 ✔
767
}
7,055 ✔
768

769
void transport_history_based_single_particle(Particle& p)
152,192,626 ✔
770
{
771
  while (p.alive()) {
2,147,483,647 ✔
772
    p.event_calculate_xs();
2,147,483,647 ✔
773
    if (p.alive()) {
2,147,483,647 ✔
774
      p.event_advance();
2,147,483,647 ✔
775
    }
776
    if (p.alive()) {
2,147,483,647 ✔
777
      if (p.collision_distance() > p.boundary().distance) {
2,147,483,647 ✔
778
        p.event_cross_surface();
1,455,663,218 ✔
779
      } else if (p.alive()) {
2,147,483,647 ✔
780
        p.event_collide();
2,147,483,647 ✔
781
      }
782
    }
783
    p.event_revive_from_secondary();
2,147,483,647 ✔
784
  }
785
  p.event_death();
152,192,616 ✔
786
}
152,192,616 ✔
787

788
void transport_history_based()
91,239 ✔
789
{
790
#pragma omp parallel for schedule(runtime)
791
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
81,629,061 ✔
792
    Particle p;
81,584,262 ✔
793
    initialize_history(p, i_work);
81,584,262 ✔
794
    transport_history_based_single_particle(p);
81,584,258 ✔
795
  }
81,584,252 ✔
796
}
91,229 ✔
797

798
void transport_event_based()
3,021 ✔
799
{
800
  int64_t remaining_work = simulation::work_per_rank;
3,021 ✔
801
  int64_t source_offset = 0;
3,021 ✔
802

803
  // To cap the total amount of memory used to store particle object data, the
804
  // number of particles in flight at any point in time can bet set. In the case
805
  // that the maximum in flight particle count is lower than the total number
806
  // of particles that need to be run this iteration, the event-based transport
807
  // loop is executed multiple times until all particles have been completed.
808
  while (remaining_work > 0) {
6,042 ✔
809
    // Figure out # of particles to run for this subiteration
810
    int64_t n_particles =
811
      std::min(remaining_work, settings::max_particles_in_flight);
3,021 ✔
812

813
    // Initialize all particle histories for this subiteration
814
    process_init_events(n_particles, source_offset);
3,021 ✔
815

816
    // Event-based transport loop
817
    while (true) {
818
      // Determine which event kernel has the longest queue
819
      int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(),
4,733,276 ✔
820
        simulation::calculate_nonfuel_xs_queue.size(),
2,366,638 ✔
821
        simulation::advance_particle_queue.size(),
2,366,638 ✔
822
        simulation::surface_crossing_queue.size(),
2,366,638 ✔
823
        simulation::collision_queue.size()});
2,366,638 ✔
824

825
      // Execute event with the longest queue
826
      if (max == 0) {
2,366,638 ✔
827
        break;
3,021 ✔
828
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,363,617 ✔
829
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
422,129 ✔
830
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,941,488 ✔
831
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
362,878 ✔
832
      } else if (max == simulation::advance_particle_queue.size()) {
1,578,610 ✔
833
        process_advance_particle_events();
780,156 ✔
834
      } else if (max == simulation::surface_crossing_queue.size()) {
798,454 ✔
835
        process_surface_crossing_events();
255,969 ✔
836
      } else if (max == simulation::collision_queue.size()) {
542,485 ✔
837
        process_collision_events();
542,485 ✔
838
      }
839
    }
2,363,617 ✔
840

841
    // Execute death event for all particles
842
    process_death_events(n_particles);
3,021 ✔
843

844
    // Adjust remaining work and source offset variables
845
    remaining_work -= n_particles;
3,021 ✔
846
    source_offset += n_particles;
3,021 ✔
847
  }
848
}
3,021 ✔
849

850
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc