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

openmc-dev / openmc / 21380032196

27 Jan 2026 12:49AM UTC coverage: 81.963% (-0.01%) from 81.977%
21380032196

Pull #3702

github

web-flow
Merge d4b973c43 into 5c502ddb3
Pull Request #3702: Random Ray Kinetic Simulation Mode

17712 of 24657 branches covered (71.83%)

Branch coverage included in aggregate %.

902 of 1043 new or added lines in 20 files covered. (86.48%)

82 existing lines in 10 files now uncovered.

56474 of 65855 relevant lines covered (85.76%)

53637379.0 hits per line

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

85.29
/src/random_ray/random_ray_simulation.cpp
1
#include "openmc/random_ray/random_ray_simulation.h"
2

3
#include "openmc/eigenvalue.h"
4
#include "openmc/geometry.h"
5
#include "openmc/message_passing.h"
6
#include "openmc/mgxs_interface.h"
7
#include "openmc/output.h"
8
#include "openmc/plot.h"
9
#include "openmc/random_ray/flat_source_domain.h"
10
#include "openmc/random_ray/random_ray.h"
11
#include "openmc/simulation.h"
12
#include "openmc/source.h"
13
#include "openmc/tallies/filter.h"
14
#include "openmc/tallies/tally.h"
15
#include "openmc/tallies/tally_scoring.h"
16
#include "openmc/timer.h"
17
#include "openmc/weight_windows.h"
18

