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

openmc-dev / openmc / 24423844846

14 Apr 2026 09:28PM UTC coverage: 81.358% (+0.03%) from 81.326%
24423844846

Pull #3717

github

web-flow
Merge ab2a8c80d into fd1bc26af
Pull Request #3717: Local adjoint source for Random Ray

17727 of 25604 branches covered (69.24%)

Branch coverage included in aggregate %.

366 of 401 new or added lines in 10 files covered. (91.27%)

307 existing lines in 10 files now uncovered.

58414 of 67984 relevant lines covered (85.92%)

44852399.71 hits per line

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

81.57
/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()
584✔
31
{
32
  // Validate tallies
33
  ///////////////////////////////////////////////////////////////////
34
  for (auto& tally : model::tallies) {
1,663✔
35

36
    // Validate score types
37
    for (auto score_bin : tally->scores_) {
2,400✔
38
      switch (score_bin) {
1,321!
39
      case SCORE_FLUX:
1,321✔
40
      case SCORE_TOTAL:
1,321✔
41
      case SCORE_FISSION:
1,321✔
42
      case SCORE_NU_FISSION:
1,321✔
43
      case SCORE_EVENTS:
1,321✔
44
      case SCORE_KAPPA_FISSION:
1,321✔
45
        break;
1,321✔
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()) {
2,347✔
55
      auto& filter = *model::tally_filters[f];
1,268✔
56

57
      switch (filter.type()) {
1,268!
58
      case FilterType::CELL:
1,268✔
59
      case FilterType::CELL_INSTANCE:
1,268✔
60
      case FilterType::DISTRIBCELL:
1,268✔
61
      case FilterType::ENERGY:
1,268✔
62
      case FilterType::MATERIAL:
1,268✔
63
      case FilterType::MESH:
1,268✔
64
      case FilterType::UNIVERSE:
1,268✔
65
      case FilterType::PARTICLE:
1,268✔
66
        break;
1,268✔
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_) {
2,169✔
78
    if (!material.is_isotropic) {
1,585!
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++) {
8,121✔
83
      if (material.exists_in_model) {
6,536✔
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;
6,492✔
89
        const int a = 0;
6,492✔
90
        double sigma_t =
6,492✔
91
          material.get_xs(MgxsType::TOTAL, g, NULL, NULL, NULL, t, a);
6,492✔
92
        if (sigma_t <= 0.0) {
6,492!
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 =
584!
106
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
584!
107
  if (!is) {
584!
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();
584!
114
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
584!
115
  if (!sb) {
584!
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()) {
584!
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();
584!
129
  Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
584!
130
  if (!id) {
584!
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) {
584✔
138
    if (model::external_sources.size() < 1) {
320!
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++) {
640✔
144
      Source* s = model::external_sources[i].get();
320!
145

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

149
      if (!is) {
320!
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();
320!
157
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
320!
158
      if (!id) {
320!
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());
320!
166
      if (is->domain_ids().size() == 0 && !sp) {
320!
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) {
320✔
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 "
550✔
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();
320!
181
      Discrete* dd = dynamic_cast<Discrete*>(d);
320!
182
      if (!dd) {
320!
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_ && !model::adjoint_sources.empty()) {
584!
193
    for (int i = 0; i < model::adjoint_sources.size(); i++) {
22✔
194
      Source* s = model::adjoint_sources[i].get();
11!
195

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

199
      if (!is) {
11!
NEW
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();
11!
207
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
11!
208
      if (!id) {
11!
NEW
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());
11!
216
      if (is->domain_ids().size() == 0 && !sp) {
11!
NEW
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) {
11!
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 "
22✔
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();
11!
231
      Discrete* dd = dynamic_cast<Discrete*>(d);
11!
232
      if (!dd) {
11!
NEW
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++) {
584!
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) {
213✔
268
    warning(
416✔
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 &&
584✔
279
      variance_reduction::weight_windows.size() > 0) {
242✔
280
    warning(
22✔
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
}
584✔
287

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

301
//==============================================================================
302
// RandomRaySimulation implementation
303
//==============================================================================
304

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

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

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

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

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

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

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

359
void RandomRaySimulation::simulate()
883✔
360
{
361
  // Random ray power iteration loop
362
  while (simulation::current_batch < settings::n_batches) {
21,845✔
363
    // Initialize the current batch
364
    initialize_batch();
20,962✔
365
    initialize_generation();
20,962✔
366

367
    // MPI not supported in random ray solver, so all work is done by rank 0
368
    // TODO: Implement domain decomposition for MPI parallelism
369
    if (mpi::master) {
20,962✔
370

371
      // Reset total starting particle weight used for normalizing tallies
372
      simulation::total_weight = 1.0;
15,962✔
373

374
      // Update source term (scattering + fission)
375
      domain_->update_all_neutron_sources();
15,962✔
376

377
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
378
      // to zero
379
      domain_->batch_reset();
15,962✔
380

381
      // At the beginning of the simulation, if mesh subdivision is in use, we
382
      // need to swap the main source region container into the base container,
383
      // as the main source region container will be used to hold the true
384
      // subdivided source regions. The base container will therefore only
385
      // contain the external source region information, the mesh indices,
386
      // material properties, and initial guess values for the flux/source.
387

388
      // Start timer for transport
389
      simulation::time_transport.start();
15,962✔
390

391
// Transport sweep over all random rays for the iteration
392
#pragma omp parallel for schedule(dynamic)                                     \
8,712✔
393
  reduction(+ : total_geometric_intersections_)
8,712✔
394
      for (int i = 0; i < settings::n_particles; i++) {
1,060,250✔
395
        RandomRay ray(i, domain_.get());
1,053,000✔
396
        total_geometric_intersections_ +=
2,106,000✔
397
          ray.transport_history_based_single_ray();
1,053,000✔
398
      }
1,053,000✔
399

400
      simulation::time_transport.stop();
15,962✔
401

402
      // Add any newly discovered source regions to the main source region
403
      // container.
404
      domain_->finalize_discovered_source_regions();
15,962✔
405

406
      // Normalize scalar flux and update volumes
407
      domain_->normalize_scalar_flux_and_volumes(
15,962✔
408
        settings::n_particles * RandomRay::distance_active_);
409

410
      // Add source to scalar flux, compute number of FSR hits
411
      int64_t n_hits = domain_->add_source_to_scalar_flux();
15,962✔
412

413
      // Apply transport stabilization factors
414
      domain_->apply_transport_stabilization();
15,962✔
415

416
      if (settings::run_mode == RunMode::EIGENVALUE) {
15,962✔
417
        // Compute random ray k-eff
418
        domain_->compute_k_eff();
5,610✔
419

420
        // Store random ray k-eff into OpenMC's native k-eff variable
421
        global_tally_tracklength = domain_->k_eff_;
5,610✔
422
      }
423

424
      // Execute all tallying tasks, if this is an active batch
425
      if (simulation::current_batch > settings::n_inactive) {
15,962✔
426

427
        // Add this iteration's scalar flux estimate to final accumulated
428
        // estimate
429
        domain_->accumulate_iteration_flux();
7,486✔
430

431
        // Use above mapping to contribute FSR flux data to appropriate
432
        // tallies
433
        domain_->random_ray_tally();
7,486✔
434
      }
435

436
      // Set phi_old = phi_new
437
      domain_->flux_swap();
15,962✔
438

439
      // Check for any obvious insabilities/nans/infs
440
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
15,962✔
441
    } // End MPI master work
442

443
    // Finalize the current batch
444
    finalize_generation();
20,962✔
445
    finalize_batch();
20,962✔
446
  } // End random ray power iteration loop
447

448
  domain_->count_external_source_regions();
883✔
449
}
883✔
450

451
void RandomRaySimulation::output_simulation_results() const
883✔
452
{
453
  // Print random ray results
454
  if (mpi::master) {
883✔
455
    print_results_random_ray(total_geometric_intersections_,
651✔
456
      avg_miss_rate_ / settings::n_batches, negroups_,
651✔
457
      domain_->n_source_regions(), domain_->n_external_source_regions_);
651✔
458
    if (model::plots.size() > 0) {
651!
459
      domain_->output_to_vtk();
×
460
    }
461
  }
462
}
883✔
463

464
// Apply a few sanity checks to catch obvious cases of numerical instability.
465
// Instability typically only occurs if ray density is extremely low.
466
void RandomRaySimulation::instability_check(
15,962✔
467
  int64_t n_hits, double k_eff, double& avg_miss_rate) const
468
{
469
  double percent_missed = ((domain_->n_source_regions() - n_hits) /
15,962!
470
                            static_cast<double>(domain_->n_source_regions())) *
15,962✔
471
                          100.0;
15,962✔
472
  avg_miss_rate += percent_missed;
15,962✔
473

474
  if (mpi::master) {
15,962!
475
    if (percent_missed > 10.0) {
15,962✔
476
      warning(fmt::format(
1,914✔
477
        "Very high FSR miss rate detected ({:.3f}%). Instability may occur. "
478
        "Increase ray density by adding more rays and/or active distance.",
479
        percent_missed));
480
    } else if (percent_missed > 1.0) {
15,005✔
481
      warning(
2!
482
        fmt::format("Elevated FSR miss rate detected ({:.3f}%). Increasing "
4!
483
                    "ray density by adding more rays and/or active "
484
                    "distance may improve simulation efficiency.",
485
          percent_missed));
486
    }
487

488
    if (k_eff > 10.0 || k_eff < 0.01 || !(std::isfinite(k_eff))) {
15,962!
489
      fatal_error(fmt::format("Instability detected: k-eff = {:.5f}", k_eff));
×
490
    }
491
  }
492
}
15,962✔
493

494
// Print random ray simulation results
495
void RandomRaySimulation::print_results_random_ray(
651✔
496
  uint64_t total_geometric_intersections, double avg_miss_rate, int negroups,
497
  int64_t n_source_regions, int64_t n_external_source_regions) const
498
{
499
  using namespace simulation;
651✔
500

501
  if (settings::verbosity >= 6) {
651!
502
    double total_integrations = total_geometric_intersections * negroups;
651✔
503
    double time_per_integration =
651✔
504
      simulation::time_transport.elapsed() / total_integrations;
651✔
505
    double misc_time = time_total.elapsed() - time_update_src.elapsed() -
651✔
506
                       time_transport.elapsed() - time_tallies.elapsed() -
651✔
507
                       time_bank_sendrecv.elapsed();
651✔
508

509
    header("Simulation Statistics", 4);
651✔
510
    fmt::print(
651✔
511
      " Total Iterations                  = {}\n", settings::n_batches);
512
    fmt::print(
651✔
513
      " Number of Rays per Iteration      = {}\n", settings::n_particles);
514
    fmt::print(" Inactive Distance                 = {} cm\n",
651✔
515
      RandomRay::distance_inactive_);
516
    fmt::print(" Active Distance                   = {} cm\n",
651✔
517
      RandomRay::distance_active_);
518
    fmt::print(" Source Regions (SRs)              = {}\n", n_source_regions);
651✔
519
    fmt::print(
651✔
520
      " SRs Containing External Sources   = {}\n", n_external_source_regions);
521
    fmt::print(" Total Geometric Intersections     = {:.4e}\n",
1,302✔
522
      static_cast<double>(total_geometric_intersections));
651✔
523
    fmt::print("   Avg per Iteration               = {:.4e}\n",
1,302✔
524
      static_cast<double>(total_geometric_intersections) / settings::n_batches);
651✔
525
    fmt::print("   Avg per Iteration per SR        = {:.2f}\n",
1,302✔
526
      static_cast<double>(total_geometric_intersections) /
651✔
527
        static_cast<double>(settings::n_batches) / n_source_regions);
651✔
528
    fmt::print(" Avg SR Miss Rate per Iteration    = {:.4f}%\n", avg_miss_rate);
651✔
529
    fmt::print(" Energy Groups                     = {}\n", negroups);
651✔
530
    fmt::print(
651✔
531
      " Total Integrations                = {:.4e}\n", total_integrations);
532
    fmt::print("   Avg per Iteration               = {:.4e}\n",
1,302✔
533
      total_integrations / settings::n_batches);
651✔
534

535
    std::string estimator;
651!
536
    switch (domain_->volume_estimator_) {
651!
537
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
22✔
538
      estimator = "Simulation Averaged";
22✔
539
      break;
540
    case RandomRayVolumeEstimator::NAIVE:
101✔
541
      estimator = "Naive";
101✔
542
      break;
543
    case RandomRayVolumeEstimator::HYBRID:
528✔
544
      estimator = "Hybrid";
528✔
545
      break;
546
    default:
×
547
      fatal_error("Invalid volume estimator type");
×
548
    }
549
    fmt::print(" Volume Estimator Type             = {}\n", estimator);
651✔
550

551
    std::string adjoint_true = (FlatSourceDomain::adjoint_) ? "ON" : "OFF";
1,875✔
552
    fmt::print(" Adjoint Flux Mode                 = {}\n", adjoint_true);
651✔
553

554
    std::string shape;
1,302!
555
    switch (RandomRay::source_shape_) {
651!
556
    case RandomRaySourceShape::FLAT:
365✔
557
      shape = "Flat";
365✔
558
      break;
559
    case RandomRaySourceShape::LINEAR:
253✔
560
      shape = "Linear";
253✔
561
      break;
562
    case RandomRaySourceShape::LINEAR_XY:
33✔
563
      shape = "Linear XY";
33✔
564
      break;
565
    default:
×
566
      fatal_error("Invalid random ray source shape");
×
567
    }
568
    fmt::print(" Source Shape                      = {}\n", shape);
651✔
569
    std::string sample_method;
1,302!
570
    switch (RandomRay::sample_method_) {
651!
571
    case RandomRaySampleMethod::PRNG:
629✔
572
      sample_method = "PRNG";
629✔
573
      break;
574
    case RandomRaySampleMethod::HALTON:
11✔
575
      sample_method = "Halton";
11✔
576
      break;
577
    case RandomRaySampleMethod::S2:
11✔
578
      sample_method = "PRNG S2";
11✔
579
      break;
580
    }
581
    fmt::print(" Sample Method                     = {}\n", sample_method);
651✔
582

583
    if (domain_->is_transport_stabilization_needed_) {
651✔
584
      fmt::print(" Transport XS Stabilization Used   = YES (rho = {:.3f})\n",
11✔
585
        FlatSourceDomain::diagonal_stabilization_rho_);
586
    } else {
587
      fmt::print(" Transport XS Stabilization Used   = NO\n");
640✔
588
    }
589

590
    header("Timing Statistics", 4);
651✔
591
    show_time("Total time for initialization", time_initialize.elapsed());
651✔
592
    show_time("Reading cross sections", time_read_xs.elapsed(), 1);
651✔
593
    show_time("Total simulation time", time_total.elapsed());
651✔
594
    show_time("Transport sweep only", time_transport.elapsed(), 1);
651✔
595
    show_time("Source update only", time_update_src.elapsed(), 1);
651✔
596
    show_time("Tally conversion only", time_tallies.elapsed(), 1);
651✔
597
    show_time("MPI source reductions only", time_bank_sendrecv.elapsed(), 1);
651✔
598
    show_time("Other iteration routines", misc_time, 1);
651✔
599
    if (settings::run_mode == RunMode::EIGENVALUE) {
651✔
600
      show_time("Time in inactive batches", time_inactive.elapsed());
275✔
601
    }
602
    show_time("Time in active batches", time_active.elapsed());
651✔
603
    show_time("Time writing statepoints", time_statepoint.elapsed());
651✔
604
    show_time("Total time for finalization", time_finalize.elapsed());
651✔
605
    show_time("Time per integration", time_per_integration);
651✔
606
  }
651✔
607

608
  if (settings::verbosity >= 4 && settings::run_mode == RunMode::EIGENVALUE) {
651!
609
    header("Results", 4);
275✔
610
    fmt::print(" k-effective                       = {:.5f} +/- {:.5f}\n",
275✔
611
      simulation::keff, simulation::keff_std);
612
  }
613
}
651✔
614

615
} // namespace openmc
616

617
//==============================================================================
618
// C API functions
619
//==============================================================================
620

621
void openmc_run_random_ray()
792✔
622
{
623
  //////////////////////////////////////////////////////////
624
  // Run forward simulation
625
  //////////////////////////////////////////////////////////
626

627
  // Check if adjoint calculation is needed, and if local adjoint source(s)
628
  // are present. If an adjoint calculation is needed and no sources are
629
  // specified, we will run a forward calculation first to calculate adjoint
630
  // sources for global variance reduction, then perform an adjoint
631
  // calculation later.
632
  bool adjoint_needed = openmc::FlatSourceDomain::adjoint_;
792✔
633
  bool fw_adjoint = openmc::model::adjoint_sources.empty() && adjoint_needed;
792✔
634

635
  // If we're going to do an adjoint simulation with forward-weighted adjoint
636
  // sources afterwards, report that this is the initial forward flux solve.
637
  if (!adjoint_needed || fw_adjoint) {
792✔
638
    // Configure the domain for forward simulation
639
    openmc::FlatSourceDomain::adjoint_ = false;
777✔
640

641
    if (adjoint_needed && openmc::mpi::master)
777✔
642
      openmc::header("FORWARD FLUX SOLVE", 3);
67✔
643
  } else {
644
    // Configure domain for adjoint simulation (later)
645
    openmc::FlatSourceDomain::adjoint_ = true;
15✔
646
  }
647

648
  // Initialize OpenMC general data structures
649
  openmc_simulation_init();
792✔
650

651
  // Validate that inputs meet requirements for random ray mode
652
  if (openmc::mpi::master)
792✔
653
    openmc::validate_random_ray_inputs();
584✔
654

655
  // Initialize Random Ray Simulation Object
656
  openmc::RandomRaySimulation sim;
792✔
657

658
  if (!adjoint_needed || fw_adjoint) {
792✔
659
    // Initialize fixed sources, if present
660
    sim.apply_fixed_sources_and_mesh_domains();
777✔
661

662
    // Begin main simulation timer
663
    openmc::simulation::time_total.start();
777✔
664

665
    // Execute random ray simulation
666
    sim.simulate();
777✔
667

668
    // End main simulation timer
669
    openmc::simulation::time_total.stop();
777✔
670

671
    // Normalize and save the final forward flux
672
    double source_normalization_factor =
777✔
673
      sim.domain()->compute_fixed_source_normalization_factor() /
777✔
674
      (openmc::settings::n_batches - openmc::settings::n_inactive);
777✔
675

676
#pragma omp parallel for
466✔
677
    for (uint64_t se = 0; se < sim.domain()->n_source_elements(); se++) {
1,203,341✔
678
      sim.domain()->source_regions_.scalar_flux_final(se) *=
1,203,030✔
679
        source_normalization_factor;
680
    }
681

682
    // Finalize OpenMC
683
    openmc_simulation_finalize();
777✔
684

685
    // Output all simulation results
686
    sim.output_simulation_results();
777✔
687
  }
688

689
  //////////////////////////////////////////////////////////
690
  // Run adjoint simulation (if enabled)
691
  //////////////////////////////////////////////////////////
692

693
  if (!adjoint_needed) {
792✔
694
    return;
686✔
695
  }
696

697
  openmc::reset_timers();
106✔
698

699
  if (openmc::mpi::master)
106✔
700
    openmc::header("ADJOINT FLUX SOLVE", 3);
78✔
701

702
  if (fw_adjoint) {
106✔
703
    // Forward simulation has already been run;
704
    // Configure the domain for adjoint simulation and
705
    // re-initialize OpenMC general data structures
706
    openmc::FlatSourceDomain::adjoint_ = true;
91✔
707

708
    openmc_simulation_init();
91✔
709

710
    sim.prepare_fw_fixed_sources_adjoint();
91✔
711
  } else {
712
    // Initialize adjoint fixed sources
713
    sim.domain()->apply_meshes();
15✔
714
    sim.prepare_local_fixed_sources_adjoint();
15✔
715
    sim.domain()->count_external_source_regions();
15✔
716
  }
717

718
  sim.domain()->k_eff_ = 1.0;
106✔
719

720
  // Transpose scattering matrix
721
  sim.domain()->transpose_scattering_matrix();
106✔
722

723
  // Swap nu_sigma_f and chi
724
  sim.domain()->nu_sigma_f_.swap(sim.domain()->chi_);
106✔
725

726
  // Begin main simulation timer
727
  openmc::simulation::time_total.start();
106✔
728

729
  // Execute random ray simulation
730
  sim.simulate();
106✔
731

732
  // End main simulation timer
733
  openmc::simulation::time_total.stop();
106✔
734

735
  // Finalize OpenMC
736
  openmc_simulation_finalize();
106✔
737

738
  // Output all simulation results
739
  sim.output_simulation_results();
106✔
740
}
792✔
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