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

openmc-dev / openmc / 14212363323

02 Apr 2025 05:40AM UTC coverage: 85.044% (-0.3%) from 85.385%
14212363323

push

github

web-flow
Random Ray Point Source Locator (#3360)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

54 of 60 new or added lines in 2 files covered. (90.0%)

202 existing lines in 26 files now uncovered.

51853 of 60972 relevant lines covered (85.04%)

36947021.36 hits per line

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

78.87
/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
    source_regions_.scalar_flux_new(sr, g) +=
880,000✔
210
      0.5f * source_regions_.external_source(sr, g) *
880,000✔
211
      source_regions_.volume_sq(sr);
880,000✔
212
  } else {
213
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
42,340,045✔
214
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
42,340,045✔
215
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
42,340,045✔
216
  }
217
}
43,220,045✔
218

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

225
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
8,928,293✔
226
{
227
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
8,928,293✔
228
}
8,928,293✔
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,550✔
233
{
234
  int64_t n_hits = 0;
11,550✔
235
  double inverse_batch = 1.0 / simulation::current_batch;
11,550✔
236

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

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

243
    // Increment the number of hits if cell was hit this iteration
244
    if (volume_iteration) {
33,247,635✔
245
      n_hits++;
29,188,480✔
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,635✔
251
      source_regions_.is_small(sr) = 1;
6,812,705✔
252
    } else {
253
      source_regions_.is_small(sr) = 0;
26,434,930✔
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,635✔
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,035✔
267
      if (source_regions_.external_source_present(sr) ||
59,888,470✔
268
          source_regions_.is_small(sr)) {
27,850,435✔
269
        volume = volume_iteration;
10,999,925✔
270
      } else {
271
        volume = volume_simulation_avg;
21,038,110✔
272
      }
273
      break;
32,038,035✔
274
    default:
275
      fatal_error("Invalid volume estimator type");
276
    }
277

278
    for (int g = 0; g < negroups_; g++) {
70,865,010✔
279
      // There are three scenarios we need to consider:
280
      if (volume_iteration > 0.0) {
37,617,375✔
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,070✔
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) && !adjoint_) {
4,059,295✔
300
          set_flux_to_old_flux(sr, g);
980✔
301
        } else {
302
          set_flux_to_source(sr, g);
4,058,315✔
303
        }
304
      }
305
    }
306
  }
307

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

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

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

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

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

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

336
    double sr_fission_source_old = 0;
307,790✔
337
    double sr_fission_source_new = 0;
307,790✔
338

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

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

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

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

359
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
2,090✔
360

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

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

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

379
  return k_eff_new;
2,090✔
380
}
2,090✔
381

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

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

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

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

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

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

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

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

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

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

451
      int64_t source_element = sr * negroups_ + g;
1,314,640✔
452

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

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

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

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

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

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

499
  mapped_all_tallies_ = all_source_regions_mapped;
440✔
500
}
440✔
501

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

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

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

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

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

561
  return source_normalization_factor;
3,739✔
562
}
563

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

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

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

580
  double source_normalization_factor =
581
    compute_fixed_source_normalization_factor();
4,675✔
582

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

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

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

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

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

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

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

631
        case SCORE_EVENTS:
632
          score = 1.0;
633
          break;
634

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

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

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

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

687
  openmc::simulation::time_tallies.stop();
4,675✔
688
}
4,675✔
689

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

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

711
  // Print header information
712
  print_plot();
×
713

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

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

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

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

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

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

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

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

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

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

817
    double source_normalization_factor =
818
      compute_fixed_source_normalization_factor();
×
819

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

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

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

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

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

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

894
    // Plot fission source
895
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
896
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
897
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
898
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
899
        int64_t fsr = voxel_indices[i];
×
900
        float total_fission = 0.0;
×
901
        if (fsr >= 0) {
×
902
          int mat = source_regions_.material(fsr);
×
903
          if (mat != MATERIAL_VOID) {
×
904
            for (int g = 0; g < negroups_; g++) {
×
905
              int64_t source_element = fsr * negroups_ + g;
×
906
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
907
              double sigma_f = sigma_f_[mat * negroups_ + g];
×
908
              total_fission += sigma_f * flux;
×
909
            }
910
          }
911
        }