19
namespace openmc {
20

21
//==============================================================================
22
// Non-member functions
23
//==============================================================================
24

25
void openmc_run_random_ray()
913✔
26
{
27
  //////////////////////////////////////////////////////////
28
  // Run forward simulation
29
  //////////////////////////////////////////////////////////
30

31
  if (mpi::master) {
913✔
32
    if (FlatSourceDomain::adjoint_) {
628✔
33
      FlatSourceDomain::adjoint_ = false;
56✔
34
      openmc::print_adjoint_header();
56✔
35
      FlatSourceDomain::adjoint_ = true;
56✔
36
    }
37
  }
38

39
  // Initialize OpenMC general data structures
40
  openmc_simulation_init();
913✔
41

42
  // Validate that inputs meet requirements for random ray mode
43
  if (mpi::master)
913✔
44
    validate_random_ray_inputs();
628✔
45

46
  // Initialize Random Ray Simulation Object
47
  RandomRaySimulation sim;
913✔
48

49
  // Initialize fixed sources, if present
50
  sim.apply_fixed_sources_and_mesh_domains();
913✔
51

52
  // Run initial random ray simulation
53
  sim.simulate();
913✔
54

55
  if (settings::kinetic_simulation) {
913✔
56
    // Timestepping loop, including k-eff correction initial
57
    // condition (i = -1)
58
    for (int i = -1; i < settings::n_timesteps; i++)
1,344✔
59
      sim.kinetic_single_time_step(i);
1,152✔
60
  }
61

62
  //////////////////////////////////////////////////////////
63
  // Run adjoint simulation (if enabled)
64
  //////////////////////////////////////////////////////////
65

66
  if (sim.adjoint_needed_) {
913✔
67
    // Setup for adjoint simulation
68
    sim.prepare_adjoint_simulation();
81✔
69

70
    // Run adjoint simulation
71
    sim.simulate();
81✔
72
  }
73
}
913✔
74

75
// Enforces restrictions on inputs in random ray mode.  While there are
76
// many features that don't make sense in random ray mode, and are therefore
77
// unsupported, we limit our testing/enforcement operations only to inputs
78
// that may cause erroneous/misleading output or crashes from the solver.
79
void validate_random_ray_inputs()
628✔
80
{
81
  // Validate tallies
82
  ///////////////////////////////////////////////////////////////////
83
  for (auto& tally : model::tallies) {
1,674✔
84

85
    // Validate score types
86
    for (auto score_bin : tally->scores_) {
2,378✔
87
      switch (score_bin) {
1,332!
88
      case SCORE_FLUX:
1,288✔
89
      case SCORE_TOTAL:
90
      case SCORE_FISSION:
91
      case SCORE_NU_FISSION:
92
      case SCORE_EVENTS:
93
      case SCORE_KAPPA_FISSION:
94
        break;
1,288✔
95

96
      // TODO: add support for prompt and delayed fission
97
      case SCORE_PRECURSORS: {
44✔
98
        if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
44!
99
          break;
100
        } else {
NEW
101
          fatal_error("Invalid score specified in tallies.xml. Precursors can "
×
102
                      "only be scored for kinetic simulations.");
103
        }
104
      }
105
      default:
106
        fatal_error(
×
107
          "Invalid score specified. Only flux, total, fission, nu-fission, "
108
          "kappa-fission and event scores are supported in random ray mode. "
109
          "(precursors are supported for kinetic simulations when delayed "
110
          "neutrons are turned on).");
111
      }
112
    }
113

114
    // Validate filter types
115
    for (auto f : tally->filters()) {
2,281✔
116
      auto& filter = *model::tally_filters[f];
1,235✔
117

118
      switch (filter.type()) {
1,235!
119
      case FilterType::CELL:
1,191✔
120
      case FilterType::CELL_INSTANCE:
121
      case FilterType::DISTRIBCELL:
122
      case FilterType::ENERGY:
123
      case FilterType::MATERIAL:
124
      case FilterType::MESH:
125
      case FilterType::UNIVERSE:
126
      case FilterType::PARTICLE:
127
        break;
1,191✔
128
      case FilterType::DELAYED_GROUP:
44✔
129
        if (settings::kinetic_simulation) {
44!
130
          break;
44✔
131
        } else {
NEW
132
          fatal_error("Invalid filter specified in tallies.xml. Kinetic "
×
133
                      "simulations is required "
134
                      "to tally with a delayed_group filter.");
135
        }
136
      default:
×
137
        fatal_error("Invalid filter specified. Only cell, cell_instance, "
×
138
                    "distribcell, energy, material, mesh, and universe filters "
139
                    "are supported in random ray mode (delayed_group is "
140
                    "supported for kinetic simulations).");
141
      }
142
    }
143
  }
144

145
  // TODO: validate kinetic data is present
146
  //  Validate MGXS data
147
  ///////////////////////////////////////////////////////////////////
148
  for (auto& material : data::mg.macro_xs_) {
2,367✔
149
    if (!material.is_isotropic) {
1,739!
150
      fatal_error("Anisotropic MGXS detected. Only isotropic XS data sets "
×
151
                  "supported in random ray mode.");
152
    }
153
    if (material.get_xsdata().size() > 1) {
1,739!
154
      warning("Non-isothermal MGXS detected. Only isothermal XS data sets "
×
155
              "supported in random ray mode. Using lowest temperature.");
156
    }
157
    for (int g = 0; g < data::mg.num_energy_groups_; g++) {
13,478✔
158
      if (material.exists_in_model) {
11,739✔
159
        // Temperature and angle indices, if using multiple temperature
160
        // data sets and/or anisotropic data sets.
161
        // TODO: Currently assumes we are only using single temp/single angle
162
        // data.
163
        const int t = 0;
11,695✔
164
        const int a = 0;
11,695✔
165
        double sigma_t =
166
          material.get_xs(MgxsType::TOTAL, g, NULL, NULL, NULL, t, a);
11,695✔
167
        if (sigma_t <= 0.0) {
11,695!
168
          fatal_error("No zero or negative total macroscopic cross sections "
×
169
                      "allowed in random ray mode. If the intention is to make "
170
                      "a void material, use a cell fill of 'None' instead.");
171
        }
172
      }
173
    }
174
  }
175

176
  // Validate ray source
177
  ///////////////////////////////////////////////////////////////////
178

179
  // Check for independent source
180
  IndependentSource* is =
181
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
628!
182
  if (!is) {
628!
183
    fatal_error("Invalid ray source definition. Ray source must provided and "
×
184
                "be of type IndependentSource.");
185
  }
186

187
  // Check for box source
188
  SpatialDistribution* space_dist = is->space();
628✔
189
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
628!
190
  if (!sb) {
628!
191
    fatal_error(
×
192
      "Invalid ray source definition -- only box sources are allowed.");
193
  }
194

195
  // Check that box source is not restricted to fissionable areas
196
  if (sb->only_fissionable()) {
628!
197
    fatal_error(
×
198
      "Invalid ray source definition -- fissionable spatial distribution "
199
      "not allowed.");
200
  }
201

202
  // Check for isotropic source
203
  UnitSphereDistribution* angle_dist = is->angle();
628✔
204
  Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
628!
205
  if (!id) {
628!
206
    fatal_error("Invalid ray source definition -- only isotropic sources are "
×
207
                "allowed.");
208
  }
209

210
  // Validate external sources
211
  ///////////////////////////////////////////////////////////////////
212
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
628✔
213
    if (model::external_sources.size() < 1) {
287!
214
      fatal_error("Must provide a particle source (in addition to ray source) "
×
215
                  "in fixed source random ray mode.");
216
    }
217

218
    for (int i = 0; i < model::external_sources.size(); i++) {
574✔
219
      Source* s = model::external_sources[i].get();
287✔
220

221
      // Check for independent source
222
      IndependentSource* is = dynamic_cast<IndependentSource*>(s);
287!
223

224
      if (!is) {
287!
225
        fatal_error(
×
226
          "Only IndependentSource external source types are allowed in "
227
          "random ray mode");
228
      }
229

230
      // Check for isotropic source
231
      UnitSphereDistribution* angle_dist = is->angle();
287✔
232
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
287!
233
      if (!id) {
287!
234
        fatal_error(
×
235
          "Invalid source definition -- only isotropic external sources are "
236
          "allowed in random ray mode.");
237
      }
238

239
      // Validate that a domain ID was specified OR that it is a point source
240
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
287!
241
      if (is->domain_ids().size() == 0 && !sp) {
287!
242
        fatal_error("Fixed sources must be point source or spatially "
×
243
                    "constrained by domain id (cell, material, or universe) in "
244
                    "random ray mode.");
245
      } else if (is->domain_ids().size() > 0 && sp) {
287✔
246
        // If both a domain constraint and a non-default point source location
247
        // are specified, notify user that domain constraint takes precedence.
248
        if (sp->r().x == 0.0 && sp->r().y == 0.0 && sp->r().z == 0.0) {
253!
249
          warning("Fixed source has both a domain constraint and a point "
253✔
250
                  "type spatial distribution. The domain constraint takes "
251
                  "precedence in random ray mode -- point source coordinate "
252
                  "will be ignored.");
253
        }
254
      }
255

256
      // Check that a discrete energy distribution was used
257
      Distribution* d = is->energy();
287✔
258
      Discrete* dd = dynamic_cast<Discrete*>(d);
287!
259
      if (!dd) {
287!
260
        fatal_error(
×
261
          "Only discrete (multigroup) energy distributions are allowed for "
262
          "external sources in random ray mode.");
263
      }
264
    }
265
  }
