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

openmc-dev / openmc / 14515233533

17 Apr 2025 12:06PM UTC coverage: 83.16% (-2.3%) from 85.414%
14515233533

Pull #3087

github

web-flow
Merge 6ed397e9d into 47ca2916a
Pull Request #3087: wheel building with scikit build core

140769 of 169274 relevant lines covered (83.16%)

11830168.1 hits per line

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

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

65
  int err = 0;
4,463✔
66
  while (status == 0 && err == 0) {
83,994✔
67
    err = openmc_next_batch(&status);
79,543✔
68
  }
69

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

75
int openmc_simulation_init()
5,103✔
76
{
77
  using namespace openmc;
78

79
  // Skip if simulation has already been initialized
80
  if (simulation::initialized)
5,103✔
81
    return 0;
×
82

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

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

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

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

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

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

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

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

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

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

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

168
int openmc_simulation_finalize()
5,091✔
169
{
170
  using namespace openmc;
171

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

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

180
  // Clear material nuclide mapping
181
  for (auto& mat : model::materials) {
14,297✔
182
    mat->mat_nuclide_index_.clear();
9,206✔
183
  }
184

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

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

193
#ifdef OPENMC_MPI
194
  broadcast_results();
2,872✔
195
#endif
196

197
  // Write tally results to tallies.out
198
  if (settings::output_tallies && mpi::master)
5,091✔
199
    write_tallies();
4,034✔
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) {
5,091✔
204
    openmc_weight_windows_export();
129✔
205
  }
206

207
  // Deactivate all tallies
208
  for (auto& t : model::tallies) {
28,814✔
209
    t->active_ = false;
23,723✔
210
  }
211

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

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

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

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

242
  initialize_batch();
79,543✔
243

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

248
    initialize_generation();
79,767✔
249

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

253
    // Transport loop
254
    if (settings::event_based) {
79,767✔
255
      transport_event_based();
3,061✔
256
    } else {
257
      transport_history_based();
76,706✔
258
    }
259

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

263
    finalize_generation();
79,755✔
264
  }
265

266
  finalize_batch();
79,531✔
267

268
  // Check simulation ending criteria
269
  if (status) {
79,531✔
270
    if (simulation::current_batch >= settings::n_max_batches) {
79,531✔
271
      *status = STATUS_EXIT_MAX_BATCH;
4,375✔
272
    } else if (simulation::satisfy_triggers) {
75,156✔
273
      *status = STATUS_EXIT_ON_TRIGGER;
65✔
274
    } else {
275
      *status = STATUS_EXIT_NORMAL;
75,091✔
276
    }
277
  }
278
  return 0;
79,531✔
279
}
280

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

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

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

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

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

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

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

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

380
  // Manage active/inactive timers and activate tallies if necessary.
381
  if (first_inactive) {
96,343✔
382
    simulation::time_inactive.start();
2,838✔
383
  } else if (first_active) {
93,505✔
384
    simulation::time_inactive.stop();
5,092✔
385
    simulation::time_active.start();
5,092✔
386
    for (auto& t : model::tallies) {
28,793✔
387
      t->active_ = true;
23,701✔
388
    }
389
  }
390

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

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

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

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

413
  // Check_triggers
414
  if (mpi::master)
96,331✔
415
    check_triggers();
74,736✔
416
#ifdef OPENMC_MPI
417
  MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm);
55,706✔
418
#endif
419
  if (simulation::satisfy_triggers ||
96,331✔
420
      (settings::trigger_on &&
2,777✔
421
        simulation::current_batch == settings::n_max_batches)) {
2,777✔
422
    settings::statepoint_batch.insert(simulation::current_batch);
135✔
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) &&
101,636✔
428
      !settings::cmfd_run) {
5,305✔
429
    if (contains(settings::sourcepoint_batch, simulation::current_batch) &&
10,444✔
430
        settings::source_write && !settings::source_separate) {
10,444✔
431
      bool b = (settings::run_mode == RunMode::EIGENVALUE);
4,435✔
432
      openmc_statepoint_write(nullptr, &b);
4,435✔
433
    } else {
434
      bool b = false;
870✔
435
      openmc_statepoint_write(nullptr, &b);
870✔
436
    }
437
  }
438

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

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

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

462
  // Write out surface source if requested.
463
  if (settings::surf_source_write &&
96,331✔
464
      simulation::ssw_current_file <= settings::ssw_max_files) {
1,494✔
465
    bool last_batch = (simulation::current_batch == settings::n_batches);
1,169✔
466
    if (simulation::surf_source_bank.full() || last_batch) {
1,169✔
467
      // Determine appropriate filename
468
      auto filename = fmt::format("{}surface_source.{}", settings::path_output,
469
        simulation::current_batch);
308✔
470
      if (settings::ssw_max_files == 1 ||
378✔
471
          (simulation::ssw_current_file == 1 && last_batch)) {
55✔
472
        filename = settings::path_output + "surface_source";
323✔
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());
378✔
478
      span<SourceSite> surfbankspan(simulation::surf_source_bank.begin(),
479
        simulation::surf_source_bank.size());
378✔
480

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

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

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

505
    // Store current value of tracklength k
506
    simulation::keff_generation = simulation::global_tallies(
68,640✔
507
      GlobalTally::K_TRACKLENGTH, TallyResult::VALUE);
508
  }
509
}
96,567✔
510

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

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

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

