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

openmc-dev / openmc / 15648508499

14 Jun 2025 04:41AM UTC coverage: 85.162% (+0.04%) from 85.126%
15648508499

Pull #3346

github

web-flow
Merge 95507c5a3 into b11eb0265
Pull Request #3346: Allow specifying number of equiprobable angles for thermal scattering data generation

52373 of 61498 relevant lines covered (85.16%)

36636961.06 hits per line

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

78.46
/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_)
640✔
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;
640✔
44
  for (const auto& c : model::cells) {
5,456✔
45
    if (c->type_ != Fill::MATERIAL) {
4,816✔
46
      source_region_offsets_.push_back(-1);
2,320✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
2,496✔
49
      base_source_regions += c->n_instances_;
2,496✔
50
    }
51
  }
52

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

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

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

75
  // Initialize tally volumes
76
  if (volume_normalized_flux_tallies_) {
640✔
77
    tally_volumes_.resize(model::tallies.size());
512✔
78
    for (int i = 0; i < model::tallies.size(); i++) {
1,920✔
79
      //  Get the shape of the 3D result tensor
80
      auto shape = model::tallies[i]->results().shape();
1,408✔
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,408✔
85
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,816✔
86
    }
87
  }
88

89
  // Compute simulation domain volume based on ray source
90
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
640✔
91
  SpatialDistribution* space_dist = is->space();
640✔
92
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
640✔
93
  Position dims = sb->upper_right() - sb->lower_left();
640✔
94
  simulation_volume_ = dims.x * dims.y * dims.z;
640✔
95
}
640✔
96

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

106
#pragma omp parallel for
6,300✔
107
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,741,425✔
108
    source_regions_.scalar_flux_new(se) = 0.0;
36,736,175✔
109
  }
110
}
11,550✔
111

112
void FlatSourceDomain::accumulate_iteration_flux()
4,675✔
113
{
114
#pragma omp parallel for
2,550✔
115
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,591,525✔
116
    source_regions_.scalar_flux_final(se) +=
16,589,400✔
117
      source_regions_.scalar_flux_new(se);
16,589,400✔
118
  }
119
}
4,675✔
120

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

127
  double inverse_k_eff = 1.0 / k_eff;
5,115✔
128

129
// Reset all source regions to zero (important for void regions)
130
#pragma omp parallel for
2,790✔
131
  for (int64_t se = 0; se < n_source_elements(); se++) {
21,597,915✔
132
    source_regions_.source(se) = 0.0;
21,595,590✔
133
  }
134

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

147
      for (int g_in = 0; g_in < negroups_; g_in++) {
59,046,440✔
148
        double scalar_flux = source_regions_.scalar_flux_old(sr, g_in);
37,650,850✔
149
        double sigma_s =
150
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
37,650,850✔
151
        double nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
37,650,850✔
152
        double chi = chi_[material * negroups_ + g_out];
37,650,850✔
153

154
        scatter_source += sigma_s * scalar_flux;
37,650,850✔
155
        fission_source += nu_sigma_f * scalar_flux * chi;
37,650,850✔
156
      }
157
      source_regions_.source(sr, g_out) =
21,395,590✔
158
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
21,395,590✔
159
    }
160
  }
161

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

170
  simulation::time_update_src.stop();
5,115✔
171
}
5,115✔
172

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

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

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

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

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

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

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

239
#pragma omp parallel for reduction(+ : n_hits)
6,300✔
240
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,252,885✔
241

242
    double volume_simulation_avg = source_regions_.volume(sr);
33,247,635✔
243
    double volume_iteration = source_regions_.volume_naive(sr);
33,247,635✔
244

245
    // Increment the number of hits if cell was hit this iteration
246
    if (volume_iteration) {
33,247,635✔
247
      n_hits++;
29,188,480✔
248
    }
249

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

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

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

310
  // Return the number of source regions that were hit this iteration
311
  return n_hits;
11,550✔
312
}
313

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

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

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

327
    // If simulation averaged volume is zero, don't include this cell
328
    double volume = source_regions_.volume(sr);
307,790✔
329
    if (volume == 0.0) {
307,790✔
330
      continue;
331
    }
332

333
    int material = source_regions_.material(sr);
307,790✔
334
    if (material == MATERIAL_VOID) {
307,790✔
335
      continue;
336
    }
337

338
    double sr_fission_source_old = 0;
307,790✔
339
    double sr_fission_source_new = 0;
307,790✔
340

341
    for (int g = 0; g < negroups_; g++) {
2,375,320✔
342
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
2,067,530✔
343
      sr_fission_source_old +=
2,067,530✔
344
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
2,067,530✔
345
      sr_fission_source_new +=
2,067,530✔
346
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
2,067,530✔
347
    }