266

267
  // Validate plotting files
268
  ///////////////////////////////////////////////////////////////////
269
  for (int p = 0; p < model::plots.size(); p++) {
628!
270

271
    // Get handle to OpenMC plot object
272
    const auto& openmc_plottable = model::plots[p];
×
273
    Plot* openmc_plot = dynamic_cast<Plot*>(openmc_plottable.get());
×
274

275
    // Random ray plots only support voxel plots
276
    if (!openmc_plot) {
×
277
      warning(fmt::format(
×
278
        "Plot {} will not be used for end of simulation data plotting -- only "
279
        "voxel plotting is allowed in random ray mode.",
280
        openmc_plottable->id()));
×
281
      continue;
×
282
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
283
      warning(fmt::format(
×
284
        "Plot {} will not be used for end of simulation data plotting -- only "
285
        "voxel plotting is allowed in random ray mode.",
286
        openmc_plottable->id()));
×
287
      continue;
×
288
    }
289
  }
290

291
  // Warn about slow MPI domain replication, if detected
292
  ///////////////////////////////////////////////////////////////////
293
#ifdef OPENMC_MPI
294
  if (mpi::n_procs > 1) {
286✔
295
    warning(
285✔
296
      "MPI parallelism is not supported by the random ray solver. All work "
297
      "will be performed by rank 0. Domain decomposition may be implemented in "
298
      "the future to provide efficient MPI scaling.");
299
  }
300
#endif
301

302
  // Warn about instability resulting from linear sources in small regions
303
  // when generating weight windows with FW-CADIS and an overlaid mesh.
304
  ///////////////////////////////////////////////////////////////////
305
  if (RandomRay::source_shape_ == RandomRaySourceShape::LINEAR &&
837✔
306
      variance_reduction::weight_windows.size() > 0) {
209✔
307
    warning(
11✔
308
      "Linear sources may result in negative fluxes in small source regions "
309
      "generated by mesh subdivision. Negative sources may result in low "
310
      "quality FW-CADIS weight windows. We recommend you use flat source mode "
311
      "when generating weight windows with an overlaid mesh tally.");
312
  }
313
}
628✔
314

315
void openmc_reset_random_ray()
8,477✔
316
{
317
  FlatSourceDomain::volume_estimator_ = RandomRayVolumeEstimator::HYBRID;
8,477✔
318
  FlatSourceDomain::volume_normalized_flux_tallies_ = false;
8,477✔
319
  FlatSourceDomain::adjoint_ = false;
8,477✔
320
  FlatSourceDomain::mesh_domain_map_.clear();
8,477✔
321
  RandomRay::ray_source_.reset();
8,477✔
322
  RandomRay::source_shape_ = RandomRaySourceShape::FLAT;
8,477✔
323
  RandomRay::sample_method_ = RandomRaySampleMethod::PRNG;
8,477✔
324
  RandomRay::bd_order_ = 3;
8,477✔
325
  RandomRay::time_method_ = RandomRayTimeMethod::ISOTROPIC;
8,477✔
326
}
8,477✔
327

