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

openmc-dev / openmc / 15799682238

21 Jun 2025 09:11PM UTC coverage: 85.197% (-0.04%) from 85.239%
15799682238

Pull #3452

github

web-flow
Merge 2b25fb3f3 into 3d16d4b10
Pull Request #3452: relaxed random ray constraints

237 of 306 new or added lines in 8 files covered. (77.45%)

2 existing lines in 1 file now uncovered.

52706 of 61864 relevant lines covered (85.2%)

36699485.74 hits per line

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

78.85
/src/random_ray/flat_source_domain.cpp
1
#include "openmc/random_ray/flat_source_domain.h"
2

3
#include "openmc/cell.h"
4
#include "openmc/constants.h"
5
#include "openmc/eigenvalue.h"
6
#include "openmc/geometry.h"
7
#include "openmc/material.h"
8
#include "openmc/message_passing.h"
9
#include "openmc/mgxs_interface.h"
10
#include "openmc/output.h"
11
#include "openmc/plot.h"
12
#include "openmc/random_ray/random_ray.h"
13
#include "openmc/simulation.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
#include <cstdio>
21

22
namespace openmc {
23

24
//==============================================================================
25
// FlatSourceDomain implementation
26
//==============================================================================
27

28
// Static Variable Declarations
29
RandomRayVolumeEstimator FlatSourceDomain::volume_estimator_ {
30
  RandomRayVolumeEstimator::HYBRID};
31
bool FlatSourceDomain::volume_normalized_flux_tallies_ {false};
32
bool FlatSourceDomain::adjoint_ {false};
33
double FlatSourceDomain::diagonal_stabilization_rho_ {1.0};
34
std::unordered_map<int, vector<std::pair<Source::DomainType, int>>>
35
  FlatSourceDomain::mesh_domain_map_;
36

37
FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_)
656✔
38
{
39
  // Count the number of source regions, compute the cell offset
40
  // indices, and store the material type The reason for the offsets is that
41
  // some cell types may not have material fills, and therefore do not
42
  // produce FSRs. Thus, we cannot index into the global arrays directly
43
  int base_source_regions = 0;
656✔
44
  for (const auto& c : model::cells) {
5,520✔
45
    if (c->type_ != Fill::MATERIAL) {
4,864✔
46
      source_region_offsets_.push_back(-1);
2,320✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
2,544✔
49
      base_source_regions += c->n_instances_;
2,544✔
50
    }
51
  }
52

53
  // Initialize source regions.
54
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
656✔
55
  source_regions_ = SourceRegionContainer(negroups_, is_linear);
656✔
56
  source_regions_.assign(
656✔
57
    base_source_regions, SourceRegion(negroups_, is_linear));
1,312✔
58

59
  // Initialize materials
60
  int64_t source_region_id = 0;
656✔
61
  for (int i = 0; i < model::cells.size(); i++) {
5,520✔
62
    Cell& cell = *model::cells[i];
4,864✔
63
    if (cell.type_ == Fill::MATERIAL) {
4,864✔
64
      for (int j = 0; j < cell.n_instances_; j++) {
768,288✔
65
        source_regions_.material(source_region_id++) = cell.material(j);
765,744✔
66
      }
67
    }
68
  }
69

70
  // Sanity check
71
  if (source_region_id != base_source_regions) {
656✔
72
    fatal_error("Unexpected number of source regions");
×
73
  }
74

75
  // Initialize tally volumes
76
  if (volume_normalized_flux_tallies_) {
656✔
77
    tally_volumes_.resize(model::tallies.size());
528✔
78
    for (int i = 0; i < model::tallies.size(); i++) {
1,984✔
79
      //  Get the shape of the 3D result tensor
80
      auto shape = model::tallies[i]->results().shape();
1,456✔
81

82
      // Create a new 2D tensor with the same size as the first
83
      // two dimensions of the 3D tensor
84
      tally_volumes_[i] =
1,456✔
85
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,912✔
86
    }
87
  }
88

89
  // Compute simulation domain volume based on ray source
90
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
656✔
91
  SpatialDistribution* space_dist = is->space();
656✔
92
  simulation_volume_ = space_dist->volume();
656✔
93
}
656✔
94

95
void FlatSourceDomain::batch_reset()
11,660✔
96
{
97
// Reset scalar fluxes and iteration volume tallies to zero
98
#pragma omp parallel for
6,360✔
99
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,447,485✔
100
    source_regions_.volume(sr) = 0.0;
32,442,185✔
101
    source_regions_.volume_sq(sr) = 0.0;
32,442,185✔
102
  }
103

104
#pragma omp parallel for
6,360✔
105
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,741,625✔
106
    source_regions_.scalar_flux_new(se) = 0.0;
36,736,325✔
107
  }
108
}
11,660✔
109

110
void FlatSourceDomain::accumulate_iteration_flux()
4,730✔
111
{
112
#pragma omp parallel for
2,580✔
113
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,591,625✔
114
    source_regions_.scalar_flux_final(se) +=
16,589,475✔
115
      source_regions_.scalar_flux_new(se);
16,589,475✔
116
  }
117
}
4,730✔
118

119
// Compute new estimate of scattering + fission sources in each source region
120
// based on the flux estimate from the previous iteration.
121
void FlatSourceDomain::update_neutron_source(double k_eff)
5,225✔
122
{
123
  simulation::time_update_src.start();
5,225✔
124

125
  double inverse_k_eff = 1.0 / k_eff;
5,225✔
126

127
// Reset all source regions to zero (important for void regions)
128
#pragma omp parallel for
2,850✔
129
  for (int64_t se = 0; se < n_source_elements(); se++) {
21,598,115✔
130
    source_regions_.source(se) = 0.0;
21,595,740✔
131
  }
132

133
  // Add scattering + fission source
134
#pragma omp parallel for
2,850✔
135
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,275,935✔
136
    int material = source_regions_.material(sr);
19,273,560✔
137
    if (material == MATERIAL_VOID) {
19,273,560✔
138
      continue;
200,000✔
139
    }
140
    for (int g_out = 0; g_out < negroups_; g_out++) {
40,469,300✔
141
      double sigma_t = sigma_t_[material * negroups_ + g_out];
21,395,740✔
142
      double scatter_source = 0.0;
21,395,740✔
143
      double fission_source = 0.0;
21,395,740✔
144

145
      for (int g_in = 0; g_in < negroups_; g_in++) {
59,046,740✔
146
        double scalar_flux = source_regions_.scalar_flux_old(sr, g_in);
37,651,000✔
147
        double sigma_s =
148
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
37,651,000✔
149
        double nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
37,651,000✔
150
        double chi = chi_[material * negroups_ + g_out];
37,651,000✔
151

152
        scatter_source += sigma_s * scalar_flux;
37,651,000✔
153
        fission_source += nu_sigma_f * scalar_flux * chi;
37,651,000✔
154
      }
155
      source_regions_.source(sr, g_out) =
21,395,740✔
156
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
21,395,740✔
157
    }
158
  }
159

160
  // Add external source if in fixed source mode
161
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,225✔
162
#pragma omp parallel for
2,490✔
163
    for (int64_t se = 0; se < n_source_elements(); se++) {
20,385,505✔
164
      source_regions_.source(se) += source_regions_.external_source(se);
20,383,430✔
165
    }
166
  }
167

168
  simulation::time_update_src.stop();
5,225✔
169
}
5,225✔
170

171
// Normalizes flux and updates simulation-averaged volume estimate
172
void FlatSourceDomain::normalize_scalar_flux_and_volumes(
5,225✔
173
  double total_active_distance_per_iteration)
174
{
175
  double normalization_factor = 1.0 / total_active_distance_per_iteration;
5,225✔
176
  double volume_normalization_factor =
5,225✔
177
    1.0 / (total_active_distance_per_iteration * simulation::current_batch);
5,225✔
178

179
// Normalize scalar flux to total distance travelled by all rays this
180
// iteration
181
#pragma omp parallel for
2,850✔
182
  for (int64_t se = 0; se < n_source_elements(); se++) {
22,191,535✔
183
    source_regions_.scalar_flux_new(se) *= normalization_factor;
22,189,160✔
184
  }
185

186
// Accumulate cell-wise ray length tallies collected this iteration, then
187
// update the simulation-averaged cell-wise volume estimates
188
#pragma omp parallel for
2,850✔
189
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,796,995✔
190
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
19,794,620✔
191
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
19,794,620✔
192
    source_regions_.volume_naive(sr) =
39,589,240✔
193
      source_regions_.volume(sr) * normalization_factor;
19,794,620✔
194
    source_regions_.volume_sq(sr) =
39,589,240✔
195
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
19,794,620✔
196
    source_regions_.volume(sr) =
19,794,620✔
197
      source_regions_.volume_t(sr) * volume_normalization_factor;
19,794,620✔
198
  }
