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

openmc-dev / openmc / 23560024828

25 Mar 2026 07:28PM UTC coverage: 80.336% (-1.0%) from 81.326%
23560024828

Pull #3702

github

web-flow
Merge 0f768b2d1 into 6cd39073b
Pull Request #3702: Random Ray Kinetic Simulation Mode

17625 of 25263 branches covered (69.77%)

Branch coverage included in aggregate %.

926 of 1957 new or added lines in 21 files covered. (47.32%)

461 existing lines in 28 files now uncovered.

57995 of 68867 relevant lines covered (84.21%)

50654337.8 hits per line

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

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

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

20
namespace openmc {
21

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

26
// Enforces restrictions on inputs in random ray mode.  While there are
27
// many features that don't make sense in random ray mode, and are therefore
28
// unsupported, we limit our testing/enforcement operations only to inputs
29
// that may cause erroneous/misleading output or crashes from the solver.
30
void validate_random_ray_inputs()
630✔
31
{
32
  // Validate tallies
33
  ///////////////////////////////////////////////////////////////////
34
  for (auto& tally : model::tallies) {
1,610✔
35

36
    // Validate score types
37
    for (auto score_bin : tally->scores_) {
2,260✔
38
      switch (score_bin) {
1,280!
39
      case SCORE_FLUX:
40
      case SCORE_TOTAL:
41
      case SCORE_FISSION:
42
      case SCORE_NU_FISSION:
43
      case SCORE_EVENTS:
44
      case SCORE_KAPPA_FISSION:
45
        break;
46

47
      // TODO: add support for prompt and delayed fission
48
      case SCORE_PRECURSORS: {
40✔
49
        if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
40!
50
          break;
51
        } else {
NEW
52
          fatal_error("Invalid score specified in tallies.xml. Precursors can "
×
53
                      "only be scored for kinetic simulations.");
54
        }
55
      }
56
      default:
×
57
        fatal_error(
×
58
          "Invalid score specified. Only flux, total, fission, nu-fission, "
59
          "kappa-fission and event scores are supported in random ray mode. "
60
          "(precursors are supported for kinetic simulations when delayed "
61
          "neutrons are turned on).");
62
      }
63
    }
64

65
    // Validate filter types
66
    for (auto f : tally->filters()) {
2,130✔
67
      auto& filter = *model::tally_filters[f];
1,150✔
68

69
      switch (filter.type()) {
1,150!
70
      case FilterType::CELL:
71
      case FilterType::CELL_INSTANCE:
72
      case FilterType::DISTRIBCELL:
73
      case FilterType::ENERGY:
74
      case FilterType::MATERIAL:
75
      case FilterType::MESH:
76
      case FilterType::UNIVERSE:
77
      case FilterType::PARTICLE:
78
        break;
79
      case FilterType::DELAYED_GROUP:
40✔
80
        if (settings::kinetic_simulation) {
40!
81
          break;
82
        } else {
NEW
83
          fatal_error("Invalid filter specified in tallies.xml. Kinetic "
×
84
                      "simulations is required "
85
                      "to tally with a delayed_group filter.");
86
        }
87
      default:
×
88
        fatal_error("Invalid filter specified. Only cell, cell_instance, "
×
89
                    "distribcell, energy, material, mesh, and universe filters "
90
                    "are supported in random ray mode (delayed_group is "
91
                    "supported for kinetic simulations).");
92
      }
93
    }
94
  }
95

96
  // TODO: validate kinetic data is present
97
  //  Validate MGXS data
98
  ///////////////////////////////////////////////////////////////////
99
  for (auto& material : data::mg.macro_xs_) {
2,350✔
100
    if (!material.is_isotropic) {
1,720!
101
      fatal_error("Anisotropic MGXS detected. Only isotropic XS data sets "
×
102
                  "supported in random ray mode.");
103
    }
104
    for (int g = 0; g < data::mg.num_energy_groups_; g++) {
12,860✔
105
      if (material.exists_in_model) {
11,140✔
106
        // Temperature and angle indices, if using multiple temperature
107
        // data sets and/or anisotropic data sets.
108
        // TODO: Currently assumes we are only using single temp/single angle
109
        // data.
110
        const int t = 0;
11,100✔
111
        const int a = 0;
11,100✔
112
        double sigma_t =
11,100✔
113
          material.get_xs(MgxsType::TOTAL, g, NULL, NULL, NULL, t, a);
11,100✔
114
        if (sigma_t <= 0.0) {
11,100!
115
          fatal_error("No zero or negative total macroscopic cross sections "
×
116
                      "allowed in random ray mode. If the intention is to make "
117
                      "a void material, use a cell fill of 'None' instead.");
118
        }
119
      }
120
    }
121
  }
122

123
  // Validate ray source
124
  ///////////////////////////////////////////////////////////////////
125

126
  // Check for independent source
127
  IndependentSource* is =
630!
128
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
630!
129
  if (!is) {
630!
130
    fatal_error("Invalid ray source definition. Ray source must provided and "
×
131
                "be of type IndependentSource.");
132
  }
133

134
  // Check for box source
135
  SpatialDistribution* space_dist = is->space();
630!
136
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
630!
137
  if (!sb) {
630!
138
    fatal_error(
×
139
      "Invalid ray source definition -- only box sources are allowed.");
140
  }
141

142
  // Check that box source is not restricted to fissionable areas
143
  if (sb->only_fissionable()) {
630!
144
    fatal_error(
×
145
      "Invalid ray source definition -- fissionable spatial distribution "
146
      "not allowed.");
147
  }
148

149
  // Check for isotropic source
150
  UnitSphereDistribution* angle_dist = is->angle();
630!
151
  Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
630!
152
  if (!id) {
630!
153
    fatal_error("Invalid ray source definition -- only isotropic sources are "
×
154
                "allowed.");
155
  }
156

157
  // Validate external sources
158
  ///////////////////////////////////////////////////////////////////
159
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
630✔
160
    if (model::external_sources.size() < 1) {
270!
161
      fatal_error("Must provide a particle source (in addition to ray source) "
×
162
                  "in fixed source random ray mode.");
163
    }
164

165
    for (int i = 0; i < model::external_sources.size(); i++) {
540✔
166
      Source* s = model::external_sources[i].get();
270!
167

168
      // Check for independent source
169
      IndependentSource* is = dynamic_cast<IndependentSource*>(s);
270!
170

171
      if (!is) {
270!
172
        fatal_error(
×
173
          "Only IndependentSource external source types are allowed in "
174
          "random ray mode");
175
      }
176

177
      // Check for isotropic source
178
      UnitSphereDistribution* angle_dist = is->angle();
270!
179
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
270!
180
      if (!id) {
270!
181
        fatal_error(
×
182
          "Invalid source definition -- only isotropic external sources are "
183
          "allowed in random ray mode.");
184
      }
185

186
      // Validate that a domain ID was specified OR that it is a point source
187
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
270!
188
      if (is->domain_ids().size() == 0 && !sp) {
270!
189
        fatal_error("Fixed sources must be point source or spatially "
×
190
                    "constrained by domain id (cell, material, or universe) in "
191
                    "random ray mode.");
192
      } else if (is->domain_ids().size() > 0 && sp) {
270✔
193
        // If both a domain constraint and a non-default point source location
194
        // are specified, notify user that domain constraint takes precedence.
195
        if (sp->r().x == 0.0 && sp->r().y == 0.0 && sp->r().z == 0.0) {
230!
196
          warning("Fixed source has both a domain constraint and a point "
460✔
197
                  "type spatial distribution. The domain constraint takes "
198
                  "precedence in random ray mode -- point source coordinate "
199
                  "will be ignored.");
200
        }
201
      }
202

203
      // Check that a discrete energy distribution was used
204
      Distribution* d = is->energy();
270!
205
      Discrete* dd = dynamic_cast<Discrete*>(d);
270!
206
      if (!dd) {
270!
207
        fatal_error(
×
208
          "Only discrete (multigroup) energy distributions are allowed for "
209
          "external sources in random ray mode.");
210
      }
211
    }
212
  }
