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

openmc-dev / openmc / 15732126548

18 Jun 2025 11:55AM UTC coverage: 85.315% (+0.2%) from 85.162%
15732126548

Pull #3443

github

web-flow
Merge 8d2680531 into f31130d36
Pull Request #3443: fixing expansion of elemental Ta bug

3 of 5 new or added lines in 1 file covered. (60.0%)

96 existing lines in 2 files now uncovered.

52577 of 61627 relevant lines covered (85.31%)

36912161.15 hits per line

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

78.59
/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
      // Halt if NaN implosion is detected
308
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
37,617,375✔
309
        fatal_error("A source region scalar flux is not finite. "
310
                    "This indicates a numerical instability in the "
311
                    "simulation. Consider increasing ray density or adjusting "
312
                    "the source region mesh.");
313
      }
314
    }
315
  }
316

317
  // Return the number of source regions that were hit this iteration
318
  return n_hits;
11,550✔
319
}
320

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

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

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

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

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

345
    double sr_fission_source_old = 0;
307,790✔
346
    double sr_fission_source_new = 0;
307,790✔
347

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

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

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

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

368
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
2,090✔
369

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

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

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

388
  return k_eff_new;
2,090✔
389
}
2,090✔
390

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

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

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

424
void FlatSourceDomain::convert_source_regions_to_tallies()
440✔
425
{
426
  openmc::simulation::time_tallies.start();
440✔
427

428
  // Tracks if we've generated a mapping yet for all source regions.
429
  bool all_source_regions_mapped = true;
440✔
430

431
// Attempt to generate mapping for all source regions
432
#pragma omp parallel for
240✔
433
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,166,040✔
434

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

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

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

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

460
      int64_t source_element = sr * negroups_ + g;
1,314,640✔
461

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

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

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

482
        // Loop over filter bins.
483
        for (; filter_iter != end; ++filter_iter) {
3,202,560✔
484
          auto filter_index = filter_iter.index_;
1,601,280✔
485
          auto filter_weight = filter_iter.weight_;
1,601,280✔
486

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

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

508
  mapped_all_tallies_ = all_source_regions_mapped;
440✔
509
}
440✔
510

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

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

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

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

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

570
  return source_normalization_factor;
3,739✔
571
}
572

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

582
void FlatSourceDomain::random_ray_tally()
4,675✔
583
{
584
  openmc::simulation::time_tallies.start();
4,675✔
585

586
  // Reset our tally volumes to zero
587
  reset_tally_volumes();
4,675✔
588

589
  double source_normalization_factor =
590
    compute_fixed_source_normalization_factor();
4,675✔
591

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

608
    double material = source_regions_.material(sr);
15,208,200✔
609
    for (int g = 0; g < negroups_; g++) {
31,797,600✔
610
      double flux =
611
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,589,400✔
612

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

618
        case SCORE_FLUX:
19,405,000✔
619
          score = flux * volume;
19,405,000✔
620
          break;
19,405,000✔
621

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

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

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

640
        case SCORE_EVENTS:
641
          score = 1.0;
642
          break;
643

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

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

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

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

696
  openmc::simulation::time_tallies.stop();
4,675✔
697
}
4,675✔
698

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

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

720
  // Print header information
UNCOV
721
  print_plot();
×
722

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

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

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

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

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

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

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

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

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

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

826
    double source_normalization_factor =
827
      compute_fixed_source_normalization_factor();
×
828

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

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

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

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

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

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

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

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

UNCOV
960
    std::fclose(plot);
×
961
  }
962
}
963

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

969
  const auto& discrete_energies = discrete->x();
2,731✔
970
  const auto& discrete_probs = discrete->prob();
2,731✔
971

972
  for (int i = 0; i < discrete_energies.size(); i++) {
5,654✔
973
    int g = data::mg.get_group_index(discrete_energies[i]);
2,923✔
974
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,923✔
975
  }
976
}
2,731✔
977

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

984
  if (cell.type_ != Fill::MATERIAL)
400✔
UNCOV
985
    return;
×
986

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

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

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

1027
void FlatSourceDomain::count_external_source_regions()
1,024✔
1028
{
1029
  n_external_source_regions_ = 0;
1,024✔
1030
#pragma omp parallel for reduction(+ : n_external_source_regions_)
576✔
1031
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,532,984✔
1032
    if (source_regions_.external_source_present(sr)) {
1,532,536✔
1033
      n_external_source_regions_++;
158,700✔
1034
    }
1035
  }