348

349
    // Compute total fission rates in FSR
350
    sr_fission_source_old *= volume;
307,790✔
351
    sr_fission_source_new *= volume;
307,790✔
352

353
    // Accumulate totals
354
    fission_rate_old += sr_fission_source_old;
307,790✔
355
    fission_rate_new += sr_fission_source_new;
307,790✔
356

357
    // Store total fission rate in the FSR for Shannon calculation
358
    p[sr] = sr_fission_source_new;
307,790✔
359
  }
360

361
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
2,090✔
362

363
  double H = 0.0;
2,090✔
364
  // defining an inverse sum for better performance
365
  double inverse_sum = 1 / fission_rate_new;
2,090✔
366

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

378
  // Adds entropy value to shared entropy vector in openmc namespace.
379
  simulation::entropy.push_back(H);
2,090✔
380

381
  return k_eff_new;
2,090✔
382
}
2,090✔
383

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

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

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

417
void FlatSourceDomain::convert_source_regions_to_tallies()
440✔
418
{
419
  openmc::simulation::time_tallies.start();
440✔
420

421
  // Tracks if we've generated a mapping yet for all source regions.
422
  bool all_source_regions_mapped = true;
440✔
423

424
// Attempt to generate mapping for all source regions
425
#pragma omp parallel for
240✔
426
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,166,040✔
427

428
    // If this source region has not been hit by a ray yet, then
429
    // we aren't going to be able to map it, so skip it.
430
    if (!source_regions_.position_recorded(sr)) {
1,165,840✔
431
      all_source_regions_mapped = false;
432
      continue;
433
    }
434

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

444
    // Loop over energy groups (so as to support energy filters)
445
    for (int g = 0; g < negroups_; g++) {
2,480,480✔
446

447
      // Set particle to the current energy
448
      p.g() = g;
1,314,640✔
449
      p.g_last() = g;
1,314,640✔
450
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,314,640✔
451
      p.E_last() = p.E();
1,314,640✔
452

453
      int64_t source_element = sr * negroups_ + g;
1,314,640✔
454

455
      // If this task has already been populated, we don't need to do
456
      // it again.
457
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,314,640✔
458
        continue;
459
      }
460

461
      // Loop over all active tallies. This logic is essentially identical
462
      // to what happens when scanning for applicable tallies during
463
      // MC transport.
464
      for (auto i_tally : model::active_tallies) {
5,193,840✔
465
        Tally& tally {*model::tallies[i_tally]};
3,879,200✔
466

467
        // Initialize an iterator over valid filter bin combinations.
468
        // If there are no valid combinations, use a continue statement
469
        // to ensure we skip the assume_separate break below.
470
        auto filter_iter = FilterBinIter(tally, p);
3,879,200✔
471
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,879,200✔
472
        if (filter_iter == end)
3,879,200✔
473
          continue;
2,277,920✔
474

475
        // Loop over filter bins.
476
        for (; filter_iter != end; ++filter_iter) {
3,202,560✔
477
          auto filter_index = filter_iter.index_;
1,601,280✔
478
          auto filter_weight = filter_iter.weight_;
1,601,280✔
479

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

488
            // Also add this task to the list of volume tasks for this source
489
            // region.
490
            source_regions_.volume_task(sr).insert(task);
1,938,400✔
491
          }
492
        }
493
      }
494
      // Reset all the filter matches for the next tally event.
495
      for (auto& match : p.filter_matches())
5,949,920✔
496
        match.bins_present_ = false;
4,635,280✔
497
    }
498
  }
1,165,840✔
499
  openmc::simulation::time_tallies.stop();
440✔
500

501
  mapped_all_tallies_ = all_source_regions_mapped;
440✔
502
}
440✔
503

504
// Set the volume accumulators to zero for all tallies
505
void FlatSourceDomain::reset_tally_volumes()
4,675✔
506
{
507
  if (volume_normalized_flux_tallies_) {
4,675✔
508
#pragma omp parallel for
2,070✔
509
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,500✔
510
      auto& tensor = tally_volumes_[i];
4,775✔
511
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,775✔
512
    }
513
  }
514
}
4,675✔
515

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

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

552
  // Step 2 is to determine the total user-specified external source strength
553
  double user_external_source_strength = 0.0;
3,739✔
554
  for (auto& ext_source : model::external_sources) {
7,478✔
555
    user_external_source_strength += ext_source->strength();
3,739✔
556
  }
557

558
  // The correction factor is the ratio of the user-specified external source
559
  // strength to the simulation external source strength.
560
  double source_normalization_factor =