213

214
  // Validate plotting files
215
  ///////////////////////////////////////////////////////////////////
216
  for (int p = 0; p < model::plots.size(); p++) {
630!
217

218
    // Get handle to OpenMC plot object
219
    const auto& openmc_plottable = model::plots[p];
×
220
    Plot* openmc_plot = dynamic_cast<Plot*>(openmc_plottable.get());
×
221

222
    // Random ray plots only support voxel plots
223
    if (!openmc_plot) {
×
224
      warning(fmt::format(
×
225
        "Plot {} will not be used for end of simulation data plotting -- only "
226
        "voxel plotting is allowed in random ray mode.",
227
        openmc_plottable->id()));
×
228
      continue;
×
229
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
230
      warning(fmt::format(
×
231
        "Plot {} will not be used for end of simulation data plotting -- only "
232
        "voxel plotting is allowed in random ray mode.",
233
        openmc_plottable->id()));
×
234
      continue;
×
235
    }
236
  }
237

238
  // Warn about slow MPI domain replication, if detected
239
  ///////////////////////////////////////////////////////////////////
240
#ifdef OPENMC_MPI
241
  if (mpi::n_procs > 1) {
189✔
242
    warning(
372✔
243
      "MPI parallelism is not supported by the random ray solver. All work "
244
      "will be performed by rank 0. Domain decomposition may be implemented in "
245
      "the future to provide efficient MPI scaling.");
246
  }
247
#endif
248

249
  // Warn about instability resulting from linear sources in small regions
250
  // when generating weight windows with FW-CADIS and an overlaid mesh.
251
  ///////////////////////////////////////////////////////////////////
252
  if (RandomRay::source_shape_ == RandomRaySourceShape::LINEAR &&
630✔
253
      variance_reduction::weight_windows.size() > 0) {
220✔
254
    warning(
20✔
255
      "Linear sources may result in negative fluxes in small source regions "
256
      "generated by mesh subdivision. Negative sources may result in low "
257
      "quality FW-CADIS weight windows. We recommend you use flat source mode "
258
      "when generating weight windows with an overlaid mesh tally.");
259
  }
