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

openmc-dev / openmc / 20278909785

16 Dec 2025 06:41PM UTC coverage: 81.834% (-0.09%) from 81.92%
20278909785

Pull #3493

github

web-flow
Merge 9dc7c7a58 into bbfa18d72
Pull Request #3493: Implement vector fitting to replace external `vectfit` package

17020 of 23572 branches covered (72.2%)

Branch coverage included in aggregate %.

188 of 207 new or added lines in 3 files covered. (90.82%)

3101 existing lines in 56 files now uncovered.

54979 of 64410 relevant lines covered (85.36%)

41388074.54 hits per line

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

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

3
#include "openmc/bank.h"
4
#include "openmc/capi.h"
5
#include "openmc/collision_track.h"
6
#include "openmc/container_util.h"
7
#include "openmc/eigenvalue.h"
8
#include "openmc/error.h"
9
#include "openmc/event.h"
10
#include "openmc/geometry_aux.h"
11
#include "openmc/ifp.h"
12
#include "openmc/material.h"
13
#include "openmc/message_passing.h"
14
#include "openmc/nuclide.h"
15
#include "openmc/output.h"
16
#include "openmc/particle.h"
17
#include "openmc/photon.h"
18
#include "openmc/random_lcg.h"
19
#include "openmc/settings.h"
20
#include "openmc/source.h"
21
#include "openmc/state_point.h"
22
#include "openmc/tallies/derivative.h"
23
#include "openmc/tallies/filter.h"
24
#include "openmc/tallies/tally.h"
25
#include "openmc/tallies/trigger.h"
26
#include "openmc/timer.h"
27
#include "openmc/track_output.h"
28
#include "openmc/weight_windows.h"
29

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

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

39
#include <fmt/format.h>
40

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

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

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

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

65
  int err = 0;
5,232✔
66
  while (status == 0 && err == 0) {
103,160!
67
    err = openmc_next_batch(&status);
97,940✔
68
  }
69

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

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

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

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

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

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

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

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

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

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

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

140
  // Display header
141
  if (mpi::master) {
6,107✔
142
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,235✔
143
      if (settings::solver_type == SolverType::MONTE_CARLO) {
2,194✔
144
        header("FIXED SOURCE TRANSPORT SIMULATION", 3);
1,902✔
145
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
292!
146
        header("FIXED SOURCE TRANSPORT SIMULATION (RANDOM RAY SOLVER)", 3);
292✔
147
      }
148
    } else if (settings::run_mode == RunMode::EIGENVALUE) {
3,041!
149
      if (settings::solver_type == SolverType::MONTE_CARLO) {
3,041✔
150
        header("K EIGENVALUE SIMULATION", 3);
2,881✔
151
      } else if (settings::solver_type == SolverType::RANDOM_RAY) {
160!
152
        header("K EIGENVALUE SIMULATION (RANDOM RAY SOLVER)", 3);
160✔
153
      }
154
      if (settings::verbosity >= 7)
3,041✔
155
        print_columns();
2,857✔
156
    }
157
  }
158

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

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

169
int openmc_simulation_finalize()
6,095✔
170
{
171
  using namespace openmc;
172

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

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

181
  // Clear material nuclide mapping
182
  for (auto& mat : model::materials) {
22,186✔
183
    mat->mat_nuclide_index_.clear();
16,091✔
184
  }
185

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

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

194
#ifdef OPENMC_MPI
195
  broadcast_results();
2,980✔
196
#endif
197

198
  // Write tally results to tallies.out
199
  if (settings::output_tallies && mpi::master)
6,095!
200
    write_tallies();
5,059✔
201

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

208
  // Deactivate all tallies
209
  for (auto& t : model::tallies) {
29,584✔
210
    t->active_ = false;
23,489✔
211
  }
212

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

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

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

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

243
  initialize_batch();
101,680✔
244

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

249
    initialize_generation();
101,876✔
250

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

254
    // Transport loop
255
    if (settings::event_based) {
101,876✔
256
      transport_event_based();
3,145✔
257
    } else {
258
      transport_history_based();
98,731✔
259
    }
260

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

264
    finalize_generation();
101,864✔
265
  }
266

267
  finalize_batch();
101,668✔
268