1036
}
1,024✔
1037

1038
void FlatSourceDomain::convert_external_sources()
384✔
1039
{
1040
  // Loop over external sources
1041
  for (int es = 0; es < model::external_sources.size(); es++) {
768✔
1042

1043
    // Extract source information
1044
    Source* s = model::external_sources[es].get();
384✔
1045
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
384✔
1046
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
384✔
1047
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
384✔
1048
    double strength_factor = is->strength();
384✔
1049

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

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

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

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

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

1143
void FlatSourceDomain::flux_swap()
11,550✔
1144
{
1145
  source_regions_.flux_swap();
11,550✔
1146
}
11,550✔
1147

1148
void FlatSourceDomain::flatten_xs()
640✔
1149
{
1150
  // Temperature and angle indices, if using multiple temperature
1151
  // data sets and/or anisotropic data sets.
1152
  // TODO: Currently assumes we are only using single temp/single angle data.
1153
  const int t = 0;
640✔
1154
  const int a = 0;
640✔
1155

1156
  n_materials_ = data::mg.macro_xs_.size();
640✔
1157
  for (auto& m : data::mg.macro_xs_) {
2,384✔
1158
    for (int g_out = 0; g_out < negroups_; g_out++) {
8,672✔
1159
      if (m.exists_in_model) {
6,928✔
1160
        double sigma_t =
1161
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
6,864✔
1162
        sigma_t_.push_back(sigma_t);
6,864✔
1163

1164
        double nu_sigma_f =
1165
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1166
        nu_sigma_f_.push_back(nu_sigma_f);
6,864✔
1167

1168
        double sigma_f =
1169
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1170
        sigma_f_.push_back(sigma_f);
6,864✔
1171

1172
        double chi =
1173
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
6,864✔
1174
        if (!std::isfinite(chi)) {
6,864✔
1175
          // MGXS interface may return NaN in some cases, such as when material
1176
          // is fissionable but has very small sigma_f.
UNCOV
1177
          chi = 0.0;
×
1178
        }
1179
        chi_.push_back(chi);
6,864✔
1180

1181
        for (int g_in = 0; g_in < negroups_; g_in++) {
257,952✔
1182
          double sigma_s =
1183
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
251,088✔
1184
          sigma_s_.push_back(sigma_s);
251,088✔
1185
          // For transport corrected XS data, diagonal elements may be negative.
1186
          // In this case, set a flag to enable transport stabilization for the
1187
          // simulation.
1188
          if (g_out == g_in && sigma_s < 0.0)
251,088✔
1189
            is_transport_stabilization_needed_ = true;
880✔
1190
        }
1191
      } else {
1192
        sigma_t_.push_back(0);
64✔
1193
        nu_sigma_f_.push_back(0);
64✔
1194
        sigma_f_.push_back(0);
64✔
1195
        chi_.push_back(0);
64✔
1196
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1197
          sigma_s_.push_back(0);
64✔
1198
        }
1199
      }
1200
    }
1201
  }
1202
}
640✔
1203

1204
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
64✔
1205
{
1206
  // Set the adjoint external source to 1/forward_flux. If the forward flux is
1207
  // negative, zero, or extremely close to zero, set the adjoint source to zero,
1208
  // as this is likely a very small source region that we don't need to bother
1209
  // trying to vector particles towards. In the case of flux "being extremely
1210
  // close to zero", we define this as being a fixed fraction of the maximum
1211
  // forward flux, below which we assume the flux would be physically
1212
  // undetectable.
1213

1214
  // First, find the maximum forward flux value
1215
  double max_flux = 0.0;
64✔
1216
#pragma omp parallel for reduction(max : max_flux)
36✔
1217
  for (int64_t se = 0; se < n_source_elements(); se++) {
169,372✔
1218
    double flux = forward_flux[se];
169,344✔
1219
    if (flux > max_flux) {
169,344✔
1220
      max_flux = flux;
25✔
1221
    }
1222
  }
1223

1224
  // Then, compute the adjoint source for each source region
1225
#pragma omp parallel for
36✔
1226
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1227
    for (int g = 0; g < negroups_; g++) {
338,688✔
1228
      double flux = forward_flux[sr * negroups_ + g];
169,344✔
1229
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
169,344✔
1230
        source_regions_.external_source(sr, g) = 0.0;
325✔
1231
      } else {
1232
        source_regions_.external_source(sr, g) = 1.0 / flux;
169,019✔
1233
      }
1234
      if (flux > 0.0) {
169,344✔
1235
        source_regions_.external_source_present(sr) = 1;
155,195✔
1236
      }
1237
    }
1238
  }