260
}
630✔
261

NEW
262
void openmc_reset_random_ray()
×
263
{
NEW
264
  FlatSourceDomain::volume_estimator_ = RandomRayVolumeEstimator::HYBRID;
×
NEW
265
  FlatSourceDomain::volume_normalized_flux_tallies_ = false;
×
NEW
266
  FlatSourceDomain::adjoint_ = false;
×
NEW
267
  FlatSourceDomain::mesh_domain_map_.clear();
×
NEW
268
  RandomRay::ray_source_.reset();
×
NEW
269
  RandomRay::source_shape_ = RandomRaySourceShape::FLAT;
×
NEW
270
  RandomRay::sample_method_ = RandomRaySampleMethod::PRNG;
×
NEW
271
  RandomRay::bd_order_ = 3;
×
NEW
272
  RandomRay::time_method_ = RandomRayTimeMethod::ISOTROPIC;
×
NEW
273
}
×
274

275
void write_random_ray_hdf5(hid_t group)
1,400✔
276
{
277
  hid_t random_ray_group = create_group(group, "random_ray");
1,400✔
278
  switch (RandomRay::source_shape_) {
1,400!
279
  case RandomRaySourceShape::FLAT:
1,140✔
280
    write_dataset(random_ray_group, "source_shape", "flat");
1,140✔
281
    break;
1,140✔
282
  case RandomRaySourceShape::LINEAR:
230✔
283
    write_dataset(random_ray_group, "source_shape", "linear");
230✔
284
    break;
230✔
285
  case RandomRaySourceShape::LINEAR_XY:
30✔
286
    write_dataset(random_ray_group, "source_shape", "linear xy");
30✔
287
    break;
30✔
288
  default:
289
    break;
290
  }
291

292
  switch (FlatSourceDomain::volume_estimator_) {
1,400!
293
  case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
20✔
294
    write_dataset(random_ray_group, "volume_estimator", "simulation averaged");
20✔
295
    break;
20✔
296
  case RandomRayVolumeEstimator::NAIVE:
60✔
297
    write_dataset(random_ray_group, "volume_estimator", "naive");
60✔
298
    break;
60✔
299
  case RandomRayVolumeEstimator::HYBRID:
1,320✔
300
    write_dataset(random_ray_group, "volume_estimator", "hybrid");
1,320✔
301
    break;
1,320✔
302
  default:
303
    break;
304
  }
305

306
  write_dataset(
1,400✔
307
    random_ray_group, "distance_active", RandomRay::distance_active_);
308
  write_dataset(
1,400✔
309
    random_ray_group, "distance_inactive", RandomRay::distance_inactive_);
310
  write_dataset(random_ray_group, "volume_normalized_flux_tallies",
1,400✔
311
    FlatSourceDomain::volume_normalized_flux_tallies_);
312
  write_dataset(random_ray_group, "adjoint_mode", FlatSourceDomain::adjoint_);
1,400✔
313

314
  write_dataset(random_ray_group, "avg_miss_rate", RandomRay::avg_miss_rate_);
1,400✔
315
  write_dataset(
1,400✔
316
    random_ray_group, "n_source_regions", RandomRay::n_source_regions_);
317
  write_dataset(random_ray_group, "n_external_source_regions",
1,400✔
318
    RandomRay::n_external_source_regions_);
319
  write_dataset(random_ray_group, "n_geometric_intersections",
1,400✔
320
    RandomRay::total_geometric_intersections_);
321
  int64_t n_integrations =
1,400✔
322
    RandomRay::total_geometric_intersections_ * data::mg.num_energy_groups_;
1,400✔
323
  write_dataset(random_ray_group, "n_integrations", n_integrations);
1,400✔
324

325
  if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,400✔
326
    write_dataset(random_ray_group, "bd_order", RandomRay::bd_order_);
600✔
327
    switch (RandomRay::time_method_) {
600!
328
    case RandomRayTimeMethod::ISOTROPIC:
400✔
329
      write_dataset(random_ray_group, "time_method", "isotropic");
400✔
330
      break;
400✔
331
    case RandomRayTimeMethod::PROPAGATION:
200✔
332
      write_dataset(random_ray_group, "time_method", "propogation");
200✔
333
      break;
200✔
334
    default:
335
      break;
336
    }
337
  }
338
  close_group(random_ray_group);
1,400✔
339
}
1,400✔
340

341
void print_adjoint_header()
100✔
342
{
343
  if (!FlatSourceDomain::adjoint_)
100✔
344
    // If we're going to do an adjoint simulation afterwards, report that this
345
    // is the initial forward flux solve.
346
    header("FORWARD FLUX SOLVE", 3);
50✔
347
  else
348
    // Otherwise report that we are doing the adjoint simulation
349
    header("ADJOINT FLUX SOLVE", 3);
50✔
350
}
100✔
351

352
//-----------------------------------------------------------------------------
353
// Non-member functions for kinetic simulations
354

