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

openmc-dev / openmc / 29079049279

10 Jul 2026 08:12AM UTC coverage: 80.467% (-0.8%) from 81.292%
29079049279

Pull #3951

github

web-flow
Merge b5a65303a into 7c408f6a1
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16741 of 24259 branches covered (69.01%)

Branch coverage included in aggregate %.

70 of 132 new or added lines in 10 files covered. (53.03%)

790 existing lines in 49 files now uncovered.

57487 of 67988 relevant lines covered (84.55%)

28150237.78 hits per line

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

79.97
/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()
212✔
31
{
32
  // Validate tallies
33
  ///////////////////////////////////////////////////////////////////
34
  for (auto& tally : model::tallies) {
604✔
35

36
    // Validate score types
37
    for (auto score_bin : tally->scores_) {
872✔
38
      switch (score_bin) {
480!
39
      case SCORE_FLUX:
480✔
40
      case SCORE_TOTAL:
480✔
41
      case SCORE_FISSION:
480✔
42
      case SCORE_NU_FISSION:
480✔
43
      case SCORE_EVENTS:
480✔
44
      case SCORE_KAPPA_FISSION:
480✔
45
        break;
480✔
46
      default:
×
47
        fatal_error(
×
48
          "Invalid score specified. Only flux, total, fission, nu-fission, "
49
          "kappa-fission, and event scores are supported in random ray mode.");
50
      }
51
    }
52

53
    // Validate filter types
54
    for (auto f : tally->filters()) {
852✔
55
      auto& filter = *model::tally_filters[f];
460✔
56

57
      switch (filter.type()) {
460!
58
      case FilterType::CELL:
460✔
59
      case FilterType::CELL_INSTANCE:
460✔
60
      case FilterType::DISTRIBCELL:
460✔
61
      case FilterType::ENERGY:
460✔
62
      case FilterType::MATERIAL:
460✔
63
      case FilterType::MESH:
460✔
64
      case FilterType::UNIVERSE:
460✔
65
      case FilterType::PARTICLE:
460✔
66
        break;
460✔
67
      default:
×
68
        fatal_error("Invalid filter specified. Only cell, cell_instance, "
×
69
                    "distribcell, energy, material, mesh, and universe filters "
70
                    "are supported in random ray mode.");
71
      }
72
    }
73
  }
74

75
  // Validate MGXS data
76
  ///////////////////////////////////////////////////////////////////
77
  for (auto& material : data::mg.macro_xs_) {
788✔
78
    if (!material.is_isotropic) {
576!
79
      fatal_error("Anisotropic MGXS detected. Only isotropic XS data sets "
×
80
                  "supported in random ray mode.");
81
    }
82
    for (int g = 0; g < data::mg.num_energy_groups_; g++) {
2,952✔
83
      if (material.exists_in_model) {
2,376✔
84
        // Temperature and angle indices, if using multiple temperature
85
        // data sets and/or anisotropic data sets.
86
        // TODO: Currently assumes we are only using single temp/single angle
87
        // data.
88
        const int t = 0;
2,360✔
89
        const int a = 0;
2,360✔
90
        double sigma_t =
2,360✔
91
          material.get_xs(MgxsType::TOTAL, g, NULL, NULL, NULL, t, a);
2,360✔
92
        if (sigma_t <= 0.0) {
2,360!
93
          fatal_error("No zero or negative total macroscopic cross sections "
×
94
                      "allowed in random ray mode. If the intention is to make "
95
                      "a void material, use a cell fill of 'None' instead.");
96
        }
97
      }
98
    }
99
  }
100

101
  // Validate ray source
102
  ///////////////////////////////////////////////////////////////////
103

104
  // Check for independent source
105
  IndependentSource* is =
212!
106
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
212!
107
  if (!is) {
212!
108
    fatal_error("Invalid ray source definition. Ray source must provided and "
×
109
                "be of type IndependentSource.");
110
  }
111

112
  // Check for box source
113
  SpatialDistribution* space_dist = is->space();
212!
114
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
212!
115
  if (!sb) {
212!
116
    fatal_error(
×
117
      "Invalid ray source definition -- only box sources are allowed.");
118
  }
119

120
  // Check that box source is not restricted to fissionable areas
121
  if (sb->only_fissionable()) {
212!
122
    fatal_error(
×
123
      "Invalid ray source definition -- fissionable spatial distribution "
124
      "not allowed.");
125
  }
126

127
  // Check for isotropic source
128
  UnitSphereDistribution* angle_dist = is->angle();
212!
129
  Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
212!
130
  if (!id) {
212!
131
    fatal_error("Invalid ray source definition -- only isotropic sources are "
×
132
                "allowed.");
133
  }
134

135
  // Validate external sources
136
  ///////////////////////////////////////////////////////////////////
137
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
212✔
138
    if (model::external_sources.size() < 1) {
116!
139
      fatal_error("Must provide a particle source (in addition to ray source) "
×
140
                  "in fixed source random ray mode.");
141
    }
142

143
    for (int i = 0; i < model::external_sources.size(); i++) {
232✔
144
      Source* s = model::external_sources[i].get();
116!
145

146
      // Check for independent source
147
      IndependentSource* is = dynamic_cast<IndependentSource*>(s);
116!
148

149
      if (!is) {
116!
150
        fatal_error(
×
151
          "Only IndependentSource external source types are allowed in "
152
          "random ray mode");
153
      }
154

155
      // Check for isotropic source
156
      UnitSphereDistribution* angle_dist = is->angle();
116!
157
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
116!
158
      if (!id) {
116!
159
        fatal_error(
×
160
          "Invalid source definition -- only isotropic external sources are "
161
          "allowed in random ray mode.");
162
      }
163

164
      // Validate that a domain ID was specified OR that it is a point source
165
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
116!
166
      if (is->domain_ids().size() == 0 && !sp) {
116!
167
        fatal_error("Fixed sources must be point source or spatially "
×
168
                    "constrained by domain id (cell, material, or universe) in "
169
                    "random ray mode.");
170
      } else if (is->domain_ids().size() > 0 && sp) {
116✔
171
        // If both a domain constraint and a point source location are
172
        // specified, notify user that domain constraint takes precedence.
173
        warning("Fixed source has both a domain constraint and a point "
200✔
174
                "type spatial distribution. The domain constraint takes "
175
                "precedence in random ray mode -- point source coordinate "
176
                "will be ignored.");
177
      }
178

179
      // Check that a discrete energy distribution was used
180
      Distribution* d = is->energy();
116!
181
      Discrete* dd = dynamic_cast<Discrete*>(d);
116!
182
      if (!dd) {
116!
183
        fatal_error(
×
184
          "Only discrete (multigroup) energy distributions are allowed for "
185
          "external sources in random ray mode.");
186
      }
187
    }
188
  }