199
}
5,225✔
200

201
void FlatSourceDomain::set_flux_to_flux_plus_source(
43,220,375✔
202
  int64_t sr, double volume, int g)
203
{
204
  int material = source_regions_.material(sr);
43,220,375✔
205
  if (material == MATERIAL_VOID) {
43,220,375✔
206
    source_regions_.scalar_flux_new(sr, g) /= volume;
880,000✔
207
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
880,000✔
208
      source_regions_.scalar_flux_new(sr, g) +=
880,000✔
209
        0.5f * source_regions_.external_source(sr, g) *
880,000✔
210
        source_regions_.volume_sq(sr);
880,000✔
211
    }
212
  } else {
213
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
42,340,375✔
214
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
42,340,375✔
215
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
42,340,375✔
216
  }
217
}
43,220,375✔
218

219
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
1,540✔
220
{
221
  source_regions_.scalar_flux_new(sr, g) =
3,080✔
222
    source_regions_.scalar_flux_old(sr, g);
1,540✔
223
}
1,540✔
224

225
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
8,927,545✔
226
{
227
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
8,927,545✔
228
}
8,927,545✔
229

230
// Combine transport flux contributions and flat source contributions from the
231
// previous iteration to generate this iteration's estimate of scalar flux.
232
int64_t FlatSourceDomain::add_source_to_scalar_flux()
11,660✔
233
{
234
  int64_t n_hits = 0;
11,660✔
235
  double inverse_batch = 1.0 / simulation::current_batch;
11,660✔
236

237
#pragma omp parallel for reduction(+ : n_hits)
6,360✔
238
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,253,085✔
239

240
    double volume_simulation_avg = source_regions_.volume(sr);
33,247,785✔
241
    double volume_iteration = source_regions_.volume_naive(sr);
33,247,785✔
242

243
    // Increment the number of hits if cell was hit this iteration
244
    if (volume_iteration) {
33,247,785✔
245
      n_hits++;
29,188,630✔
246
    }
247

248
    // Set the SR to small status if its expected number of hits
249
    // per iteration is less than 1.5
250
    if (source_regions_.n_hits(sr) * inverse_batch < MIN_HITS_PER_BATCH) {
33,247,785✔
251
      source_regions_.is_small(sr) = 1;
6,812,705✔
252
    } else {
253
      source_regions_.is_small(sr) = 0;
26,435,080✔
254
    }
255

256
    // The volume treatment depends on the volume estimator type
257
    // and whether or not an external source is present in the cell.
258
    double volume;
259
    switch (volume_estimator_) {
33,247,785✔
260
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
261
      volume = volume_iteration;
777,600✔
262
      break;
777,600✔
263
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
264
      volume = volume_simulation_avg;
432,000✔
265
      break;
432,000✔
266
    case RandomRayVolumeEstimator::HYBRID:
32,038,185✔
267
      if (source_regions_.external_source_present(sr) ||
59,888,720✔
268
          source_regions_.is_small(sr)) {
27,850,535✔
269
        volume = volume_iteration;
10,999,975✔
270
      } else {
271
        volume = volume_simulation_avg;
21,038,210✔
272
      }
273
      break;
32,038,185✔
274
    default:
275
      fatal_error("Invalid volume estimator type");
276
    }
277

278
    for (int g = 0; g < negroups_; g++) {
70,865,310✔
279
      // There are three scenarios we need to consider:
280
      if (volume_iteration > 0.0) {
37,617,525✔
281
        // 1. If the FSR was hit this iteration, then the new flux is equal to
282
        // the flat source from the previous iteration plus the contributions
283
        // from rays passing through the source region (computed during the
284
        // transport sweep)
285
        set_flux_to_flux_plus_source(sr, volume, g);
33,558,220✔
286
      } else if (volume_simulation_avg > 0.0) {
4,059,305✔
287
        // 2. If the FSR was not hit this iteration, but has been hit some
288
        // previous iteration, then we need to make a choice about what
289
        // to do. Naively we will usually want to set the flux to be equal
290
        // to the reduced source. However, in fixed source problems where
291
        // there is a strong external source present in the cell, and where
292
        // the cell has a very low cross section, this approximation will
293
        // cause a huge upward bias in the flux estimate of the cell (in these
294
        // conditions, the flux estimate can be orders of magnitude too large).
295
        // Thus, to avoid this bias, if any external source is present
296
        // in the cell we will use the previous iteration's flux estimate. This
297
        // injects a small degree of correlation into the simulation, but this
298
        // is going to be trivial when the miss rate is a few percent or less.
299
        if (source_regions_.external_source_present(sr)) {
4,059,295✔
300
          set_flux_to_old_flux(sr, g);
1,320✔
301
        } else {
302
          set_flux_to_source(sr, g);
4,057,975✔
303
        }
304
      }
305
      // Halt if NaN implosion is detected
306
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
37,617,525✔
307
        fatal_error("A source region scalar flux is not finite. "
308
                    "This indicates a numerical instability in the "
309
                    "simulation. Consider increasing ray density or adjusting "
310
                    "the source region mesh.");
311
      }
312
    }
313
  }
314

315
  // Return the number of source regions that were hit this iteration
316
  return n_hits;
11,660✔
317
}
318

319
// Generates new estimate of k_eff based on the differences between this
320
// iteration's estimate of the scalar flux and the last iteration's estimate.
321
double FlatSourceDomain::compute_k_eff(double k_eff_old) const
2,090✔
322
{
323
  double fission_rate_old = 0;
2,090✔
324
  double fission_rate_new = 0;
2,090✔
325

326
  // Vector for gathering fission source terms for Shannon entropy calculation
327
  vector<float> p(n_source_regions(), 0.0f);
2,090✔
328

329
#pragma omp parallel for reduction(+ : fission_rate_old, fission_rate_new)
1,140✔
330
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
308,740✔
331

332
    // If simulation averaged volume is zero, don't include this cell
333
    double volume = source_regions_.volume(sr);
307,790✔
334
    if (volume == 0.0) {
307,790✔
335
      continue;
336
    }
337

338
    int material = source_regions_.material(sr);
307,790✔
339
    if (material == MATERIAL_VOID) {
307,790✔
340
      continue;
341
    }
342

343
    double sr_fission_source_old = 0;
307,790✔
344
    double sr_fission_source_new = 0;
307,790✔
345

346
    for (int g = 0; g < negroups_; g++) {
2,375,320✔
347
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
2,067,530✔
348
      sr_fission_source_old +=
2,067,530✔
349
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
2,067,530✔
350
      sr_fission_source_new +=
2,067,530✔
351
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
2,067,530✔
352
    }
353

354
    // Compute total fission rates in FSR
355
    sr_fission_source_old *= volume;
307,790✔
356
    sr_fission_source_new *= volume;
307,790✔
357

358
    // Accumulate totals
359
    fission_rate_old += sr_fission_source_old;
307,790✔
360
    fission_rate_new += sr_fission_source_new;
307,790✔
361

362
    // Store total fission rate in the FSR for Shannon calculation
363
    p[sr] = sr_fission_source_new;
307,790✔
364
  }
365

366
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
2,090✔
367

368
  double H = 0.0;
2,090✔
369
  // defining an inverse sum for better performance
370
  double inverse_sum = 1 / fission_rate_new;
2,090✔
371

372
#pragma omp parallel for reduction(+ : H)
1,140✔
373
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
308,740✔
374
    // Only if FSR has non-negative and non-zero fission source
375
    if (p[sr] > 0.0f) {
307,790✔
376
      // Normalize to total weight of bank sites. p_i for better performance
377
      float p_i = p[sr] * inverse_sum;
130,995✔
378
      // Sum values to obtain Shannon entropy.
379
      H -= p_i * std::log2(p_i);
130,995✔
380
    }
381
  }
382

383
  // Adds entropy value to shared entropy vector in openmc namespace.
384
  simulation::entropy.push_back(H);
2,090✔
385

386
  return k_eff_new;
2,090✔
387
}
2,090✔
388