3,739✔
561
    user_external_source_strength / simulation_external_source_strength;
562

563
  return source_normalization_factor;
3,739✔
564
}
565

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

575
void FlatSourceDomain::random_ray_tally()
4,675✔
576
{
577
  openmc::simulation::time_tallies.start();
4,675✔
578

579
  // Reset our tally volumes to zero
580
  reset_tally_volumes();
4,675✔
581

582
  double source_normalization_factor =
583
    compute_fixed_source_normalization_factor();
4,675✔
584

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

601
    double material = source_regions_.material(sr);
15,208,200✔
602
    for (int g = 0; g < negroups_; g++) {
31,797,600✔
603
      double flux =
604
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,589,400✔
605

606
      // Determine numerical score value
607
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,166,800✔
608
        double score = 0.0;
22,577,400✔
609
        switch (task.score_type) {
22,577,400✔
610

611
        case SCORE_FLUX:
19,405,000✔
612
          score = flux * volume;
19,405,000✔
613
          break;
19,405,000✔
614

615
        case SCORE_TOTAL:
616
          if (material != MATERIAL_VOID) {
617
            score = flux * volume * sigma_t_[material * negroups_ + g];
618
          }
619
          break;
620

621
        case SCORE_FISSION:
1,586,200✔
622
          if (material != MATERIAL_VOID) {
1,586,200✔
623
            score = flux * volume * sigma_f_[material * negroups_ + g];
1,586,200✔
624
          }
625
          break;
1,586,200✔
626

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

633
        case SCORE_EVENTS:
634
          score = 1.0;
635
          break;
636

637
        default:
638
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
639
                      "total, fission, nu-fission, and events are supported in "
640
                      "random ray mode.");
641
          break;
642
        }
643

644
        // Apply score to the appropriate tally bin
645
        Tally& tally {*model::tallies[task.tally_idx]};
22,577,400✔
646
#pragma omp atomic
647
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,577,400✔
648
          score;
649
      }
650
    }
651

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

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

689
  openmc::simulation::time_tallies.stop();
4,675✔
690
}
4,675✔
691

692
double FlatSourceDomain::evaluate_flux_at_point(
×
693
  Position r, int64_t sr, int g) const
694
{
695
  return source_regions_.scalar_flux_final(sr, g) /
×
696
         (settings::n_batches - settings::n_inactive);
×
697
}
698

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

713
  // Print header information
714
  print_plot();
×
715

716
  // Outer loop over plots
717
  for (int p = 0; p < model::plots.size(); p++) {
×
718

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

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

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

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

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

777
          bool found = exhaustive_find_cell(p);
778
          if (!found) {
779
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
780
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
781
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
782
            continue;
783
          }
784

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

804
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
805
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
806

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

819
    double source_normalization_factor =
820
      compute_fixed_source_normalization_factor();
×
821

822
    // Open file for writing
823
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
824

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

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

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

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

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

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

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

953
    std::fclose(plot);
×
954
  }
955
}
956

957
void FlatSourceDomain::apply_external_source_to_source_region(
2,731✔
958
  Discrete* discrete, double strength_factor, SourceRegionHandle& srh)
959
{
960
  srh.external_source_present() = 1;
2,731✔
961

962
  const auto& discrete_energies = discrete->x();
2,731✔
963
  const auto& discrete_probs = discrete->prob();
2,731✔
964

965
  for (int i = 0; i < discrete_energies.size(); i++) {
5,654✔
966
    int g = data::mg.get_group_index(discrete_energies[i]);
2,923✔
967
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,923✔
968
  }
969
}
2,731✔
970

971
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
400✔
972
  Discrete* discrete, double strength_factor, int target_material_id,
973
  const vector<int32_t>& instances)
974
{
975
  Cell& cell = *model::cells[i_cell];
400✔
976

977
  if (cell.type_ != Fill::MATERIAL)
400✔
978
    return;
×
979

980
  for (int j : instances) {
30,640✔
981
    int cell_material_idx = cell.material(j);
30,240✔
982
    int cell_material_id;
983
    if (cell_material_idx == MATERIAL_VOID) {
30,240✔
984
      cell_material_id = MATERIAL_VOID;
256✔
985
    } else {
986
      cell_material_id = model::materials[cell_material_idx]->id();
29,984✔
987
    }
988
    if (target_material_id == C_NONE ||
30,240✔
989
        cell_material_id == target_material_id) {
990
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,720✔
991
      SourceRegionHandle srh =
992
        source_regions_.get_source_region_handle(source_region);
2,720✔
993
      apply_external_source_to_source_region(discrete, strength_factor, srh);
2,720✔
994
    }
995
  }
996
}
997

