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

openmc-dev / openmc / 23614254024

26 Mar 2026 07:36PM UTC coverage: 81.332% (+0.006%) from 81.326%
23614254024

Pull #3717

github

web-flow
Merge 21160f71e into 8223099ed
Pull Request #3717: Local adjoint source for Random Ray

17730 of 25632 branches covered (69.17%)

Branch coverage included in aggregate %.

370 of 405 new or added lines in 10 files covered. (91.36%)

13 existing lines in 2 files now uncovered.

58368 of 67933 relevant lines covered (85.92%)

44884305.8 hits per line

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

81.05
/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 non-default point source location
172
        // are specified, notify user that domain constraint takes precedence.
173
        if (sp->r().x == 0.0 && sp->r().y == 0.0 && sp->r().z == 0.0) {
275!
174
          warning("Fixed source has both a domain constraint and a point "
450✔
175
                  "type spatial distribution. The domain constraint takes "
176
                  "precedence in random ray mode -- point source coordinate "
177
                  "will be ignored.");
178
        }
179
      }
180

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

192
  // Validate adjoint sources
193
  ///////////////////////////////////////////////////////////////////
194
  if (FlatSourceDomain::adjoint_ && !model::adjoint_sources.empty()) {
584!
195
    for (int i = 0; i < model::adjoint_sources.size(); i++) {
22✔
196
      Source* s = model::adjoint_sources[i].get();
11!
197

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

201
      if (!is) {
11!
NEW
202
        fatal_error(
×
203
          "Only IndependentSource adjoint source types are allowed in "
204
          "random ray mode");
205
      }
206

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

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

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

244
  // Validate plotting files
245
  ///////////////////////////////////////////////////////////////////
246
  for (int p = 0; p < model::plots.size(); p++) {
584!
247

248
    // Get handle to OpenMC plot object
249
    const auto& openmc_plottable = model::plots[p];
×
250
    Plot* openmc_plot = dynamic_cast<Plot*>(openmc_plottable.get());
×
251

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

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

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

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

305
//==============================================================================
306
// RandomRaySimulation implementation
307
//==============================================================================
308

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

316
  // Random ray mode does not have an inner loop over generations within a
317
  // batch, so set the current gen to 1
318
  simulation::current_gen = 1;
792✔
319

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

332
  // Convert OpenMC native MGXS into a more efficient format
333
  // internal to the random ray solver
334
  domain_->flatten_xs();
792✔
335
}
792✔
336

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

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

356
void RandomRaySimulation::prepare_local_fixed_sources_adjoint()
15✔
357
{
358
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
15!
359
    domain_->set_local_adjoint_sources();
15✔
360
  }
361
}
15✔
362

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

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

375
      // Reset total starting particle weight used for normalizing tallies
376
      simulation::total_weight = 1.0;
15,962✔
377

378
      // Update source term (scattering + fission)
379
      domain_->update_all_neutron_sources();
15,962✔
380

381
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
382
      // to zero
383
      domain_->batch_reset();
15,962✔
384

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

392
      // Start timer for transport
393
      simulation::time_transport.start();
15,962✔
394

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

404
      simulation::time_transport.stop();
15,962✔
405

406
      // Add any newly discovered source regions to the main source region
407
      // container.
408
      domain_->finalize_discovered_source_regions();
15,962✔
409

410
      // Normalize scalar flux and update volumes
411
      domain_->normalize_scalar_flux_and_volumes(
15,962✔
412
        settings::n_particles * RandomRay::distance_active_);
413

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

417
      // Apply transport stabilization factors
418
      domain_->apply_transport_stabilization();
15,962✔
419

420
      if (settings::run_mode == RunMode::EIGENVALUE) {
15,962✔
421
        // Compute random ray k-eff
422
        domain_->compute_k_eff();
5,610✔
423

424
        // Store random ray k-eff into OpenMC's native k-eff variable
425
        global_tally_tracklength = domain_->k_eff_;
5,610✔
426
      }
427

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

431
        // Add this iteration's scalar flux estimate to final accumulated
432
        // estimate
433
        domain_->accumulate_iteration_flux();
7,486✔
434

435
        // Use above mapping to contribute FSR flux data to appropriate
436
        // tallies
437
        domain_->random_ray_tally();
7,486✔
438
      }