189

190
  // Validate adjoint sources
191
  ///////////////////////////////////////////////////////////////////
192
  if (FlatSourceDomain::adjoint_requested_ && !model::adjoint_sources.empty()) {
212✔
193
    for (int i = 0; i < model::adjoint_sources.size(); i++) {
8✔
194
      Source* s = model::adjoint_sources[i].get();
4!
195

196
      // Check for independent source
197
      IndependentSource* is = dynamic_cast<IndependentSource*>(s);
4!
198

199
      if (!is) {
4!
200
        fatal_error(
×
201
          "Only IndependentSource adjoint source types are allowed in "
202
          "random ray mode");
203
      }
204

205
      // Check for isotropic source
206
      UnitSphereDistribution* angle_dist = is->angle();
4!
207
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
4!
208
      if (!id) {
4!
209
        fatal_error(
×
210
          "Invalid source definition -- only isotropic adjoint sources are "
211
          "allowed in random ray mode.");
212
      }
213

214
      // Validate that a domain ID was specified OR that it is a point source
215
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
4!
216
      if (is->domain_ids().size() == 0 && !sp) {
4!
217
        fatal_error("Adjoint sources must be point source or spatially "
×
218
                    "constrained by domain id (cell, material, or universe) in "
219
                    "random ray mode.");
220
      } else if (is->domain_ids().size() > 0 && sp) {
4!
221
        // If both a domain constraint and a point source location are
222
        // specified, notify user that domain constraint takes precedence.
223
        warning("Adjoint source has both a domain constraint and a point "
8✔
224
                "type spatial distribution. The domain constraint takes "
225
                "precedence in random ray mode -- point source coordinate "
226
                "will be ignored.");
227
      }
228

229
      // Check that a discrete energy distribution was used
230
      Distribution* d = is->energy();
4!
231
      Discrete* dd = dynamic_cast<Discrete*>(d);
4!
232
      if (!dd) {
4!
233
        fatal_error(
×
234
          "Only discrete (multigroup) energy distributions are allowed for "
235
          "adjoint sources in random ray mode.");
236
      }
237
    }
238
  }