998
void FlatSourceDomain::apply_external_source_to_cell_and_children(
432✔
999
  int32_t i_cell, Discrete* discrete, double strength_factor,
1000
  int32_t target_material_id)
1001
{
1002
  Cell& cell = *model::cells[i_cell];
432✔
1003

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

1020
void FlatSourceDomain::count_external_source_regions()
1,024✔
1021
{
1022
  n_external_source_regions_ = 0;
1,024✔
1023
#pragma omp parallel for reduction(+ : n_external_source_regions_)
576✔
1024
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,532,984✔
1025
    if (source_regions_.external_source_present(sr)) {
1,532,536✔
1026
      n_external_source_regions_++;
158,700✔
1027
    }
1028
  }
1029
}
1,024✔
1030

1031
void FlatSourceDomain::convert_external_sources()
384✔
1032
{
1033
  // Loop over external sources
1034
  for (int es = 0; es < model::external_sources.size(); es++) {
768✔
1035

1036
    // Extract source information
1037
    Source* s = model::external_sources[es].get();
384✔
1038
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
384✔
1039
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
384✔
1040
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
384✔
1041
    double strength_factor = is->strength();
384✔
1042

1043
    // If there is no domain constraint specified, then this must be a point
1044
    // source. In this case, we need to find the source region that contains the
1045
    // point source and apply or relate it to the external source.
1046
    if (is->domain_ids().size() == 0) {
384✔
1047

1048
      // Extract the point source coordinate and find the base source region at
1049
      // that point
1050
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
16✔
1051
      GeometryState gs;
16✔
1052
      gs.r() = sp->r();
16✔
1053
      gs.r_last() = sp->r();
16✔
1054
      gs.u() = {1.0, 0.0, 0.0};
16✔
1055
      bool found = exhaustive_find_cell(gs);
16✔
1056
      if (!found) {
16✔
1057
        fatal_error(fmt::format("Could not find cell containing external "
×
1058
                                "point source at {}",
1059
          sp->r()));
×
1060
      }
1061
      int i_cell = gs.lowest_coord().cell;
16✔
1062
      int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
16✔
1063

1064
      if (RandomRay::mesh_subdivision_enabled_) {
16✔
1065
        // If mesh subdivision is enabled, we need to determine which subdivided
1066
        // mesh bin the point source coordinate is in as well
1067
        int mesh_idx = source_regions_.mesh(sr);
16✔
1068
        int mesh_bin;
1069
        if (mesh_idx == C_NONE) {
16✔
1070
          mesh_bin = 0;
×
1071
        } else {
1072
          mesh_bin = model::meshes[mesh_idx]->get_bin(gs.r());
16✔
1073
        }
1074
        // With the source region and mesh bin known, we can use the
1075
        // accompanying SourceRegionKey as a key into a map that stores the
1076
        // corresponding external source index for the point source. Notably, we
1077
        // do not actually apply the external source to any source regions here,
1078
        // as if mesh subdivision is enabled, they haven't actually been
1079
        // discovered & initilized yet. When discovered, they will read from the
1080
        // point_source_map to determine if there are any point source terms
1081
        // that should be applied.
1082
        SourceRegionKey key {sr, mesh_bin};
16✔
1083
        point_source_map_[key] = es;
16✔
1084
      } else {
1085
        // If we are not using mesh subdivision, we can apply the external
1086
        // source directly to the source region as we do for volumetric domain
1087
        // constraint sources.
1088
        SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
×
1089
        apply_external_source_to_source_region(energy, strength_factor, srh);
×
1090
      }
1091

1092
    } else {
16✔
1093
      // If not a point source, then use the volumetric domain constraints to
1094
      // determine which source regions to apply the external source to.
1095
      if (is->domain_type() == Source::DomainType::MATERIAL) {
368✔
1096
        for (int32_t material_id : domain_ids) {
32✔
1097
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1098
            apply_external_source_to_cell_and_children(
80✔
1099
              i_cell, energy, strength_factor, material_id);
1100
          }
1101
        }
1102
      } else if (is->domain_type() == Source::DomainType::CELL) {
352✔
1103
        for (int32_t cell_id : domain_ids) {
32✔
1104
          int32_t i_cell = model::cell_map[cell_id];
16✔
1105
          apply_external_source_to_cell_and_children(
16✔
1106
            i_cell, energy, strength_factor, C_NONE);
1107
        }
1108
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
336✔
1109
        for (int32_t universe_id : domain_ids) {
672✔
1110
          int32_t i_universe = model::universe_map[universe_id];
336✔
1111
          Universe& universe = *model::universes[i_universe];
336✔
1112
          for (int32_t i_cell : universe.cells_) {
672✔
1113
            apply_external_source_to_cell_and_children(
336✔
1114
              i_cell, energy, strength_factor, C_NONE);
1115
          }
1116
        }
1117
      }
1118
    }
1119
  } // End loop over external sources