912
        total_fission = convert_to_big_endian<float>(total_fission);
×
913
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
914
      }
915
    } else {
916
      std::fprintf(plot, "SCALARS external_source float\n");
×
917
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
918
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
919
        int64_t fsr = voxel_indices[i];
×
920
        float total_external = 0.0f;
×
921
        if (fsr >= 0) {
×
922
          for (int g = 0; g < negroups_; g++) {
×
923
            total_external += source_regions_.external_source(fsr, g);
×
924
          }
925
        }
926
        total_external = convert_to_big_endian<float>(total_external);
×
927
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
928
      }
929
    }
930

931
    // Plot weight window data
932
    if (variance_reduction::weight_windows.size() == 1) {
×
933
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
934
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
935
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
936
        float weight = weight_windows[i];
×
937
        if (weight == 0.0)
×
938
          weight = min_weight;
×
939
        weight = convert_to_big_endian<float>(weight);
×
940
        std::fwrite(&weight, sizeof(float), 1, plot);
×
941
      }
942
    }
943

944
    std::fclose(plot);
×
945
  }
946
}
947

948
void FlatSourceDomain::apply_external_source_to_source_region(
2,731✔
949
  Discrete* discrete, double strength_factor, SourceRegionHandle& srh)
950
{
951
  srh.external_source_present() = 1;
2,731✔
952

953
  const auto& discrete_energies = discrete->x();
2,731✔
954
  const auto& discrete_probs = discrete->prob();
2,731✔
955

956
  for (int i = 0; i < discrete_energies.size(); i++) {
5,654✔
957
    int g = data::mg.get_group_index(discrete_energies[i]);
2,923✔
958
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,923✔
959
  }
960
}
2,731✔
961

962
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
400✔
963
  Discrete* discrete, double strength_factor, int target_material_id,
964
  const vector<int32_t>& instances)
965
{
966
  Cell& cell = *model::cells[i_cell];
400✔
967

968
  if (cell.type_ != Fill::MATERIAL)
400✔
969
    return;
×
970

971
  for (int j : instances) {
30,640✔
972
    int cell_material_idx = cell.material(j);
30,240✔
973
    int cell_material_id;
974
    if (cell_material_idx == MATERIAL_VOID) {
30,240✔
975
      cell_material_id = MATERIAL_VOID;
256✔
976
    } else {
977
      cell_material_id = model::materials[cell_material_idx]->id();
29,984✔
978
    }
979
    if (target_material_id == C_NONE ||
30,240✔
980
        cell_material_id == target_material_id) {
981
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,720✔
982
      SourceRegionHandle srh =
983
        source_regions_.get_source_region_handle(source_region);
2,720✔
984
      apply_external_source_to_source_region(discrete, strength_factor, srh);
2,720✔
985
    }
986
  }
987
}
988

989
void FlatSourceDomain::apply_external_source_to_cell_and_children(
432✔
990
  int32_t i_cell, Discrete* discrete, double strength_factor,
991
  int32_t target_material_id)
992
{
993
  Cell& cell = *model::cells[i_cell];
432✔
994

995
  if (cell.type_ == Fill::MATERIAL) {
432✔
996
    vector<int> instances(cell.n_instances_);
400✔
997
    std::iota(instances.begin(), instances.end(), 0);
400✔
998
    apply_external_source_to_cell_instances(
400✔
999
      i_cell, discrete, strength_factor, target_material_id, instances);
1000
  } else if (target_material_id == C_NONE) {
432✔
1001
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1002
      cell.get_contained_cells(0, nullptr);
×
1003
    for (const auto& pair : cell_instance_list) {
×
1004
      int32_t i_child_cell = pair.first;
×
1005
      apply_external_source_to_cell_instances(i_child_cell, discrete,
×
1006
        strength_factor, target_material_id, pair.second);
×
1007
    }
1008
  }
1009
}
432✔
1010

1011
void FlatSourceDomain::count_external_source_regions()
1,024✔
1012
{
1013
  n_external_source_regions_ = 0;
1,024✔
1014
#pragma omp parallel for reduction(+ : n_external_source_regions_)
576✔
1015
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,532,984✔
1016
    if (source_regions_.external_source_present(sr)) {
1,532,536✔
1017
      n_external_source_regions_++;
158,700✔
1018
    }
1019
  }