239

240
  // Validate plotting files
241
  ///////////////////////////////////////////////////////////////////
242
  for (int p = 0; p < model::plots.size(); p++) {
212!
243

244
    // Get handle to OpenMC plot object
245
    const auto& openmc_plottable = model::plots[p];
×
246
    Plot* openmc_plot = dynamic_cast<Plot*>(openmc_plottable.get());
×
247

248
    // Random ray plots only support voxel plots
249
    if (!openmc_plot) {
×
250
      warning(fmt::format(
×
251
        "Plot {} will not be used for end of simulation data plotting -- only "
252
        "voxel plotting is allowed in random ray mode.",
253
        openmc_plottable->id()));
×
254
      continue;
×
255
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
256
      warning(fmt::format(
×
257
        "Plot {} will not be used for end of simulation data plotting -- only "
258
        "voxel plotting is allowed in random ray mode.",
259
        openmc_plottable->id()));
×
260
      continue;
×
261
    }
262
  }
263

264
  // Warn about slow MPI domain replication, if detected
265
  ///////////////////////////////////////////////////////////////////
266
#ifdef OPENMC_MPI
267
  if (mpi::n_procs > 1) {
268
    warning(
269
      "MPI parallelism is not supported by the random ray solver. All work "
270
      "will be performed by rank 0. Domain decomposition may be implemented in "
271
      "the future to provide efficient MPI scaling.");
272
  }
273
#endif
274

275
  // Warn about instability resulting from linear sources in small regions
276
  // when generating weight windows with FW-CADIS and an overlaid mesh.
277
  ///////////////////////////////////////////////////////////////////
278
  if (RandomRay::source_shape_ == RandomRaySourceShape::LINEAR &&
212✔
279
      variance_reduction::weight_windows.size() > 0) {
88✔
280
    warning(
8✔
281
      "Linear sources may result in negative fluxes in small source regions "
282
      "generated by mesh subdivision. Negative sources may result in low "
283
      "quality FW-CADIS weight windows. We recommend you use flat source "
284
      "mode when generating weight windows with an overlaid mesh tally.");
285
  }
286
}
212✔
287

288
void openmc_finalize_random_ray()
2,100✔
289
{
290
  FlatSourceDomain::volume_estimator_ = RandomRayVolumeEstimator::HYBRID;
2,100✔
291
  FlatSourceDomain::volume_normalized_flux_tallies_ = false;
2,100✔
292
  FlatSourceDomain::adjoint_requested_ = false;
2,100✔
293
  FlatSourceDomain::solve_ = RandomRaySolve::FORWARD;
2,100✔
294
  FlatSourceDomain::fw_cadis_local_ = false;
2,100✔
295
  FlatSourceDomain::fw_cadis_local_targets_.clear();
2,100✔
296
  FlatSourceDomain::mesh_domain_map_.clear();
2,100✔
297
  RandomRay::ray_source_.reset();
2,100✔
298
  RandomRay::source_shape_ = RandomRaySourceShape::FLAT;
2,100✔
299
  RandomRay::sample_method_ = RandomRaySampleMethod::PRNG;
2,100✔
300
}
2,100✔
301