269
  // Check simulation ending criteria
270
  if (status) {
101,668!
271
    if (simulation::current_batch >= settings::n_max_batches) {
101,668✔
272
      *status = STATUS_EXIT_MAX_BATCH;
5,394✔
273
    } else if (simulation::satisfy_triggers) {
96,274✔
274
      *status = STATUS_EXIT_ON_TRIGGER;
86✔
275
    } else {
276
      *status = STATUS_EXIT_NORMAL;
96,188✔
277
    }
278
  }
279
  return 0;
101,668✔
280
}
281

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

287
  if (!simulation::initialized)
2,850!
UNCOV
288
    return false;
×
289
  else
290
    return contains(settings::statepoint_batch, simulation::current_batch);
2,850✔
291
}
292

293
namespace openmc {
294

295
//==============================================================================
296
// Global variables
297
//==============================================================================
298

299
namespace simulation {
300

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

320
const RegularMesh* entropy_mesh {nullptr};
321
const RegularMesh* ufs_mesh {nullptr};
322

323
vector<double> k_generation;
324
vector<int64_t> work_index;
325

326
} // namespace simulation
327

328
//==============================================================================
329
// Non-member functions
330
//==============================================================================
331

332
void allocate_banks()
6,107✔
333
{
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
6,107✔
335
      settings::solver_type == SolverType::MONTE_CARLO) {
3,675✔
336
    // Allocate source bank
337
    simulation::source_bank.resize(simulation::work_per_rank);
3,451✔
338

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

342
    // Allocate IFP bank
343
    if (settings::ifp_on) {
3,451✔
344
      resize_simulation_ifp_banks();
68✔
345
    }
346
  }
347

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

353
  if (settings::collision_track) {
6,107✔
354
    // Allocate collision track bank
355
    collision_track_reserve_bank();
137✔
356
  }
357
}
6,107✔
358

359
void initialize_batch()
117,092✔
360
{
361
  // Increment current batch
362
  ++simulation::current_batch;
117,092✔
363
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
117,092✔
364
    if (settings::solver_type == SolverType::RANDOM_RAY &&
41,925✔
365
        simulation::current_batch < settings::n_inactive + 1) {
12,192✔
366
      write_message(
7,426✔
367
        6, "Simulating batch {:<4} (inactive)", simulation::current_batch);
368
    } else {
369
      write_message(6, "Simulating batch {}", simulation::current_batch);
34,499✔
370
    }
371
  }
372

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

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

387
  // Manage active/inactive timers and activate tallies if necessary.
388
  if (first_inactive) {
117,092✔
389
    simulation::time_inactive.start();
3,115✔
390
  } else if (first_active) {
113,977✔
391
    simulation::time_inactive.stop();
6,063✔
392
    simulation::time_active.start();
6,063✔
393
    for (auto& t : model::tallies) {
29,532✔
394
      t->active_ = true;
23,469✔
395
    }
396
  }
397

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

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

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

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

420
  // Check_triggers
421
  if (mpi::master)
117,080✔
422
    check_triggers();
99,193✔
423
#ifdef OPENMC_MPI
424
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
57,754✔
425
#endif
426
  if (simulation::satisfy_triggers ||
117,080✔
427
      (settings::trigger_on &&
2,362✔
428
        simulation::current_batch == settings::n_max_batches)) {
2,362✔
429
    settings::statepoint_batch.insert(simulation::current_batch);
130✔
430
  }
431

432
  // Write out state point if it's been specified for this batch and is not
433
  // a CMFD run instance
434
  if (contains(settings::statepoint_batch, simulation::current_batch) &&
123,382✔
435
      !settings::cmfd_run) {
6,302✔
436
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
12,088✔
437
        settings::source_write && !settings::source_separate) {
12,088✔
438
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
5,248✔
439
      openmc_statepoint_write(nullptr, &b);
5,248✔
440
    } else {
441
      bool b = false;
894✔
442
      openmc_statepoint_write(nullptr, &b);
894✔
443
    }
444
  }
445

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

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

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

469
  // Write out surface source if requested.
