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

openmc-dev / openmc / 23285088002

19 Mar 2026 07:51AM UTC coverage: 80.71% (-0.7%) from 81.447%
23285088002

Pull #3886

github

web-flow
Merge 9cdb2d588 into 3ce6cbfdd
Pull Request #3886: Implement python tally types

16322 of 23494 branches covered (69.47%)

Branch coverage included in aggregate %.

215 of 264 new or added lines in 11 files covered. (81.44%)

713 existing lines in 49 files now uncovered.

56449 of 66670 relevant lines covered (84.67%)

14035992.85 hits per line

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

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

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

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

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

149
      if (!is) {
54!
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();
54!
157
      Isotropic* id = dynamic_cast<Isotropic*>(angle_dist);
54!
158
      if (!id) {
54!
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());
54!
166
      if (is->domain_ids().size() == 0 && !sp) {
54!
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) {
54✔
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) {
46!
174
          warning("Fixed source has both a domain constraint and a point "
92✔
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();
54!
183
      Discrete* dd = dynamic_cast<Discrete*>(d);
54!
184
      if (!dd) {
54!
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 plotting files
193
  ///////////////////////////////////////////////////////////////////
194
  for (int p = 0; p < model::plots.size(); p++) {
102!
195

196
    // Get handle to OpenMC plot object
197
    const auto& openmc_plottable = model::plots[p];
×
198
    Plot* openmc_plot = dynamic_cast<Plot*>(openmc_plottable.get());
×
199

200
    // Random ray plots only support voxel plots
201
    if (!openmc_plot) {
×
202
      warning(fmt::format(
×
203
        "Plot {} will not be used for end of simulation data plotting -- only "
204
        "voxel plotting is allowed in random ray mode.",
205
        openmc_plottable->id()));
×
206
      continue;
×
207
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
208
      warning(fmt::format(
×
209
        "Plot {} will not be used for end of simulation data plotting -- only "
210
        "voxel plotting is allowed in random ray mode.",
211
        openmc_plottable->id()));
×
212
      continue;
×
213
    }
214
  }
215

216
  // Warn about slow MPI domain replication, if detected
217
  ///////////////////////////////////////////////////////////////////
218
#ifdef OPENMC_MPI
219
  if (mpi::n_procs > 1) {
220
    warning(
221
      "MPI parallelism is not supported by the random ray solver. All work "
222
      "will be performed by rank 0. Domain decomposition may be implemented in "
223
      "the future to provide efficient MPI scaling.");
224
  }
225
#endif
226

227
  // Warn about instability resulting from linear sources in small regions
228
  // when generating weight windows with FW-CADIS and an overlaid mesh.
229
  ///////////////////////////////////////////////////////////////////
230
  if (RandomRay::source_shape_ == RandomRaySourceShape::LINEAR &&
102✔
231
      variance_reduction::weight_windows.size() > 0) {
44✔
232
    warning(
4✔
233
      "Linear sources may result in negative fluxes in small source regions "
234
      "generated by mesh subdivision. Negative sources may result in low "
235
      "quality FW-CADIS weight windows. We recommend you use flat source mode "
236
      "when generating weight windows with an overlaid mesh tally.");
237
  }
238
}
102✔
239

240
void print_adjoint_header()
20✔
241
{
242
  if (!FlatSourceDomain::adjoint_)
20✔
243
    // If we're going to do an adjoint simulation afterwards, report that this
244
    // is the initial forward flux solve.
245
    header("FORWARD FLUX SOLVE", 3);
10✔
246
  else
247
    // Otherwise report that we are doing the adjoint simulation
248
    header("ADJOINT FLUX SOLVE", 3);
10✔
249
}
20✔
250

251
//==============================================================================
252
// RandomRaySimulation implementation
253
//==============================================================================
254

255
RandomRaySimulation::RandomRaySimulation()
102✔
256
  : negroups_(data::mg.num_energy_groups_)
102!
257
{
258
  // There are no source sites in random ray mode, so be sure to disable to
259
  // ensure we don't attempt to write source sites to statepoint
260
  settings::source_write = false;
102✔
261

262
  // Random ray mode does not have an inner loop over generations within a
263
  // batch, so set the current gen to 1
264
  simulation::current_gen = 1;
102✔
265

266
  switch (RandomRay::source_shape_) {
102!
267
  case RandomRaySourceShape::FLAT:
52✔
268
    domain_ = make_unique<FlatSourceDomain>();
52✔
269
    break;
52✔
270
  case RandomRaySourceShape::LINEAR:
50✔
271
  case RandomRaySourceShape::LINEAR_XY:
50✔
272
    domain_ = make_unique<LinearSourceDomain>();
50✔
273
    break;
50✔
274
  default:
×
275
    fatal_error("Unknown random ray source shape");
×
276
  }
277

278
  // Convert OpenMC native MGXS into a more efficient format
279
  // internal to the random ray solver
280
  domain_->flatten_xs();
102✔
281

282
  // Check if adjoint calculation is needed. If it is, we will run the forward
283
  // calculation first and then the adjoint calculation later.
284
  adjoint_needed_ = FlatSourceDomain::adjoint_;
102✔
285

286
  // Adjoint is always false for the forward calculation
287
  FlatSourceDomain::adjoint_ = false;
102✔
288

289
  // The first simulation is run after initialization
290
  is_first_simulation_ = true;
102✔
291
}
102✔
292

293
void RandomRaySimulation::apply_fixed_sources_and_mesh_domains()
102✔
294
{
295
  domain_->apply_meshes();
102✔
296
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
102✔
297
    // Transfer external source user inputs onto random ray source regions
298
    domain_->convert_external_sources();
54✔
299
    domain_->count_external_source_regions();
54✔
300
  }
301
}
102✔
302

303
void RandomRaySimulation::prepare_fixed_sources_adjoint()
10✔
304
{
305
  domain_->source_regions_.adjoint_reset();
10✔
306
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
10✔
307
    domain_->set_adjoint_sources();
8✔
308
  }
309
}
10✔
310

311
void RandomRaySimulation::prepare_adjoint_simulation()
10✔
312
{
313
  // Configure the domain for adjoint simulation
314
  FlatSourceDomain::adjoint_ = true;
10✔
315

316
  // Reset k-eff
317
  domain_->k_eff_ = 1.0;
10✔
318

319
  // Initialize adjoint fixed sources, if present
320
  prepare_fixed_sources_adjoint();
10✔
321

322
  // Transpose scattering matrix
323
  domain_->transpose_scattering_matrix();
10✔
324

325
  // Swap nu_sigma_f and chi
326
  domain_->nu_sigma_f_.swap(domain_->chi_);
10✔
327
}
10✔
328

329
void RandomRaySimulation::simulate()
112✔
330
{
331
  if (!is_first_simulation_) {
112✔
332
    if (mpi::master && adjoint_needed_)
10!
333
      openmc::print_adjoint_header();
10✔
334

335
    // Reset the timers and reinitialize the general OpenMC datastructures if
336
    // this is after the first simulation
337
    reset_timers();
10✔
338

339
    // Initialize OpenMC general data structures
340
    openmc_simulation_init();
10✔
341
  }
342

343
  // Begin main simulation timer
344
  simulation::time_total.start();
112✔
345

346
  // Random ray power iteration loop
347
  while (simulation::current_batch < settings::n_batches) {
3,064✔
348
    // Initialize the current batch
349
    initialize_batch();
2,840✔
350
    initialize_generation();
2,840✔
351

352
    // MPI not supported in random ray solver, so all work is done by rank 0
353
    // TODO: Implement domain decomposition for MPI parallelism
354
    if (mpi::master) {
2,840!
355

356
      // Reset total starting particle weight used for normalizing tallies
357
      simulation::total_weight = 1.0;
2,840✔
358

359
      // Update source term (scattering + fission)
360
      domain_->update_all_neutron_sources();
2,840✔
361

362
      // Reset scalar fluxes, iteration volume tallies, and region hit flags
363
      // to zero
364
      domain_->batch_reset();
2,840✔
365

366
      // At the beginning of the simulation, if mesh subdivision is in use, we
367
      // need to swap the main source region container into the base container,
368
      // as the main source region container will be used to hold the true
369
      // subdivided source regions. The base container will therefore only
370
      // contain the external source region information, the mesh indices,
371
      // material properties, and initial guess values for the flux/source.
372

373
      // Start timer for transport
374
      simulation::time_transport.start();
2,840✔
375

376
// Transport sweep over all random rays for the iteration
377
#pragma omp parallel for schedule(dynamic)                                     \
378
  reduction(+ : total_geometric_intersections_)
379
      for (int i = 0; i < settings::n_particles; i++) {
394,040✔
380
        RandomRay ray(i, domain_.get());
391,200✔
381
        total_geometric_intersections_ +=
782,400✔
382
          ray.transport_history_based_single_ray();
391,200✔
383
      }
391,200✔
384

385
      simulation::time_transport.stop();
2,840✔
386

387
      // Add any newly discovered source regions to the main source region
388
      // container.
389
      domain_->finalize_discovered_source_regions();
2,840✔
390

391
      // Normalize scalar flux and update volumes
392
      domain_->normalize_scalar_flux_and_volumes(
2,840✔
393
        settings::n_particles * RandomRay::distance_active_);
394

395
      // Add source to scalar flux, compute number of FSR hits
396
      int64_t n_hits = domain_->add_source_to_scalar_flux();
2,840✔
397

398
      // Apply transport stabilization factors
399
      domain_->apply_transport_stabilization();
2,840✔
400

401
      if (settings::run_mode == RunMode::EIGENVALUE) {
2,840✔
402
        // Compute random ray k-eff
403
        domain_->compute_k_eff();
1,020✔
404

405
        // Store random ray k-eff into OpenMC's native k-eff variable
406
        global_tally_tracklength = domain_->k_eff_;
1,020✔
407
      }
408

409
      // Execute all tallying tasks, if this is an active batch
410
      if (simulation::current_batch > settings::n_inactive) {
2,840✔
411

412
        // Add this iteration's scalar flux estimate to final accumulated
413
        // estimate
414
        domain_->accumulate_iteration_flux();
1,330✔
415

416
        // Use above mapping to contribute FSR flux data to appropriate
417
        // tallies
418
        domain_->random_ray_tally();
1,330✔
419
      }
420

421
      // Set phi_old = phi_new
422
      domain_->flux_swap();
2,840✔
423

424
      // Check for any obvious insabilities/nans/infs
425
      instability_check(n_hits, domain_->k_eff_, avg_miss_rate_);
2,840✔
426
    } // End MPI master work
427

428
    // Finalize the current batch
429
    finalize_generation();
2,840✔
430
    finalize_batch();
2,840✔
431
  } // End random ray power iteration loop
432

433
  domain_->count_external_source_regions();
112✔
434

435
  // End main simulation timer
436
  simulation::time_total.stop();
112✔
437

438
  // Normalize and save the final flux
439
  double source_normalization_factor =
112✔
440
    domain_->compute_fixed_source_normalization_factor() /
112✔
441
    (settings::n_batches - settings::n_inactive);
112✔
442

443
#pragma omp parallel for
444
  for (uint64_t se = 0; se < domain_->n_source_elements(); se++) {
541,460✔
445
    domain_->source_regions_.scalar_flux_final(se) *=
541,348✔
446
      source_normalization_factor;
447
  }
448

449
  // Finalize OpenMC
450
  openmc_simulation_finalize();
112✔
451

452
  // Output all simulation results
453
  output_simulation_results();
112✔
454

455
  // Toggle that the simulation object has been initialized after the first
456
  // simulation
457
  if (is_first_simulation_)
112✔
458
    is_first_simulation_ = false;
102✔
459
}
112✔
460

461
void RandomRaySimulation::output_simulation_results() const
112✔
462
{
463
  // Print random ray results
464
  if (mpi::master) {
112!
465
    print_results_random_ray(total_geometric_intersections_,
112✔
466
      avg_miss_rate_ / settings::n_batches, negroups_,
112✔
467
      domain_->n_source_regions(), domain_->n_external_source_regions_);
112✔
468
    if (model::plots.size() > 0) {
112!
469
      domain_->output_to_vtk();
×
470
    }
471
  }
472
}
112✔
473

474
// Apply a few sanity checks to catch obvious cases of numerical instability.
475
// Instability typically only occurs if ray density is extremely low.
476
void RandomRaySimulation::instability_check(
2,840✔
477
  int64_t n_hits, double k_eff, double& avg_miss_rate) const
478
{
479
  double percent_missed = ((domain_->n_source_regions() - n_hits) /
2,840!
480
                            static_cast<double>(domain_->n_source_regions())) *
2,840✔
481
                          100.0;
2,840✔
482
  avg_miss_rate += percent_missed;
2,840✔
483

484
  if (mpi::master) {
2,840!
485
    if (percent_missed > 10.0) {
2,840✔
486
      warning(fmt::format(
348✔
487
        "Very high FSR miss rate detected ({:.3f}%). Instability may occur. "
488
        "Increase ray density by adding more rays and/or active distance.",
489
        percent_missed));
490
    } else if (percent_missed > 1.0) {
2,666!
UNCOV
491
      warning(
×
UNCOV
492
        fmt::format("Elevated FSR miss rate detected ({:.3f}%). Increasing "
×
493
                    "ray density by adding more rays and/or active "
494
                    "distance may improve simulation efficiency.",
495
          percent_missed));
496
    }
497

498
    if (k_eff > 10.0 || k_eff < 0.01 || !(std::isfinite(k_eff))) {
2,840!
499
      fatal_error(fmt::format("Instability detected: k-eff = {:.5f}", k_eff));
×
500
    }
501
  }
502
}
2,840✔
503

504
// Print random ray simulation results
505
void RandomRaySimulation::print_results_random_ray(
112✔
506
  uint64_t total_geometric_intersections, double avg_miss_rate, int negroups,
507
  int64_t n_source_regions, int64_t n_external_source_regions) const
508
{
509
  using namespace simulation;
112✔
510

511
  if (settings::verbosity >= 6) {
112!
512
    double total_integrations = total_geometric_intersections * negroups;
112✔
513
    double time_per_integration =
112✔
514
      simulation::time_transport.elapsed() / total_integrations;
112✔
515
    double misc_time = time_total.elapsed() - time_update_src.elapsed() -
112✔
516
                       time_transport.elapsed() - time_tallies.elapsed() -
112✔
517
                       time_bank_sendrecv.elapsed();
112✔
518

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

545
    std::string estimator;
112!
546
    switch (domain_->volume_estimator_) {
112!
547
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
4✔
548
      estimator = "Simulation Averaged";
4✔
549
      break;
550
    case RandomRayVolumeEstimator::NAIVE:
12✔
551
      estimator = "Naive";
12✔
552
      break;
553
    case RandomRayVolumeEstimator::HYBRID:
96✔
554
      estimator = "Hybrid";
96✔
555
      break;
556
    default:
×
557
      fatal_error("Invalid volume estimator type");
×
558
    }
559
    fmt::print(" Volume Estimator Type             = {}\n", estimator);
112✔
560

561
    std::string adjoint_true = (FlatSourceDomain::adjoint_) ? "ON" : "OFF";
326✔
562
    fmt::print(" Adjoint Flux Mode                 = {}\n", adjoint_true);
112✔
563

564
    std::string shape;
224!
565
    switch (RandomRay::source_shape_) {
112!
566
    case RandomRaySourceShape::FLAT:
60✔
567
      shape = "Flat";
60✔
568
      break;
569
    case RandomRaySourceShape::LINEAR:
46✔
570
      shape = "Linear";
46✔
571
      break;
572
    case RandomRaySourceShape::LINEAR_XY:
6✔
573
      shape = "Linear XY";
6✔
574
      break;
575
    default:
×
576
      fatal_error("Invalid random ray source shape");
×
577
    }
578
    fmt::print(" Source Shape                      = {}\n", shape);
112✔
579
    std::string sample_method;
224!
580
    switch (RandomRay::sample_method_) {
112!
581
    case RandomRaySampleMethod::PRNG:
108✔
582
      sample_method = "PRNG";
108✔
583
      break;
584
    case RandomRaySampleMethod::HALTON:
2✔
585
      sample_method = "Halton";
2✔
586
      break;
587
    case RandomRaySampleMethod::S2:
2✔
588
      sample_method = "PRNG S2";
2✔
589
      break;
590
    }
591
    fmt::print(" Sample Method                     = {}\n", sample_method);
112✔
592

593
    if (domain_->is_transport_stabilization_needed_) {
112✔
594
      fmt::print(" Transport XS Stabilization Used   = YES (rho = {:.3f})\n",
2✔
595
        FlatSourceDomain::diagonal_stabilization_rho_);
596
    } else {
597
      fmt::print(" Transport XS Stabilization Used   = NO\n");
110✔
598
    }
599

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

618
  if (settings::verbosity >= 4 && settings::run_mode == RunMode::EIGENVALUE) {
112!
619
    header("Results", 4);
50✔
620
    fmt::print(" k-effective                       = {:.5f} +/- {:.5f}\n",
50✔
621
      simulation::keff, simulation::keff_std);
622
  }
623
}
112✔
624

625
void openmc_finalize_random_ray()
1,330✔
626
{
627
  FlatSourceDomain::volume_estimator_ = RandomRayVolumeEstimator::HYBRID;
1,330✔
628
  FlatSourceDomain::volume_normalized_flux_tallies_ = false;
1,330✔
629
  FlatSourceDomain::adjoint_ = false;
1,330✔
630
  FlatSourceDomain::mesh_domain_map_.clear();
1,330✔
631
  RandomRay::ray_source_.reset();
1,330✔
632
  RandomRay::source_shape_ = RandomRaySourceShape::FLAT;
1,330✔
633
  RandomRay::sample_method_ = RandomRaySampleMethod::PRNG;
1,330✔
634
}
1,330✔
635

636
} // namespace openmc
637

638
//==============================================================================
639
// C API functions
640
//==============================================================================
641

642
void openmc_run_random_ray()
102✔
643
{
644
  //////////////////////////////////////////////////////////
645
  // Run forward simulation
646
  //////////////////////////////////////////////////////////
647

648
  if (openmc::mpi::master) {
102!
649
    if (openmc::FlatSourceDomain::adjoint_) {
102✔
650
      openmc::FlatSourceDomain::adjoint_ = false;
10✔
651
      openmc::print_adjoint_header();
10✔
652
      openmc::FlatSourceDomain::adjoint_ = true;
10✔
653
    }
654
  }
655

656
  // Initialize OpenMC general data structures
657
  openmc_simulation_init();
102✔
658

659
  // Validate that inputs meet requirements for random ray mode
660
  if (openmc::mpi::master)
102!
661
    openmc::validate_random_ray_inputs();
102✔
662

663
  // Initialize Random Ray Simulation Object
664
  openmc::RandomRaySimulation sim;
102✔
665

666
  // Initialize fixed sources, if present
667
  sim.apply_fixed_sources_and_mesh_domains();
102✔
668

669
  // Run initial random ray simulation
670
  sim.simulate();
102✔
671

672
  //////////////////////////////////////////////////////////
673
  // Run adjoint simulation (if enabled)
674
  //////////////////////////////////////////////////////////
675

676
  if (sim.adjoint_needed_) {
102✔
677
    // Setup for adjoint simulation
678
    sim.prepare_adjoint_simulation();
10✔
679

680
    // Run adjoint simulation
681
    sim.simulate();
10✔
682
  }
683
}
102✔
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