302
//==============================================================================
303
// RandomRaySimulation implementation
304
//==============================================================================
305

306
RandomRaySimulation::RandomRaySimulation()
212✔
307
  : negroups_(data::mg.num_energy_groups_)
212!
308
{
309
  // There are no source sites in random ray mode, so be sure to disable to
310
  // ensure we don't attempt to write source sites to statepoint
311
  settings::source_write = false;
212✔
312

313
  // Random ray mode does not have an inner loop over generations within a
314
  // batch, so set the current gen to 1
315
  simulation::current_gen = 1;
212✔
316

317
  switch (RandomRay::source_shape_) {
212!
318
  case RandomRaySourceShape::FLAT:
112✔
319
    domain_ = make_unique<FlatSourceDomain>();
112✔
320
    break;
112✔
321
  case RandomRaySourceShape::LINEAR:
100✔
322
  case RandomRaySourceShape::LINEAR_XY:
100✔
323
    domain_ = make_unique<LinearSourceDomain>();
100✔
324
    break;
100✔
325
  default:
×
326
    fatal_error("Unknown random ray source shape");
×
327
  }
328

329
  // Convert OpenMC native MGXS into a more efficient format
330
  // internal to the random ray solver
331
  domain_->flatten_xs();
212✔
332
}
212✔
333

334
void RandomRaySimulation::apply_fixed_sources_and_mesh_domains()
208✔
335
{
336
  domain_->apply_meshes();
208✔
337
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
208✔
338
    // Transfer external source user inputs onto random ray source regions
339
    domain_->convert_external_sources(false);
112✔
340
    domain_->count_external_source_regions();
112✔
341
  }
342
}
208✔
343

344
void RandomRaySimulation::prepare_fw_fixed_sources_adjoint()
24✔
345
{
346
  // Prepare adjoint fixed sources using forward flux
347
  domain_->source_regions_.adjoint_reset();
24✔
348
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
24✔
349
    domain_->set_fw_adjoint_sources();
20✔
350
  }
351
}
24✔
352

353
void RandomRaySimulation::prepare_local_fixed_sources_adjoint()
4✔
354
{
355
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
4!
356
    domain_->set_local_adjoint_sources();
4✔
357
  }
358
}
4✔
359

360
void RandomRaySimulation::prepare_adjoint_simulation(bool from_forward)
28✔
361
{
362
  reset_timers();
28✔
363

364
  if (mpi::master)
28!
365
    header("ADJOINT FLUX SOLVE", 3);
28✔
366

367
  if (from_forward) {
28✔
368
    // The forward solve has already run. Re-initialize OpenMC's general data
369
    // structures for the adjoint solve and derive the adjoint source from the
370
    // forward flux.
371
    openmc_simulation_init();
24✔
372

373
    prepare_fw_fixed_sources_adjoint();
24✔
374
  } else {
375
    // Initialize adjoint fixed sources
376
    domain_->apply_meshes();
4✔
377
    prepare_local_fixed_sources_adjoint();
4✔
378
    domain_->count_external_source_regions();
4✔
379
  }
380

381
  domain_->k_eff_ = 1.0;
28✔
382

383
  // Transpose scattering matrix
384
  domain_->transpose_scattering_matrix();
28✔
385

386
  // Swap nu_sigma_f and chi
387
  domain_->nu_sigma_f_.swap(domain_->chi_);
28✔
388
}
28✔
389