355
void rename_time_step_file(
1,872✔
356
  std::string base_filename, std::string extension, int i)
357
{
358
  // Rename file
359
  std::string old_filename_ =
1,872✔
360
    fmt::format("{0}{1}{2}", settings::path_output, base_filename, extension);
1,872✔
361
  std::string new_filename_ = fmt::format(
1,872✔
362
    "{0}{1}_{2}{3}", settings::path_output, base_filename, i, extension);
1,872✔
363

364
  const char* old_fname = old_filename_.c_str();
1,872✔
365
  const char* new_fname = new_filename_.c_str();
1,872✔
366
  std::rename(old_fname, new_fname);
1,872✔
367
}
1,872✔
368

369
//==============================================================================
370
// RandomRaySimulation implementation
371
//==============================================================================
372

373
RandomRaySimulation::RandomRaySimulation()
816✔
374
  : negroups_(data::mg.num_energy_groups_),
816!
375
    ndgroups_(data::mg.num_delayed_groups_)
816!
376
{
377
  // There are no source sites in random ray mode, so be sure to disable to
378
  // ensure we don't attempt to write source sites to statepoint
379
  settings::source_write = false;
816✔
380

381
  // Random ray mode does not have an inner loop over generations within a
382
  // batch, so set the current gen to 1
383
  simulation::current_gen = 1;
816✔
384

385
  switch (RandomRay::source_shape_) {
816!
386
  case RandomRaySourceShape::FLAT:
491✔
387
    domain_ = make_unique<FlatSourceDomain>();
491✔
388
    break;
491✔
389
  case RandomRaySourceShape::LINEAR:
325✔
390
  case RandomRaySourceShape::LINEAR_XY:
325✔
391
    domain_ = make_unique<LinearSourceDomain>();
325✔
392
    break;
325✔
393
  default:
×
394
    fatal_error("Unknown random ray source shape");
×
395
  }
396

397
  // Convert OpenMC native MGXS into a more efficient format
398
  // internal to the random ray solver
399
  domain_->flatten_xs();
816✔
400

401
  // Check if adjoint calculation is needed. If it is, we will run the forward
402
  // calculation first and then the adjoint calculation later.
403
  adjoint_needed_ = FlatSourceDomain::adjoint_;
816✔
404

405
  // Adjoint is always false for the forward calculation
406
  FlatSourceDomain::adjoint_ = false;
816✔
407

408
  // The first simulation is run after initialization
409
  is_first_simulation_ = true;
816✔
410

411
  // Initialize vectors used for baking in the initial condition during time
412
  // stepping
413
  if (settings::kinetic_simulation) {
816✔
414
    // Initialize vars used for time-consistent seed approach
415
    static_avg_k_eff_;
416
    static_k_eff_;
417
    static_fission_rate_;
418
  }
419
}
816✔
420

421
void RandomRaySimulation::apply_fixed_sources_and_mesh_domains()
816✔
422
{
423
  domain_->apply_meshes();
816✔
424
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
816✔
425
    // Transfer external source user inputs onto random ray source regions
426
    domain_->convert_external_sources();
351✔
427
    domain_->count_external_source_regions();
351✔
428
  }
429
}
816✔
430

431
void RandomRaySimulation::prepare_fixed_sources_adjoint()
65✔
432
{
433
  domain_->source_regions_.adjoint_reset();
65✔
434
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
65✔
435
    domain_->set_adjoint_sources();
52✔
436
  }
437
}
65✔
438

439
void RandomRaySimulation::prepare_adjoint_simulation()
65✔
440
{
441
  // Configure the domain for adjoint simulation
442
  FlatSourceDomain::adjoint_ = true;
65✔
443

444
  // Reset k-eff
445
  domain_->k_eff_ = 1.0;
65✔
446

447
  // Initialize adjoint fixed sources, if present
448
  prepare_fixed_sources_adjoint();
65✔
449

450
  // Transpose scattering matrix
451
  domain_->transpose_scattering_matrix();
65✔
452

453
  // Swap nu_sigma_f and chi
454
  domain_->nu_sigma_f_.swap(domain_->chi_);
65✔
455
}
65✔
456