389
// This function is responsible for generating a mapping between random
390
// ray flat source regions (cell instances) and tally bins. The mapping
391
// takes the form of a "TallyTask" object, which accounts for one single
392
// score being applied to a single tally. Thus, a single source region
393
// may have anywhere from zero to many tally tasks associated with it ---
394
// meaning that the global "tally_task" data structure is in 2D. The outer
395
// dimension corresponds to the source element (i.e., each entry corresponds
396
// to a specific energy group within a specific source region), and the
397
// inner dimension corresponds to the tallying task itself. Mechanically,
398
// the mapping between FSRs and spatial filters is done by considering
399
// the location of a single known ray midpoint that passed through the
400
// FSR. I.e., during transport, the first ray to pass through a given FSR
401
// will write down its midpoint for use with this function. This is a cheap
402
// and easy way of mapping FSRs to spatial tally filters, but comes with
403
// the downside of adding the restriction that spatial tally filters must
404
// share boundaries with the physical geometry of the simulation (so as
405
// not to subdivide any FSR). It is acceptable for a spatial tally region
406
// to contain multiple FSRs, but not the other way around.
407

408
// TODO: In future work, it would be preferable to offer a more general
409
// (but perhaps slightly more expensive) option for handling arbitrary
410
// spatial tallies that would be allowed to subdivide FSRs.
411

412
// Besides generating the mapping structure, this function also keeps track
413
// of whether or not all flat source regions have been hit yet. This is
414
// required, as there is no guarantee that all flat source regions will
415
// be hit every iteration, such that in the first few iterations some FSRs
416
// may not have a known position within them yet to facilitate mapping to
417
// spatial tally filters. However, after several iterations, if all FSRs
418
// have been hit and have had a tally map generated, then this status will
419
// be passed back to the caller to alert them that this function doesn't
420
// need to be called for the remainder of the simulation.
421

422
void FlatSourceDomain::convert_source_regions_to_tallies()
451✔
423
{
424
  openmc::simulation::time_tallies.start();
451✔
425

426
  // Tracks if we've generated a mapping yet for all source regions.
427
  bool all_source_regions_mapped = true;
451✔
428

429
// Attempt to generate mapping for all source regions
430
#pragma omp parallel for
246✔
431
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,166,060✔
432

433
    // If this source region has not been hit by a ray yet, then
434
    // we aren't going to be able to map it, so skip it.
435
    if (!source_regions_.position_recorded(sr)) {
1,165,855✔
436
      all_source_regions_mapped = false;
437
      continue;
438
    }
439

440
    // A particle located at the recorded midpoint of a ray
441
    // crossing through this source region is used to estabilish
442
    // the spatial location of the source region
443
    Particle p;
1,165,855✔
444
    p.r() = source_regions_.position(sr);
1,165,855✔
445
    p.r_last() = source_regions_.position(sr);
1,165,855✔
446
    p.u() = {1.0, 0.0, 0.0};
1,165,855✔
447
    bool found = exhaustive_find_cell(p);
1,165,855✔
448

449
    // Loop over energy groups (so as to support energy filters)
450
    for (int g = 0; g < negroups_; g++) {
2,480,510✔
451

452
      // Set particle to the current energy
453
      p.g() = g;
1,314,655✔
454
      p.g_last() = g;
1,314,655✔
455
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,314,655✔
456
      p.E_last() = p.E();
1,314,655✔
457

458
      int64_t source_element = sr * negroups_ + g;
1,314,655✔
459

460
      // If this task has already been populated, we don't need to do
461
      // it again.
462
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,314,655✔
463
        continue;
464
      }
465

466
      // Loop over all active tallies. This logic is essentially identical
467
      // to what happens when scanning for applicable tallies during
468
      // MC transport.
469
      for (auto i_tally : model::active_tallies) {
5,193,900✔
470
        Tally& tally {*model::tallies[i_tally]};
3,879,245✔
471

472
        // Initialize an iterator over valid filter bin combinations.
473
        // If there are no valid combinations, use a continue statement
474
        // to ensure we skip the assume_separate break below.
475
        auto filter_iter = FilterBinIter(tally, p);
3,879,245✔
476
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,879,245✔
477
        if (filter_iter == end)
3,879,245✔
478
          continue;
2,277,950✔
479

480
        // Loop over filter bins.
481
        for (; filter_iter != end; ++filter_iter) {
3,202,590✔
482
          auto filter_index = filter_iter.index_;
1,601,295✔
483
          auto filter_weight = filter_iter.weight_;
1,601,295✔
484

485
          // Loop over scores
486
          for (int score = 0; score < tally.scores_.size(); score++) {
3,539,710✔
487
            auto score_bin = tally.scores_[score];
1,938,415✔
488
            // If a valid tally, filter, and score combination has been found,
489
            // then add it to the list of tally tasks for this source element.
490
            TallyTask task(i_tally, filter_index, score, score_bin);
1,938,415✔
491
            source_regions_.tally_task(sr, g).push_back(task);
1,938,415✔
492

493
            // Also add this task to the list of volume tasks for this source
494
            // region.
495
            source_regions_.volume_task(sr).insert(task);
1,938,415✔
496
          }
497
        }
498
      }
499
      // Reset all the filter matches for the next tally event.
500
      for (auto& match : p.filter_matches())
5,949,980✔
501
        match.bins_present_ = false;
4,635,325✔
502
    }
503
  }
1,165,855✔
504
  openmc::simulation::time_tallies.stop();
451✔
505

506
  mapped_all_tallies_ = all_source_regions_mapped;
451✔
507
}
451✔
508

509
// Set the volume accumulators to zero for all tallies
510
void FlatSourceDomain::reset_tally_volumes()
4,730✔
511
{
512
  if (volume_normalized_flux_tallies_) {
4,730✔
513
#pragma omp parallel for
2,100✔
514
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,600✔
515
      auto& tensor = tally_volumes_[i];
4,850✔
516
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,850✔
517
    }
518
  }
519
}
4,730✔
520

521
// In fixed source mode, due to the way that volumetric fixed sources are
522
// converted and applied as volumetric sources in one or more source regions,
523
// we need to perform an additional normalization step to ensure that the
524
// reported scalar fluxes are in units per source neutron. This allows for
525
// direct comparison of reported tallies to Monte Carlo flux results.
526
// This factor needs to be computed at each iteration, as it is based on the
527
// volume estimate of each FSR, which improves over the course of the
528
// simulation
529
double FlatSourceDomain::compute_fixed_source_normalization_factor() const
5,306✔
530
{
531
  // If we are not in fixed source mode, then there are no external sources
532
  // so no normalization is needed.
533
  if (settings::run_mode != RunMode::FIXED_SOURCE || adjoint_) {
5,306✔
534
    return 1.0;
1,496✔
535
  }
536

537
  // Step 1 is to sum over all source regions and energy groups to get the
538
  // total external source strength in the simulation.
539
  double simulation_external_source_strength = 0.0;
3,810✔
540
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
2,085✔
541
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
14,651,965✔
542
    int material = source_regions_.material(sr);
14,650,240✔
543
    double volume = source_regions_.volume(sr) * simulation_volume_;
14,650,240✔
544
    for (int g = 0; g < negroups_; g++) {
29,851,712✔
545
      // For non-void regions, we store the external source pre-divided by
546
      // sigma_t. We need to multiply non-void regions back up by sigma_t
547
      // to get the total source strength in the expected units.
548
      double sigma_t = 1.0;
15,201,472✔
549
      if (material != MATERIAL_VOID) {
15,201,472✔
550
        sigma_t = sigma_t_[material * negroups_ + g];
14,987,472✔
551
      }
552
      simulation_external_source_strength +=
15,201,472✔
553
        source_regions_.external_source(sr, g) * sigma_t * volume;
15,201,472✔
554
    }
555
  }
556

557
  // Step 2 is to determine the total user-specified external source strength
558
  double user_external_source_strength = 0.0;
3,810✔
559
  for (auto& ext_source : model::external_sources) {
7,620✔
560
    user_external_source_strength += ext_source->strength();
3,810✔
561
  }
562

563
  // The correction factor is the ratio of the user-specified external source
564
  // strength to the simulation external source strength.
565
  double source_normalization_factor =
3,810✔
566
    user_external_source_strength / simulation_external_source_strength;
567

568
  return source_normalization_factor;
3,810✔
569
}
570

571
// Tallying in random ray is not done directly during transport, rather,
572
// it is done only once after each power iteration. This is made possible
573
// by way of a mapping data structure that relates spatial source regions
574
// (FSRs) to tally/filter/score combinations. The mechanism by which the
575
// mapping is done (and the limitations incurred) is documented in the
576
// "convert_source_regions_to_tallies()" function comments above. The present
577
// tally function simply traverses the mapping data structure and executes
578
// the scoring operations to OpenMC's native tally result arrays.
579