390
void RandomRaySimulation::simulate()
236✔
391
{
392
  // Begin main simulation timer
393
  simulation::time_total.start();
236✔
394

395
  // Random ray power iteration loop
396
  while (simulation::current_batch < settings::n_batches) {
6,272✔
397
    // Initialize the current batch
398
    initialize_batch();
5,800✔
399
    initialize_generation();
5,800✔
400

401
    // MPI not supported in random ray solver, so all work is done by rank 0
402
    // TODO: Implement domain decomposition for MPI parallelism
403
    if (mpi::master) {
5,800!
404

405
      // Reset total starting particle weight used for normalizing tallies
406
      simulation::total_weight = 1.0;
5,800✔
407

408
      // Update source term (scattering + fission)
409
      domain_->update_all_neutron_sources();
5,800✔
410

411
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
412
      // to zero
413
      domain_->batch_reset();
5,800✔
414

415
      // At the beginning of the simulation, if mesh subdivision is in use, we
416
      // need to swap the main source region container into the base container,
417
      // as the main source region container will be used to hold the true
418
      // subdivided source regions. The base container will therefore only
419
      // contain the external source region information, the mesh indices,
420
      // material properties, and initial guess values for the flux/source.
421

422
      // Start timer for transport
423
      simulation::time_transport.start();
5,800✔
424

425
// Transport sweep over all random rays for the iteration
426
#pragma omp parallel for schedule(dynamic)                                     \
427
  reduction(+ : total_geometric_intersections_)
428
      for (int i = 0; i < settings::n_particles; i++) {
848,200✔
429
        RandomRay ray(i, domain_.get());
842,400✔
430
        total_geometric_intersections_ +=
1,684,800✔
431
          ray.transport_history_based_single_ray();
842,400✔
432
      }
842,400✔
433

434
      simulation::time_transport.stop();
5,800✔
435

436
      // Add any newly discovered source regions to the main source region
437
      // container.
438
      domain_->finalize_discovered_source_regions();
5,800✔
439

440
      // Normalize scalar flux and update volumes
441
      domain_->normalize_scalar_flux_and_volumes(
5,800✔
442
        settings::n_particles * RandomRay::distance_active_);
443

444
      // Add source to scalar flux, compute number of FSR hits
445
      int64_t n_hits = domain_->add_source_to_scalar_flux();
5,800✔
446

447
      // Apply transport stabilization factors
448
      domain_->apply_transport_stabilization();
5,800✔
449

450
      if (settings::run_mode == RunMode::EIGENVALUE) {
5,800✔
451
        // Compute random ray k-eff
452
        domain_->compute_k_eff();
2,040✔
453

454
        // Store random ray k-eff into OpenMC's native k-eff variable
455
        global_tally_tracklength = domain_->k_eff_;
2,040✔
456
      }
457

458
      // Execute all tallying tasks, if this is an active batch
459
      if (simulation::current_batch > settings::n_inactive) {
5,800✔
460

461
        // Add this iteration's scalar flux estimate to final accumulated
462
        // estimate
463
        domain_->accumulate_iteration_flux();
2,720✔
464

465
        // Use above mapping to contribute FSR flux data to appropriate
466
        // tallies
467
        domain_->random_ray_tally();
2,720✔
468
      }
469

470
      // Set phi_old = phi_new
471
      domain_->flux_swap();
5,800✔
472

473
      // Check for any obvious insabilities/nans/infs
474
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
5,800✔
475
    } // End MPI master work
476

477
    // Finalize the current batch
478
    finalize_generation();
5,800✔
479
    finalize_batch();
5,800✔
480
  } // End random ray power iteration loop
481

482
  domain_->count_external_source_regions();
236✔
483

484
  // End main simulation timer
485
  simulation::time_total.stop();
236✔
486

487
  // Normalize and save the final forward flux
488
  double source_normalization_factor =
236✔
489
    domain_->compute_fixed_source_normalization_factor() /
236✔
490
    (settings::n_batches - settings::n_inactive);
236✔
491

492
#pragma omp parallel for
493
  for (uint64_t se = 0; se < domain_->n_source_elements(); se++) {
1,115,860✔
494
    domain_->source_regions_.scalar_flux_final(se) *=
1,115,624✔
495
      source_normalization_factor;
496
  }
497

498
  // Finalize OpenMC
499
  openmc_simulation_finalize();
236✔
500

501
  // Output all simulation results
502
  output_simulation_results();
236✔
503
}
236✔
504