533
  if (settings::run_mode == RunMode::EIGENVALUE &&
96,555✔
534
      settings::solver_type == SolverType::MONTE_CARLO) {
68,640✔
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();
65,600✔
539

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

544
  if (settings::run_mode == RunMode::EIGENVALUE) {
96,555✔
545

546
    // Calculate shannon entropy
547
    if (settings::entropy_on &&
68,640✔
548
        settings::solver_type == SolverType::MONTE_CARLO)
4,300✔
549
      shannon_entropy();
1,260✔
550

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

555
    // Write generation output
556
    if (mpi::master && settings::verbosity >= 7) {
68,640✔
557
      print_generation();
51,701✔
558
    }
559
  }
560
}
96,555✔
561

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

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

583
  // set progeny count to zero
584
  p.n_progeny() = 0;
147,908,787✔
585

586
  // Reset particle event counter
587
  p.n_event() = 0;
147,908,787✔
588

589
  // Reset split counter
590
  p.n_split() = 0;
147,908,787✔
591

592
  // Reset weight window ratio
593
  p.ww_factor() = 0.0;
147,908,787✔
594

595
  // set particle history start weight
596
  p.wgt_born() = p.wgt();
147,908,787✔
597

598
  // Reset pulse_height_storage
599
  std::fill(p.pht_storage().begin(), p.pht_storage().end(), 0);
147,908,787✔
600

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

607
  // set particle trace
608
  p.trace() = false;
147,908,787✔
609
  if (simulation::current_batch == settings::trace_batch &&
295,828,574✔
610
      simulation::current_gen == settings::trace_gen &&
147,919,787✔
611
      p.id() == settings::trace_particle)
11,000✔
612
    p.trace() = true;
11✔
613

614
  // Set particle track.
615
  p.write_track() = check_track_criteria(p);
147,908,787✔
616

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

622
// Add particle's starting weight to count for normalizing tallies later
623
#pragma omp atomic
80,823,037✔
624
  simulation::total_weight += p.wgt();
147,908,787✔
625

626
  // Force calculation of cross-sections by setting last energy to zero
627
  if (settings::run_CE) {
147,908,787✔
628
    p.invalidate_neutron_xs();
35,884,787✔
629
  }
630

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

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

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

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

650
  int64_t i_bank = 0;
5,103✔
651
  simulation::work_index.resize(mpi::n_procs + 1);
5,103✔
652
  simulation::work_index[0] = 0;
5,103✔
653
  for (int i = 0; i < mpi::n_procs; ++i) {
12,165✔
654
    // Number of particles for rank i
655
    int64_t work_i = i < remainder ? min_work + 1 : min_work;
7,062✔
656

657
    // Set number of particles
658
    if (mpi::rank == i)
7,062✔
659
      simulation::work_per_rank = work_i;
5,103✔
660

661
    // Set index into source bank for rank i
662
    i_bank += work_i;
7,062✔
663
    simulation::work_index[i + 1] = i_bank;
7,062✔
664
  }
665
}
5,103✔
666

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

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

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

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

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

737
#ifdef OPENMC_MPI
738
void broadcast_results()
2,872✔
739
{
740
  // Broadcast tally results so that each process has access to results
741
  for (auto& t : model::tallies) {
17,369✔
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_;
14,497✔
746

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

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

770
#endif
771

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

778
void transport_history_based_single_particle(Particle& p)
135,865,420✔
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();
685,736,757✔
788
      } else if (p.alive()) {
2,095,886,338✔
789
        p.event_collide();
2,095,886,338✔
790
      }
791
    }
792
    p.event_revive_from_secondary();
2,147,483,647✔
793
  }
794
  p.event_death();
135,865,411✔
795
}
135,865,411✔
796

797
void transport_history_based()
76,706✔
798
{
799
#pragma omp parallel for schedule(runtime)
800
  for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) {
67,183,624✔
801
    Particle p;
67,148,418✔
802
    initialize_history(p, i_work);
67,148,418✔
803
    transport_history_based_single_particle(p);
67,148,415✔
804
  }
67,148,410✔
805
}
76,698✔
806

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

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

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

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

834
      // Execute event with the longest queue
835
      if (max == 0) {
2,368,778✔
836
        break;
3,061✔
837
      } else if (max == simulation::calculate_fuel_xs_queue.size()) {
2,365,717✔
838
        process_calculate_xs_events(simulation::calculate_fuel_xs_queue);
422,650✔
839
      } else if (max == simulation::calculate_nonfuel_xs_queue.size()) {
1,943,067✔
840
        process_calculate_xs_events(simulation::calculate_nonfuel_xs_queue);
363,007✔
841
      } else if (max == simulation::advance_particle_queue.size()) {
1,580,060✔
842
        process_advance_particle_events();
780,793✔
843
      } else if (max == simulation::surface_crossing_queue.size()) {
799,267✔
844
        process_surface_crossing_events();
256,227✔
845
      } else if (max == simulation::collision_queue.size()) {
543,040✔
846
        process_collision_events();
543,040✔
847
      }
848
    }
2,365,717✔
849

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

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

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

© 2025 Coveralls, Inc