457
// TODO: Add support for time-dependent restart
458
void RandomRaySimulation::kinetic_single_time_step(int i)
936✔
459
{
460
  // Increment time step
461
  simulation::current_timestep = i + 1;
936✔
462
  if (i >= 0)
936✔
463
    // Increment the current time
464
    simulation::current_time += settings::dt;
780✔
465

466
  // Set eigenvalue if needed
467
  if (settings::run_mode == RunMode::EIGENVALUE) {
936!
468
    if (i == -1) {
936✔
469
      // Set flag for k_eff correction if initial condition
470
      simulation::k_eff_correction = true;
156✔
471

472
      // Store average keff from initial simulation
473
      static_avg_k_eff_ = simulation::keff;
156✔
474
    }
475
    domain_->k_eff_ = static_avg_k_eff_;
936✔
476
  }
477
  domain_->source_regions_.adjoint_reset();
936✔
478
  domain_->propagate_final_quantities();
936✔
479
  domain_->source_regions_.time_step_reset();
936✔
480

481
  if (i >= 0) {
936✔
482
    // Compute RHS backward differences
483
    domain_->compute_rhs_bd_quantities();
780✔
484

485
    // Update time dependent cross section based on the density
486
    domain_->update_material_density(i);
780✔
487
  }
488

489
  // Run the initial condition
490
  simulate();
936✔
491

492
  if (i == -1) {
936✔
493
    // Initialize the BD arrays if initial condition
494
    domain_->store_time_step_quantities(false);
156✔
495
    // Reset flags for kinetic simulation if initial condition
496
    simulation::is_initial_condition = false;
156✔
497
    simulation::k_eff_correction = false;
156✔
498
  } else {
499
    // Else, store final quantities for the current time step
500
    domain_->store_time_step_quantities();
780✔
501
  }
502

503
  // Rename statepoint and tallies file for the current time step
504
  rename_time_step_file(fmt::format("statepoint.{0}", settings::n_batches),
1,872✔
505
    ".h5", simulation::current_timestep);
506
  if (settings::output_tallies)
936!
507
    rename_time_step_file("tallies", ".out", simulation::current_timestep);
1,872✔
508
}
936✔
509

510
void RandomRaySimulation::simulate()
1,817✔
511
{
512
  if (!is_first_simulation_) {
1,817✔
513
    if (mpi::master && adjoint_needed_)
1,001✔
514
      openmc::print_adjoint_header();
50✔
515

516
    // Reset the timers and reinitialize the general OpenMC datastructures if
517
    // this is after the first simulation
518
    reset_timers();
1,001✔
519

520
    // Initialize OpenMC general data structures
521
    openmc_simulation_init();
1,001✔
522
  }
523

524
  // Begin main simulation timer
525
  simulation::time_total.start();
1,817✔
526

527
  // Random ray power iteration loop
528
  while (simulation::current_batch < settings::n_batches) {
176,194✔
529
    // Initialize the current batch
530
    initialize_batch();
172,560✔
531
    initialize_generation();
172,560✔
532

533
    // MPI not supported in random ray solver, so all work is done by rank 0
534
    // TODO: Implement domain decomposition for MPI parallelism
535
    if (mpi::master) {
172,560✔
536

537
      // Reset total starting particle weight used for normalizing tallies
538
      simulation::total_weight = 1.0;
133,200✔
539

540
      // Update source term (scattering + fission (+ delayed if kinetic))
541
      domain_->update_all_neutron_sources();
133,200✔
542

543
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
544
      // to zero
545
      domain_->batch_reset();
133,200✔
546

547
      // At the beginning of the simulation, if mesh subdivision is in use, we
548
      // need to swap the main source region container into the base container,
549
      // as the main source region container will be used to hold the true
550
      // subdivided source regions. The base container will therefore only
551
      // contain the external source region information, the mesh indices,
552
      // material properties, and initial guess values for the flux/source.
553

554
      // Start timer for transport
555
      simulation::time_transport.start();
133,200✔
556

557
// Transport sweep over all random rays for the iteration
558
#pragma omp parallel for schedule(dynamic)                                     \
66,600✔
559
  reduction(+ : total_geometric_intersections_)
66,600✔
560
      for (int i = 0; i < settings::n_particles; i++) {
6,994,600✔
561
        RandomRay ray(i, domain_.get());
6,928,000✔
562
        total_geometric_intersections_ +=
13,856,000✔
563
          ray.transport_history_based_single_ray();
6,928,000✔
564
      }
6,928,000✔
565

566
      simulation::time_transport.stop();
133,200✔
567

568
      // Add any newly discovered source regions to the main source region
569
      // container.
570
      domain_->finalize_discovered_source_regions();
133,200✔
571

572
      // Normalize scalar flux and update volumes
573
      domain_->normalize_scalar_flux_and_volumes(
133,200✔
574
        settings::n_particles * RandomRay::distance_active_);
575

576
      // Add source to scalar flux, compute number of FSR hits
577
      int64_t n_hits = domain_->add_source_to_scalar_flux();
133,200✔
578

579
      // Apply transport stabilization factors
580
      domain_->apply_transport_stabilization();
133,200✔
581

582
      if (settings::run_mode == RunMode::EIGENVALUE) {
133,200✔
583
        // Compute random ray k-eff
584
        if (!settings::kinetic_simulation ||
124,100✔
585
            settings::kinetic_simulation && simulation::is_initial_condition) {
119,000✔
586
          domain_->compute_k_eff();
39,100✔
587
          if (simulation::k_eff_correction) {
39,100✔
588
            static_fission_rate_.push_back(domain_->fission_rate_);
17,000✔
589
            static_k_eff_.push_back(domain_->k_eff_);
17,000✔
590
          }
591
        } else {
592
          domain_->k_eff_ = static_k_eff_[simulation::current_batch - 1];
85,000✔
593
          domain_->fission_rate_ =
85,000✔
594
            static_fission_rate_[simulation::current_batch - 1];
85,000✔
595
        }
596

597
        // Store random ray k-eff into OpenMC's native k-eff variable
598
        global_tally_tracklength = domain_->k_eff_;
124,100✔
599
      }
600

601
      // Compute precursors if delayed neutrons are turned on
602
      if (settings::kinetic_simulation && settings::create_delayed_neutrons)
133,200!
603
        domain_->compute_all_precursors();
119,000✔
604

605
      // Execute all tallying tasks, if this is an active batch
606
      if (simulation::current_batch > settings::n_inactive) {
133,200✔
607

608
        // Add this iteration's scalar flux estimate to final accumulated
609
        // estimate
610
        domain_->accumulate_iteration_quantities();
65,450✔
611

612
        // Use above mapping to contribute FSR flux data to appropriate
613
        // tallies
614
        domain_->random_ray_tally();
65,450✔
615
      }
616

617
      // Set phi_old = phi_new
618
      domain_->flux_swap();
133,200✔
619
      if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
133,200!
620
        domain_->precursors_swap();
119,000✔
621
      }
622

623
      // Check for any obvious insabilities/nans/infs
624
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
133,200✔
625
    } // End MPI master work
626

627
    // Store simulation metrics
628
    RandomRay::avg_miss_rate_ = avg_miss_rate_ / settings::n_batches;
172,560✔
629
    RandomRay::total_geometric_intersections_ = total_geometric_intersections_;
172,560✔
630
    RandomRay::n_external_source_regions_ = domain_->n_external_source_regions_;
172,560✔
631
    RandomRay::n_source_regions_ = domain_->n_source_regions();
172,560✔
632

633
    // Finalize the current batch
634
    finalize_generation();
172,560✔
635
    finalize_batch();
172,560✔
636
  } // End random ray power iteration loop