1120

1121
// Divide the fixed source term by sigma t (to save time when applying each
1122
// iteration)
1123
#pragma omp parallel for
216✔
1124
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
271,152✔
1125
    int material = source_regions_.material(sr);
270,984✔
1126
    if (material == MATERIAL_VOID) {
270,984✔
1127
      continue;
14,000✔
1128
    }
1129
    for (int g = 0; g < negroups_; g++) {
543,200✔
1130
      double sigma_t = sigma_t_[material * negroups_ + g];
286,216✔
1131
      source_regions_.external_source(sr, g) /= sigma_t;
286,216✔
1132
    }
1133
  }
1134
}
384✔
1135

1136
void FlatSourceDomain::flux_swap()
11,550✔
1137
{
1138
  source_regions_.flux_swap();
11,550✔
1139
}
11,550✔
1140

1141
void FlatSourceDomain::flatten_xs()
640✔
1142
{
1143
  // Temperature and angle indices, if using multiple temperature
1144
  // data sets and/or anisotropic data sets.
1145
  // TODO: Currently assumes we are only using single temp/single angle data.
1146
  const int t = 0;
640✔
1147
  const int a = 0;
640✔
1148

1149
  n_materials_ = data::mg.macro_xs_.size();
640✔
1150
  for (auto& m : data::mg.macro_xs_) {
2,384✔
1151
    for (int g_out = 0; g_out < negroups_; g_out++) {
8,672✔
1152
      if (m.exists_in_model) {
6,928✔
1153
        double sigma_t =
1154
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
6,864✔
1155
        sigma_t_.push_back(sigma_t);
6,864✔
1156

1157
        double nu_Sigma_f =
1158
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1159
        nu_sigma_f_.push_back(nu_Sigma_f);
6,864✔
1160

1161
        double sigma_f =
1162
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1163
        sigma_f_.push_back(sigma_f);
6,864✔
1164

1165
        double chi =
1166
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
6,864✔
1167
        chi_.push_back(chi);
6,864✔
1168

1169
        for (int g_in = 0; g_in < negroups_; g_in++) {
257,952✔
1170
          double sigma_s =
1171
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
251,088✔
1172
          sigma_s_.push_back(sigma_s);
251,088✔
1173
          // For transport corrected XS data, diagonal elements may be negative.
1174
          // In this case, set a flag to enable transport stabilization for the
1175
          // simulation.
1176
          if (g_out == g_in && sigma_s < 0.0)
251,088✔
1177
            is_transport_stabilization_needed_ = true;
880✔
1178
        }
1179
      } else {
1180
        sigma_t_.push_back(0);
64✔
1181
        nu_sigma_f_.push_back(0);
64✔
1182
        sigma_f_.push_back(0);
64✔
1183
        chi_.push_back(0);
64✔
1184
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1185
          sigma_s_.push_back(0);
64✔
1186
        }
1187
      }
1188
    }
1189
  }
1190
}
640✔
1191

1192
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
64✔
1193
{
1194
  // Set the external source to 1/forward_flux. If the forward flux is negative
1195
  // or zero, set the adjoint source to zero, as this is likely a very small
1196
  // source region that we don't need to bother trying to vector particles
1197
  // towards. Flux negativity in random ray is not related to the flux being
1198
  // small in magnitude, but rather due to the source region being physically
1199
  // small in volume and thus having a noisy flux estimate.
1200
#pragma omp parallel for
36✔
1201
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1202
    for (int g = 0; g < negroups_; g++) {
338,688✔
1203
      double flux = forward_flux[sr * negroups_ + g];
169,344✔
1204
      if (flux <= 0.0) {
169,344✔
1205
        source_regions_.external_source(sr, g) = 0.0;
325✔
1206
      } else {
1207
        source_regions_.external_source(sr, g) = 1.0 / flux;
169,019✔
1208
      }
1209
      if (flux > 0.0) {
169,344✔
1210
        source_regions_.external_source_present(sr) = 1;
155,195✔
1211
      }
1212
    }
1213
  }
1214

1215
  // Divide the fixed source term by sigma t (to save time when applying each
1216
  // iteration)
1217
#pragma omp parallel for
36✔
1218
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1219
    int material = source_regions_.material(sr);
169,344✔
1220
    if (material == MATERIAL_VOID) {
169,344✔
1221
      continue;
1222
    }
1223
    for (int g = 0; g < negroups_; g++) {
338,688✔
1224
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1225
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1226
    }