580
void FlatSourceDomain::random_ray_tally()
4,730✔
581
{
582
  openmc::simulation::time_tallies.start();
4,730✔
583

584
  // Reset our tally volumes to zero
585
  reset_tally_volumes();
4,730✔
586

587
  double source_normalization_factor =
588
    compute_fixed_source_normalization_factor();
4,730✔
589

590
// We loop over all source regions and energy groups. For each
591
// element, we check if there are any scores needed and apply
592
// them.
593
#pragma omp parallel for
2,580✔
594
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,210,425✔
595
    // The fsr.volume_ is the unitless fractional simulation averaged volume
596
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
597
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
598
    // entire global simulation domain (as defined by the ray source box).
599
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
600
    // its fraction of the total volume by the total volume. Not important in
601
    // eigenvalue solves, but useful in fixed source solves for returning the
602
    // flux shape with a magnitude that makes sense relative to the fixed
603
    // source strength.
604
    double volume = source_regions_.volume(sr) * simulation_volume_;
15,208,275✔
605

606
    double material = source_regions_.material(sr);
15,208,275✔
607
    for (int g = 0; g < negroups_; g++) {
31,797,750✔
608
      double flux =
609
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,589,475✔
610

611
      // Determine numerical score value
612
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,166,950✔
613
        double score = 0.0;
22,577,475✔
614
        switch (task.score_type) {
22,577,475✔
615

616
        case SCORE_FLUX:
19,405,075✔
617
          score = flux * volume;
19,405,075✔
618
          break;
19,405,075✔
619

620
        case SCORE_TOTAL:
621
          if (material != MATERIAL_VOID) {
622
            score = flux * volume * sigma_t_[material * negroups_ + g];
623
          }
624
          break;
625

626
        case SCORE_FISSION:
1,586,200✔
627
          if (material != MATERIAL_VOID) {
1,586,200✔
628
            score = flux * volume * sigma_f_[material * negroups_ + g];
1,586,200✔
629
          }
630
          break;
1,586,200✔
631

632
        case SCORE_NU_FISSION:
1,586,200✔
633
          if (material != MATERIAL_VOID) {
1,586,200✔
634
            score = flux * volume * nu_sigma_f_[material * negroups_ + g];
1,586,200✔
635
          }
636
          break;
1,586,200✔
637

638
        case SCORE_EVENTS:
639
          score = 1.0;
640
          break;
641

642
        default:
643
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
644
                      "total, fission, nu-fission, and events are supported in "
645
                      "random ray mode.");
646
          break;
647
        }
648

649
        // Apply score to the appropriate tally bin
650
        Tally& tally {*model::tallies[task.tally_idx]};
22,577,475✔
651
#pragma omp atomic
652
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,577,475✔
653
          score;
654
      }
655
    }
656

657
    // For flux tallies, the total volume of the spatial region is needed
658
    // for normalizing the flux. We store this volume in a separate tensor.
659
    // We only contribute to each volume tally bin once per FSR.
660
    if (volume_normalized_flux_tallies_) {
15,208,275✔
661
      for (const auto& task : source_regions_.volume_task(sr)) {
35,771,350✔
662
        if (task.score_type == SCORE_FLUX) {
20,707,275✔
663
#pragma omp atomic
664
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
18,752,875✔
665
            volume;
666
        }
667
      }
668
    }
669
  } // end FSR loop
670

671
  // Normalize any flux scores by the total volume of the FSRs scoring to that
672
  // bin. To do this, we loop over all tallies, and then all filter bins,
673
  // and then scores. For each score, we check the tally data structure to
674
  // see what index that score corresponds to. If that score is a flux score,
675
  // then we divide it by volume.
676
  if (volume_normalized_flux_tallies_) {
4,730✔
677
    for (int i = 0; i < model::tallies.size(); i++) {
14,520✔
678
      Tally& tally {*model::tallies[i]};
10,670✔
679
#pragma omp parallel for
5,820✔
680
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
704,025✔
681
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,416,550✔
682
          auto score_type = tally.scores_[score_idx];
717,375✔
683
          if (score_type == SCORE_FLUX) {
717,375✔
684
            double vol = tally_volumes_[i](bin, score_idx);
699,175✔
685
            if (vol > 0.0) {
699,175✔
686
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
699,175✔
687
            }
688
          }
689
        }
690
      }
691
    }
692
  }
693

694
  openmc::simulation::time_tallies.stop();
4,730✔
695
}
4,730✔
696

697
double FlatSourceDomain::evaluate_flux_at_point(
×
698
  Position r, int64_t sr, int g) const
699
{
700
  return source_regions_.scalar_flux_final(sr, g) /
×
701
         (settings::n_batches - settings::n_inactive);
×
702
}
703

704
// Outputs all basic material, FSR ID, multigroup flux, and
705
// fission source data to .vtk file that can be directly
706
// loaded and displayed by Paraview. Note that .vtk binary
707
// files require big endian byte ordering, so endianness
708
// is checked and flipped if necessary.
709
void FlatSourceDomain::output_to_vtk() const
×
710
{
711
  // Rename .h5 plot filename(s) to .vtk filenames
712
  for (int p = 0; p < model::plots.size(); p++) {
×
713
    PlottableInterface* plot = model::plots[p].get();
×
714
    plot->path_plot() =
×
715
      plot->path_plot().substr(0, plot->path_plot().find_last_of('.')) + ".vtk";
×
716
  }
717

718
  // Print header information
719
  print_plot();
×
720

721
  // Outer loop over plots
722
  for (int p = 0; p < model::plots.size(); p++) {
×
723

724
    // Get handle to OpenMC plot object and extract params
725
    Plot* openmc_plot = dynamic_cast<Plot*>(model::plots[p].get());
×
726

727
    // Random ray plots only support voxel plots
728
    if (!openmc_plot) {
×
729
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
730
                          "is allowed in random ray mode.",
731
        p));
732
      continue;
×
733
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
734
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
735
                          "is allowed in random ray mode.",
736
        p));
737
      continue;
×
738
    }
739

740
    int Nx = openmc_plot->pixels_[0];
×
741
    int Ny = openmc_plot->pixels_[1];
×
742
    int Nz = openmc_plot->pixels_[2];
×
743
    Position origin = openmc_plot->origin_;
×
744
    Position width = openmc_plot->width_;
×
745
    Position ll = origin - width / 2.0;
×
746
    double x_delta = width.x / Nx;
×
747
    double y_delta = width.y / Ny;
×
748
    double z_delta = width.z / Nz;
×
749
    std::string filename = openmc_plot->path_plot();
×
750

751
    // Perform sanity checks on file size
752
    uint64_t bytes = Nx * Ny * Nz * (negroups_ + 1 + 1 + 1) * sizeof(float);
×
753
    write_message(5, "Processing plot {}: {}... (Estimated size is {} MB)",
×
754
      openmc_plot->id(), filename, bytes / 1.0e6);
×
755
    if (bytes / 1.0e9 > 1.0) {
×
756
      warning("Voxel plot specification is very large (>1 GB). Plotting may be "
×
757
              "slow.");
758
    } else if (bytes / 1.0e9 > 100.0) {
×
759
      fatal_error("Voxel plot specification is too large (>100 GB). Exiting.");
×
760
    }
761

762
    // Relate voxel spatial locations to random ray source regions
763
    vector<int> voxel_indices(Nx * Ny * Nz);
×
764
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
765
    vector<double> weight_windows(Nx * Ny * Nz);
×
766
    float min_weight = 1e20;