328
void write_random_ray_hdf5(hid_t group)
1,476✔
329
{
330
  hid_t random_ray_group = create_group(group, "random_ray");
1,476✔
331
  switch (RandomRay::source_shape_) {
1,476!
332
  case RandomRaySourceShape::FLAT:
1,223✔
333
    write_dataset(random_ray_group, "source_shape", "flat");
1,223✔
334
    break;
1,223✔
335
  case RandomRaySourceShape::LINEAR:
220✔
336
    write_dataset(random_ray_group, "source_shape", "linear");
220✔
337
    break;
220✔
338
  case RandomRaySourceShape::LINEAR_XY:
33✔
339
    write_dataset(random_ray_group, "source_shape", "linear xy");
33✔
340
    break;
33✔
NEW
341
  default:
×
NEW
342
    break;
×
343
  }
344

345
  switch (FlatSourceDomain::volume_estimator_) {
1,476!
346
  case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
22✔
347
    write_dataset(random_ray_group, "volume_estimator", "simulation averaged");
22✔
348
    break;
22✔
349
  case RandomRayVolumeEstimator::NAIVE:
68✔
350
    write_dataset(random_ray_group, "volume_estimator", "naive");
68✔
351
    break;
68✔
352
  case RandomRayVolumeEstimator::HYBRID:
1,386✔
353
    write_dataset(random_ray_group, "volume_estimator", "hybrid");
1,386✔
354
    break;
1,386✔
NEW
355
  default:
×
NEW
356
    break;
×
357
  }
358

359
  write_dataset(
1,476✔
360
    random_ray_group, "distance_active", RandomRay::distance_active_);
361
  write_dataset(
1,476✔
362
    random_ray_group, "distance_inactive", RandomRay::distance_inactive_);
363
  write_dataset(random_ray_group, "volume_normalized_flux_tallies",
1,476✔
364
    FlatSourceDomain::volume_normalized_flux_tallies_);
365
  write_dataset(random_ray_group, "adjoint_mode", FlatSourceDomain::adjoint_);
1,476✔
366

367
  write_dataset(random_ray_group, "avg_miss_rate", RandomRay::avg_miss_rate_);
1,476✔
368
  write_dataset(
1,476✔
369
    random_ray_group, "n_source_regions", RandomRay::n_source_regions_);
370
  write_dataset(random_ray_group, "n_external_source_regions",
1,476✔
371
    RandomRay::n_external_source_regions_);
372
  write_dataset(random_ray_group, "n_geometric_intersections",
1,476✔
373
    RandomRay::total_geometric_intersections_);
374
  int64_t n_integrations =
1,476✔
375
    RandomRay::total_geometric_intersections_ * data::mg.num_energy_groups_;
1,476✔
376
  write_dataset(random_ray_group, "n_integrations", n_integrations);
1,476✔
377

378
  if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,476✔
379
    write_dataset(random_ray_group, "bd_order", RandomRay::bd_order_);
660✔
380
    switch (RandomRay::time_method_) {
660!
381
    case RandomRayTimeMethod::ISOTROPIC:
440✔
382
      write_dataset(random_ray_group, "time_method", "isotropic");
440✔
383
      break;
440✔
384
    case RandomRayTimeMethod::PROPAGATION:
220✔
385
      write_dataset(random_ray_group, "time_method", "propogation");
220✔
386
      break;
220✔
NEW
387
    default:
×
NEW
388
      break;
×
389
    }
390
  }
391
  close_group(random_ray_group);
1,476✔
392
}
1,476✔
393

394
void print_adjoint_header()
112✔
395
{
396
  if (!FlatSourceDomain::adjoint_)
112✔
397
    // If we're going to do an adjoint simulation afterwards, report that this
398
    // is the initial forward flux solve.
399
    header("FORWARD FLUX SOLVE", 3);
56✔
400
  else
401
    // Otherwise report that we are doing the adjoint simulation
402
    header("ADJOINT FLUX SOLVE", 3);
56✔
403
}
112✔
404

405
//-----------------------------------------------------------------------------
406
// Non-member functions for kinetic simulations
407

408
void rename_time_step_file(
2,304✔
409
  std::string base_filename, std::string extension, int i)
410
{
411
  // Rename file
412
  std::string old_filename_ =
413
    fmt::format("{0}{1}{2}", settings::path_output, base_filename, extension);
2,304✔
414
  std::string new_filename_ = fmt::format(
415
    "{0}{1}_{2}{3}", settings::path_output, base_filename, i, extension);
1,872✔
416

417
  const char* old_fname = old_filename_.c_str();
2,304✔
418
  const char* new_fname = new_filename_.c_str();
2,304✔
419
  std::rename(old_fname, new_fname);
2,304✔
420
}
2,304✔
421

422
//==============================================================================
423
// RandomRaySimulation implementation
424
//==============================================================================
425

426
RandomRaySimulation::RandomRaySimulation()
913✔
427
  : negroups_(data::mg.num_energy_groups_),
913✔
428
    ndgroups_(data::mg.num_delayed_groups_)
913✔
429
{
430
  // There are no source sites in random ray mode, so be sure to disable to
431
  // ensure we don't attempt to write source sites to statepoint
432
  settings::source_write = false;
913✔
433

434
  // Random ray mode does not have an inner loop over generations within a
435
  // batch, so set the current gen to 1
436
  simulation::current_gen = 1;
913✔
437

438
  switch (RandomRay::source_shape_) {
913!
439
  case RandomRaySourceShape::FLAT:
561✔
440
    domain_ = make_unique<FlatSourceDomain>();
561✔
441
    break;
561✔
442
  case RandomRaySourceShape::LINEAR:
352✔
443
  case RandomRaySourceShape::LINEAR_XY:
444
    domain_ = make_unique<LinearSourceDomain>();
352✔
445
    break;
352✔
446
  default:
×
447
    fatal_error("Unknown random ray source shape");
×
448
  }
449

450
  // Convert OpenMC native MGXS into a more efficient format
451
  // internal to the random ray solver
452
  domain_->flatten_xs();
913✔
453

454
  // Check if adjoint calculation is needed. If it is, we will run the forward
455
  // calculation first and then the adjoint calculation later.
456
  adjoint_needed_ = FlatSourceDomain::adjoint_;
913✔
457

458
  // Adjoint is always false for the forward calculation
459
  FlatSourceDomain::adjoint_ = false;
913✔
460

461
  // The first simulation is run after initialization
462
  is_first_simulation_ = true;
913✔
463

464
  // Initialize vectors used for baking in the initial condition during time
465
  // stepping
466
  if (settings::kinetic_simulation) {
913✔
467
    // Initialize vars used for time-consistent seed approach
468
    static_avg_k_eff_;
469
    static_k_eff_;
470
    static_fission_rate_;
471
  }
472
}
913✔
473