1227
  }
1228
}
64✔
1229

1230
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1231
{
1232
  // Transpose the inner two dimensions for each material
1233
  for (int m = 0; m < n_materials_; ++m) {
304✔
1234
    int material_offset = m * negroups_ * negroups_;
224✔
1235
    for (int i = 0; i < negroups_; ++i) {
640✔
1236
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1237
        // Calculate indices of the elements to swap
1238
        int idx1 = material_offset + i * negroups_ + j;
672✔
1239
        int idx2 = material_offset + j * negroups_ + i;
672✔
1240

1241
        // Swap the elements to transpose the matrix
1242
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1243
      }
1244
    }
1245
  }
1246
}
80✔
1247

1248
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
560✔
1249
{
1250
  // Ensure array is correct size
1251
  flux.resize(n_source_regions() * negroups_);
560✔
1252
// Serialize the final fluxes for output
1253
#pragma omp parallel for
315✔
1254
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,258,577✔
1255
    flux[se] = source_regions_.scalar_flux_final(se);
1,258,332✔
1256
  }
1257
}
560✔
1258

1259
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
608✔
1260
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1261
  bool is_target_void)
1262
{
1263
  Cell& cell = *model::cells[i_cell];
608✔
1264
  if (cell.type_ != Fill::MATERIAL)
608✔
1265
    return;
×
1266
  for (int32_t j : instances) {
174,944✔
1267
    int cell_material_idx = cell.material(j);
174,336✔
1268
    int cell_material_id = (cell_material_idx == C_NONE)
1269
                             ? C_NONE
174,336✔
1270
                             : model::materials[cell_material_idx]->id();
174,336✔
1271

1272
    if ((target_material_id == C_NONE && !is_target_void) ||
174,336✔
1273
        cell_material_id == target_material_id) {
1274
      int64_t sr = source_region_offsets_[i_cell] + j;
142,336✔
1275
      if (source_regions_.mesh(sr) != C_NONE) {
142,336✔
1276
        // print out the source region that is broken:
1277
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1278
                                "applied, but trying to apply mesh idx {}",
1279
          sr, source_regions_.mesh(sr), mesh_idx));
1280
      }
1281
      source_regions_.mesh(sr) = mesh_idx;
142,336✔
1282
    }
1283
  }
1284
}
1285

1286
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
480✔
1287
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1288
{
1289
  Cell& cell = *model::cells[i_cell];
480✔
1290

1291
  if (cell.type_ == Fill::MATERIAL) {
480✔
1292
    vector<int> instances(cell.n_instances_);
352✔
1293
    std::iota(instances.begin(), instances.end(), 0);
352✔
1294
    apply_mesh_to_cell_instances(
352✔
1295
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1296
  } else if (target_material_id == C_NONE && !is_target_void) {
480✔
1297
    for (int j = 0; j < cell.n_instances_; j++) {
128✔
1298
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1299
        cell.get_contained_cells(j, nullptr);
64✔
1300
      for (const auto& pair : cell_instance_list) {
320✔
1301
        int32_t i_child_cell = pair.first;
256✔
1302
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
256✔
1303
          pair.second, is_target_void);
256✔
1304
      }
1305
    }
64✔
1306
  }
1307
}
480✔
1308

1309
void FlatSourceDomain::apply_meshes()
560✔
1310
{
1311
  // Skip if there are no mappings between mesh IDs and domains
1312
  if (mesh_domain_map_.empty())
560✔
1313
    return;
400✔
1314

1315
  // Loop over meshes
1316
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
400✔
1317
    Mesh* mesh = model::meshes[mesh_idx].get();
240✔
1318
    int mesh_id = mesh->id();
240✔
1319

1320
    // Skip if mesh id is not present in the map
1321
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
240✔
1322
      continue;
16✔
1323

1324
    // Loop over domains associated with the mesh
1325
    for (auto& domain : mesh_domain_map_[mesh_id]) {
448✔
1326
      Source::DomainType domain_type = domain.first;
224✔
1327
      int domain_id = domain.second;
224✔
1328

1329
      if (domain_type == Source::DomainType::MATERIAL) {
224✔
1330
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1331
          if (domain_id == C_NONE) {
160✔
1332
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1333
          } else {
1334
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1335
          }
1336
        }
1337
      } else if (domain_type == Source::DomainType::CELL) {
192✔
1338
        int32_t i_cell = model::cell_map[domain_id];
32✔
1339
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1340
      } else if (domain_type == Source::DomainType::UNIVERSE) {
160✔
1341
        int32_t i_universe = model::universe_map[domain_id];
160✔
1342
        Universe& universe = *model::universes[i_universe];
160✔
1343
        for (int32_t i_cell : universe.cells_) {
448✔
1344
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
288✔
1345
        }
1346
      }
1347
    }