637

638
  domain_->count_external_source_regions();
1,817✔
639

640
  // End main simulation timer
641
  simulation::time_total.stop();
1,817✔
642

643
  // Normalize and save the final forward quantities
644
  domain_->normalize_final_quantities();
1,817✔
645

646
  // Finalize OpenMC
647
  openmc_simulation_finalize();
1,817✔
648

649
  // Output all simulation results
650
  output_simulation_results();
1,817✔
651

652
  // Toggle that the simulation object has been initialized after the first
653
  // simulation
654
  if (is_first_simulation_)
1,817✔
655
    is_first_simulation_ = false;
816✔
656
}
1,817✔
657

658
void RandomRaySimulation::output_simulation_results() const
1,817✔
659
{
660
  // Print random ray results
661
  if (mpi::master) {
1,817✔
662
    print_results_random_ray();
1,400✔
663
    if (model::plots.size() > 0) {
1,400!
UNCOV
664
      domain_->output_to_vtk();
×
665
    }
666
  }
667
}
1,817✔
668

669
// Apply a few sanity checks to catch obvious cases of numerical instability.
670
// Instability typically only occurs if ray density is extremely low.
671
void RandomRaySimulation::instability_check(
133,200✔
672
  int64_t n_hits, double k_eff, double& avg_miss_rate) const
673
{
674
  double percent_missed = ((domain_->n_source_regions() - n_hits) /
133,200!
675
                            static_cast<double>(domain_->n_source_regions())) *
133,200✔
676
                          100.0;
133,200✔
677
  avg_miss_rate += percent_missed;
133,200✔
678

679
  if (mpi::master) {
133,200!
680
    if (percent_missed > 10.0) {
133,200✔
681
      warning(fmt::format(
1,740✔
682
        "Very high FSR miss rate detected ({:.3f}%). Instability may occur. "
683
        "Increase ray density by adding more rays and/or active distance.",
684
        percent_missed));
685
    } else if (percent_missed > 1.0) {
132,330!
UNCOV
686
      warning(
×
UNCOV
687
        fmt::format("Elevated FSR miss rate detected ({:.3f}%). Increasing "
×
688
                    "ray density by adding more rays and/or active "
689
                    "distance may improve simulation efficiency.",
690
          percent_missed));
691
    }
692

693
    if (k_eff > 10.0 || k_eff < 0.01 || !(std::isfinite(k_eff))) {
133,200!
UNCOV
694
      fatal_error(fmt::format("Instability detected: k-eff = {:.5f}", k_eff));
×
695
    }
696
  }
697
}
133,200✔
698