505
void RandomRaySimulation::output_simulation_results() const
236✔
506
{
507
  // Print random ray results
508
  if (mpi::master) {
236!
509
    print_results_random_ray(total_geometric_intersections_,
236✔
510
      avg_miss_rate_ / settings::n_batches, negroups_,
236✔
511
      domain_->n_source_regions(), domain_->n_external_source_regions_);
236✔
512
    if (model::plots.size() > 0) {
236!
513
      domain_->output_to_vtk();
×
514
    }
515
  }
516
}
236✔
517

518
// Apply a few sanity checks to catch obvious cases of numerical instability.
519
// Instability typically only occurs if ray density is extremely low.
520
void RandomRaySimulation::instability_check(
5,800✔
521
  int64_t n_hits, double k_eff, double& avg_miss_rate) const
522
{
523
  double percent_missed = ((domain_->n_source_regions() - n_hits) /
5,800!
524
                            static_cast<double>(domain_->n_source_regions())) *
5,800✔
525
                          100.0;
5,800✔
526
  avg_miss_rate += percent_missed;
5,800✔
527

528
  if (mpi::master) {
5,800!
529
    if (percent_missed > 10.0) {
5,800✔
530
      warning(fmt::format(
696✔
531
        "Very high FSR miss rate detected ({:.3f}%). Instability may occur. "
532
        "Increase ray density by adding more rays and/or active distance.",
533
        percent_missed));
534
    } else if (percent_missed > 1.0) {
5,452!
UNCOV
535
      warning(
×
UNCOV
536
        fmt::format("Elevated FSR miss rate detected ({:.3f}%). Increasing "
×
537
                    "ray density by adding more rays and/or active "
538
                    "distance may improve simulation efficiency.",
539
          percent_missed));
540
    }
541

542
    if (k_eff > 10.0 || k_eff < 0.01 || !(std::isfinite(k_eff))) {
5,800!
543
      fatal_error(fmt::format("Instability detected: k-eff = {:.5f}", k_eff));
×
544
    }
545
  }
546
}
5,800✔
547

548
// Print random ray simulation results
549
void RandomRaySimulation::print_results_random_ray(
236✔
550
  uint64_t total_geometric_intersections, double avg_miss_rate, int negroups,
551
  int64_t n_source_regions, int64_t n_external_source_regions) const