1348
  }
1349
}
1350

1351
void FlatSourceDomain::prepare_base_source_regions()
110✔
1352
{
1353
  std::swap(source_regions_, base_source_regions_);
110✔
1354
  source_regions_.negroups() = base_source_regions_.negroups();
110✔
1355
  source_regions_.is_linear() = base_source_regions_.is_linear();
110✔
1356
}
110✔
1357

1358
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
871,515,854✔
1359
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1360
{
1361
  SourceRegionKey sr_key {sr, mesh_bin};
871,515,854✔
1362

1363
  // Case 1: Check if the source region key is already present in the permanent
1364
  // map. This is the most common condition, as any source region visited in a
1365
  // previous power iteration will already be present in the permanent map. If
1366
  // the source region key is found, we translate the key into a specific 1D
1367
  // source region index and return a handle its position in the
1368
  // source_regions_ vector.
1369
  auto it = source_region_map_.find(sr_key);
871,515,854✔
1370
  if (it != source_region_map_.end()) {
871,515,854✔
1371
    int64_t sr = it->second;
850,445,145✔
1372
    return source_regions_.get_source_region_handle(sr);
850,445,145✔
1373
  }
1374

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

1383
  // If the key is found in the temporary map, then we return a handle to the
1384
  // source region that is stored in the temporary map.
1385
  if (discovered_source_regions_.contains(sr_key)) {
21,070,709✔
1386
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
19,099,003✔
1387
    discovered_source_regions_.unlock(sr_key);
19,099,003✔
1388
    return handle;
19,099,003✔
1389
  }
1390

1391
  // Case 3: The source region key is not present anywhere, but it is only due
1392
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1393
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1394
  // result in the ray tracer detecting an additional (very short) segment
1395
  // though a mesh bin that is actually past the physical source region
1396
  // boundary. This is a result of the the multi-level ray tracing treatment in
1397
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1398
  // result in the wrong surface being selected as the nearest. This can happen
1399
  // in a lattice when there are two directions that both are very close in
1400
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1401
  // treated as being equivalent so alternative logic is used. However, when we
1402
  // go and ray trace on this with the mesh tracer we may go past the surface
1403
  // bounding the current source region.
1404
  //
1405
  // To filter out this case, before we create the new source region, we double
1406
  // check that the actual starting point of this segment (r) is still in the
1407
  // same geometry source region that we started in. If an artifact is detected,
1408
  // we discard the segment (and attenuation through it) as it is not really a
1409
  // valid source region and will have only an infinitessimally small cell
1410
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1411
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1412
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1413
  // consequences for the general ray tracer, so for now we do the below sanity
1414
  // checks before generating phantom source regions. A significant extra cost
1415
  // is incurred in instantiating the GeometryState object and doing a cell
1416
  // lookup, but again, this is going to be an extremely rare thing to check
1417
  // after the first power iteration has completed.
1418

1419
  // Sanity check on source region id
1420
  GeometryState gs;
1,971,706✔
1421
  gs.r() = r + TINY_BIT * u;
1,971,706✔
1422
  gs.u() = {1.0, 0.0, 0.0};
1,971,706✔
1423
  exhaustive_find_cell(gs);
1,971,706✔
1424
  int gs_i_cell = gs.lowest_coord().cell;
1,971,706✔
1425
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,971,706✔
1426
  if (sr_found != sr) {
1,971,706✔
1427
    discovered_source_regions_.unlock(sr_key);
88✔
1428
    SourceRegionHandle handle;
88✔
1429
    handle.is_numerical_fp_artifact_ = true;
88✔
1430
    return handle;
88✔
1431
  }
1432

1433
  // Sanity check on mesh bin
1434
  int mesh_idx = base_source_regions_.mesh(sr);
1,971,618✔
1435
  if (mesh_idx == C_NONE) {
1,971,618✔
1436
    if (mesh_bin != 0) {
×
1437
      discovered_source_regions_.unlock(sr_key);
×
1438
      SourceRegionHandle handle;
×
1439
      handle.is_numerical_fp_artifact_ = true;
×
1440
      return handle;
×
1441
    }
1442
  } else {
1443
    Mesh* mesh = model::meshes[mesh_idx].get();
1,971,618✔
1444
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,971,618✔
1445
    if (bin_found != mesh_bin) {
1,971,618✔
1446
      discovered_source_regions_.unlock(sr_key);
×
1447
      SourceRegionHandle handle;
×
1448
      handle.is_numerical_fp_artifact_ = true;
×
1449
      return handle;
×
1450
    }
1451
  }
1452

1453
  // Case 4: The source region key is valid, but is not present anywhere. This
1454
  // condition only occurs the first time the source region is discovered
1455
  // (typically in the first power iteration). In this case, we need to handle
1456
  // creation of the new source region and its storage into the parallel map.
1457
  // The new source region is created by copying the base source region, so as
1458
  // to inherit material, external source, and some flux properties etc. We
1459
  // also pass the base source region id to allow the new source region to
1460
  // know which base source region it is derived from.
1461
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
1,971,618✔
1462
    sr_key, {base_source_regions_.get_source_region_handle(sr), sr});