439

440
      // Set phi_old = phi_new
441
      domain_->flux_swap();
15,962✔
442

443
      // Check for any obvious insabilities/nans/infs
444
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
15,962✔
445
    } // End MPI master work
446

447
    // Finalize the current batch
448
    finalize_generation();
20,962✔
449
    finalize_batch();
20,962✔
450
  } // End random ray power iteration loop
451

452
  domain_->count_external_source_regions();
883✔
453
}
883✔
454

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

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

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

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

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

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

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

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

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

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

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

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

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

619
} // namespace openmc
620

621
//==============================================================================
622
// C API functions
623
//==============================================================================
624

625
void openmc_run_random_ray()
792✔
626
{
627
  //////////////////////////////////////////////////////////
628
  // Run forward simulation
629
  //////////////////////////////////////////////////////////
630

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

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

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

652
  // Initialize OpenMC general data structures
653
  openmc_simulation_init();
792✔
654

655
  // Validate that inputs meet requirements for random ray mode
656
  if (openmc::mpi::master)
792✔
657
    openmc::validate_random_ray_inputs();
584✔
658

659
  // Initialize Random Ray Simulation Object
660
  openmc::RandomRaySimulation sim;
792✔
661

662
  if (!adjoint_needed || fw_adjoint) {
792✔
663
    // Initialize fixed sources, if present
664
    sim.apply_fixed_sources_and_mesh_domains();
777✔
665

666
    // Begin main simulation timer
667
    openmc::simulation::time_total.start();
777✔
668

669
    // Execute random ray simulation
670
    sim.simulate();
777✔
671

672
    // End main simulation timer
673
    openmc::simulation::time_total.stop();
777✔
674

675
    // Normalize and save the final forward flux
676
    double source_normalization_factor =
777✔
677
      sim.domain()->compute_fixed_source_normalization_factor() /
777✔
678
      (openmc::settings::n_batches - openmc::settings::n_inactive);
777✔
679

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

686
    // Finalize OpenMC
687
    openmc_simulation_finalize();
777✔
688

689
    // Output all simulation results
690
    sim.output_simulation_results();
777✔
691
  }
692

693
  //////////////////////////////////////////////////////////
694
  // Run adjoint simulation (if enabled)
695
  //////////////////////////////////////////////////////////
696

697
  if (!adjoint_needed) {
792✔
698
    return;
686✔
699
  }
700

701
  openmc::reset_timers();
106✔
702

703
  if (openmc::mpi::master)
106✔
704
    openmc::header("ADJOINT FLUX SOLVE", 3);
78✔
705

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

712
    openmc_simulation_init();
91✔
713

714
    sim.prepare_fw_fixed_sources_adjoint();
91✔
715
  } else {
716
    // Initialize adjoint fixed sources
717
    sim.domain()->apply_meshes();
15✔
718
    sim.prepare_local_fixed_sources_adjoint();
15✔
719
    sim.domain()->count_external_source_regions();
15✔
720
  }
721

722
  sim.domain()->k_eff_ = 1.0;
106✔
723

724
  // Transpose scattering matrix
725
  sim.domain()->transpose_scattering_matrix();
106✔
726

727
  // Swap nu_sigma_f and chi
728
  sim.domain()->nu_sigma_f_.swap(sim.domain()->chi_);
106✔
729

730
  // Begin main simulation timer
731
  openmc::simulation::time_total.start();
106✔
732

733
  // Execute random ray simulation
734
  sim.simulate();
106✔
735

736
  // End main simulation timer
737
  openmc::simulation::time_total.stop();
106✔
738

739
  // Finalize OpenMC
740
  openmc_simulation_finalize();
106✔
741

742
  // Output all simulation results
743
  sim.output_simulation_results();
106✔
744
}
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