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

openmc-dev / openmc / 15371300071

01 Jun 2025 05:04AM UTC coverage: 85.143% (+0.3%) from 84.827%
15371300071

Pull #3176

github

web-flow
Merge 4f739184a into cb95c784b
Pull Request #3176: MeshFilter rotation - solution to issue #3166

86 of 99 new or added lines in 4 files covered. (86.87%)

3707 existing lines in 117 files now uncovered.

52212 of 61323 relevant lines covered (85.14%)

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

65
  int err = 0;
7,004✔
66
  while (status == 0 && err == 0) {
129,137✔
67
    err = openmc_next_batch(&status);
122,151✔
68
  }
69

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

75
int openmc_simulation_init()
8,262✔
76
{
77
  using namespace openmc;
78

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

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

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

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

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

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

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

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

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

139
  // Display header
140
  if (mpi::master) {
8,247✔
141
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
6,876✔
142
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,779✔
143
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
2,359✔
144
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
420✔
145
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
420✔
146
      }
147
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
4,097✔
148
      if (settings::solver_type == SolverType::MONTE_CARLO) {
4,097✔
149
        header("K EIGENVALUE SIMULATION", 3);
3,917✔
150
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
180✔
151
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
180✔
152
      }
153
      if (settings::verbosity >= 7)
4,097✔
154
        print_columns();
3,793✔
155
    }
156
  }
157

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

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

168
int openmc_simulation_finalize()
8,229✔
169
{
170
  using namespace openmc;
171

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

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

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

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

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

193
#ifdef OPENMC_MPI
194
  broadcast_results();
4,623✔
195
#endif
196

197
  // Write tally results to tallies.out
198
  if (settings::output_tallies && mpi::master)
8,229✔
199
    write_tallies();
6,753✔
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) {
8,229✔
204
    openmc_weight_windows_export();
177✔
205
  }
206

207
  // Deactivate all tallies
208
  for (auto& t : model::tallies) {
43,635✔
209
    t->active_ = false;
35,406✔
210
  }
211

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

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

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

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

242
  initialize_batch();
128,331✔
243

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

248
    initialize_generation();
128,639✔
249

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

253
    // Transport loop
254
    if (settings::event_based) {
128,639✔
255
      transport_event_based();
3,066✔
256
    } else {
257
      transport_history_based();
125,573✔
258
    }
259

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

263
    finalize_generation();
128,621✔
264
  }
265

266
  finalize_batch();
128,313✔
267

268
  // Check simulation ending criteria
269
  if (status) {
128,313✔
270
    if (simulation::current_batch >= settings::n_max_batches) {
128,313✔
271
      *status = STATUS_EXIT_MAX_BATCH;
7,317✔
272
    } else if (simulation::satisfy_triggers) {
120,996✔
273
      *status = STATUS_EXIT_ON_TRIGGER;
89✔
274
    } else {
275
      *status = STATUS_EXIT_NORMAL;
120,907✔
276
    }
277
  }
278
  return 0;
128,313✔
279
}
280

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

286
  if (!simulation::initialized)
4,845✔
UNCOV
287
    return false;
×
288
  else
289
    return contains(settings::statepoint_batch, simulation::current_batch);
4,845✔
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()
8,247✔
331
{
332
  if (settings::run_mode == RunMode::EIGENVALUE &&
8,247✔
333
      settings::solver_type == SolverType::MONTE_CARLO) {
5,097✔
334
    // Allocate source bank
335
    simulation::source_bank.resize(simulation::work_per_rank);
4,833✔
336

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

340
    // Allocate IFP bank
341
    if (settings::ifp_on) {
4,833✔
342
      resize_simulation_ifp_banks();
22✔
343
    }
344
  }
345

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

352
void initialize_batch()
151,431✔
353
{
354
  // Increment current batch
355
  ++simulation::current_batch;
151,431✔
356
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
151,431✔
357
    if (settings::solver_type == SolverType::RANDOM_RAY &&
43,109✔
358
        simulation::current_batch < settings::n_inactive + 1) {
18,920✔
359
      write_message(
11,550✔
360
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
361
    } else {
362
      write_message(6, "Simulating batch {}", simulation::current_batch);
31,559✔
363
    }
364
  }
365

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

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

380
  // Manage active/inactive timers and activate tallies if necessary.
381
  if (first_inactive) {
151,431✔
382
    simulation::time_inactive.start();
4,316✔
383
  } else if (first_active) {
147,115✔
384
    simulation::time_inactive.stop();
8,214✔
385
    simulation::time_active.start();
8,214✔
386
    for (auto& t : model::tallies) {
43,590✔
387
      t->active_ = true;
35,376✔
388
    }
389
  }
390

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

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

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

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

413
  // Check_triggers
414
  if (mpi::master)
151,413✔
415
    check_triggers();
121,215✔
416
#ifdef OPENMC_MPI
417
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
87,316✔
418
#endif
419
  if (simulation::satisfy_triggers ||
151,413✔
420
      (settings::trigger_on &&
4,105✔
421
        simulation::current_batch == settings::n_max_batches)) {
4,105✔
422
    settings::statepoint_batch.insert(simulation::current_batch);
200✔
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) &&
160,010✔
428
      !settings::cmfd_run) {
8,597✔
429
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
16,347✔
430
        settings::source_write && !settings::source_separate) {
16,347✔
431
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
7,054✔
432
      openmc_statepoint_write(nullptr, &b);
7,054✔
433
    } else {
434
      bool b = false;
1,271✔
435
      openmc_statepoint_write(nullptr, &b);
1,271✔
436
    }
437
  }