×
767
#pragma omp parallel for collapse(3) reduction(min : min_weight)
768
    for (int z = 0; z < Nz; z++) {
769
      for (int y = 0; y < Ny; y++) {
770
        for (int x = 0; x < Nx; x++) {
771
          Position sample;
772
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
773
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
774
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
775
          Particle p;
776
          p.r() = sample;
777
          p.r_last() = sample;
778
          p.E() = 1.0;
779
          p.E_last() = 1.0;
780
          p.u() = {1.0, 0.0, 0.0};
781

782
          bool found = exhaustive_find_cell(p);
783
          if (!found) {
784
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
785
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
786
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
787
            continue;
788
          }
789

790
          int i_cell = p.lowest_coord().cell;
791
          int64_t sr = source_region_offsets_[i_cell] + p.cell_instance();
792
          if (RandomRay::mesh_subdivision_enabled_) {
793
            int mesh_idx = base_source_regions_.mesh(sr);
794
            int mesh_bin;
795
            if (mesh_idx == C_NONE) {
796
              mesh_bin = 0;
797
            } else {
798
              mesh_bin = model::meshes[mesh_idx]->get_bin(p.r());
799
            }
800
            SourceRegionKey sr_key {sr, mesh_bin};
801
            auto it = source_region_map_.find(sr_key);
802
            if (it != source_region_map_.end()) {
803
              sr = it->second;
804
            } else {
805
              sr = -1;
806
            }
807
          }
808

809
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
810
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
811

812
          if (variance_reduction::weight_windows.size() == 1) {
813
            WeightWindow ww =
814
              variance_reduction::weight_windows[0]->get_weight_window(p);
815
            float weight = ww.lower_weight;
816
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
817
            if (weight < min_weight)
818
              min_weight = weight;
819
          }
820
        }
821
      }
822
    }
823

824
    double source_normalization_factor =
825
      compute_fixed_source_normalization_factor();
×
826

827
    // Open file for writing
828
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
829

830
    // Write vtk metadata
831
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
832
    std::fprintf(plot, "Dataset File\n");
×
833
    std::fprintf(plot, "BINARY\n");
×
834
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
835
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
836
    std::fprintf(plot, "ORIGIN %lf %lf %lf\n", ll.x, ll.y, ll.z);
×
837
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
838
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
839

840
    int64_t num_neg = 0;
×
841
    int64_t num_samples = 0;
×
842
    float min_flux = 0.0;
×
843
    float max_flux = -1.0e20;
×
844
    // Plot multigroup flux data
845
    for (int g = 0; g < negroups_; g++) {
×
846
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
847
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
848
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
849
        int64_t fsr = voxel_indices[i];
×
850
        int64_t source_element = fsr * negroups_ + g;
×
851
        float flux = 0;
×
852
        if (fsr >= 0) {
×
853
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
854
          if (flux < 0.0)
×
855
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
856
              voxel_positions[i], fsr, g);
×
857
        }
858
        if (flux < 0.0) {
×
859
          num_neg++;
×
860
          if (flux < min_flux) {
×
861
            min_flux = flux;
×
862
          }
863
        }
864
        if (flux > max_flux)
×
865
          max_flux = flux;
×
866
        num_samples++;
×
867
        flux = convert_to_big_endian<float>(flux);
×
868
        std::fwrite(&flux, sizeof(float), 1, plot);
×
869
      }
870
    }
871

872
    // Slightly negative fluxes can be normal when sampling corners of linear
873
    // source regions. However, very common and high magnitude negative fluxes
874
    // may indicate numerical instability.
875
    if (num_neg > 0) {
×
876
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
877
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
878
        num_neg, (100.0 * num_neg) / num_samples, min_flux, max_flux));
×
879
    }
880

881
    // Plot FSRs
882
    std::fprintf(plot, "SCALARS FSRs float\n");
×
883
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
884
    for (int fsr : voxel_indices) {
×
885
      float value = future_prn(10, fsr);
×
886
      value = convert_to_big_endian<float>(value);
×
887
      std::fwrite(&value, sizeof(float), 1, plot);
×
888
    }
889

890
    // Plot Materials
891
    std::fprintf(plot, "SCALARS Materials int\n");
×
892
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
893
    for (int fsr : voxel_indices) {
×
894
      int mat = -1;
×
895
      if (fsr >= 0)
×
896
        mat = source_regions_.material(fsr);
×
897
      mat = convert_to_big_endian<int>(mat);
×
898
      std::fwrite(&mat, sizeof(int), 1, plot);
×
899
    }
900

901
    // Plot fission source
902
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
903
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
904
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
905
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
906
        int64_t fsr = voxel_indices[i];
×
907
        float total_fission = 0.0;
×
908
        if (fsr >= 0) {
×
909
          int mat = source_regions_.material(fsr);
×
910
          if (mat != MATERIAL_VOID) {
×
911
            for (int g = 0; g < negroups_; g++) {
×
912
              int64_t source_element = fsr * negroups_ + g;
×
913
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
914
              double sigma_f = sigma_f_[mat * negroups_ + g];
×
915
              total_fission += sigma_f * flux;
×
916
            }
917
          }
918
        }
919
        total_fission = convert_to_big_endian<float>(total_fission);
×
920
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
921
      }
922
    } else {
923
      std::fprintf(plot, "SCALARS external_source float\n");
×
924
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
925
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
926
        int64_t fsr = voxel_indices[i];
×
927
        int mat = source_regions_.material(fsr);
×
928
        float total_external = 0.0f;
×
929
        if (fsr >= 0) {
×
930
          for (int g = 0; g < negroups_; g++) {
×
931
            // External sources are already divided by sigma_t, so we need to
932
            // multiply it back to get the true external source.
933
            double sigma_t = 1.0;
×
934
            if (mat != MATERIAL_VOID) {
×
935
              sigma_t = sigma_t_[mat * negroups_ + g];
×
936
            }
937
            total_external += source_regions_.external_source(fsr, g) * sigma_t;
×
938
          }
939
        }
940
        total_external = convert_to_big_endian<float>(total_external);
×
941
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
942
      }
943
    }
944

945
    // Plot weight window data
946
    if (variance_reduction::weight_windows.size() == 1) {
×
947
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
948
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
949
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
950
        float weight = weight_windows[i];
×
951
        if (weight == 0.0)
×
952
          weight = min_weight;
×
953
        weight = convert_to_big_endian<float>(weight);
×
954
        std::fwrite(&weight, sizeof(float), 1, plot);
×
955
      }
956
    }
957

958
    std::fclose(plot);
×
959
  }
960
}
961

962
void FlatSourceDomain::apply_external_source_to_source_region(
2,747✔
963
  Discrete* discrete, double strength_factor, SourceRegionHandle& srh)
964
{
965
  srh.external_source_present() = 1;
2,747✔
966

967
  const auto& discrete_energies = discrete->x();
2,747✔
968
  const auto& discrete_probs = discrete->prob();
2,747✔
969

970
  for (int i = 0; i < discrete_energies.size(); i++) {
5,686✔
971
    int g = data::mg.get_group_index(discrete_energies[i]);
2,939✔
972
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,939✔
973
  }
974
}
2,747✔
975

976
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
416✔
977
  Discrete* discrete, double strength_factor, int target_material_id,
978
  const vector<int32_t>& instances)
979
{
980
  Cell& cell = *model::cells[i_cell];
416✔
981

982
  if (cell.type_ != Fill::MATERIAL)
416✔
983
    return;
×
984

985
  for (int j : instances) {
30,672✔
986
    int cell_material_idx = cell.material(j);
30,256✔
987
    int cell_material_id;
988
    if (cell_material_idx == MATERIAL_VOID) {
30,256✔
989
      cell_material_id = MATERIAL_VOID;
256✔
990
    } else {
991
      cell_material_id = model::materials[cell_material_idx]->id();
30,000✔
992
    }
993
    if (target_material_id == C_NONE ||
30,256✔
994
        cell_material_id == target_material_id) {
995
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,736✔
996
      SourceRegionHandle srh =
997
        source_regions_.get_source_region_handle(source_region);
2,736✔
998
      apply_external_source_to_source_region(discrete, strength_factor, srh);
2,736✔
999
    }
1000
  }
1001
}
1002

1003
void FlatSourceDomain::apply_external_source_to_cell_and_children(
448✔
1004
  int32_t i_cell, Discrete* discrete, double strength_factor,
1005
  int32_t target_material_id)
1006
{
1007
  Cell& cell = *model::cells[i_cell];
448✔
1008

1009
  if (cell.type_ == Fill::MATERIAL) {
448✔
1010
    vector<int> instances(cell.n_instances_);
416✔
1011
    std::iota(instances.begin(), instances.end(), 0);
416✔
1012
    apply_external_source_to_cell_instances(
416✔
1013
      i_cell, discrete, strength_factor, target_material_id, instances);
1014
  } else if (target_material_id == C_NONE) {
448✔
1015
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1016
      cell.get_contained_cells(0, nullptr);
×
1017
    for (const auto& pair : cell_instance_list) {
×
1018
      int32_t i_child_cell = pair.first;
×
1019
      apply_external_source_to_cell_instances(i_child_cell, discrete,
×
1020
        strength_factor, target_material_id, pair.second);
×
1021
    }
1022
  }
1023
}
448✔
1024