1020
}
1,024✔
1021

1022
void FlatSourceDomain::convert_external_sources()
384✔
1023
{
1024
  // Loop over external sources
1025
  for (int es = 0; es < model::external_sources.size(); es++) {
768✔
1026

1027
    // Extract source information
1028
    Source* s = model::external_sources[es].get();
384✔
1029
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
384✔
1030
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
384✔
1031
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
384✔
1032
    double strength_factor = is->strength();
384✔
1033

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

1039
      // Extract the point source coordinate and find the base source region at
1040
      // that point
1041
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
16✔
1042
      GeometryState gs;
16✔
1043
      gs.r() = sp->r();
16✔
1044
      gs.r_last() = sp->r();
16✔
1045
      gs.u() = {1.0, 0.0, 0.0};
16✔
1046
      bool found = exhaustive_find_cell(gs);
16✔
1047
      if (!found) {
16✔
NEW
1048
        fatal_error(fmt::format("Could not find cell containing external "
×
1049
                                "point source at {}",
NEW
1050
          sp->r()));
×
1051
      }
1052
      int i_cell = gs.lowest_coord().cell;
16✔
1053
      int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
16✔
1054

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

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

1112
// Divide the fixed source term by sigma t (to save time when applying each
1113
// iteration)
1114
#pragma omp parallel for
216✔
1115
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
271,152✔
1116
    int material = source_regions_.material(sr);
270,984✔
1117
    if (material == MATERIAL_VOID) {
270,984✔
1118
      continue;
14,000✔
1119
    }
1120
    for (int g = 0; g < negroups_; g++) {
543,200✔
1121
      double sigma_t = sigma_t_[material * negroups_ + g];
286,216✔
1122
      source_regions_.external_source(sr, g) /= sigma_t;
286,216✔
1123
    }
1124
  }
1125
}
384✔
1126

1127
void FlatSourceDomain::flux_swap()
11,550✔
1128
{
1129
  source_regions_.flux_swap();
11,550✔
1130
}
11,550✔
1131

1132
void FlatSourceDomain::flatten_xs()
640✔
1133
{
1134
  // Temperature and angle indices, if using multiple temperature
1135
  // data sets and/or anisotropic data sets.
1136
  // TODO: Currently assumes we are only using single temp/single angle data.
1137
  const int t = 0;
640✔
1138
  const int a = 0;
640✔
1139

1140
  n_materials_ = data::mg.macro_xs_.size();
640✔
1141
  for (auto& m : data::mg.macro_xs_) {
2,384✔
1142
    for (int g_out = 0; g_out < negroups_; g_out++) {
8,672✔
1143
      if (m.exists_in_model) {
6,928✔
1144
        double sigma_t =
1145
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
6,864✔
1146
        sigma_t_.push_back(sigma_t);
6,864✔
1147

1148
        double nu_Sigma_f =
1149
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1150
        nu_sigma_f_.push_back(nu_Sigma_f);
6,864✔
1151

1152
        double sigma_f =
1153
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1154
        sigma_f_.push_back(sigma_f);
6,864✔
1155

1156
        double chi =
1157
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
6,864✔
1158
        chi_.push_back(chi);
6,864✔
1159

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

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

1206
  // Divide the fixed source term by sigma t (to save time when applying each
1207
  // iteration)
1208
#pragma omp parallel for
36✔
1209
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1210
    int material = source_regions_.material(sr);
169,344✔
1211
    if (material == MATERIAL_VOID) {
169,344✔
1212
      continue;
1213
    }
1214
    for (int g = 0; g < negroups_; g++) {
338,688✔
1215
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1216
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1217
    }
1218
  }
1219
}
64✔
1220

1221
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1222
{
1223
  // Transpose the inner two dimensions for each material
1224
  for (int m = 0; m < n_materials_; ++m) {
304✔
1225
    int material_offset = m * negroups_ * negroups_;
224✔
1226
    for (int i = 0; i < negroups_; ++i) {
640✔
1227
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1228
        // Calculate indices of the elements to swap
1229
        int idx1 = material_offset + i * negroups_ + j;
672✔
1230
        int idx2 = material_offset + j * negroups_ + i;
672✔
1231

1232
        // Swap the elements to transpose the matrix
1233
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1234
      }
1235
    }
1236
  }
1237
}
80✔
1238

1239
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
560✔
1240
{
1241
  // Ensure array is correct size
1242
  flux.resize(n_source_regions() * negroups_);
560✔
1243
// Serialize the final fluxes for output
1244
#pragma omp parallel for
315✔
1245
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,258,577✔
1246
    flux[se] = source_regions_.scalar_flux_final(se);
1,258,332✔
1247
  }
1248
}
560✔
1249