470
  if (settings::surf_source_write &&
117,080✔
471
      simulation::ssw_current_file <= settings::ssw_max_files) {
8,445✔
472
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,632✔
473
    if (simulation::surf_source_bank.full() || last_batch) {
1,632✔
474
      // Determine appropriate filename
475
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
476
        simulation::current_batch);
733✔
477
      if (settings::ssw_max_files == 1 ||
917✔
478
          (simulation::ssw_current_file == 1 && last_batch)) {
50!
479
        filename = settings::path_output + "surface_source";
867✔
480
      }
481

482
      // Get span of source bank and calculate parallel index vector
483
      auto surf_work_index = mpi::calculate_parallel_index_vector(
484
        simulation::surf_source_bank.size());
917✔
485
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
486
        simulation::surf_source_bank.size());
917✔
487

488
      // Write surface source file
489
      write_source_point(
917✔
490
        filename, surfbankspan, surf_work_index, settings::surf_mcpl_write);
491

492
      // Reset surface source bank and increment counter
493
      simulation::surf_source_bank.clear();
917✔
494
      if (!last_batch && settings::ssw_max_files >= 1) {
917!
495
        simulation::surf_source_bank.reserve(settings::ssw_max_particles);
752✔
496
      }
497
      ++simulation::ssw_current_file;
917✔
498
    }
917✔
499
  }
500
  // Write collision track file if requested
501
  if (settings::collision_track) {
117,080✔
502
    collision_track_flush_bank();
565✔
503
  }
504
}
117,080✔
505

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

512
    // Count source sites if using uniform fission source weighting
513
    if (settings::ufs_on)
75,363✔
514
      ufs_count_sites();
140✔
515

516
    // Store current value of tracklength k
517
    simulation::keff_generation = simulation::global_tallies(
75,363✔
518
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
519
  }
520
}
117,288✔
521

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

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

536
  // reset tallies
537
  if (settings::run_mode == RunMode::EIGENVALUE) {
117,276✔
538
    global_tally_collision = 0.0;
75,362✔
539
    global_tally_absorption = 0.0;
75,362✔
540
    global_tally_tracklength = 0.0;
75,362✔
541
  }
542
  global_tally_leakage = 0.0;
117,276✔
543

544
  if (settings::run_mode == RunMode::EIGENVALUE &&
117,276✔
545
      settings::solver_type == SolverType::MONTE_CARLO) {
75,362✔
546
    // If using shared memory, stable sort the fission bank (by parent IDs)
547
    // so as to allow for reproducibility regardless of which order particles
548
    // are run in.
549
    sort_fission_bank();
72,142✔
550

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

555
  if (settings::run_mode == RunMode::EIGENVALUE) {
117,276✔
556

557
    // Calculate shannon entropy
558
    if (settings::entropy_on &&
75,362✔
559
        settings::solver_type == SolverType::MONTE_CARLO)
10,210✔
560
      shannon_entropy();
6,990✔
561

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

566
    // Write generation output
567
    if (mpi::master && settings::verbosity >= 7) {
75,362✔
568
      print_generation();
59,395✔
569
    }
570
  }
571
}
117,276✔
572

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

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

594
  // set progeny count to zero
595
  p.n_progeny() = 0;
150,438,022✔
596

597
  // Reset particle event counter
598
  p.n_event() = 0;
150,438,022✔
599

600
  // Reset split counter
601
  p.n_split() = 0;
150,438,022✔
602

603
  // Reset weight window ratio
604
  p.ww_factor() = 0.0;
150,438,022✔
605

606
  // set particle history start weight
607
  p.wgt_born() = p.wgt();
150,438,022✔
608

609
  // Reset pulse_height_storage
610
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
150,438,022✔
611

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

618
  // set particle trace
619
  p.trace() = false;
150,438,022✔
620
  if (simulation::current_batch == settings::trace_batch &&
300,886,044✔
621
      simulation::current_gen == settings::trace_gen &&
150,448,022!
622
      p.id() == settings::trace_particle)
10,000✔
623
    p.trace() = true;
10✔
624

625
  // Set particle track.
626
  p.write_track() = check_track_criteria(p);
150,438,022✔
627

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

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

637
// Add particle's starting weight to count for normalizing tallies later
638
#pragma omp atomic
90,503,877✔
639
  simulation::total_weight += p.wgt();