1025
void FlatSourceDomain::count_external_source_regions()
1,056✔
1026
{
1027
  n_external_source_regions_ = 0;
1,056✔
1028
#pragma omp parallel for reduction(+ : n_external_source_regions_)
594✔
1029
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,533,040✔
1030
    if (source_regions_.external_source_present(sr)) {
1,532,578✔
1031
      n_external_source_regions_++;
158,714✔
1032
    }
1033
  }
1034
}
1,056✔
1035

1036
void FlatSourceDomain::convert_external_sources()
400✔
1037
{
1038
  // Loop over external sources
1039
  for (int es = 0; es < model::external_sources.size(); es++) {
800✔
1040

1041
    // Extract source information
1042
    Source* s = model::external_sources[es].get();
400✔
1043
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
400✔
1044
    auto* energy = is->energy();
400✔
1045

1046
    // Convert energy distribution to discrete
1047
    std::vector<double> x;
400✔
1048
    std::vector<double> p;
400✔
1049
    for (int g = 0; g < data::mg.num_energy_groups_; ++g) {
992✔
1050
      double prob = energy->integral(
592✔
1051
        data::mg.energy_bins_[g + 1], data::mg.energy_bins_[g]);
592✔
1052
      if (prob > 0.0) {
592✔
1053
        x.push_back(data::mg.energy_bin_avg_[g]);
592✔
1054
        p.push_back(prob);
592✔
1055
      }
1056
    }
1057
    is->set_energy(UPtrDist {new Discrete(&x[0], &p[0], x.size())});
400✔
1058
    Discrete* discrete = dynamic_cast<Discrete*>(is->energy());
400✔
1059
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
400✔
1060
    double strength_factor = is->strength();
400✔
1061

1062
    // If there is no domain constraint specified, then this must be a point
1063
    // source. In this case, we need to find the source region that contains the
1064
    // point source and apply or relate it to the external source.
1065
    if (is->domain_ids().size() == 0) {
400✔
1066

1067
      // Extract the point source coordinate and find the base source region at
1068
      // that point
1069
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
16✔
1070
      GeometryState gs;
16✔
1071
      gs.r() = sp->r();
16✔
1072
      gs.r_last() = sp->r();
16✔
1073
      gs.u() = {1.0, 0.0, 0.0};
16✔
1074
      bool found = exhaustive_find_cell(gs);
16✔
1075
      if (!found) {
16✔
1076
        fatal_error(fmt::format("Could not find cell containing external "
×
1077
                                "point source at {}",
1078
          sp->r()));
×
1079
      }
1080
      int i_cell = gs.lowest_coord().cell;
16✔
1081
      int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
16✔
1082

1083
      if (RandomRay::mesh_subdivision_enabled_) {
16✔
1084
        // If mesh subdivision is enabled, we need to determine which subdivided
1085
        // mesh bin the point source coordinate is in as well
1086
        int mesh_idx = source_regions_.mesh(sr);
16✔
1087
        int mesh_bin;
1088
        if (mesh_idx == C_NONE) {
16✔
1089
          mesh_bin = 0;
×
1090
        } else {
1091
          mesh_bin = model::meshes[mesh_idx]->get_bin(gs.r());
16✔
1092
        }
1093
        // With the source region and mesh bin known, we can use the
1094
        // accompanying SourceRegionKey as a key into a map that stores the
1095
        // corresponding external source index for the point source. Notably, we
1096
        // do not actually apply the external source to any source regions here,
1097
        // as if mesh subdivision is enabled, they haven't actually been
1098
        // discovered & initilized yet. When discovered, they will read from the
1099
        // point_source_map to determine if there are any point source terms
1100
        // that should be applied.
1101
        SourceRegionKey key {sr, mesh_bin};
16✔
1102
        point_source_map_[key] = es;
16✔
1103
      } else {
1104
        // If we are not using mesh subdivision, we can apply the external
1105
        // source directly to the source region as we do for volumetric domain
1106
        // constraint sources.
1107
        SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
×
NEW
1108
        apply_external_source_to_source_region(discrete, strength_factor, srh);
×
1109
      }
1110

1111
    } else {
16✔
1112
      // If not a point source, then use the volumetric domain constraints to
1113
      // determine which source regions to apply the external source to.
1114
      if (is->domain_type() == Source::DomainType::MATERIAL) {
384✔
1115
        for (int32_t material_id : domain_ids) {
32✔
1116
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1117
            apply_external_source_to_cell_and_children(
80✔
1118
              i_cell, discrete, strength_factor, material_id);
1119
          }
1120
        }
1121
      } else if (is->domain_type() == Source::DomainType::CELL) {
368✔
1122
        for (int32_t cell_id : domain_ids) {
64✔
1123
          int32_t i_cell = model::cell_map[cell_id];
32✔
1124
          apply_external_source_to_cell_and_children(
32✔
1125
            i_cell, discrete, strength_factor, C_NONE);
1126
        }
1127
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
336✔
1128
        for (int32_t universe_id : domain_ids) {
672✔
1129
          int32_t i_universe = model::universe_map[universe_id];
336✔
1130
          Universe& universe = *model::universes[i_universe];
336✔
1131
          for (int32_t i_cell : universe.cells_) {
672✔
1132
            apply_external_source_to_cell_and_children(
336✔
1133
              i_cell, discrete, strength_factor, C_NONE);
1134
          }
1135
        }
1136
      }
1137
    }
1138
  } // End loop over external sources
400✔
1139

1140
// Divide the fixed source term by sigma t (to save time when applying each
1141
// iteration)
1142
#pragma omp parallel for
225✔
1143
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
271,180✔
1144
    int material = source_regions_.material(sr);
271,005✔
1145
    if (material == MATERIAL_VOID) {
271,005✔
1146
      continue;
14,000✔
1147
    }
1148
    for (int g = 0; g < negroups_; g++) {
543,242✔
1149
      double sigma_t = sigma_t_[material * negroups_ + g];
286,237✔
1150
      source_regions_.external_source(sr, g) /= sigma_t;
286,237✔
1151
    }
1152
  }
1153
}
400✔
1154

1155
void FlatSourceDomain::flux_swap()
11,660✔
1156
{
1157
  source_regions_.flux_swap();
11,660✔
1158
}
11,660✔
1159

1160
void FlatSourceDomain::flatten_xs()
656✔
1161
{
1162
  // Temperature and angle indices, if using multiple temperature
1163
  // data sets and/or anisotropic data sets.
1164
  // TODO: Currently assumes we are only using single temp/single angle data.
1165
  const int t = 0;
656✔
1166
  const int a = 0;
656✔
1167

1168
  n_materials_ = data::mg.macro_xs_.size();
656✔
1169
  for (auto& m : data::mg.macro_xs_) {
2,448✔
1170
    for (int g_out = 0; g_out < negroups_; g_out++) {
8,768✔
1171
      if (m.exists_in_model) {
6,976✔
1172
        double sigma_t =
1173
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
6,912✔
1174
        sigma_t_.push_back(sigma_t);
6,912✔
1175

1176
        double nu_sigma_f =
1177
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
6,912✔
1178
        nu_sigma_f_.push_back(nu_sigma_f);
6,912✔
1179

1180
        double sigma_f =
1181
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
6,912✔
1182
        sigma_f_.push_back(sigma_f);
6,912✔
1183

1184
        double chi =
1185
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
6,912✔
1186
        if (!std::isfinite(chi)) {
6,912✔
1187
          // MGXS interface may return NaN in some cases, such as when material
1188
          // is fissionable but has very small sigma_f.
1189
          chi = 0.0;
×
1190
        }
1191
        chi_.push_back(chi);
6,912✔
1192

1193
        for (int g_in = 0; g_in < negroups_; g_in++) {
258,048✔
1194
          double sigma_s =
1195
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
251,136✔
1196
          sigma_s_.push_back(sigma_s);
251,136✔
1197
          // For transport corrected XS data, diagonal elements may be negative.
1198
          // In this case, set a flag to enable transport stabilization for the
1199
          // simulation.
1200
          if (g_out == g_in && sigma_s < 0.0)
251,136✔
1201
            is_transport_stabilization_needed_ = true;
880✔
1202
        }
1203
      } else {
1204
        sigma_t_.push_back(0);
64✔
1205
        nu_sigma_f_.push_back(0);
64✔
1206
        sigma_f_.push_back(0);
64✔
1207
        chi_.push_back(0);
64✔
1208
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1209
          sigma_s_.push_back(0);
64✔
1210
        }
1211
      }
1212
    }
1213
  }