552
{
553
  using namespace simulation;
236✔
554

555
  if (settings::verbosity >= 6) {
236!
556
    double total_integrations = total_geometric_intersections * negroups;
236✔
557
    double time_per_integration =
236✔
558
      simulation::time_transport.elapsed() / total_integrations;
236✔
559
    double misc_time = time_total.elapsed() - time_update_src.elapsed() -
236✔
560
                       time_transport.elapsed() - time_tallies.elapsed() -
236✔
561
                       time_bank_sendrecv.elapsed();
236✔
562

563
    header("Simulation Statistics", 4);
236✔
564
    fmt::print(
236✔
565
      " Total Iterations                  = {}\n", settings::n_batches);
566
    fmt::print(
236✔
567
      " Number of Rays per Iteration      = {}\n", settings::n_particles);
568
    fmt::print(" Inactive Distance                 = {} cm\n",
236✔
569
      RandomRay::distance_inactive_);
570
    fmt::print(" Active Distance                   = {} cm\n",
236✔
571
      RandomRay::distance_active_);
572
    fmt::print(" Source Regions (SRs)              = {}\n", n_source_regions);
236✔
573
    fmt::print(
236✔
574
      " SRs Containing External Sources   = {}\n", n_external_source_regions);
575
    fmt::print(" Total Geometric Intersections     = {:.4e}\n",
472✔
576
      static_cast<double>(total_geometric_intersections));
236✔
577
    fmt::print("   Avg per Iteration               = {:.4e}\n",
472✔
578
      static_cast<double>(total_geometric_intersections) / settings::n_batches);
236✔
579
    fmt::print("   Avg per Iteration per SR        = {:.2f}\n",
472✔
580
      static_cast<double>(total_geometric_intersections) /
236✔
581
        static_cast<double>(settings::n_batches) / n_source_regions);
236✔
582
    fmt::print(" Avg SR Miss Rate per Iteration    = {:.4f}%\n", avg_miss_rate);
236✔
583
    fmt::print(" Energy Groups                     = {}\n", negroups);
236✔
584
    fmt::print(
236✔
585
      " Total Integrations                = {:.4e}\n", total_integrations);
586
    fmt::print("   Avg per Iteration               = {:.4e}\n",
472✔
587
      total_integrations / settings::n_batches);
236✔
588

589
    std::string estimator;
236!
590
    switch (domain_->volume_estimator_) {
236!
591
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
8✔
592
      estimator = "Simulation Averaged";
8✔
593
      break;
594
    case RandomRayVolumeEstimator::NAIVE:
36✔
595
      estimator = "Naive";
36✔
596
      break;
597
    case RandomRayVolumeEstimator::HYBRID:
192✔
598
      estimator = "Hybrid";
192✔
599
      break;
600
    default:
×
601
      fatal_error("Invalid volume estimator type");
×
602
    }
603
    fmt::print(" Volume Estimator Type             = {}\n", estimator);
236✔
604

605
    std::string adjoint_true =
236✔
606
      (FlatSourceDomain::solve_ == RandomRaySolve::ADJOINT) ? "ON" : "OFF";
680✔
607
    fmt::print(" Adjoint Flux Mode                 = {}\n", adjoint_true);
236✔
608

609
    std::string shape;
472!
610
    switch (RandomRay::source_shape_) {
236!
611
    case RandomRaySourceShape::FLAT:
132✔
612
      shape = "Flat";
132✔
613
      break;
614
    case RandomRaySourceShape::LINEAR:
92✔
615
      shape = "Linear";
92✔
616
      break;
617
    case RandomRaySourceShape::LINEAR_XY:
12✔
618
      shape = "Linear XY";
12✔
619
      break;
620
    default:
×
621
      fatal_error("Invalid random ray source shape");
×
622
    }
623
    fmt::print(" Source Shape                      = {}\n", shape);
236✔
624
    std::string sample_method;
472!
625
    switch (RandomRay::sample_method_) {
236!
626
    case RandomRaySampleMethod::PRNG:
228✔
627
      sample_method = "PRNG";
228✔
628
      break;
629
    case RandomRaySampleMethod::HALTON:
4✔
630
      sample_method = "Halton";
4✔
631
      break;
632
    case RandomRaySampleMethod::S2:
4✔
633
      sample_method = "PRNG S2";
4✔
634
      break;
635
    }
636
    fmt::print(" Sample Method                     = {}\n", sample_method);
236✔
637

638
    if (domain_->is_transport_stabilization_needed_) {
236✔
639
      fmt::print(" Transport XS Stabilization Used   = YES (rho = {:.3f})\n",
4✔
640
        FlatSourceDomain::diagonal_stabilization_rho_);
641
    } else {
642
      fmt::print(" Transport XS Stabilization Used   = NO\n");
232✔
643
    }
644

645
    header("Timing Statistics", 4);
236✔
646
    show_time("Total time for initialization", time_initialize.elapsed());
236✔
647
    show_time("Reading cross sections", time_read_xs.elapsed(), 1);
236✔
648
    show_time("Total simulation time", time_total.elapsed());
236✔
649
    show_time("Transport sweep only", time_transport.elapsed(), 1);
236✔
650
    show_time("Source update only", time_update_src.elapsed(), 1);
236✔
651
    show_time("Tally conversion only", time_tallies.elapsed(), 1);
236✔
652
    show_time("MPI source reductions only", time_bank_sendrecv.elapsed(), 1);
236✔
653
    show_time("Other iteration routines", misc_time, 1);
236✔
654
    if (settings::run_mode == RunMode::EIGENVALUE) {
236✔
655
      show_time("Time in inactive batches", time_inactive.elapsed());
100✔
656
    }
657
    show_time("Time in active batches", time_active.elapsed());
236✔
658
    show_time("Time writing statepoints", time_statepoint.elapsed());
236✔
659
    show_time("Total time for finalization", time_finalize.elapsed());
236✔
660
    show_time("Time per integration", time_per_integration);
236✔
661
  }
236✔
662

663
  if (settings::verbosity >= 4 && settings::run_mode == RunMode::EIGENVALUE) {
236!
664
    header("Results", 4);
100✔
665
    fmt::print(" k-effective                       = {:.5f} +/- {:.5f}\n",
100✔
666
      simulation::keff, simulation::keff_std);
667
  }
668
}
236✔
669