1239

1240
  // Divide the fixed source term by sigma t (to save time when applying each
1241
  // iteration)
1242
#pragma omp parallel for
36✔
1243
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1244
    int material = source_regions_.material(sr);
169,344✔
1245
    if (material == MATERIAL_VOID) {
169,344✔
1246
      continue;
1247
    }
1248
    for (int g = 0; g < negroups_; g++) {
338,688✔
1249
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1250
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1251
    }
1252
  }
1253
}
64✔
1254

1255
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1256
{
1257
  // Transpose the inner two dimensions for each material
1258
  for (int m = 0; m < n_materials_; ++m) {
304✔
1259
    int material_offset = m * negroups_ * negroups_;
224✔
1260
    for (int i = 0; i < negroups_; ++i) {
640✔
1261
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1262
        // Calculate indices of the elements to swap
1263
        int idx1 = material_offset + i * negroups_ + j;
672✔
1264
        int idx2 = material_offset + j * negroups_ + i;
672✔
1265

1266
        // Swap the elements to transpose the matrix
1267
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1268
      }
1269
    }
1270
  }
1271
}
80✔
1272

1273
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
560✔
1274
{
1275
  // Ensure array is correct size
1276
  flux.resize(n_source_regions() * negroups_);
560✔
1277
// Serialize the final fluxes for output
1278
#pragma omp parallel for
315✔
1279
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,258,577✔
1280
    flux[se] = source_regions_.scalar_flux_final(se);
1,258,332✔
1281
  }
1282
}
560✔
1283

1284
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
608✔
1285
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1286
  bool is_target_void)
1287
{
1288
  Cell& cell = *model::cells[i_cell];
608✔
1289
  if (cell.type_ != Fill::MATERIAL)
608✔
UNCOV
1290
    return;
×
1291
  for (int32_t j : instances) {
174,944✔
1292
    int cell_material_idx = cell.material(j);
174,336✔
1293
    int cell_material_id = (cell_material_idx == C_NONE)
1294
                             ? C_NONE
174,336✔
1295
                             : model::materials[cell_material_idx]->id();
174,336✔
1296

1297
    if ((target_material_id == C_NONE && !is_target_void) ||
174,336✔
1298
        cell_material_id == target_material_id) {
1299
      int64_t sr = source_region_offsets_[i_cell] + j;
142,336✔
1300
      if (source_regions_.mesh(sr) != C_NONE) {
142,336✔
1301
        // print out the source region that is broken:
UNCOV
1302
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1303
                                "applied, but trying to apply mesh idx {}",
1304
          sr, source_regions_.mesh(sr), mesh_idx));
1305
      }
1306
      source_regions_.mesh(sr) = mesh_idx;
142,336✔
1307
    }
1308
  }
1309
}
1310

1311
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
480✔
1312
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1313
{
1314
  Cell& cell = *model::cells[i_cell];
480✔
1315

1316
  if (cell.type_ == Fill::MATERIAL) {
480✔
1317
    vector<int> instances(cell.n_instances_);
352✔
1318
    std::iota(instances.begin(), instances.end(), 0);
352✔
1319
    apply_mesh_to_cell_instances(
352✔
1320
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1321
  } else if (target_material_id == C_NONE && !is_target_void) {
480✔
1322
    for (int j = 0; j < cell.n_instances_; j++) {
128✔
1323
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1324
        cell.get_contained_cells(j, nullptr);
64✔
1325
      for (const auto& pair : cell_instance_list) {
320✔
1326
        int32_t i_child_cell = pair.first;
256✔
1327
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
256✔
1328
          pair.second, is_target_void);
256✔
1329
      }
1330
    }
64✔
1331
  }
1332
}
480✔
1333