1214
}
656✔
1215

1216
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
64✔
1217
{
1218
  // Set the adjoint external source to 1/forward_flux. If the forward flux is
1219
  // negative, zero, or extremely close to zero, set the adjoint source to zero,
1220
  // as this is likely a very small source region that we don't need to bother
1221
  // trying to vector particles towards. In the case of flux "being extremely
1222
  // close to zero", we define this as being a fixed fraction of the maximum
1223
  // forward flux, below which we assume the flux would be physically
1224
  // undetectable.
1225

1226
  // First, find the maximum forward flux value
1227
  double max_flux = 0.0;
64✔
1228
#pragma omp parallel for reduction(max : max_flux)
36✔
1229
  for (int64_t se = 0; se < n_source_elements(); se++) {
169,372✔
1230
    double flux = forward_flux[se];
169,344✔
1231
    if (flux > max_flux) {
169,344✔
1232
      max_flux = flux;
25✔
1233
    }
1234
  }
1235

1236
  // Then, compute the adjoint source for each source region
1237
#pragma omp parallel for
36✔
1238
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1239
    for (int g = 0; g < negroups_; g++) {
338,688✔
1240
      double flux = forward_flux[sr * negroups_ + g];
169,344✔
1241
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
169,344✔
1242
        source_regions_.external_source(sr, g) = 0.0;
325✔
1243
      } else {
1244
        source_regions_.external_source(sr, g) = 1.0 / flux;
169,019✔
1245
      }
1246
      if (flux > 0.0) {
169,344✔
1247
        source_regions_.external_source_present(sr) = 1;
155,195✔
1248
      }
1249
    }
1250
  }
1251

1252
  // Divide the fixed source term by sigma t (to save time when applying each
1253
  // iteration)
1254
#pragma omp parallel for
36✔
1255
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1256
    int material = source_regions_.material(sr);
169,344✔
1257
    if (material == MATERIAL_VOID) {
169,344✔
1258
      continue;
1259
    }
1260
    for (int g = 0; g < negroups_; g++) {
338,688✔
1261
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1262
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1263
    }
1264
  }
1265
}
64✔
1266

1267
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1268
{
1269
  // Transpose the inner two dimensions for each material
1270
  for (int m = 0; m < n_materials_; ++m) {
304✔
1271
    int material_offset = m * negroups_ * negroups_;
224✔
1272
    for (int i = 0; i < negroups_; ++i) {
640✔
1273
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1274
        // Calculate indices of the elements to swap
1275
        int idx1 = material_offset + i * negroups_ + j;
672✔
1276
        int idx2 = material_offset + j * negroups_ + i;
672✔
1277

1278
        // Swap the elements to transpose the matrix
1279
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1280
      }
1281
    }
1282
  }
1283
}
80✔
1284

1285
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
576✔
1286
{
1287
  // Ensure array is correct size
1288
  flux.resize(n_source_regions() * negroups_);
576✔
1289
// Serialize the final fluxes for output
1290
#pragma omp parallel for
324✔
1291
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,258,605✔
1292
    flux[se] = source_regions_.scalar_flux_final(se);
1,258,353✔
1293
  }
1294
}
576✔
1295

1296
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
608✔
1297
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1298
  bool is_target_void)
1299
{
1300
  Cell& cell = *model::cells[i_cell];
608✔
1301
  if (cell.type_ != Fill::MATERIAL)
608✔
1302
    return;
×
1303
  for (int32_t j : instances) {
174,944✔
1304
    int cell_material_idx = cell.material(j);
174,336✔
1305
    int cell_material_id = (cell_material_idx == C_NONE)
1306
                             ? C_NONE
174,336✔
1307
                             : model::materials[cell_material_idx]->id();
174,336✔
1308

1309
    if ((target_material_id == C_NONE && !is_target_void) ||
174,336✔
1310
        cell_material_id == target_material_id) {
1311
      int64_t sr = source_region_offsets_[i_cell] + j;
142,336✔
1312
      if (source_regions_.mesh(sr) != C_NONE) {
142,336✔
1313
        // print out the source region that is broken:
1314
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1315
                                "applied, but trying to apply mesh idx {}",
1316
          sr, source_regions_.mesh(sr), mesh_idx));
1317
      }
1318
      source_regions_.mesh(sr) = mesh_idx;
142,336✔
1319
    }
1320
  }
1321
}
1322

1323
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
480✔
1324
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1325
{
1326
  Cell& cell = *model::cells[i_cell];
480✔
1327

1328
  if (cell.type_ == Fill::MATERIAL) {
480✔
1329
    vector<int> instances(cell.n_instances_);
352✔
1330
    std::iota(instances.begin(), instances.end(), 0);
352✔
1331
    apply_mesh_to_cell_instances(
352✔
1332
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1333
  } else if (target_material_id == C_NONE && !is_target_void) {
480✔
1334
    for (int j = 0; j < cell.n_instances_; j++) {
128✔
1335
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1336
        cell.get_contained_cells(j, nullptr);
64✔
1337
      for (const auto& pair : cell_instance_list) {
320✔
1338
        int32_t i_child_cell = pair.first;
256✔
1339
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
256✔
1340
          pair.second, is_target_void);
256✔
1341
      }
1342
    }
64✔
1343
  }
1344
}
480✔
1345

1346
void FlatSourceDomain::apply_meshes()
576✔
1347
{
1348
  // Skip if there are no mappings between mesh IDs and domains
1349
  if (mesh_domain_map_.empty())
576✔
1350
    return;
416✔
1351

1352
  // Loop over meshes
1353
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
400✔
1354
    Mesh* mesh = model::meshes[mesh_idx].get();
240✔
1355
    int mesh_id = mesh->id();
240✔
1356

1357
    // Skip if mesh id is not present in the map
1358
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
240✔
1359
      continue;
16✔
1360

1361
    // Loop over domains associated with the mesh
1362
    for (auto& domain : mesh_domain_map_[mesh_id]) {
448✔
1363
      Source::DomainType domain_type = domain.first;
224✔
1364
      int domain_id = domain.second;
224✔
1365

1366
      if (domain_type == Source::DomainType::MATERIAL) {
224✔
1367
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1368
          if (domain_id == C_NONE) {
160✔
1369
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1370
          } else {
1371
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1372
          }
1373
        }
1374
      } else if (domain_type == Source::DomainType::CELL) {
192✔
1375
        int32_t i_cell = model::cell_map[domain_id];
32✔
1376
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1377
      } else if (domain_type == Source::DomainType::UNIVERSE) {
160✔
1378
        int32_t i_universe = model::universe_map[domain_id];
160✔
1379
        Universe& universe = *model::universes[i_universe];
160✔
1380
        for (int32_t i_cell : universe.cells_) {
448✔
1381
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
288✔
1382
        }
1383
      }
1384
    }
1385
  }
1386
}
1387

1388
void FlatSourceDomain::prepare_base_source_regions()
110✔
1389
{
1390
  std::swap(source_regions_, base_source_regions_);
110✔
1391
  source_regions_.negroups() = base_source_regions_.negroups();
110✔
1392
  source_regions_.is_linear() = base_source_regions_.is_linear();
110✔
1393
}
110✔
1394