1250
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
608✔
1251
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1252
  bool is_target_void)
1253
{
1254
  Cell& cell = *model::cells[i_cell];
608✔
1255
  if (cell.type_ != Fill::MATERIAL)
608✔
1256
    return;
×
1257
  for (int32_t j : instances) {
174,944✔
1258
    int cell_material_idx = cell.material(j);
174,336✔
1259
    int cell_material_id = (cell_material_idx == C_NONE)
1260
                             ? C_NONE
174,336✔
1261
                             : model::materials[cell_material_idx]->id();
174,336✔
1262

1263
    if ((target_material_id == C_NONE && !is_target_void) ||
174,336✔
1264
        cell_material_id == target_material_id) {
1265
      int64_t sr = source_region_offsets_[i_cell] + j;
142,336✔
1266
      if (source_regions_.mesh(sr) != C_NONE) {
142,336✔
1267
        // print out the source region that is broken:
1268
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1269
                                "applied, but trying to apply mesh idx {}",
1270
          sr, source_regions_.mesh(sr), mesh_idx));
1271
      }
1272
      source_regions_.mesh(sr) = mesh_idx;
142,336✔
1273
    }
1274
  }
1275
}
1276

1277
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
480✔
1278
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1279
{
1280
  Cell& cell = *model::cells[i_cell];
480✔
1281

1282
  if (cell.type_ == Fill::MATERIAL) {
480✔
1283
    vector<int> instances(cell.n_instances_);
352✔
1284
    std::iota(instances.begin(), instances.end(), 0);
352✔
1285
    apply_mesh_to_cell_instances(
352✔
1286
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1287
  } else if (target_material_id == C_NONE && !is_target_void) {
480✔
1288
    for (int j = 0; j < cell.n_instances_; j++) {
128✔
1289
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1290
        cell.get_contained_cells(j, nullptr);
64✔
1291
      for (const auto& pair : cell_instance_list) {
320✔
1292
        int32_t i_child_cell = pair.first;
256✔
1293
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
256✔
1294
          pair.second, is_target_void);
256✔
1295
      }
1296
    }
64✔
1297
  }
1298
}
480✔
1299

1300
void FlatSourceDomain::apply_meshes()
560✔
1301
{
1302
  // Skip if there are no mappings between mesh IDs and domains
1303
  if (mesh_domain_map_.empty())
560✔
1304
    return;
400✔
1305

1306
  // Loop over meshes
1307
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
400✔
1308
    Mesh* mesh = model::meshes[mesh_idx].get();
240✔
1309
    int mesh_id = mesh->id();
240✔
1310

1311
    // Skip if mesh id is not present in the map
1312
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
240✔
1313
      continue;
16✔
1314

1315
    // Loop over domains associated with the mesh
1316
    for (auto& domain : mesh_domain_map_[mesh_id]) {
448✔
1317
      Source::DomainType domain_type = domain.first;
224✔
1318
      int domain_id = domain.second;
224✔
1319

1320
      if (domain_type == Source::DomainType::MATERIAL) {
224✔
1321
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1322
          if (domain_id == C_NONE) {
160✔
1323
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1324
          } else {
1325
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1326
          }
1327
        }
1328
      } else if (domain_type == Source::DomainType::CELL) {
192✔
1329
        int32_t i_cell = model::cell_map[domain_id];
32✔
1330
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1331
      } else if (domain_type == Source::DomainType::UNIVERSE) {
160✔
1332
        int32_t i_universe = model::universe_map[domain_id];
160✔
1333
        Universe& universe = *model::universes[i_universe];
160✔
1334
        for (int32_t i_cell : universe.cells_) {
448✔
1335
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
288✔
1336
        }
1337
      }
1338
    }
1339
  }
1340
}
1341