438

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

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

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

462
  // Write out surface source if requested.
463
  if (settings::surf_source_write &&
151,413✔
464
      simulation::ssw_current_file <= settings::ssw_max_files) {
5,200✔
465
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,920✔
466
    if (simulation::surf_source_bank.full() || last_batch) {
1,920✔
467
      // Determine appropriate filename
468
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
469
        simulation::current_batch);
721✔
470
      if (settings::ssw_max_files == 1 ||
833✔
471
          (simulation::ssw_current_file == 1 && last_batch)) {
75✔
472
        filename = settings::path_output + "surface_source";
758✔
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());
833✔
478
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
479
        simulation::surf_source_bank.size());
833✔
480

481
      // Write surface source file
482
      write_source_point(
833✔
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();
833✔
487
      if (!last_batch && settings::ssw_max_files >= 1) {
833✔
488
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
581✔
489
      }
490
      ++simulation::ssw_current_file;
833✔
491
    }
833✔
492
  }
493
}
151,413✔
494

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

501
    // Count source sites if using uniform fission source weighting
502
    if (settings::ufs_on)
108,630✔
503
      ufs_count_sites();
220✔
504

505
    // Store current value of tracklength k
506
    simulation::keff_generation = simulation::global_tallies(
108,630✔
507
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
508
  }
509
}
151,739✔
510

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

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

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

533
  if (settings::run_mode == RunMode::EIGENVALUE &&
151,721✔
534
      settings::solver_type == SolverType::MONTE_CARLO) {
108,630✔
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();
104,450✔
539

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

544
  if (settings::run_mode == RunMode::EIGENVALUE) {
151,721✔
545

546
    // Calculate shannon entropy
547
    if (settings::entropy_on &&
108,630✔
548
        settings::solver_type == SolverType::MONTE_CARLO)
15,245✔
549
      shannon_entropy();
11,065✔
550

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

555
    // Write generation output
556
    if (mpi::master && settings::verbosity >= 7) {
108,630✔
557
      print_generation();
81,585✔
558
    }
559
  }
560
}
151,721✔
561

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

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

583
  // set progeny count to zero
584
  p.n_progeny() = 0;
213,256,219✔
585

586
  // Reset particle event counter
587
  p.n_event() = 0;
213,256,219✔
588

589
  // Reset split counter
590
  p.n_split() = 0;
213,256,219✔
591

592
  // Reset weight window ratio
593
  p.ww_factor() = 0.0;
213,256,219✔
594

595
  // set particle history start weight
596
  p.wgt_born() = p.wgt();
213,256,219✔
597

598
  // Reset pulse_height_storage
599
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
213,256,219✔
600

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

607
  // set particle trace
608
  p.trace() = false;
213,256,219✔
609
  if (simulation::current_batch == settings::trace_batch &&
426,527,438✔
610
      simulation::current_gen == settings::trace_gen &&
213,271,219✔
611
      p.id() == settings::trace_particle)
15,000✔
612
    p.trace() = true;
15✔
613

614
  // Set particle track.
615
  p.write_track() = check_track_criteria(p);
213,256,219✔
616

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

622
// Add particle's starting weight to count for normalizing tallies later
623
#pragma omp atomic
85,550,785✔
624
  simulation::total_weight += p.wgt();
213,256,219✔
625

626
  // Force calculation of cross-sections by setting last energy to zero
627
  if (settings::run_CE) {
213,256,219✔
628
    p.invalidate_neutron_xs();
60,496,219✔
629
  }