699
// Print random ray simulation results
700
void RandomRaySimulation::print_results_random_ray() const
1,400✔
701
{
702
  using namespace simulation;
1,400✔
703

704
  if (settings::verbosity >= 6) {
1,400!
705
    double total_integrations =
1,400✔
706
      RandomRay::total_geometric_intersections_ * negroups_;
1,400✔
707
    double time_per_integration =
1,400✔
708
      simulation::time_transport.elapsed() / total_integrations;
1,400✔
709
    double misc_time = time_total.elapsed() - time_update_src.elapsed() -
1,400✔
710
                       time_transport.elapsed() - time_tallies.elapsed() -
1,400✔
711
                       time_bank_sendrecv.elapsed();
1,400✔
712

713
    if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,400✔
714
      misc_time -= time_update_bd_vectors.elapsed();
600✔
715
    }
716
    header("Simulation Statistics", 4);
1,400✔
717
    fmt::print(
1,400✔
718
      " Total Iterations                  = {}\n", settings::n_batches);
719
    fmt::print(
1,400✔
720
      " Number of Rays per Iteration      = {}\n", settings::n_particles);
721
    fmt::print(" Inactive Distance                 = {} cm\n",
1,400✔
722
      RandomRay::distance_inactive_);
723
    fmt::print(" Active Distance                   = {} cm\n",
1,400✔
724
      RandomRay::distance_active_);
725
    fmt::print(" Source Regions (SRs)              = {}\n",
1,400✔
726
      RandomRay::n_source_regions_);
727
    fmt::print(" SRs Containing External Sources   = {}\n",
1,400✔
728
      RandomRay::n_external_source_regions_);
729
    fmt::print(" Total Geometric Intersections     = {:.4e}\n",
2,800✔
730
      static_cast<double>(RandomRay::total_geometric_intersections_));
1,400✔
731
    fmt::print("   Avg per Iteration               = {:.4e}\n",
2,800✔
732
      static_cast<double>(RandomRay::total_geometric_intersections_) /
1,400✔
733
        settings::n_batches);
734
    fmt::print("   Avg per Iteration per SR        = {:.2f}\n",
2,800✔
735
      static_cast<double>(RandomRay::total_geometric_intersections_) /
1,400✔
736
        static_cast<double>(settings::n_batches) /
1,400✔
737
        RandomRay::n_source_regions_);
738
    fmt::print(" Avg SR Miss Rate per Iteration    = {:.4f}%\n",
1,400✔
739
      RandomRay::avg_miss_rate_);
740
    fmt::print(" Energy Groups                     = {}\n", negroups_);
1,400✔
741
    if (settings::kinetic_simulation)
1,400✔
742
      fmt::print(" Delay Groups                      = {}\n", ndgroups_);
840✔
743
    fmt::print(
1,400✔
744
      " Total Integrations                = {:.4e}\n", total_integrations);
745
    fmt::print("   Avg per Iteration               = {:.4e}\n",
2,800✔
746
      total_integrations / settings::n_batches);
1,400✔
747

748
    std::string estimator;
1,400!
749
    switch (domain_->volume_estimator_) {
1,400!
750
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
20✔
751
      estimator = "Simulation Averaged";
20✔
752
      break;
753
    case RandomRayVolumeEstimator::NAIVE:
60✔
754
      estimator = "Naive";
60✔
755
      break;
756
    case RandomRayVolumeEstimator::HYBRID:
1,320✔
757
      estimator = "Hybrid";
1,320✔
758
      break;
UNCOV
759
    default:
×
UNCOV
760
      fatal_error("Invalid volume estimator type");
×
761
    }
762
    fmt::print(" Volume Estimator Type             = {}\n", estimator);
1,400✔
763

764
    std::string adjoint_true = (FlatSourceDomain::adjoint_) ? "ON" : "OFF";
4,150✔
765
    fmt::print(" Adjoint Flux Mode                 = {}\n", adjoint_true);
1,400✔
766

767
    std::string shape;
2,800!
768
    switch (RandomRay::source_shape_) {
1,400!
769
    case RandomRaySourceShape::FLAT:
1,140✔
770
      shape = "Flat";
1,140✔
771
      break;
772
    case RandomRaySourceShape::LINEAR:
230✔
773
      shape = "Linear";
230✔
774
      break;
775
    case RandomRaySourceShape::LINEAR_XY:
30✔
776
      shape = "Linear XY";
30✔
777
      break;
UNCOV
778
    default:
×
UNCOV
779
      fatal_error("Invalid random ray source shape");
×
780
    }
781
    fmt::print(" Source Shape                      = {}\n", shape);
1,400✔
782
    std::string sample_method;
2,800!
783
    switch (RandomRay::sample_method_) {
1,400!
784
    case RandomRaySampleMethod::PRNG:
1,380✔
785
      sample_method = "PRNG";
1,380✔
786
      break;
787
    case RandomRaySampleMethod::HALTON:
10✔
788
      sample_method = "Halton";
10✔
789
      break;
790
    case RandomRaySampleMethod::S2:
10✔
791
      sample_method = "PRNG S2";
10✔
792
      break;
793
    }
794
    fmt::print(" Sample Method                     = {}\n", sample_method);
1,400✔
795

796
    if (domain_->is_transport_stabilization_needed_) {
1,400✔
797
      fmt::print(" Transport XS Stabilization Used   = YES (rho = {:.3f})\n",
150✔
798
        FlatSourceDomain::diagonal_stabilization_rho_);
799
    } else {
800
      fmt::print(" Transport XS Stabilization Used   = NO\n");
1,250✔
801
    }
802
    if (settings::kinetic_simulation && !simulation::is_initial_condition) {
1,400✔
803
      std::string time_method =
600✔
804
        (RandomRay::time_method_ == RandomRayTimeMethod::ISOTROPIC)
600✔
805
          ? "ISOTROPIC"
806
          : "PROPAGATION";
800✔
807
      fmt::print(" Time Method                       = {}\n", time_method);
600✔
808
      fmt::print(
600✔
809
        " Backwards Difference Order        = {}\n", RandomRay::bd_order_);
810
    }
600✔
811

812
    header("Timing Statistics", 4);
1,400✔
813
    show_time("Total time for initialization", time_initialize.elapsed());
1,400✔
814
    show_time("Reading cross sections", time_read_xs.elapsed(), 1);
1,400✔
815
    show_time("Total simulation time", time_total.elapsed());
1,400✔
816
    show_time("Transport sweep only", time_transport.elapsed(), 1);
1,400✔
817
    show_time("Source update only", time_update_src.elapsed(), 1);
1,400✔
818
    if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
1,400!
819
      show_time(
840✔
820
        "Precursor computation only", time_compute_precursors.elapsed(), 1);
821
      misc_time -= time_compute_precursors.elapsed();
840✔
822
    }