150,438,022✔
640

641
  // Force calculation of cross-sections by setting last energy to zero
642
  if (settings::run_CE) {
150,438,022✔
643
    p.invalidate_neutron_xs();
48,598,022✔
644
  }
645

646
  // Prepare to write out particle track.
647
  if (p.write_track())
150,438,022✔
648
    add_particle_track(p);
930✔
649
}
150,438,022✔
650

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

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

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

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

672
    // Set number of particles
673
    if (mpi::rank == i)
7,850✔
674
      simulation::work_per_rank = work_i;
6,107✔
675

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

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

688
  for (const auto& nuc : data::nuclides) {
30,206✔
689
    if (nuc->grid_.size() >= 1) {
25,155!
690
      int neutron = static_cast<int>(ParticleType::neutron);
25,155✔
691
      data::energy_min[neutron] =
50,310✔
692
        std::max(data::energy_min[neutron], nuc->grid_[0].energy.front());
25,155✔
693
      data::energy_max[neutron] =
25,155✔
694
        std::min(data::energy_max[neutron], nuc->grid_[0].energy.back());
25,155✔
695
    }
696
  }
697

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

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

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

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

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

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

753
  // Set up logarithmic grid for nuclides
754
  for (auto& nuc : data::nuclides) {
30,206✔
755
    nuc->init_grid();
25,155✔
756
  }
757
  int neutron = static_cast<int>(ParticleType::neutron);
5,051✔
758
  simulation::log_spacing =
5,051✔
759
    std::log(data::energy_max[neutron] / data::energy_min[neutron]) /
5,051✔
760
    settings::n_log_bins;
761
}
5,051✔
762

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

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

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

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

796
#endif
797

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

804
void transport_history_based_single_particle(Particle& p)
138,328,352✔
805
{
806
  while (p.alive()) {
2,147,483,647✔
807
    p.event_calculate_xs();
2,147,483,647✔
808
    if (p.alive()) {
2,147,483,647!
809
      p.event_advance();
2,147,483,647✔
810
    }
811
    if (p.alive()) {
2,147,483,647✔
812
      if (p.collision_distance() > p.boundary().distance()) {
2,147,483,647✔
813
        p.event_cross_surface();
1,222,739,184✔
814
      } else if (p.alive()) {
2,147,483,647!
815
        p.event_collide();
2,147,483,647✔
816
      }
817
    }
818
    p.event_revive_from_secondary();
2,147,483,647✔
819
  }
820
  p.event_death();
138,328,343✔
821
}
138,328,343✔
822

823
void transport_history_based()
98,731✔
824
{
825
#pragma omp parallel for schedule(runtime)
826
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
60,142,492✔
827
    Particle p;
60,103,955✔
828
    initialize_history(p, i_work);
60,103,955✔
829
    transport_history_based_single_particle(p);
60,103,952✔
830
  }
60,103,948✔
831
}
98,724✔
832

833
void transport_event_based()
3,145✔
834
{
835
  int64_t remaining_work = simulation::work_per_rank;
3,145✔
836
  int64_t source_offset = 0;
3,145✔
837

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

848
    // Initialize all particle histories for this subiteration
849
    process_init_events(n_particles, source_offset);
3,145!
850

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

860
      // Execute event with the longest queue
861
      if (max == 0) {
2,360,886✔
862
        break;
3,145✔
863
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,357,741✔
864
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
425,030!
865
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,932,711✔
866
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
358,275!
867
      } else if (max == simulation::advance_particle_queue.size()) {
1,574,436✔
868
        process_advance_particle_events();
778,086!
869
      } else if (max == simulation::surface_crossing_queue.size()) {
796,350✔
870
        process_surface_crossing_events();
258,328!
871
      } else if (max == simulation::collision_queue.size()) {
538,022!
872
        process_collision_events();
538,022!
873
      }
874
    }
2,357,741✔
875

876
    // Execute death event for all particles
877
    process_death_events(n_particles);
3,145!
878

879
    // Adjust remaining work and source offset variables
880
    remaining_work -= n_particles;
3,145✔
881
    source_offset += n_particles;
3,145✔
882
  }
883
}
3,145✔
884

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

© 2025 Coveralls, Inc