474
void RandomRaySimulation::apply_fixed_sources_and_mesh_domains()
913✔
475
{
476
  domain_->apply_meshes();
913✔
477
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
913✔
478
    // Transfer external source user inputs onto random ray source regions
479
    domain_->convert_external_sources();
417✔
480
    domain_->count_external_source_regions();
417✔
481
  }
482
}
913✔
483

484
void RandomRaySimulation::prepare_fixed_sources_adjoint()
81✔
485
{
486
  domain_->source_regions_.adjoint_reset();
81✔
487
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
81✔
488
    domain_->set_adjoint_sources();
65✔
489
  }
490
}
81✔
491

492
void RandomRaySimulation::prepare_adjoint_simulation()
81✔
493
{
494
  // Configure the domain for adjoint simulation
495
  FlatSourceDomain::adjoint_ = true;
81✔
496

497
  // Reset k-eff
498
  domain_->k_eff_ = 1.0;
81✔
499

500
  // Initialize adjoint fixed sources, if present
501
  prepare_fixed_sources_adjoint();
81✔
502

503
  // Transpose scattering matrix
504
  domain_->transpose_scattering_matrix();
81✔
505

506
  // Swap nu_sigma_f and chi
507
  domain_->nu_sigma_f_.swap(domain_->chi_);
81✔
508
}
81✔
509

510
// TODO: Add support for time-dependent restart
511
void RandomRaySimulation::kinetic_single_time_step(int i)
1,152✔
512
{
513
  // Increment time step
514
  simulation::current_timestep = i + 1;
1,152✔
515
  if (i >= 0)
1,152✔
516
    // Increment the current time
517
    simulation::current_time += settings::dt;
960✔
518

519
  // Set eigenvalue if needed
520
  if (settings::run_mode == RunMode::EIGENVALUE) {
1,152!
521
    if (i == -1) {
1,152✔
522
      // Set flag for k_eff correction if initial condition
523
      simulation::k_eff_correction = true;
192✔
524

525
      // Store average keff from initial simulation
526
      static_avg_k_eff_ = simulation::keff;
192✔
527
    }
528
    domain_->k_eff_ = static_avg_k_eff_;
1,152✔
529
  }
530
  domain_->source_regions_.adjoint_reset();
1,152✔
531
  domain_->propagate_final_quantities();
1,152✔
532
  domain_->source_regions_.time_step_reset();
1,152✔
533

534
  if (i >= 0) {
1,152✔
535
    // Compute RHS backward differences
536
    domain_->compute_rhs_bd_quantities();
960✔
537

538
    // Update time dependent cross section based on the density
539
    domain_->update_material_density(i);
960✔
540
  }
541

542
  // Run the initial condition
543
  simulate();
1,152✔
544

545
  if (i == -1) {
1,152✔
546
    // Initialize the BD arrays if initial condition
547
    domain_->store_time_step_quantities(false);
192✔
548
    // Reset flags for kinetic simulation if initial condition
549
    simulation::is_initial_condition = false;
192✔
550
    simulation::k_eff_correction = false;
192✔
551
  } else {
552
    // Else, store final quantities for the current time step
553
    domain_->store_time_step_quantities();
960✔
554
  }
555

556
  // Rename statepoint and tallies file for the current time step
557
  rename_time_step_file(fmt::format("statepoint.{0}", settings::n_batches),
2,304✔
558
    ".h5", simulation::current_timestep);
559
  if (settings::output_tallies)
1,152!
560
    rename_time_step_file("tallies", ".out", simulation::current_timestep);
1,152✔
561
}
1,152✔
562