823
    show_time("Tally conversion only", time_tallies.elapsed(), 1);
1,400✔
824
    show_time("MPI source reductions only", time_bank_sendrecv.elapsed(), 1);
1,400✔
825
    show_time("Other iteration routines", misc_time, 1);
1,400✔
826
    if (settings::run_mode == RunMode::EIGENVALUE) {
1,400✔
827
      show_time("Time in inactive batches", time_inactive.elapsed());
1,090✔
828
    }
829
    show_time("Time in active batches", time_active.elapsed());
1,400✔
830
    show_time("Time writing statepoints", time_statepoint.elapsed());
1,400✔
831
    show_time("Total time for finalization", time_finalize.elapsed());
1,400✔
832
    show_time("Time per integration", time_per_integration);
1,400✔
833
  }
1,400✔
834

835
  if (settings::verbosity >= 4 && settings::run_mode == RunMode::EIGENVALUE) {
1,400!
836
    header("Results", 4);
1,090✔
837
    fmt::print(" k-effective                       = {:.5f} +/- {:.5f}\n",
1,090✔
838
      simulation::keff, simulation::keff_std);
839
  }
840
}
1,400✔
841

842
void openmc_finalize_random_ray()
7,613✔
843
{
844
  FlatSourceDomain::volume_estimator_ = RandomRayVolumeEstimator::HYBRID;
7,613✔
845
  FlatSourceDomain::volume_normalized_flux_tallies_ = false;
7,613✔
846
  FlatSourceDomain::adjoint_ = false;
7,613✔
847
  FlatSourceDomain::mesh_domain_map_.clear();
7,613✔
848
  RandomRay::ray_source_.reset();
7,613✔
849
  RandomRay::source_shape_ = RandomRaySourceShape::FLAT;
7,613✔
850
  RandomRay::sample_method_ = RandomRaySampleMethod::PRNG;
7,613✔
851
}
7,613✔
852

853
} // namespace openmc
854

855
//==============================================================================
856
// C API functions
857
//==============================================================================
858

859
void openmc_run_random_ray()
816✔
860
{
861
  //////////////////////////////////////////////////////////
862
  // Run forward simulation
863
  //////////////////////////////////////////////////////////
864

865
  if (openmc::mpi::master) {
816✔
866
    if (openmc::FlatSourceDomain::adjoint_) {
630✔
867
      openmc::FlatSourceDomain::adjoint_ = false;
50✔
868
      openmc::print_adjoint_header();
50✔
869
      openmc::FlatSourceDomain::adjoint_ = true;
50✔
870
    }
871
  }
872

873
  // Initialize OpenMC general data structures
874
  openmc_simulation_init();
816✔
875

876
  // Validate that inputs meet requirements for random ray mode
877
  if (openmc::mpi::master)
816✔
878
    openmc::validate_random_ray_inputs();
630✔
879

880
  // Initialize Random Ray Simulation Object
881
  openmc::RandomRaySimulation sim;
816✔
882

883
  // Initialize fixed sources, if present
884
  sim.apply_fixed_sources_and_mesh_domains();
816✔
885

886
  // Run initial random ray simulation
887
  sim.simulate();
816✔
888

889
  if (openmc::settings::kinetic_simulation) {
816✔
890
    // Timestepping loop, including k-eff correction initial
891
    // condition (i = -1)
892
    for (int i = -1; i < openmc::settings::n_timesteps; i++)
1,092✔
893
      sim.kinetic_single_time_step(i);
936✔
894
  }
895

896
  //////////////////////////////////////////////////////////
897
  // Run adjoint simulation (if enabled)
898
  //////////////////////////////////////////////////////////
899

900
  if (sim.adjoint_needed_) {
816✔
901
    // Setup for adjoint simulation
902
    sim.prepare_adjoint_simulation();
65✔
903

904
    // Run adjoint simulation
905
    sim.simulate();
65✔
906
  }
907
}
816✔
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