1395
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
871,515,854✔
1396
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1397
{
1398
  SourceRegionKey sr_key {sr, mesh_bin};
871,515,854✔
1399

1400
  // Case 1: Check if the source region key is already present in the permanent
1401
  // map. This is the most common condition, as any source region visited in a
1402
  // previous power iteration will already be present in the permanent map. If
1403
  // the source region key is found, we translate the key into a specific 1D
1404
  // source region index and return a handle its position in the
1405
  // source_regions_ vector.
1406
  auto it = source_region_map_.find(sr_key);
871,515,854✔
1407
  if (it != source_region_map_.end()) {
871,515,854✔
1408
    int64_t sr = it->second;
850,445,145✔
1409
    return source_regions_.get_source_region_handle(sr);
850,445,145✔
1410
  }
1411

1412
  // Case 2: Check if the source region key is present in the temporary (thread
1413
  // safe) map. This is a common occurrence in the first power iteration when
1414
  // the source region has already been visited already by some other ray. We
1415
  // begin by locking the temporary map before any operations are performed. The
1416
  // lock is not global over the full data structure -- it will be dependent on
1417
  // which key is used.
1418
  discovered_source_regions_.lock(sr_key);
21,070,709✔
1419

1420
  // If the key is found in the temporary map, then we return a handle to the
1421
  // source region that is stored in the temporary map.
1422
  if (discovered_source_regions_.contains(sr_key)) {
21,070,709✔
1423
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
19,099,003✔
1424
    discovered_source_regions_.unlock(sr_key);
19,099,003✔
1425
    return handle;
19,099,003✔
1426
  }
1427

1428
  // Case 3: The source region key is not present anywhere, but it is only due
1429
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1430
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1431
  // result in the ray tracer detecting an additional (very short) segment
1432
  // though a mesh bin that is actually past the physical source region
1433
  // boundary. This is a result of the the multi-level ray tracing treatment in
1434
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1435
  // result in the wrong surface being selected as the nearest. This can happen
1436
  // in a lattice when there are two directions that both are very close in
1437
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1438
  // treated as being equivalent so alternative logic is used. However, when we
1439
  // go and ray trace on this with the mesh tracer we may go past the surface
1440
  // bounding the current source region.
1441
  //
1442
  // To filter out this case, before we create the new source region, we double
1443
  // check that the actual starting point of this segment (r) is still in the
1444
  // same geometry source region that we started in. If an artifact is detected,
1445
  // we discard the segment (and attenuation through it) as it is not really a
1446
  // valid source region and will have only an infinitessimally small cell
1447
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1448
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1449
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1450
  // consequences for the general ray tracer, so for now we do the below sanity
1451
  // checks before generating phantom source regions. A significant extra cost
1452
  // is incurred in instantiating the GeometryState object and doing a cell
1453
  // lookup, but again, this is going to be an extremely rare thing to check
1454
  // after the first power iteration has completed.
1455

1456
  // Sanity check on source region id
1457
  GeometryState gs;
1,971,706✔
1458
  gs.r() = r + TINY_BIT * u;
1,971,706✔
1459
  gs.u() = {1.0, 0.0, 0.0};
1,971,706✔
1460
  exhaustive_find_cell(gs);
1,971,706✔
1461
  int gs_i_cell = gs.lowest_coord().cell;
1,971,706✔
1462
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,971,706✔
1463
  if (sr_found != sr) {
1,971,706✔
1464
    discovered_source_regions_.unlock(sr_key);
88✔
1465
    SourceRegionHandle handle;
88✔
1466
    handle.is_numerical_fp_artifact_ = true;
88✔
1467
    return handle;
88✔
1468
  }
1469

1470
  // Sanity check on mesh bin
1471
  int mesh_idx = base_source_regions_.mesh(sr);
1,971,618✔
1472
  if (mesh_idx == C_NONE) {
1,971,618✔
1473
    if (mesh_bin != 0) {
×
1474
      discovered_source_regions_.unlock(sr_key);
×
1475
      SourceRegionHandle handle;
×
1476
      handle.is_numerical_fp_artifact_ = true;
×
1477
      return handle;
×
1478
    }
1479
  } else {
1480
    Mesh* mesh = model::meshes[mesh_idx].get();
1,971,618✔
1481
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,971,618✔
1482
    if (bin_found != mesh_bin) {
1,971,618✔
1483
      discovered_source_regions_.unlock(sr_key);
×
1484
      SourceRegionHandle handle;
×
1485
      handle.is_numerical_fp_artifact_ = true;
×
1486
      return handle;
×
1487
    }
1488
  }
1489

1490
  // Case 4: The source region key is valid, but is not present anywhere. This
1491
  // condition only occurs the first time the source region is discovered
1492
  // (typically in the first power iteration). In this case, we need to handle
1493
  // creation of the new source region and its storage into the parallel map.
1494
  // The new source region is created by copying the base source region, so as
1495
  // to inherit material, external source, and some flux properties etc. We
1496
  // also pass the base source region id to allow the new source region to
1497
  // know which base source region it is derived from.
1498
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
1,971,618✔
1499
    sr_key, {base_source_regions_.get_source_region_handle(sr), sr});
1,971,618✔
1500
  discovered_source_regions_.unlock(sr_key);
1,971,618✔
1501
  SourceRegionHandle handle {*sr_ptr};
1,971,618✔
1502

1503
  // Check if the new source region contains a point source and apply it if so
1504
  auto it2 = point_source_map_.find(sr_key);
1,971,618✔
1505
  if (it2 != point_source_map_.end()) {
1,971,618✔
1506
    int es = it2->second;
11✔
1507
    auto s = model::external_sources[es].get();
11✔
1508
    auto is = dynamic_cast<IndependentSource*>(s);
11✔
1509
    auto energy = dynamic_cast<Discrete*>(is->energy());
11✔
1510
    double strength_factor = is->strength();
11✔
1511
    apply_external_source_to_source_region(energy, strength_factor, handle);
11✔
1512
    int material = handle.material();
11✔
1513
    if (material != MATERIAL_VOID) {
11✔
1514
      for (int g = 0; g < negroups_; g++) {
22✔
1515
        double sigma_t = sigma_t_[material * negroups_ + g];
11✔
1516
        handle.external_source(g) /= sigma_t;
11✔
1517
      }
1518
    }
1519
  }
1520

1521
  return handle;
1,971,618✔
1522
}
1,971,706✔
1523

1524
void FlatSourceDomain::finalize_discovered_source_regions()
2,970✔
1525
{
1526
  // Extract keys for entries with a valid volume.
1527
  vector<SourceRegionKey> keys;
2,970✔
1528
  for (const auto& pair : discovered_source_regions_) {
1,974,588✔
1529
    if (pair.second.volume_ > 0.0) {
1,971,618✔
1530
      keys.push_back(pair.first);
1,870,176✔
1531
    }
1532
  }
1533

1534
  if (!keys.empty()) {
2,970✔
1535
    // Sort the keys, so as to ensure reproducible ordering given that source
1536
    // regions may have been added to discovered_source_regions_ in an arbitrary
1537
    // order due to shared memory threading.
1538
    std::sort(keys.begin(), keys.end());
440✔
1539

1540
    // Append the source regions in the sorted key order.
1541
    for (const auto& key : keys) {
1,870,616✔
1542
      const SourceRegion& sr = discovered_source_regions_[key];
1,870,176✔
1543
      source_region_map_[key] = source_regions_.n_source_regions();
1,870,176✔
1544
      source_regions_.push_back(sr);
1,870,176✔
1545
    }
1546

1547
    // If any new source regions were discovered, we need to update the
1548
    // tally mapping between source regions and tally bins.
1549
    mapped_all_tallies_ = false;
440✔
1550
  }
1551

1552
  discovered_source_regions_.clear();
2,970✔
1553
}
2,970✔
1554

1555
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1556
//
1557
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1558
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1559
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1560
// https://doi.org/10.1016/j.anucene.2018.10.036.
1561
void FlatSourceDomain::apply_transport_stabilization()
11,660✔
1562
{
1563
  // Don't do anything if all in-group scattering
1564
  // cross sections are positive
1565
  if (!is_transport_stabilization_needed_) {
11,660✔
1566
    return;
11,440✔
1567
  }
1568

1569
  // Apply the stabilization factor to all source elements
1570
#pragma omp parallel for
120✔
1571
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1572
    int material = source_regions_.material(sr);
1,200✔
1573
    if (material == MATERIAL_VOID) {
1,200✔
1574
      continue;
1575
    }
1576
    for (int g = 0; g < negroups_; g++) {
85,200✔
1577
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1578
      // negative
1579
      double sigma_s =
1580
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g];
84,000✔
1581
      if (sigma_s < 0.0) {
84,000✔
1582
        double sigma_t = sigma_t_[material * negroups_ + g];
22,000✔
1583
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1584
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
1585

1586
        // Equation 18 in the above Gunow et al. 2019 paper. For a default
1587
        // rho of 1.0, this ensures there are no negative diagonal elements
1588
        // in the iteration matrix. A lesser rho could be used (or exposed
1589
        // as a user input parameter) to reduce the negative impact on
1590
        // convergence rate though would need to be experimentally tested to see
1591
        // if it doesn't become unstable. rho = 1.0 is good as it gives the
1592
        // highest assurance of stability, and the impacts on convergence rate
1593
        // are pretty mild.
1594
        double D = diagonal_stabilization_rho_ * sigma_s / sigma_t;
22,000✔
1595

1596
        // Equation 16 in the above Gunow et al. 2019 paper
1597
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1598
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1599
      }
1600
    }
1601
  }
1602
}
1603

1604
} // namespace openmc
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

© 2025 Coveralls, Inc