670
} // namespace openmc
671

672
//==============================================================================
673
// C API functions
674
//==============================================================================
675

676
void openmc_run_random_ray()
212✔
677
{
678
  using namespace openmc;
212✔
679

680
  // Determine which solves to run. If adjoint results are requested and no
681
  // user-defined adjoint source is present, an initial forward solve is needed
682
  // to construct the adjoint source from the forward flux (FW-CADIS). If the
683
  // user has defined an adjoint source, the forward solve is skipped and only
684
  // the adjoint solve is run.
685
  const bool run_adjoint = FlatSourceDomain::adjoint_requested_;
212✔
686
  const bool have_adjoint_source = !model::adjoint_sources.empty();
212✔
687
  const bool run_forward = !(run_adjoint && have_adjoint_source);
212✔
688

689
  // Set the initial solve type
690
  if (!run_forward) {
212✔
691
    FlatSourceDomain::solve_ = RandomRaySolve::ADJOINT;
4✔
692
  } else if (run_adjoint) {
208✔
693
    FlatSourceDomain::solve_ = RandomRaySolve::FORWARD_FOR_ADJOINT;
24✔
694
  } else {
695
    FlatSourceDomain::solve_ = RandomRaySolve::FORWARD;
184✔
696
  }
697

698
  // Initialize OpenMC general data structures
699
  openmc_simulation_init();
212✔
700

701
  // Validate that inputs meet requirements for random ray mode
702
  if (mpi::master)
212!
703
    validate_random_ray_inputs();
212✔
704

705
  // Initialize Random Ray Simulation Object
706
  RandomRaySimulation sim;
212✔
707

708
  // Run the forward solve
709
  if (run_forward) {
212✔
710
    // When an adjoint solve follows, report this as the initial forward solve
711
    if (run_adjoint && mpi::master)
208!
712
      header("FORWARD FLUX SOLVE", 3);
24✔
713
    sim.apply_fixed_sources_and_mesh_domains();
208✔
714
    sim.simulate();
208✔
715
  }
716

717
  // Run the adjoint solve
718
  if (run_adjoint) {
212✔
719
    FlatSourceDomain::solve_ = RandomRaySolve::ADJOINT;
28✔
720
    sim.prepare_adjoint_simulation(run_forward);
28✔
721
    sim.simulate();
28✔
722
  }
723
}
212✔
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