1334
void FlatSourceDomain::apply_meshes()
560✔
1335
{
1336
  // Skip if there are no mappings between mesh IDs and domains
1337
  if (mesh_domain_map_.empty())
560✔
1338
    return;
400✔
1339

1340
  // Loop over meshes
1341
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
400✔
1342
    Mesh* mesh = model::meshes[mesh_idx].get();
240✔
1343
    int mesh_id = mesh->id();
240✔
1344

1345
    // Skip if mesh id is not present in the map
1346
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
240✔
1347
      continue;
16✔
1348

1349
    // Loop over domains associated with the mesh
1350
    for (auto& domain : mesh_domain_map_[mesh_id]) {
448✔
1351
      Source::DomainType domain_type = domain.first;
224✔
1352
      int domain_id = domain.second;
224✔
1353

1354
      if (domain_type == Source::DomainType::MATERIAL) {
224✔
1355
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1356
          if (domain_id == C_NONE) {
160✔
UNCOV
1357
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1358
          } else {
1359
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1360
          }
1361
        }
1362
      } else if (domain_type == Source::DomainType::CELL) {
192✔
1363
        int32_t i_cell = model::cell_map[domain_id];
32✔
1364
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1365
      } else if (domain_type == Source::DomainType::UNIVERSE) {
160✔
1366
        int32_t i_universe = model::universe_map[domain_id];
160✔
1367
        Universe& universe = *model::universes[i_universe];
160✔
1368
        for (int32_t i_cell : universe.cells_) {
448✔
1369
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
288✔
1370
        }
1371
      }
1372
    }
1373
  }
1374
}
1375

1376
void FlatSourceDomain::prepare_base_source_regions()
110✔
1377
{
1378
  std::swap(source_regions_, base_source_regions_);
110✔
1379
  source_regions_.negroups() = base_source_regions_.negroups();
110✔
1380
  source_regions_.is_linear() = base_source_regions_.is_linear();
110✔
1381
}
110✔
1382

1383
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
871,515,854✔
1384
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1385
{
1386
  SourceRegionKey sr_key {sr, mesh_bin};
871,515,854✔
1387

1388
  // Case 1: Check if the source region key is already present in the permanent
1389
  // map. This is the most common condition, as any source region visited in a
1390
  // previous power iteration will already be present in the permanent map. If
1391
  // the source region key is found, we translate the key into a specific 1D
1392
  // source region index and return a handle its position in the
1393
  // source_regions_ vector.
1394
  auto it = source_region_map_.find(sr_key);
871,515,854✔
1395
  if (it != source_region_map_.end()) {
871,515,854✔
1396
    int64_t sr = it->second;
850,445,145✔
1397
    return source_regions_.get_source_region_handle(sr);
850,445,145✔
1398
  }
1399

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

1408
  // If the key is found in the temporary map, then we return a handle to the
1409
  // source region that is stored in the temporary map.
1410
  if (discovered_source_regions_.contains(sr_key)) {
21,070,709✔
1411
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
19,099,003✔
1412
    discovered_source_regions_.unlock(sr_key);
19,099,003✔
1413
    return handle;
19,099,003✔
1414
  }
1415

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

1444
  // Sanity check on source region id
1445
  GeometryState gs;
1,971,706✔
1446
  gs.r() = r + TINY_BIT * u;
1,971,706✔
1447
  gs.u() = {1.0, 0.0, 0.0};
1,971,706✔
1448
  exhaustive_find_cell(gs);
1,971,706✔
1449
  int gs_i_cell = gs.lowest_coord().cell;
1,971,706✔
1450
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,971,706✔
1451
  if (sr_found != sr) {
1,971,706✔
1452
    discovered_source_regions_.unlock(sr_key);
88✔
1453
    SourceRegionHandle handle;
88✔
1454
    handle.is_numerical_fp_artifact_ = true;
88✔
1455
    return handle;
88✔
1456
  }
1457

1458
  // Sanity check on mesh bin
1459
  int mesh_idx = base_source_regions_.mesh(sr);
1,971,618✔
1460
  if (mesh_idx == C_NONE) {
1,971,618✔
UNCOV
1461
    if (mesh_bin != 0) {
×
UNCOV
1462
      discovered_source_regions_.unlock(sr_key);
×
UNCOV
1463
      SourceRegionHandle handle;
×
UNCOV
1464
      handle.is_numerical_fp_artifact_ = true;
×
UNCOV
1465
      return handle;
×
1466
    }
1467
  } else {
1468
    Mesh* mesh = model::meshes[mesh_idx].get();
1,971,618✔
1469
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,971,618✔
1470
    if (bin_found != mesh_bin) {
1,971,618✔
UNCOV
1471
      discovered_source_regions_.unlock(sr_key);
×
UNCOV
1472
      SourceRegionHandle handle;
×
UNCOV
1473
      handle.is_numerical_fp_artifact_ = true;
×
UNCOV
1474
      return handle;
×
1475
    }
1476
  }
1477

1478
  // Case 4: The source region key is valid, but is not present anywhere. This
1479
  // condition only occurs the first time the source region is discovered
1480
  // (typically in the first power iteration). In this case, we need to handle
1481
  // creation of the new source region and its storage into the parallel map.
1482
  // The new source region is created by copying the base source region, so as
1483
  // to inherit material, external source, and some flux properties etc. We
1484
  // also pass the base source region id to allow the new source region to
1485
  // know which base source region it is derived from.
1486
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
1,971,618✔
1487
    sr_key, {base_source_regions_.get_source_region_handle(sr), sr});