563
void RandomRaySimulation::simulate()
2,146✔
564
{
565
  if (!is_first_simulation_) {
2,146✔
566
    if (mpi::master && adjoint_needed_)
1,233✔
567
      openmc::print_adjoint_header();
56✔
568

569
    // Reset the timers and reinitialize the general OpenMC datastructures if
570
    // this is after the first simulation
571
    reset_timers();
1,233✔
572

573
    // Initialize OpenMC general data structures
574
    openmc_simulation_init();
1,233✔
575
  }
576

577
  // Begin main simulation timer
578
  simulation::time_total.start();
2,146✔
579

580
  // Random ray power iteration loop
581
  while (simulation::current_batch < settings::n_batches) {
210,958✔
582
    // Initialize the current batch
583
    initialize_batch();
208,812✔
584
    initialize_generation();
208,812✔
585

586
    // MPI not supported in random ray solver, so all work is done by rank 0
587
    // TODO: Implement domain decomposition for MPI parallelism
588
    if (mpi::master) {
208,812✔
589

590
      // Reset total starting particle weight used for normalizing tallies
591
      simulation::total_weight = 1.0;
143,562✔
592

593
      // Update source term (scattering + fission (+ delayed if kinetic))
594
      domain_->update_all_neutron_sources();
143,562✔
595

596
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
597
      // to zero
598
      domain_->batch_reset();
143,562✔
599

600
      // At the beginning of the simulation, if mesh subdivision is in use, we
601
      // need to swap the main source region container into the base container,
602
      // as the main source region container will be used to hold the true
603
      // subdivided source regions. The base container will therefore only
604
      // contain the external source region information, the mesh indices,
605
      // material properties, and initial guess values for the flux/source.
606

607
      // Start timer for transport
608
      simulation::time_transport.start();
143,562✔
609

610
// Transport sweep over all random rays for the iteration
611
#pragma omp parallel for schedule(dynamic)                                     \
78,312✔
612
  reduction(+ : total_geometric_intersections_)
78,312✔
613
      for (int i = 0; i < settings::n_particles; i++) {
6,908,250✔
614
        RandomRay ray(i, domain_.get());
6,843,000✔
615
        total_geometric_intersections_ +=
6,843,000✔
616
          ray.transport_history_based_single_ray();
6,843,000✔
617
      }
6,843,000✔
618

619
      simulation::time_transport.stop();
143,562✔
620

621
      // Add any newly discovered source regions to the main source region
622
      // container.
623
      domain_->finalize_discovered_source_regions();
143,562✔
624

625
      // Normalize scalar flux and update volumes
626
      domain_->normalize_scalar_flux_and_volumes(
143,562✔
627
        settings::n_particles * RandomRay::distance_active_);
628

629
      // Add source to scalar flux, compute number of FSR hits
630
      int64_t n_hits = domain_->add_source_to_scalar_flux();
143,562✔
631

632
      // Apply transport stabilization factors
633
      domain_->apply_transport_stabilization();
143,562✔
634

635
      if (settings::run_mode == RunMode::EIGENVALUE) {
143,562✔
636
        // Compute random ray k-eff
637
        if (!settings::kinetic_simulation ||
133,870!
638
            settings::kinetic_simulation && simulation::is_initial_condition) {
130,900✔
639
          domain_->compute_k_eff();
40,370✔
640
          if (simulation::k_eff_correction) {
40,370✔
641
            static_fission_rate_.push_back(domain_->fission_rate_);
18,700✔
642
            static_k_eff_.push_back(domain_->k_eff_);
18,700✔
643
          }
644
        } else {
645
          domain_->k_eff_ = static_k_eff_[simulation::current_batch - 1];
93,500✔
646
          domain_->fission_rate_ =
93,500✔
647
            static_fission_rate_[simulation::current_batch - 1];
93,500✔
648
        }
649

650
        // Store random ray k-eff into OpenMC's native k-eff variable
651
        global_tally_tracklength = domain_->k_eff_;
133,870✔
652
      }
653

654
      // Compute precursors if delayed neutrons are turned on
655
      if (settings::kinetic_simulation && settings::create_delayed_neutrons)
143,562!
656
        domain_->compute_all_precursors();
130,900✔
657

658
      // Execute all tallying tasks, if this is an active batch
659
      if (simulation::current_batch > settings::n_inactive) {
143,562✔
660

661
        // Add this iteration's scalar flux estimate to final accumulated
662
        // estimate
663
        domain_->accumulate_iteration_quantities();
69,911✔
664

665
        // Use above mapping to contribute FSR flux data to appropriate
666
        // tallies
667
        domain_->random_ray_tally();
69,911✔
668
      }
669

670
      // Set phi_old = phi_new
671
      domain_->flux_swap();
143,562✔
672
      if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
143,562!
673
        domain_->precursors_swap();
130,900✔
674
      }
675

676
      // Check for any obvious insabilities/nans/infs
677
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
143,562✔
678
    } // End MPI master work
679

680
    // Store simulation metrics
681
    RandomRay::avg_miss_rate_ = avg_miss_rate_ / settings::n_batches;
208,812✔
682
    RandomRay::total_geometric_intersections_ = total_geometric_intersections_;
208,812✔
683
    RandomRay::n_external_source_regions_ = domain_->n_external_source_regions_;
208,812✔
684
    RandomRay::n_source_regions_ = domain_->n_source_regions();
208,812✔
685

686
    // Finalize the current batch
687
    finalize_generation();
208,812✔
688
    finalize_batch();
208,812✔
689
  } // End random ray power iteration loop
690

691
  domain_->count_external_source_regions();
2,146✔
692