1,971,618✔
1463
  discovered_source_regions_.unlock(sr_key);
1,971,618✔
1464
  SourceRegionHandle handle {*sr_ptr};
1,971,618✔
1465

1466
  // Check if the new source region contains a point source and apply it if so
1467
  auto it2 = point_source_map_.find(sr_key);
1,971,618✔
1468
  if (it2 != point_source_map_.end()) {
1,971,618✔
1469
    int es = it2->second;
11✔
1470
    auto s = model::external_sources[es].get();
11✔
1471
    auto is = dynamic_cast<IndependentSource*>(s);
11✔
1472
    auto energy = dynamic_cast<Discrete*>(is->energy());
11✔
1473
    double strength_factor = is->strength();
11✔
1474
    apply_external_source_to_source_region(energy, strength_factor, handle);
11✔
1475
    int material = handle.material();
11✔
1476
    if (material != MATERIAL_VOID) {
11✔
1477
      for (int g = 0; g < negroups_; g++) {
22✔
1478
        double sigma_t = sigma_t_[material * negroups_ + g];
11✔
1479
        handle.external_source(g) /= sigma_t;
11✔
1480
      }
1481
    }
1482
  }
1483

1484
  return handle;
1,971,618✔
1485
}
1,971,706✔
1486

1487
void FlatSourceDomain::finalize_discovered_source_regions()
2,970✔
1488
{
1489
  // Extract keys for entries with a valid volume.
1490
  vector<SourceRegionKey> keys;
2,970✔
1491
  for (const auto& pair : discovered_source_regions_) {
1,974,588✔
1492
    if (pair.second.volume_ > 0.0) {
1,971,618✔
1493
      keys.push_back(pair.first);
1,870,176✔
1494
    }
1495
  }
1496

1497
  if (!keys.empty()) {
2,970✔
1498
    // Sort the keys, so as to ensure reproducible ordering given that source
1499
    // regions may have been added to discovered_source_regions_ in an arbitrary
1500
    // order due to shared memory threading.
1501
    std::sort(keys.begin(), keys.end());
440✔
1502

1503
    // Append the source regions in the sorted key order.
1504
    for (const auto& key : keys) {
1,870,616✔
1505
      const SourceRegion& sr = discovered_source_regions_[key];
1,870,176✔
1506
      source_region_map_[key] = source_regions_.n_source_regions();
1,870,176✔
1507
      source_regions_.push_back(sr);
1,870,176✔
1508
    }
1509

1510
    // If any new source regions were discovered, we need to update the
1511
    // tally mapping between source regions and tally bins.
1512
    mapped_all_tallies_ = false;
440✔
1513
  }
1514

1515
  discovered_source_regions_.clear();
2,970✔
1516
}
2,970✔
1517

1518
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1519
//
1520
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1521
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1522
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1523
// https://doi.org/10.1016/j.anucene.2018.10.036.
1524
void FlatSourceDomain::apply_transport_stabilization()
11,550✔
1525
{
1526
  // Don't do anything if all in-group scattering
1527
  // cross sections are positive
1528
  if (!is_transport_stabilization_needed_) {
11,550✔
1529
    return;
11,330✔
1530
  }
1531

1532
  // Apply the stabilization factor to all source elements
1533
#pragma omp parallel for
120✔
1534
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1535
    int material = source_regions_.material(sr);
1,200✔
1536
    if (material == MATERIAL_VOID) {
1,200✔
1537
      continue;
1538
    }
1539
    for (int g = 0; g < negroups_; g++) {
85,200✔
1540
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1541
      // negative
1542
      double sigma_s =
1543
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g];
84,000✔
1544
      if (sigma_s < 0.0) {
84,000✔
1545
        double sigma_t = sigma_t_[material * negroups_ + g];
22,000✔
1546
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1547
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
1548

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

1559
        // Equation 16 in the above Gunow et al. 2019 paper
1560
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1561
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1562
      }
1563
    }
1564
  }
1565
}
1566

1567
} // 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

© 2026 Coveralls, Inc