1,971,618✔
1488
  discovered_source_regions_.unlock(sr_key);
1,971,618✔
1489
  SourceRegionHandle handle {*sr_ptr};
1,971,618✔
1490

1491
  // Check if the new source region contains a point source and apply it if so
1492
  auto it2 = point_source_map_.find(sr_key);
1,971,618✔
1493
  if (it2 != point_source_map_.end()) {
1,971,618✔
1494
    int es = it2->second;
11✔
1495
    auto s = model::external_sources[es].get();
11✔
1496
    auto is = dynamic_cast<IndependentSource*>(s);
11✔
1497
    auto energy = dynamic_cast<Discrete*>(is->energy());
11✔
1498
    double strength_factor = is->strength();
11✔
1499
    apply_external_source_to_source_region(energy, strength_factor, handle);
11✔
1500
    int material = handle.material();
11✔
1501
    if (material != MATERIAL_VOID) {
11✔
1502
      for (int g = 0; g < negroups_; g++) {
22✔
1503
        double sigma_t = sigma_t_[material * negroups_ + g];
11✔
1504
        handle.external_source(g) /= sigma_t;
11✔
1505
      }
1506
    }
1507
  }
1508

1509
  return handle;
1,971,618✔
1510
}
1,971,706✔
1511

1512
void FlatSourceDomain::finalize_discovered_source_regions()
2,970✔
1513
{
1514
  // Extract keys for entries with a valid volume.
1515
  vector<SourceRegionKey> keys;
2,970✔
1516
  for (const auto& pair : discovered_source_regions_) {
1,974,588✔
1517
    if (pair.second.volume_ > 0.0) {
1,971,618✔
1518
      keys.push_back(pair.first);
1,870,176✔
1519
    }
1520
  }
1521

1522
  if (!keys.empty()) {
2,970✔
1523
    // Sort the keys, so as to ensure reproducible ordering given that source
1524
    // regions may have been added to discovered_source_regions_ in an arbitrary
1525
    // order due to shared memory threading.
1526
    std::sort(keys.begin(), keys.end());
440✔
1527

1528
    // Append the source regions in the sorted key order.
1529
    for (const auto& key : keys) {
1,870,616✔
1530
      const SourceRegion& sr = discovered_source_regions_[key];
1,870,176✔
1531
      source_region_map_[key] = source_regions_.n_source_regions();
1,870,176✔
1532
      source_regions_.push_back(sr);
1,870,176✔
1533
    }
1534

1535
    // If any new source regions were discovered, we need to update the
1536
    // tally mapping between source regions and tally bins.
1537
    mapped_all_tallies_ = false;
440✔
1538
  }
1539

1540
  discovered_source_regions_.clear();
2,970✔
1541
}
2,970✔
1542

1543
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1544
//
1545
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1546
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1547
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1548
// https://doi.org/10.1016/j.anucene.2018.10.036.
1549
void FlatSourceDomain::apply_transport_stabilization()
11,550✔
1550
{
1551
  // Don't do anything if all in-group scattering
1552
  // cross sections are positive
1553
  if (!is_transport_stabilization_needed_) {
11,550✔
1554
    return;
11,330✔
1555
  }
1556

1557
  // Apply the stabilization factor to all source elements
1558
#pragma omp parallel for
120✔
1559
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1560
    int material = source_regions_.material(sr);
1,200✔
1561
    if (material == MATERIAL_VOID) {
1,200✔
1562
      continue;
1563
    }
1564
    for (int g = 0; g < negroups_; g++) {
85,200✔
1565
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1566
      // negative
1567
      double sigma_s =
1568
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g];
84,000✔
1569
      if (sigma_s < 0.0) {
84,000✔
1570
        double sigma_t = sigma_t_[material * negroups_ + g];
22,000✔
1571
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1572
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
1573

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

1584
        // Equation 16 in the above Gunow et al. 2019 paper
1585
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1586
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1587
      }
1588
    }
1589
  }
1590
}
1591

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