693
  // End main simulation timer
694
  simulation::time_total.stop();
2,146✔
695

696
  // Normalize and save the final forward quantities
697
  domain_->normalize_final_quantities();
2,146✔
698

699
  // Finalize OpenMC
700
  openmc_simulation_finalize();
2,146✔
701

702
  // Output all simulation results
703
  output_simulation_results();
2,146✔
704

705
  // Toggle that the simulation object has been initialized after the first
706
  // simulation
707
  if (is_first_simulation_)
2,146✔
708
    is_first_simulation_ = false;
913✔
709
}
2,146✔
710

711
void RandomRaySimulation::output_simulation_results() const
2,146✔
712
{
713
  // Print random ray results
714
  if (mpi::master) {
2,146✔
715
    print_results_random_ray();
1,476✔
716
    if (model::plots.size() > 0) {
1,476!
717
      domain_->output_to_vtk();
×
718
    }
719
  }
720
}
2,146✔
721

722
// Apply a few sanity checks to catch obvious cases of numerical instability.
723
// Instability typically only occurs if ray density is extremely low.
724
void RandomRaySimulation::instability_check(
143,562✔
725
  int64_t n_hits, double k_eff, double& avg_miss_rate) const
726
{
727
  double percent_missed = ((domain_->n_source_regions() - n_hits) /
143,562✔
728
                            static_cast<double>(domain_->n_source_regions())) *
143,562✔
729
                          100.0;
143,562✔
730
  avg_miss_rate += percent_missed;
143,562✔
731

732
  if (mpi::master) {
143,562!
733
    if (percent_missed > 10.0) {
143,562✔
734
      warning(fmt::format(
957✔
735
        "Very high FSR miss rate detected ({:.3f}%). Instability may occur. "
736
        "Increase ray density by adding more rays and/or active distance.",
737
        percent_missed));
738
    } else if (percent_missed > 1.0) {
142,605✔
739
      warning(
2!
740
        fmt::format("Elevated FSR miss rate detected ({:.3f}%). Increasing "
4!
741
                    "ray density by adding more rays and/or active "
742
                    "distance may improve simulation efficiency.",
743
          percent_missed));
744
    }
745

746
    if (k_eff > 10.0 || k_eff < 0.01 || !(std::isfinite(k_eff))) {
143,562!
747
      fatal_error(fmt::format("Instability detected: k-eff = {:.5f}", k_eff));
×
748
    }
749
  }
750
}
143,562✔
751