1342
void FlatSourceDomain::prepare_base_source_regions()
110✔
1343
{
1344
  std::swap(source_regions_, base_source_regions_);
110✔
1345
  source_regions_.negroups() = base_source_regions_.negroups();
110✔
1346
  source_regions_.is_linear() = base_source_regions_.is_linear();
110✔
1347
}
110✔
1348

1349
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
871,515,854✔
1350
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1351
{
1352
  SourceRegionKey sr_key {sr, mesh_bin};
871,515,854✔
1353

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

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

1374
  // If the key is found in the temporary map, then we return a handle to the
1375
  // source region that is stored in the temporary map.
1376
  if (discovered_source_regions_.contains(sr_key)) {
21,070,709✔
1377
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
19,099,003✔
1378
    discovered_source_regions_.unlock(sr_key);
19,099,003✔
1379
    return handle;
19,099,003✔
1380
  }
1381

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

1410
  // Sanity check on source region id
1411
  GeometryState gs;
1,971,706✔
1412
  gs.r() = r + TINY_BIT * u;
1,971,706✔
1413
  gs.u() = {1.0, 0.0, 0.0};
1,971,706✔
1414
  exhaustive_find_cell(gs);
1,971,706✔
1415
  int gs_i_cell = gs.lowest_coord().cell;
1,971,706✔
1416
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,971,706✔
1417
  if (sr_found != sr) {
1,971,706✔
1418
    discovered_source_regions_.unlock(sr_key);
88✔
1419
    SourceRegionHandle handle;
88✔
1420
    handle.is_numerical_fp_artifact_ = true;
88✔
1421
    return handle;
88✔
1422
  }
1423

1424
  // Sanity check on mesh bin
1425
  int mesh_idx = base_source_regions_.mesh(sr);
1,971,618✔
1426
  if (mesh_idx == C_NONE) {
1,971,618✔
1427
    if (mesh_bin != 0) {
×
1428
      discovered_source_regions_.unlock(sr_key);
×
1429
      SourceRegionHandle handle;
×
1430
      handle.is_numerical_fp_artifact_ = true;
×
1431
      return handle;
×
1432
    }
1433
  } else {
1434
    Mesh* mesh = model::meshes[mesh_idx].get();
1,971,618✔
1435
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,971,618✔
1436
    if (bin_found != mesh_bin) {
1,971,618✔
1437
      discovered_source_regions_.unlock(sr_key);
×
1438
      SourceRegionHandle handle;
×
1439
      handle.is_numerical_fp_artifact_ = true;
×
1440
      return handle;
×
1441
    }
1442
  }
1443

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

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

1475
  return handle;
1,971,618✔
1476
}
1,971,706✔
1477

1478
void FlatSourceDomain::finalize_discovered_source_regions()
2,970✔
1479
{
1480
  // Extract keys for entries with a valid volume.
1481
  vector<SourceRegionKey> keys;
2,970✔
1482
  for (const auto& pair : discovered_source_regions_) {
1,974,588✔
1483
    if (pair.second.volume_ > 0.0) {
1,971,618✔
1484
      keys.push_back(pair.first);
1,870,176✔
1485
    }
1486
  }
1487

1488
  if (!keys.empty()) {
2,970✔
1489
    // Sort the keys, so as to ensure reproducible ordering given that source
1490
    // regions may have been added to discovered_source_regions_ in an arbitrary
1491
    // order due to shared memory threading.
1492
    std::sort(keys.begin(), keys.end());
440✔
1493

1494
    // Append the source regions in the sorted key order.
1495
    for (const auto& key : keys) {
1,870,616✔
1496
      const SourceRegion& sr = discovered_source_regions_[key];
1,870,176✔
1497
      source_region_map_[key] = source_regions_.n_source_regions();
1,870,176✔
1498
      source_regions_.push_back(sr);
1,870,176✔
1499
    }
1500

1501
    // If any new source regions were discovered, we need to update the
1502
    // tally mapping between source regions and tally bins.
1503
    mapped_all_tallies_ = false;
440✔
1504
  }
1505

1506
  discovered_source_regions_.clear();
2,970✔
1507
}
2,970✔
1508

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

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

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

1550
        // Equation 16 in the above Gunow et al. 2019 paper
1551
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1552
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1553
      }
1554
    }
1555
  }
1556
}
1557

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