630

631
  // Prepare to write out particle track.
632
  if (p.write_track())
213,256,219✔
633
    add_particle_track(p);
1,455✔
634
}
213,256,219✔
635

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

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

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

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

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

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

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

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

694
    if (settings::electron_treatment == ElectronTreatment::TTB) {
340✔
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) {
340✔
698
        int photon = static_cast<int>(ParticleType::photon);
340✔
699
        int n_e = data::ttb_e_grid.size();
340✔
700
        data::energy_min[photon] =
680✔
701
          std::max(data::energy_min[photon], std::exp(data::ttb_e_grid(1)));
340✔
702
        data::energy_max[photon] = std::min(
340✔
703
          data::energy_max[photon], std::exp(data::ttb_e_grid(n_e - 1)));
680✔
704
      }
705
    }
706
  }
707

708
  // Show which nuclide results in lowest energy for neutron transport
709
  for (const auto& nuc : data::nuclides) {
8,311✔
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) {
7,754✔
713
      double max_E = nuc->grid_[0].energy.back();
7,754✔
714
      int neutron = static_cast<int>(ParticleType::neutron);
7,754✔
715
      if (max_E == data::energy_max[neutron]) {
7,754✔
716
        write_message(7, "Maximum neutron transport energy: {} eV for {}",
6,143✔
717
          data::energy_max[neutron], nuc->name_);
6,143✔
718
        if (mpi::master && data::energy_max[neutron] < 20.0e6) {
6,143✔
UNCOV
719
          warning("Maximum neutron energy is below 20 MeV. This may bias "
×
720
                  "the results.");
721
        }
722
        break;
6,143✔
723
      }
724
    }
725
  }
726

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

737
#ifdef OPENMC_MPI
738
void broadcast_results()
4,623✔
739
{
740
  // Broadcast tally results so that each process has access to results
741
  for (auto& t : model::tallies) {
26,315✔
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_;
21,692✔
746

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

756
  // Also broadcast global tally results
757
  auto& gt = simulation::global_tallies;
4,623✔
758
  MPI_Bcast(gt.data(), gt.size(), MPI_DOUBLE, 0, mpi::intracomm);
4,623✔
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};
4,623✔
764
  MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm);
4,623✔
765
  simulation::k_col_abs = temp[0];
4,623✔
766
  simulation::k_col_tra = temp[1];
4,623✔
767
  simulation::k_abs_tra = temp[2];
4,623✔
768
}
4,623✔
769

770
#endif
771

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

778
void transport_history_based_single_particle(Particle& p)
201,207,864✔
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,700,824,785✔
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();
201,207,851✔
795
}
201,207,851✔
796

797
void transport_history_based()
125,573✔
798
{
799
#pragma omp parallel for schedule(runtime)
800
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
127,861,468✔
801
    Particle p;
127,785,252✔
802
    initialize_history(p, i_work);
127,785,252✔
803
    transport_history_based_single_particle(p);
127,785,247✔
804
  }
127,785,238✔
805
}
125,559✔
806

807
void transport_event_based()
3,066✔
808
{
809
  int64_t remaining_work = simulation::work_per_rank;
3,066✔
810
  int64_t source_offset = 0;
3,066✔
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,132✔
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,066✔
821

822
    // Initialize all particle histories for this subiteration
823
    process_init_events(n_particles, source_offset);
3,066✔
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,672,546✔
829
        simulation::calculate_nonfuel_xs_queue.size(),
2,336,273✔
830
        simulation::advance_particle_queue.size(),
2,336,273✔
831
        simulation::surface_crossing_queue.size(),
2,336,273✔
832
        simulation::collision_queue.size()});
2,336,273✔
833

834
      // Execute event with the longest queue
835
      if (max == 0) {
2,336,273✔
836
        break;
3,066✔
837
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,333,207✔
838
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
422,737✔
839
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,910,470✔
840
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
352,079✔
841
      } else if (max == simulation::advance_particle_queue.size()) {
1,558,391✔
842
        process_advance_particle_events();
769,954✔
843
      } else if (max == simulation::surface_crossing_queue.size()) {
788,437✔
844
        process_surface_crossing_events();
256,494✔
845
      } else if (max == simulation::collision_queue.size()) {
531,943✔
846
        process_collision_events();
531,943✔
847
      }
848
    }
2,333,207✔
849

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

853
    // Adjust remaining work and source offset variables
854
    remaining_work -= n_particles;
3,066✔
855
    source_offset += n_particles;
3,066✔
856
  }
857
}
3,066✔
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