752
// Print random ray simulation results
753
void RandomRaySimulation::print_results_random_ray() const
1,476✔
754
{
755
  using namespace simulation;
756

757
  if (settings::verbosity >= 6) {
1,476!
758
    double total_integrations =
1,476✔
759
      RandomRay::total_geometric_intersections_ * negroups_;
1,476✔
760
    double time_per_integration =
761
      simulation::time_transport.elapsed() / total_integrations;
1,476✔
762
    double misc_time = time_total.elapsed() - time_update_src.elapsed() -
1,476✔
763
                       time_transport.elapsed() - time_tallies.elapsed() -
1,476✔
764
                       time_bank_sendrecv.elapsed();
1,476✔
765

766
    if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,476✔
767
      misc_time -= time_update_bd_vectors.elapsed();
660✔
768
    }
769
    header("Simulation Statistics", 4);
1,476✔
770
    fmt::print(
1,476✔
771
      " Total Iterations                  = {}\n", settings::n_batches);
772
    fmt::print(
1,476✔
773
      " Number of Rays per Iteration      = {}\n", settings::n_particles);
774
    fmt::print(" Inactive Distance                 = {} cm\n",
1,476✔
775
      RandomRay::distance_inactive_);
776
    fmt::print(" Active Distance                   = {} cm\n",
1,476✔
777
      RandomRay::distance_active_);
778
    fmt::print(" Source Regions (SRs)              = {}\n",
1,476✔
779
      RandomRay::n_source_regions_);
780
    fmt::print(" SRs Containing External Sources   = {}\n",
1,208✔
781
      RandomRay::n_external_source_regions_);
782
    fmt::print(" Total Geometric Intersections     = {:.4e}\n",
1,208✔
783
      static_cast<double>(RandomRay::total_geometric_intersections_));
1,476✔
784
    fmt::print("   Avg per Iteration               = {:.4e}\n",
1,208✔
785
      static_cast<double>(RandomRay::total_geometric_intersections_) /
1,476✔
786
        settings::n_batches);
787
    fmt::print("   Avg per Iteration per SR        = {:.2f}\n",
1,208✔
788
      static_cast<double>(RandomRay::total_geometric_intersections_) /
1,476✔
789
        static_cast<double>(settings::n_batches) /
2,952✔
790
        RandomRay::n_source_regions_);
791
    fmt::print(" Avg SR Miss Rate per Iteration    = {:.4f}%\n",
1,208✔
792
      RandomRay::avg_miss_rate_);
793
    fmt::print(" Energy Groups                     = {}\n", negroups_);
2,684✔
794
    if (settings::kinetic_simulation)
1,476✔
795
      fmt::print(" Delay Groups                      = {}\n", ndgroups_);
1,848✔
796
    fmt::print(
1,208✔
797
      " Total Integrations                = {:.4e}\n", total_integrations);
798
    fmt::print("   Avg per Iteration               = {:.4e}\n",
1,208✔
799
      total_integrations / settings::n_batches);
1,476✔
800

801
    std::string estimator;
1,476✔
802
    switch (domain_->volume_estimator_) {
1,476!
803
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
22✔
804
      estimator = "Simulation Averaged";
22✔
805
      break;
22✔
806
    case RandomRayVolumeEstimator::NAIVE:
68✔
807
      estimator = "Naive";
68✔
808
      break;
68✔
809
    case RandomRayVolumeEstimator::HYBRID:
1,386✔
810
      estimator = "Hybrid";
1,386✔
811
      break;
1,386✔
812
    default:
×
813
      fatal_error("Invalid volume estimator type");
×
814
    }
815
    fmt::print(" Volume Estimator Type             = {}\n", estimator);
1,208✔
816

817
    std::string adjoint_true = (FlatSourceDomain::adjoint_) ? "ON" : "OFF";
4,428✔
818
    fmt::print(" Adjoint Flux Mode                 = {}\n", adjoint_true);
1,208✔
819

820
    std::string shape;
2,952✔
821
    switch (RandomRay::source_shape_) {
1,476!
822
    case RandomRaySourceShape::FLAT:
1,223✔
823
      shape = "Flat";
1,223✔
824
      break;
1,223✔
825
    case RandomRaySourceShape::LINEAR:
220✔
826
      shape = "Linear";
220✔
827
      break;
220✔
828
    case RandomRaySourceShape::LINEAR_XY:
33✔
829
      shape = "Linear XY";
33✔
830
      break;
33✔
831
    default:
×
832
      fatal_error("Invalid random ray source shape");
×
833
    }
834
    fmt::print(" Source Shape                      = {}\n", shape);
1,208✔
835
    std::string sample_method =
836
      (RandomRay::sample_method_ == RandomRaySampleMethod::PRNG) ? "PRNG"
1,476✔
837
                                                                 : "Halton";
4,428✔
838
    fmt::print(" Sample Method                     = {}\n", sample_method);
1,208✔
839

840
    if (domain_->is_transport_stabilization_needed_) {
1,476✔
841
      fmt::print(" Transport XS Stabilization Used   = YES (rho = {:.3f})\n",
165✔
842
        FlatSourceDomain::diagonal_stabilization_rho_);
843
    } else {
844
      fmt::print(" Transport XS Stabilization Used   = NO\n");
1,311✔
845
    }
846
    if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,476✔
847
      std::string time_method =
848
        (RandomRay::time_method_ == RandomRayTimeMethod::ISOTROPIC)
660✔
849
          ? "ISOTROPIC"
850
          : "PROPAGATION";
1,320✔
851
      fmt::print(" Time Method                       = {}\n", time_method);
660✔
852
      fmt::print(
540✔
853
        " Backwards Difference Order        = {}\n", RandomRay::bd_order_);
854
    }
660✔
855

856
    header("Timing Statistics", 4);
1,476✔
857
    show_time("Total time for initialization", time_initialize.elapsed());
1,476✔
858
    show_time("Reading cross sections", time_read_xs.elapsed(), 1);
1,476✔
859
    show_time("Total simulation time", time_total.elapsed());
1,476✔
860
    show_time("Transport sweep only", time_transport.elapsed(), 1);
1,476✔
861
    show_time("Source update only", time_update_src.elapsed(), 1);
1,476✔
862
    if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
1,476!
863
      show_time(
924✔
864
        "Precursor computation only", time_compute_precursors.elapsed(), 1);
865
      misc_time -= time_compute_precursors.elapsed();
924✔
866
    }
867
    show_time("Tally conversion only", time_tallies.elapsed(), 1);
1,476✔
868
    show_time("MPI source reductions only", time_bank_sendrecv.elapsed(), 1);
1,476✔
869
    show_time("Other iteration routines", misc_time, 1);
1,476✔
870
    if (settings::run_mode == RunMode::EIGENVALUE) {
1,476✔
871
      show_time("Time in inactive batches", time_inactive.elapsed());
1,144✔
872
    }
873
    show_time("Time in active batches", time_active.elapsed());
1,476✔
874
    show_time("Time writing statepoints", time_statepoint.elapsed());
1,476✔
875
    show_time("Total time for finalization", time_finalize.elapsed());
1,476✔
876
    show_time("Time per integration", time_per_integration);
1,476✔
877
  }
1,476✔
878

879
  if (settings::verbosity >= 4 && settings::run_mode == RunMode::EIGENVALUE) {
1,476!
880
    header("Results", 4);
1,144✔
881
    fmt::print(" k-effective                       = {:.5f} +/- {:.5f}\n",
1,144✔
882
      simulation::keff, simulation::keff_std);
883
  }
884
}
1,476✔
885

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