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

openmc-dev / openmc / 21043587909

15 Jan 2026 07:25PM UTC coverage: 81.332% (-0.7%) from 82.044%
21043587909

Pull #3734

github

web-flow
Merge 0c6701672 into 179048b80
Pull Request #3734: Specify temperature from a field (structured mesh only)

16365 of 22657 branches covered (72.23%)

Branch coverage included in aggregate %.

157 of 180 new or added lines in 12 files covered. (87.22%)

681 existing lines in 43 files now uncovered.

54412 of 64365 relevant lines covered (84.54%)

23556062.71 hits per line

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

68.15
/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_)
252✔
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;
252✔
44
  for (const auto& c : model::cells) {
2,070✔
45
    if (c->type_ != Fill::MATERIAL) {
1,818✔
46
      source_region_offsets_.push_back(-1);
846✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
972✔
49
      base_source_regions += c->n_instances();
972✔
50
    }
51
  }
52

53
  // Initialize source regions.
54
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
252✔
55
  source_regions_ = SourceRegionContainer(negroups_, is_linear);
252✔
56

57
  // Initialize tally volumes
58
  if (volume_normalized_flux_tallies_) {
252✔
59
    tally_volumes_.resize(model::tallies.size());
180✔
60
    for (int i = 0; i < model::tallies.size(); i++) {
654✔
61
      //  Get the shape of the 3D result tensor
62
      auto shape = model::tallies[i]->results().shape();
474✔
63

64
      // Create a new 2D tensor with the same size as the first
65
      // two dimensions of the 3D tensor
66
      tally_volumes_[i] =
474✔
67
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
948✔
68
    }
69
  }
70

71
  // Compute simulation domain volume based on ray source
72
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
252!
73
  SpatialDistribution* space_dist = is->space();
252✔
74
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
252!
75
  Position dims = sb->upper_right() - sb->lower_left();
252✔
76
  simulation_volume_ = dims.x * dims.y * dims.z;
252✔
77
}
252✔
78

79
void FlatSourceDomain::batch_reset()
4,480✔
80
{
81
// Reset scalar fluxes and iteration volume tallies to zero
82
#pragma omp parallel for
83
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
25,930,236✔
84
    source_regions_.volume(sr) = 0.0;
25,925,756✔
85
    source_regions_.volume_sq(sr) = 0.0;
25,925,756✔
86
  }
87

88
#pragma omp parallel for
89
  for (int64_t se = 0; se < n_source_elements(); se++) {
29,377,644✔
90
    source_regions_.scalar_flux_new(se) = 0.0;
29,373,164✔
91
  }
92
}
4,480✔
93

94
void FlatSourceDomain::accumulate_iteration_flux()
1,840✔
95
{
96
#pragma omp parallel for
97
  for (int64_t se = 0; se < n_source_elements(); se++) {
13,384,320✔
98
    source_regions_.scalar_flux_final(se) +=
13,382,480✔
99
      source_regions_.scalar_flux_new(se);
13,382,480✔
100
  }
101
}
1,840✔
102

103
void FlatSourceDomain::update_single_neutron_source(SourceRegionHandle& srh)
16,008,408✔
104
{
105
  // Reset all source regions to zero (important for void regions)
106
  for (int g = 0; g < negroups_; g++) {
33,991,032✔
107
    srh.source(g) = 0.0;
17,982,624✔
108
  }
109

110
  // Add scattering + fission source
111
  int material = srh.material();
16,008,408✔
112
  double density_mult = srh.density_mult();
16,008,408✔
113
  if (material != MATERIAL_VOID) {
16,008,408✔
114
    double inverse_k_eff = 1.0 / k_eff_;
15,848,088✔
115
    for (int g_out = 0; g_out < negroups_; g_out++) {
33,670,392✔
116
      double sigma_t = sigma_t_[material * negroups_ + g_out] * density_mult;
17,822,304✔
117
      double scatter_source = 0.0;
17,822,304✔
118
      double fission_source = 0.0;
17,822,304✔
119

120
      for (int g_in = 0; g_in < negroups_; g_in++) {
49,464,120✔
121
        double scalar_flux = srh.scalar_flux_old(g_in);
31,641,816✔
122
        double sigma_s = sigma_s_[material * negroups_ * negroups_ +
31,641,816✔
123
                                  g_out * negroups_ + g_in] *
31,641,816✔
124
                         density_mult;
31,641,816✔
125
        double nu_sigma_f =
126
          nu_sigma_f_[material * negroups_ + g_in] * density_mult;
31,641,816✔
127
        double chi = chi_[material * negroups_ + g_out];
31,641,816✔
128

129
        scatter_source += sigma_s * scalar_flux;
31,641,816✔
130
        if (settings::create_fission_neutrons) {
31,641,816!
131
          fission_source += nu_sigma_f * scalar_flux * chi;
31,641,816✔
132
        }
133
      }
134
      srh.source(g_out) =
17,822,304✔
135
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
17,822,304✔
136
    }
137
  }
138

139
  // Add external source if in fixed source mode
140
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
16,008,408✔
141
    for (int g = 0; g < negroups_; g++) {
32,709,784✔
142
      srh.source(g) += srh.external_source(g);
16,876,892✔
143
    }
144
  }
145
}
16,008,408✔
146

147
// Compute new estimate of scattering + fission sources in each source region
148
// based on the flux estimate from the previous iteration.
149
void FlatSourceDomain::update_all_neutron_sources()
4,480✔
150
{
151
  simulation::time_update_src.start();
4,480✔
152

153
#pragma omp parallel for
154
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
25,930,236✔
155
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
25,925,756✔
156
    update_single_neutron_source(srh);
25,925,756✔
157
  }
158

159
  simulation::time_update_src.stop();
4,480✔
160
}
4,480✔
161

162
// Normalizes flux and updates simulation-averaged volume estimate
163
void FlatSourceDomain::normalize_scalar_flux_and_volumes(
1,980✔
164
  double total_active_distance_per_iteration)
165
{
166
  double normalization_factor = 1.0 / total_active_distance_per_iteration;
1,980✔
167
  double volume_normalization_factor =
1,980✔
168
    1.0 / (total_active_distance_per_iteration * simulation::current_batch);
1,980✔
169

170
// Normalize scalar flux to total distance travelled by all rays this
171
// iteration
172
#pragma omp parallel for
173
  for (int64_t se = 0; se < n_source_elements(); se++) {
17,959,748✔
174
    source_regions_.scalar_flux_new(se) *= normalization_factor;
17,957,768✔
175
  }
176

177
// Accumulate cell-wise ray length tallies collected this iteration, then
178
// update the simulation-averaged cell-wise volume estimates
179
#pragma omp parallel for
180
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,985,556✔
181
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
15,983,576✔
182
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
15,983,576✔
183
    source_regions_.volume_naive(sr) =
31,967,152✔
184
      source_regions_.volume(sr) * normalization_factor;
15,983,576✔
185
    source_regions_.volume_sq(sr) =
31,967,152✔
186
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
15,983,576✔
187
    source_regions_.volume(sr) =
15,983,576✔
188
      source_regions_.volume_t(sr) * volume_normalization_factor;
15,983,576✔
189
  }
190
}
1,980✔
191

192
void FlatSourceDomain::set_flux_to_flux_plus_source(
15,922,940✔
193
  int64_t sr, double volume, int g)
194
{
195
  int material = source_regions_.material(sr);
15,922,940✔
196
  if (material == MATERIAL_VOID) {
15,922,940✔
197
    source_regions_.scalar_flux_new(sr, g) /= volume;
320,320✔
198
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
320,320!
199
      source_regions_.scalar_flux_new(sr, g) +=
320,320✔
200
        0.5f * source_regions_.external_source(sr, g) *
320,320✔
201
        source_regions_.volume_sq(sr);
320,320✔
202
    }
203
  } else {
204
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g] *
15,602,620✔
205
                     source_regions_.density_mult(sr);
15,602,620✔
206
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
15,602,620✔
207
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
15,602,620✔
208
  }
209
}
15,922,940✔
210

211
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
560✔
212
{
213
  source_regions_.scalar_flux_new(sr, g) =
1,120✔
214
    source_regions_.scalar_flux_old(sr, g);
560✔
215
}
560✔
216

217
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
3,246,380✔
218
{
219
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
3,246,380✔
220
}
3,246,380✔
221

222
// Combine transport flux contributions and flat source contributions from the
223
// previous iteration to generate this iteration's estimate of scalar flux.
224
int64_t FlatSourceDomain::add_source_to_scalar_flux()
4,480✔
225
{
226
  int64_t n_hits = 0;
4,480✔
227
  double inverse_batch = 1.0 / simulation::current_batch;
4,480✔
228

229
#pragma omp parallel for reduction(+ : n_hits)
230
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
26,752,508✔
231

232
    double volume_simulation_avg = source_regions_.volume(sr);
26,748,028✔
233
    double volume_iteration = source_regions_.volume_naive(sr);
26,748,028✔
234

235
    // Increment the number of hits if cell was hit this iteration
236
    if (volume_iteration) {
26,748,028✔
237
      n_hits++;
23,500,704✔
238
    }
239

240
    // Set the SR to small status if its expected number of hits
241
    // per iteration is less than 1.5
242
    if (source_regions_.n_hits(sr) * inverse_batch < MIN_HITS_PER_BATCH) {
26,748,028✔
243
      source_regions_.is_small(sr) = 1;
5,450,164✔
244
    } else {
245
      source_regions_.is_small(sr) = 0;
21,297,864✔
246
    }
247

248
    // The volume treatment depends on the volume estimator type
249
    // and whether or not an external source is present in the cell.
250
    double volume;
251
    switch (volume_estimator_) {
26,748,028!
252
    case RandomRayVolumeEstimator::NAIVE:
622,080✔
253
      volume = volume_iteration;
622,080✔
254
      break;
622,080✔
255
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
345,600✔
256
      volume = volume_simulation_avg;
345,600✔
257
      break;
345,600✔
258
    case RandomRayVolumeEstimator::HYBRID:
25,780,348✔
259
      if (source_regions_.external_source_present(sr) ||
48,209,976✔
260
          source_regions_.is_small(sr)) {
22,429,628✔
261
        volume = volume_iteration;
8,800,580✔
262
      } else {
263
        volume = volume_simulation_avg;
16,979,768✔
264
      }
265
      break;
25,780,348✔
UNCOV
266
    default:
×
UNCOV
267
      fatal_error("Invalid volume estimator type");
×
268
    }
269

270
    for (int g = 0; g < negroups_; g++) {
57,063,848✔
271
      // There are three scenarios we need to consider:
272
      if (volume_iteration > 0.0) {
30,315,820✔
273
        // 1. If the FSR was hit this iteration, then the new flux is equal to
274
        // the flat source from the previous iteration plus the contributions
275
        // from rays passing through the source region (computed during the
276
        // transport sweep)
277
        set_flux_to_flux_plus_source(sr, volume, g);
27,068,376✔
278
      } else if (volume_simulation_avg > 0.0) {
3,247,444✔
279
        // 2. If the FSR was not hit this iteration, but has been hit some
280
        // previous iteration, then we need to make a choice about what
281
        // to do. Naively we will usually want to set the flux to be equal
282
        // to the reduced source. However, in fixed source problems where
283
        // there is a strong external source present in the cell, and where
284
        // the cell has a very low cross section, this approximation will
285
        // cause a huge upward bias in the flux estimate of the cell (in these
286
        // conditions, the flux estimate can be orders of magnitude too large).
287
        // Thus, to avoid this bias, if any external source is present
288
        // in the cell we will use the previous iteration's flux estimate. This
289
        // injects a small degree of correlation into the simulation, but this
290
        // is going to be trivial when the miss rate is a few percent or less.
291
        if (source_regions_.external_source_present(sr)) {
3,247,436✔
292
          set_flux_to_old_flux(sr, g);
1,056✔
293
        } else {
294
          set_flux_to_source(sr, g);
3,246,380✔
295
        }
296
      }
297
      // Halt if NaN implosion is detected
298
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
30,315,820!
UNCOV
299
        fatal_error("A source region scalar flux is not finite. "
×
300
                    "This indicates a numerical instability in the "
301
                    "simulation. Consider increasing ray density or adjusting "
302
                    "the source region mesh.");
303
      }
304
    }
305
  }
306

307
  // Return the number of source regions that were hit this iteration
308
  return n_hits;
4,480✔
309
}
310

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

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

321
#pragma omp parallel for reduction(+ : fission_rate_old, fission_rate_new)
322
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
258,872✔
323

324
    // If simulation averaged volume is zero, don't include this cell
325
    double volume = source_regions_.volume(sr);
257,912✔
326
    if (volume == 0.0) {
257,912!
UNCOV
327
      continue;
×
328
    }
329

330
    int material = source_regions_.material(sr);
257,912✔
331
    if (material == MATERIAL_VOID) {
257,912!
UNCOV
332
      continue;
×
333
    }
334

335
    double sr_fission_source_old = 0;
257,912✔
336
    double sr_fission_source_new = 0;
257,912✔
337

338
    for (int g = 0; g < negroups_; g++) {
1,995,616✔
339
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g] *
1,737,704✔
340
                          source_regions_.density_mult(sr);
1,737,704✔
341
      sr_fission_source_old +=
1,737,704✔
342
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
1,737,704✔
343
      sr_fission_source_new +=
1,737,704✔
344
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
1,737,704✔
345
    }
346

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

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

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

359
  double k_eff_new = k_eff_ * (fission_rate_new / fission_rate_old);
960✔
360

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

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

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

379
  fission_rate_ = fission_rate_new;
960✔
380
  k_eff_ = k_eff_new;
960✔
381
}
960✔
382

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

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

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

416
// It takes as an argument the starting index in the source region array,
417
// and it will operate from that index until the end of the array. This
418
// is useful as it can be called for both explicit user source regions or
419
// when a source region mesh is overlaid.
420

421
void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id)
288✔
422
{
423
  openmc::simulation::time_tallies.start();
288✔
424

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

428
// Attempt to generate mapping for all source regions
429
#pragma omp parallel for
430
  for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) {
822,560✔
431

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

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

448
    // Loop over energy groups (so as to support energy filters)
449
    for (int g = 0; g < negroups_; g++) {
1,764,928✔
450

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

457
      int64_t source_element = sr * negroups_ + g;
942,656✔
458

459
      // If this task has already been populated, we don't need to do
460
      // it again.
461
      if (source_regions_.tally_task(sr, g).size() > 0) {
942,656!
UNCOV
462
        continue;
×
463
      }
464

465
      // Loop over all active tallies. This logic is essentially identical
466
      // to what happens when scanning for applicable tallies during
467
      // MC transport.
468
      for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) {
3,596,736✔
469
        Tally& tally {*model::tallies[i_tally]};
2,654,080✔
470

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

479
        // Loop over filter bins.
480
        for (; filter_iter != end; ++filter_iter) {
2,105,856✔
481
          auto filter_index = filter_iter.index_;
1,052,928✔
482
          auto filter_weight = filter_iter.weight_;
1,052,928✔
483

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

492
            // Also add this task to the list of volume tasks for this source
493
            // region.
494
            source_regions_.volume_task(sr).insert(task);
1,322,624✔
495
          }
496
        }
497
      }
498
      // Reset all the filter matches for the next tally event.
499
      for (auto& match : p.filter_matches())
3,966,592✔
500
        match.bins_present_ = false;
3,023,936✔
501
    }
502
  }
822,272✔
503
  openmc::simulation::time_tallies.stop();
288✔
504

505
  mapped_all_tallies_ = all_source_regions_mapped;
288✔
506
}
288✔
507

508
// Set the volume accumulators to zero for all tallies
509
void FlatSourceDomain::reset_tally_volumes()
1,840✔
510
{
511
  if (volume_normalized_flux_tallies_) {
1,840✔
512
#pragma omp parallel for
513
    for (int i = 0; i < tally_volumes_.size(); i++) {
5,400✔
514
      auto& tensor = tally_volumes_[i];
3,960✔
515
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
3,960✔
516
    }
517
  }
518
}
1,840✔
519

520
// In fixed source mode, due to the way that volumetric fixed sources are
521
// converted and applied as volumetric sources in one or more source regions,
522
// we need to perform an additional normalization step to ensure that the
523
// reported scalar fluxes are in units per source neutron. This allows for
524
// direct comparison of reported tallies to Monte Carlo flux results.
525
// This factor needs to be computed at each iteration, as it is based on the
526
// volume estimate of each FSR, which improves over the course of the
527
// simulation
528
double FlatSourceDomain::compute_fixed_source_normalization_factor() const
2,092✔
529
{
530
  // Eigenvalue mode normalization
531
  if (settings::run_mode == RunMode::EIGENVALUE) {
2,092✔
532
    // Normalize fluxes by total number of fission neutrons produced. This
533
    // ensures consistent scaling of the eigenvector such that its magnitude is
534
    // comparable to the eigenvector produced by the Monte Carlo solver.
535
    // Multiplying by the eigenvalue is unintuitive, but it is necessary.
536
    // If the eigenvalue is 1.2, per starting source neutron, you will
537
    // generate 1.2 neutrons. Thus if we normalize to generating only ONE
538
    // neutron in total for the whole domain, then we don't actually have enough
539
    // flux to generate the required 1.2 neutrons. We only know the flux
540
    // required to generate 1 neutron (which would have required less than one
541
    // starting neutron). Thus, you have to scale the flux up by the eigenvalue
542
    // such that 1.2 neutrons are generated, so as to be consistent with the
543
    // bookkeeping in MC which is all done per starting source neutron (not per
544
    // neutron produced).
545
    return k_eff_ / (fission_rate_ * simulation_volume_);
556✔
546
  }
547

548
  // If we are in adjoint mode of a fixed source problem, the external
549
  // source is already normalized, such that all resulting fluxes are
550
  // also normalized.
551
  if (adjoint_) {
1,536✔
552
    return 1.0;
120✔
553
  }
554

555
  // Fixed source mode normalization
556

557
  // Step 1 is to sum over all source regions and energy groups to get the
558
  // total external source strength in the simulation.
559
  double simulation_external_source_strength = 0.0;
1,416✔
560
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
561
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
11,742,536✔
562
    int material = source_regions_.material(sr);
11,741,120✔
563
    double volume = source_regions_.volume(sr) * simulation_volume_;
11,741,120✔
564
    for (int g = 0; g < negroups_; g++) {
23,916,544✔
565
      // For non-void regions, we store the external source pre-divided by
566
      // sigma_t. We need to multiply non-void regions back up by sigma_t
567
      // to get the total source strength in the expected units.
568
      double sigma_t = 1.0;
12,175,424✔
569
      if (material != MATERIAL_VOID) {
12,175,424✔
570
        sigma_t =
12,007,232✔
571
          sigma_t_[material * negroups_ + g] * source_regions_.density_mult(sr);
12,007,232✔
572
      }
573
      simulation_external_source_strength +=
12,175,424✔
574
        source_regions_.external_source(sr, g) * sigma_t * volume;
12,175,424✔
575
    }
576
  }
577

578
  // Step 2 is to determine the total user-specified external source strength
579
  double user_external_source_strength = 0.0;
1,416✔
580
  for (auto& ext_source : model::external_sources) {
2,832✔
581
    user_external_source_strength += ext_source->strength();
1,416✔
582
  }
583

584
  // The correction factor is the ratio of the user-specified external source
585
  // strength to the simulation external source strength.
586
  double source_normalization_factor =
1,416✔
587
    user_external_source_strength / simulation_external_source_strength;
588

589
  return source_normalization_factor;
1,416✔
590
}
591

592
// Tallying in random ray is not done directly during transport, rather,
593
// it is done only once after each power iteration. This is made possible
594
// by way of a mapping data structure that relates spatial source regions
595
// (FSRs) to tally/filter/score combinations. The mechanism by which the
596
// mapping is done (and the limitations incurred) is documented in the
597
// "convert_source_regions_to_tallies()" function comments above. The present
598
// tally function simply traverses the mapping data structure and executes
599
// the scoring operations to OpenMC's native tally result arrays.
600

601
void FlatSourceDomain::random_ray_tally()
1,840✔
602
{
603
  openmc::simulation::time_tallies.start();
1,840✔
604

605
  // Reset our tally volumes to zero
606
  reset_tally_volumes();
1,840✔
607

608
  double source_normalization_factor =
609
    compute_fixed_source_normalization_factor();
1,840✔
610

611
// We loop over all source regions and energy groups. For each
612
// element, we check if there are any scores needed and apply
613
// them.
614
#pragma omp parallel for
615
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
12,243,360✔
616
    // The fsr.volume_ is the unitless fractional simulation averaged volume
617
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
618
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
619
    // entire global simulation domain (as defined by the ray source box).
620
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
621
    // its fraction of the total volume by the total volume. Not important in
622
    // eigenvalue solves, but useful in fixed source solves for returning the
623
    // flux shape with a magnitude that makes sense relative to the fixed
624
    // source strength.
625
    double volume = source_regions_.volume(sr) * simulation_volume_;
12,241,520✔
626

627
    int material = source_regions_.material(sr);
12,241,520✔
628
    double density_mult = source_regions_.density_mult(sr);
12,241,520✔
629

630
    for (int g = 0; g < negroups_; g++) {
25,624,000✔
631
      double flux =
632
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
13,382,480✔
633

634
      // Determine numerical score value
635
      for (auto& task : source_regions_.tally_task(sr, g)) {
31,616,000✔
636
        double score = 0.0;
18,233,520✔
637
        switch (task.score_type) {
18,233,520!
638

639
        case SCORE_FLUX:
15,627,280✔
640
          score = flux * volume;
15,627,280✔
641
          break;
15,627,280✔
642

UNCOV
643
        case SCORE_TOTAL:
×
UNCOV
644
          if (material != MATERIAL_VOID) {
×
UNCOV
645
            score =
×
UNCOV
646
              flux * volume * sigma_t_[material * negroups_ + g] * density_mult;
×
647
          }
UNCOV
648
          break;
×
649

650
        case SCORE_FISSION:
1,303,120✔
651
          if (material != MATERIAL_VOID) {
1,303,120!
652
            score =
1,303,120✔
653
              flux * volume * sigma_f_[material * negroups_ + g] * density_mult;
1,303,120✔
654
          }
655
          break;
1,303,120✔
656

657
        case SCORE_NU_FISSION:
1,303,120✔
658
          if (material != MATERIAL_VOID) {
1,303,120!
659
            score = flux * volume * nu_sigma_f_[material * negroups_ + g] *
1,303,120✔
660
                    density_mult;
661
          }
662
          break;
1,303,120✔
663

UNCOV
664
        case SCORE_EVENTS:
×
UNCOV
665
          score = 1.0;
×
UNCOV
666
          break;
×
667

UNCOV
668
        default:
×
UNCOV
669
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
×
670
                      "total, fission, nu-fission, and events are supported in "
671
                      "random ray mode.");
672
          break;
673
        }
674
        // Apply score to the appropriate tally bin
675
        Tally& tally {*model::tallies[task.tally_idx]};
18,233,520✔
676
#pragma omp atomic
677
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
18,233,520✔
678
          score;
679
      }
680
    }
681

682
    // For flux tallies, the total volume of the spatial region is needed
683
    // for normalizing the flux. We store this volume in a separate tensor.
684
    // We only contribute to each volume tally bin once per FSR.
685
    if (volume_normalized_flux_tallies_) {
12,241,520✔
686
      for (const auto& task : source_regions_.volume_task(sr)) {
28,862,560✔
687
        if (task.score_type == SCORE_FLUX) {
16,737,360✔
688
#pragma omp atomic
689
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
15,105,520✔
690
            volume;
691
        }
692
      }
693
    }
694
  } // end FSR loop
695

696
  // Normalize any flux scores by the total volume of the FSRs scoring to that
697
  // bin. To do this, we loop over all tallies, and then all filter bins,
698
  // and then scores. For each score, we check the tally data structure to
699
  // see what index that score corresponds to. If that score is a flux score,
700
  // then we divide it by volume.
701
  if (volume_normalized_flux_tallies_) {
1,840✔
702
    for (int i = 0; i < model::tallies.size(); i++) {
5,400✔
703
      Tally& tally {*model::tallies[i]};
3,960✔
704
#pragma omp parallel for
705
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
563,920✔
706
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,135,600✔
707
          auto score_type = tally.scores_[score_idx];
575,640✔
708
          if (score_type == SCORE_FLUX) {
575,640✔
709
            double vol = tally_volumes_[i](bin, score_idx);
559,960✔
710
            if (vol > 0.0) {
559,960!
711
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
559,960✔
712
            }
713
          }
714
        }
715
      }
716
    }
717
  }
718

719
  openmc::simulation::time_tallies.stop();
1,840✔
720
}
1,840✔
721

722
double FlatSourceDomain::evaluate_flux_at_point(
×
723
  Position r, int64_t sr, int g) const
724
{
725
  return source_regions_.scalar_flux_final(sr, g) /
×
726
         (settings::n_batches - settings::n_inactive);
×
727
}
728

729
// Outputs all basic material, FSR ID, multigroup flux, and
730
// fission source data to .vtk file that can be directly
731
// loaded and displayed by Paraview. Note that .vtk binary
732
// files require big endian byte ordering, so endianness
733
// is checked and flipped if necessary.
734
void FlatSourceDomain::output_to_vtk() const
×
735
{
736
  // Rename .h5 plot filename(s) to .vtk filenames
737
  for (int p = 0; p < model::plots.size(); p++) {
×
738
    PlottableInterface* plot = model::plots[p].get();
×
739
    plot->path_plot() =
×
740
      plot->path_plot().substr(0, plot->path_plot().find_last_of('.')) + ".vtk";
×
741
  }
742

743
  // Print header information
744
  print_plot();
×
745

746
  // Outer loop over plots
747
  for (int plt = 0; plt < model::plots.size(); plt++) {
×
748

749
    // Get handle to OpenMC plot object and extract params
750
    Plot* openmc_plot = dynamic_cast<Plot*>(model::plots[plt].get());
×
751

752
    // Random ray plots only support voxel plots
753
    if (!openmc_plot) {
×
754
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
755
                          "is allowed in random ray mode.",
756
        plt));
757
      continue;
×
758
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
759
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
760
                          "is allowed in random ray mode.",
761
        plt));
762
      continue;
×
763
    }
764

765
    int Nx = openmc_plot->pixels_[0];
×
766
    int Ny = openmc_plot->pixels_[1];
×
767
    int Nz = openmc_plot->pixels_[2];
×
768
    Position origin = openmc_plot->origin_;
×
769
    Position width = openmc_plot->width_;
×
770
    Position ll = origin - width / 2.0;
×
771
    double x_delta = width.x / Nx;
×
772
    double y_delta = width.y / Ny;
×
773
    double z_delta = width.z / Nz;
×
774
    std::string filename = openmc_plot->path_plot();
×
775

776
    // Perform sanity checks on file size
777
    uint64_t bytes = Nx * Ny * Nz * (negroups_ + 1 + 1 + 1) * sizeof(float);
×
778
    write_message(5, "Processing plot {}: {}... (Estimated size is {} MB)",
×
779
      openmc_plot->id(), filename, bytes / 1.0e6);
×
780
    if (bytes / 1.0e9 > 1.0) {
×
781
      warning("Voxel plot specification is very large (>1 GB). Plotting may be "
×
782
              "slow.");
783
    } else if (bytes / 1.0e9 > 100.0) {
×
784
      fatal_error("Voxel plot specification is too large (>100 GB). Exiting.");
×
785
    }
786

787
    // Relate voxel spatial locations to random ray source regions
788
    vector<int> voxel_indices(Nx * Ny * Nz);
×
789
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
790
    vector<double> weight_windows(Nx * Ny * Nz);
×
791
    float min_weight = 1e20;
×
792
#pragma omp parallel for collapse(3) reduction(min : min_weight)
UNCOV
793
    for (int z = 0; z < Nz; z++) {
×
UNCOV
794
      for (int y = 0; y < Ny; y++) {
×
UNCOV
795
        for (int x = 0; x < Nx; x++) {
×
UNCOV
796
          Position sample;
×
UNCOV
797
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
×
UNCOV
798
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
×
UNCOV
799
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
×
UNCOV
800
          Particle p;
×
UNCOV
801
          p.r() = sample;
×
UNCOV
802
          p.r_last() = sample;
×
UNCOV
803
          p.E() = 1.0;
×
UNCOV
804
          p.E_last() = 1.0;
×
UNCOV
805
          p.u() = {1.0, 0.0, 0.0};
×
806

UNCOV
807
          bool found = exhaustive_find_cell(p);
×
UNCOV
808
          if (!found) {
×
UNCOV
809
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
×
UNCOV
810
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
×
UNCOV
811
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
×
UNCOV
812
            continue;
×
813
          }
814

UNCOV
815
          SourceRegionKey sr_key = lookup_source_region_key(p);
×
UNCOV
816
          int64_t sr = -1;
×
UNCOV
817
          auto it = source_region_map_.find(sr_key);
×
UNCOV
818
          if (it != source_region_map_.end()) {
×
UNCOV
819
            sr = it->second;
×
820
          }
821

UNCOV
822
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
×
UNCOV
823
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
×
824

UNCOV
825
          if (variance_reduction::weight_windows.size() == 1) {
×
826
            WeightWindow ww =
UNCOV
827
              variance_reduction::weight_windows[0]->get_weight_window(p);
×
UNCOV
828
            float weight = ww.lower_weight;
×
UNCOV
829
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
×
UNCOV
830
            if (weight < min_weight)
×
UNCOV
831
              min_weight = weight;
×
832
          }
UNCOV
833
        }
×
834
      }
835
    }
836

837
    double source_normalization_factor =
838
      compute_fixed_source_normalization_factor();
×
839

840
    // Open file for writing
841
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
842

843
    // Write vtk metadata
844
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
845
    std::fprintf(plot, "Dataset File\n");
×
846
    std::fprintf(plot, "BINARY\n");
×
847
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
848
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
849
    std::fprintf(plot, "ORIGIN %lf %lf %lf\n", ll.x, ll.y, ll.z);
×
850
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
851
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
852

853
    int64_t num_neg = 0;
×
854
    int64_t num_samples = 0;
×
855
    float min_flux = 0.0;
×
856
    float max_flux = -1.0e20;
×
857
    // Plot multigroup flux data
858
    for (int g = 0; g < negroups_; g++) {
×
859
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
860
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
861
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
862
        int64_t fsr = voxel_indices[i];
×
863
        int64_t source_element = fsr * negroups_ + g;
×
864
        float flux = 0;
×
865
        if (fsr >= 0) {
×
866
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
867
          if (flux < 0.0)
×
868
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
869
              voxel_positions[i], fsr, g);
×
870
        }
871
        if (flux < 0.0) {
×
872
          num_neg++;
×
873
          if (flux < min_flux) {
×
874
            min_flux = flux;
×
875
          }
876
        }
877
        if (flux > max_flux)
×
878
          max_flux = flux;
×
879
        num_samples++;
×
880
        flux = convert_to_big_endian<float>(flux);
×
881
        std::fwrite(&flux, sizeof(float), 1, plot);
×
882
      }
883
    }
884

885
    // Slightly negative fluxes can be normal when sampling corners of linear
886
    // source regions. However, very common and high magnitude negative fluxes
887
    // may indicate numerical instability.
888
    if (num_neg > 0) {
×
889
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
890
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
891
        num_neg, (100.0 * num_neg) / num_samples, min_flux, max_flux));
×
892
    }
893

894
    // Plot FSRs
895
    std::fprintf(plot, "SCALARS FSRs float\n");
×
896
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
897
    for (int fsr : voxel_indices) {
×
898
      float value = future_prn(10, fsr);
×
899
      value = convert_to_big_endian<float>(value);
×
900
      std::fwrite(&value, sizeof(float), 1, plot);
×
901
    }
902

903
    // Plot Materials
904
    std::fprintf(plot, "SCALARS Materials int\n");
×
905
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
906
    for (int fsr : voxel_indices) {
×
907
      int mat = -1;
×
908
      if (fsr >= 0)
×
909
        mat = source_regions_.material(fsr);
×
910
      mat = convert_to_big_endian<int>(mat);
×
911
      std::fwrite(&mat, sizeof(int), 1, plot);
×
912
    }
913

914
    // Plot fission source
915
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
916
      std::fprintf(plot, "SCALARS total_fission_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_fission = 0.0;
×
921
        if (fsr >= 0) {
×
922
          int mat = source_regions_.material(fsr);
×
923
          if (mat != MATERIAL_VOID) {
×
924
            for (int g = 0; g < negroups_; g++) {
×
925
              int64_t source_element = fsr * negroups_ + g;
×
926
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
927
              double sigma_f = sigma_f_[mat * negroups_ + g] *
×
928
                               source_regions_.density_mult(fsr);
×
929
              total_fission += sigma_f * flux;
×
930
            }
931
          }
932
        }
933
        total_fission = convert_to_big_endian<float>(total_fission);
×
934
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
935
      }
936
    } else {
937
      std::fprintf(plot, "SCALARS external_source float\n");
×
938
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
939
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
940
        int64_t fsr = voxel_indices[i];
×
941
        int mat = source_regions_.material(fsr);
×
942
        float total_external = 0.0f;
×
943
        if (fsr >= 0) {
×
944
          for (int g = 0; g < negroups_; g++) {
×
945
            // External sources are already divided by sigma_t, so we need to
946
            // multiply it back to get the true external source.
947
            double sigma_t = 1.0;
×
948
            if (mat != MATERIAL_VOID) {
×
949
              sigma_t = sigma_t_[mat * negroups_ + g] *
×
950
                        source_regions_.density_mult(fsr);
×
951
            }
952
            total_external += source_regions_.external_source(fsr, g) * sigma_t;
×
953
          }
954
        }
955
        total_external = convert_to_big_endian<float>(total_external);
×
956
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
957
      }
958
    }
959

960
    // Plot weight window data
961
    if (variance_reduction::weight_windows.size() == 1) {
×
962
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
963
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
964
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
965
        float weight = weight_windows[i];
×
966
        if (weight == 0.0)
×
967
          weight = min_weight;
×
968
        weight = convert_to_big_endian<float>(weight);
×
969
        std::fwrite(&weight, sizeof(float), 1, plot);
×
970
      }
971
    }
972

973
    std::fclose(plot);
×
974
  }
×
975
}
×
976

977
void FlatSourceDomain::apply_external_source_to_source_region(
1,668✔
978
  int src_idx, SourceRegionHandle& srh)
979
{
980
  auto s = model::external_sources[src_idx].get();
1,668✔
981
  auto is = dynamic_cast<IndependentSource*>(s);
1,668!
982
  auto discrete = dynamic_cast<Discrete*>(is->energy());
1,668!
983
  double strength_factor = is->strength();
1,668✔
984
  const auto& discrete_energies = discrete->x();
1,668✔
985
  const auto& discrete_probs = discrete->prob();
1,668✔
986

987
  srh.external_source_present() = 1;
1,668✔
988

989
  for (int i = 0; i < discrete_energies.size(); i++) {
3,384✔
990
    int g = data::mg.get_group_index(discrete_energies[i]);
1,716✔
991
    srh.external_source(g) += discrete_probs[i] * strength_factor;
1,716✔
992
  }
993
}
1,668✔
994

995
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
162✔
996
  int src_idx, int target_material_id, const vector<int32_t>& instances)
997
{
998
  Cell& cell = *model::cells[i_cell];
162✔
999

1000
  if (cell.type_ != Fill::MATERIAL)
162!
1001
    return;
×
1002

1003
  for (int j : instances) {
11,598✔
1004
    int cell_material_idx = cell.material(j);
11,436✔
1005
    int cell_material_id;
1006
    if (cell_material_idx == MATERIAL_VOID) {
11,436✔
1007
      cell_material_id = MATERIAL_VOID;
96✔
1008
    } else {
1009
      cell_material_id = model::materials[cell_material_idx]->id();
11,340✔
1010
    }
1011
    if (target_material_id == C_NONE ||
11,436✔
1012
        cell_material_id == target_material_id) {
1013
      int64_t source_region = source_region_offsets_[i_cell] + j;
1,116✔
1014
      external_volumetric_source_map_[source_region].push_back(src_idx);
1,116✔
1015
    }
1016
  }
1017
}
1018

1019
void FlatSourceDomain::apply_external_source_to_cell_and_children(
174✔
1020
  int32_t i_cell, int src_idx, int32_t target_material_id)
1021
{
1022
  Cell& cell = *model::cells[i_cell];
174✔
1023

1024
  if (cell.type_ == Fill::MATERIAL) {
174✔
1025
    vector<int> instances(cell.n_instances());
162✔
1026
    std::iota(instances.begin(), instances.end(), 0);
162✔
1027
    apply_external_source_to_cell_instances(
162✔
1028
      i_cell, src_idx, target_material_id, instances);
1029
  } else if (target_material_id == C_NONE) {
174!
1030
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1031
      cell.get_contained_cells(0, nullptr);
×
1032
    for (const auto& pair : cell_instance_list) {
×
1033
      int32_t i_child_cell = pair.first;
×
1034
      apply_external_source_to_cell_instances(
×
1035
        i_child_cell, src_idx, target_material_id, pair.second);
×
1036
    }
1037
  }
×
1038
}
174✔
1039

1040
void FlatSourceDomain::count_external_source_regions()
438✔
1041
{
1042
  n_external_source_regions_ = 0;
438✔
1043
#pragma omp parallel for reduction(+ : n_external_source_regions_)
1044
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
948,102✔
1045
    if (source_regions_.external_source_present(sr)) {
947,664✔
1046
      n_external_source_regions_++;
125,800✔
1047
    }
1048
  }
1049
}
438✔
1050

1051
void FlatSourceDomain::convert_external_sources()
156✔
1052
{
1053
  // Loop over external sources
1054
  for (int es = 0; es < model::external_sources.size(); es++) {
312✔
1055

1056
    // Extract source information
1057
    Source* s = model::external_sources[es].get();
156✔
1058
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
156!
1059
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
156!
1060
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
156✔
1061
    double strength_factor = is->strength();
156✔
1062

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

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

1083
      // With the source region and mesh bin known, we can use the
1084
      // accompanying SourceRegionKey as a key into a map that stores the
1085
      // corresponding external source index for the point source. Notably, we
1086
      // do not actually apply the external source to any source regions here,
1087
      // as if mesh subdivision is enabled, they haven't actually been
1088
      // discovered & initilized yet. When discovered, they will read from the
1089
      // external_source_map to determine if there are any external source
1090
      // terms that should be applied.
1091
      external_point_source_map_[key].push_back(es);
6✔
1092

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

1120
void FlatSourceDomain::flux_swap()
4,480✔
1121
{
1122
  source_regions_.flux_swap();
4,480✔
1123
}
4,480✔
1124

1125
void FlatSourceDomain::flatten_xs()
252✔
1126
{
1127
  // Temperature and angle indices, if using multiple temperature
1128
  // data sets and/or anisotropic data sets.
1129
  // TODO: Currently assumes we are only using single temp/single angle data.
1130
  const int t = 0;
252✔
1131
  const int a = 0;
252✔
1132

1133
  n_materials_ = data::mg.macro_xs_.size();
252✔
1134
  for (int i = 0; i < n_materials_; i++) {
942✔
1135
    auto& m = data::mg.macro_xs_[i];
690✔
1136
    for (int g_out = 0; g_out < negroups_; g_out++) {
3,828✔
1137
      if (m.exists_in_model) {
3,138✔
1138
        double sigma_t =
1139
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
3,114✔
1140
        sigma_t_.push_back(sigma_t);
3,114✔
1141

1142
        if (sigma_t < MINIMUM_MACRO_XS) {
3,114✔
1143
          Material* mat = model::materials[i].get();
6✔
1144
          warning(fmt::format(
6✔
1145
            "Material \"{}\" (id: {}) has a group {} total cross section "
1146
            "({:.3e}) below the minimum threshold "
1147
            "({:.3e}). Material will be treated as pure void.",
1148
            mat->name(), mat->id(), g_out, sigma_t, MINIMUM_MACRO_XS));
12✔
1149
        }
1150

1151
        double nu_sigma_f =
1152
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
3,114✔
1153
        nu_sigma_f_.push_back(nu_sigma_f);
3,114✔
1154

1155
        double sigma_f =
1156
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
3,114✔
1157
        sigma_f_.push_back(sigma_f);
3,114✔
1158

1159
        double chi =
1160
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
3,114✔
1161
        if (!std::isfinite(chi)) {
3,114✔
1162
          // MGXS interface may return NaN in some cases, such as when material
1163
          // is fissionable but has very small sigma_f.
1164
          chi = 0.0;
216✔
1165
        }
1166
        chi_.push_back(chi);
3,114✔
1167

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

1191
void FlatSourceDomain::set_adjoint_sources()
24✔
1192
{
1193
  // Set the adjoint external source to 1/forward_flux. If the forward flux is
1194
  // negative, zero, or extremely close to zero, set the adjoint source to zero,
1195
  // as this is likely a very small source region that we don't need to bother
1196
  // trying to vector particles towards. In the case of flux "being extremely
1197
  // close to zero", we define this as being a fixed fraction of the maximum
1198
  // forward flux, below which we assume the flux would be physically
1199
  // undetectable.
1200

1201
  // First, find the maximum forward flux value
1202
  double max_flux = 0.0;
24✔
1203
#pragma omp parallel for reduction(max : max_flux)
1204
  for (int64_t se = 0; se < n_source_elements(); se++) {
124,440✔
1205
    double flux = source_regions_.scalar_flux_final(se);
124,416✔
1206
    if (flux > max_flux) {
124,416✔
1207
      max_flux = flux;
20✔
1208
    }
1209
  }
1210

1211
  // Then, compute the adjoint source for each source region
1212
#pragma omp parallel for
1213
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
124,440✔
1214
    for (int g = 0; g < negroups_; g++) {
248,832✔
1215
      double flux = source_regions_.scalar_flux_final(sr, g);
124,416✔
1216
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
124,416✔
1217
        source_regions_.external_source(sr, g) = 0.0;
260✔
1218
      } else {
1219
        source_regions_.external_source(sr, g) = 1.0 / flux;
124,156✔
1220
      }
1221
      if (flux > 0.0) {
124,416✔
1222
        source_regions_.external_source_present(sr) = 1;
124,156✔
1223
      }
1224
      source_regions_.scalar_flux_final(sr, g) = 0.0;
124,416✔
1225
    }
1226
  }
1227

1228
  // "Small" source regions in OpenMC are defined as those that are hit by
1229
  // MIN_HITS_PER_BATCH rays or fewer each batch. These regions typically have
1230
  // very small volumes combined with a low aspect ratio, and are often
1231
  // generated when applying a source region mesh that clips the edge of a
1232
  // curved surface. As perhaps only a few rays will visit these regions over
1233
  // the entire forward simulation, the forward flux estimates are extremely
1234
  // noisy and unreliable. In some cases, the noise may make the forward fluxes
1235
  // extremely low, leading to unphysically large adjoint source terms,
1236
  // resulting in weight windows that aggressively try to drive particles
1237
  // towards these regions. To fix this, we simply filter out any "small" source
1238
  // regions from consideration. If a source region is "small", we
1239
  // set its adjoint source to zero. This adds negligible bias to the adjoint
1240
  // flux solution, as the true total adjoint source contribution from small
1241
  // regions is likely to be negligible.
1242
#pragma omp parallel for
1243
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
124,440✔
1244
    if (source_regions_.is_small(sr)) {
124,416!
UNCOV
1245
      for (int g = 0; g < negroups_; g++) {
×
UNCOV
1246
        source_regions_.external_source(sr, g) = 0.0;
×
1247
      }
UNCOV
1248
      source_regions_.external_source_present(sr) = 0;
×
1249
    }
1250
  }
1251
  // Divide the fixed source term by sigma t (to save time when applying each
1252
  // iteration)
1253
#pragma omp parallel for
1254
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
124,440✔
1255
    int material = source_regions_.material(sr);
124,416✔
1256
    if (material == MATERIAL_VOID) {
124,416!
UNCOV
1257
      continue;
×
1258
    }
1259
    for (int g = 0; g < negroups_; g++) {
248,832✔
1260
      double sigma_t =
1261
        sigma_t_[material * negroups_ + g] * source_regions_.density_mult(sr);
124,416✔
1262
      source_regions_.external_source(sr, g) /= sigma_t;
124,416✔
1263
    }
1264
  }
1265
}
24✔
1266

1267
void FlatSourceDomain::transpose_scattering_matrix()
30✔
1268
{
1269
  // Transpose the inner two dimensions for each material
1270
  for (int m = 0; m < n_materials_; ++m) {
114✔
1271
    int material_offset = m * negroups_ * negroups_;
84✔
1272
    for (int i = 0; i < negroups_; ++i) {
240✔
1273
      for (int j = i + 1; j < negroups_; ++j) {
408✔
1274
        // Calculate indices of the elements to swap
1275
        int idx1 = material_offset + i * negroups_ + j;
252✔
1276
        int idx2 = material_offset + j * negroups_ + i;
252✔
1277

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

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

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

1309
    if ((target_material_id == C_NONE && !is_target_void) ||
65,448!
1310
        cell_material_id == target_material_id) {
1311
      int64_t sr = source_region_offsets_[i_cell] + j;
53,448✔
1312
      // Check if the key is already present in the mesh_map_
1313
      if (mesh_map_.find(sr) != mesh_map_.end()) {
53,448!
1314
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1315
                                "applied, but trying to apply mesh idx {}",
1316
          sr, mesh_map_[sr], mesh_idx));
×
1317
      }
1318
      // If the SR has not already been assigned, then we can write to it
1319
      mesh_map_[sr] = mesh_idx;
53,448✔
1320
    }
1321
  }
1322
}
1323

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

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

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

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

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

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

1367
      if (domain_type == Source::DomainType::MATERIAL) {
108✔
1368
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
72✔
1369
          if (domain_id == C_NONE) {
60!
1370
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1371
          } else {
1372
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
60✔
1373
          }
1374
        }
1375
      } else if (domain_type == Source::DomainType::CELL) {
96✔
1376
        int32_t i_cell = model::cell_map[domain_id];
12✔
1377
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
12✔
1378
      } else if (domain_type == Source::DomainType::UNIVERSE) {
84!
1379
        int32_t i_universe = model::universe_map[domain_id];
84✔
1380
        Universe& universe = *model::universes[i_universe];
84✔
1381
        for (int32_t i_cell : universe.cells_) {
264✔
1382
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
180✔
1383
        }
1384
      }
1385
    }
1386
  }
1387
}
1388

1389
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
457,674,596✔
1390
  SourceRegionKey sr_key, Position r, Direction u)
1391
{
1392
  // Case 1: Check if the source region key is already present in the permanent
1393
  // map. This is the most common condition, as any source region visited in a
1394
  // previous power iteration will already be present in the permanent map. If
1395
  // the source region key is found, we translate the key into a specific 1D
1396
  // source region index and return a handle its position in the
1397
  // source_regions_ vector.
1398
  auto it = source_region_map_.find(sr_key);
457,674,596✔
1399
  if (it != source_region_map_.end()) {
457,674,596✔
1400
    int64_t sr = it->second;
443,710,496✔
1401
    return source_regions_.get_source_region_handle(sr);
443,710,496✔
1402
  }
1403

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

1412
  // If the key is found in the temporary map, then we return a handle to the
1413
  // source region that is stored in the temporary map.
1414
  if (discovered_source_regions_.contains(sr_key)) {
13,964,100✔
1415
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
13,104,908✔
1416
    discovered_source_regions_.unlock(sr_key);
13,104,908✔
1417
    return handle;
13,104,908✔
1418
  }
1419

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

1448
  // Sanity check on source region id
1449
  GeometryState gs;
859,192✔
1450
  gs.r() = r + TINY_BIT * u;
859,192✔
1451
  gs.u() = {1.0, 0.0, 0.0};
859,192✔
1452
  exhaustive_find_cell(gs);
859,192✔
1453
  int64_t sr_found = lookup_base_source_region_idx(gs);
859,192✔
1454
  if (sr_found != sr_key.base_source_region_id) {
859,192✔
1455
    discovered_source_regions_.unlock(sr_key);
32✔
1456
    SourceRegionHandle handle;
32✔
1457
    handle.is_numerical_fp_artifact_ = true;
32✔
1458
    return handle;
32✔
1459
  }
1460

1461
  // Sanity check on mesh bin
1462
  int mesh_idx = lookup_mesh_idx(sr_key.base_source_region_id);
859,160✔
1463
  if (mesh_idx == C_NONE) {
859,160✔
1464
    if (sr_key.mesh_bin != 0) {
142,016!
1465
      discovered_source_regions_.unlock(sr_key);
×
1466
      SourceRegionHandle handle;
×
1467
      handle.is_numerical_fp_artifact_ = true;
×
1468
      return handle;
×
1469
    }
1470
  } else {
1471
    Mesh* mesh = model::meshes[mesh_idx].get();
717,144✔
1472
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
717,144✔
1473
    if (bin_found != sr_key.mesh_bin) {
717,144!
1474
      discovered_source_regions_.unlock(sr_key);
×
1475
      SourceRegionHandle handle;
×
1476
      handle.is_numerical_fp_artifact_ = true;
×
1477
      return handle;
×
1478
    }
1479
  }
1480

1481
  // Case 4: The source region key is valid, but is not present anywhere. This
1482
  // condition only occurs the first time the source region is discovered
1483
  // (typically in the first power iteration). In this case, we need to handle
1484
  // creation of the new source region and its storage into the parallel map.
1485
  // Additionally, we need to determine the source region's material, initialize
1486
  // the starting scalar flux guess, and apply any known external sources.
1487

1488
  // Call the basic constructor for the source region and store in the parallel
1489
  // map.
1490
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
859,160✔
1491
  SourceRegion* sr_ptr =
1492
    discovered_source_regions_.emplace(sr_key, {negroups_, is_linear});
859,160✔
1493
  SourceRegionHandle handle {*sr_ptr};
859,160✔
1494

1495
  // Determine the material
1496
  int gs_i_cell = gs.lowest_coord().cell();
859,160✔
1497
  Cell& cell = *model::cells[gs_i_cell];
859,160✔
1498
  int material = cell.material(gs.cell_instance());
859,160✔
1499

1500
  // If material total XS is extremely low, just set it to void to avoid
1501
  // problems with 1/Sigma_t
1502
  for (int g = 0; g < negroups_; g++) {
1,830,696✔
1503
    double sigma_t = sigma_t_[material * negroups_ + g];
979,568✔
1504
    if (sigma_t < MINIMUM_MACRO_XS) {
979,568✔
1505
      material = MATERIAL_VOID;
8,032✔
1506
      break;
8,032✔
1507
    }
1508
  }
1509

1510
  handle.material() = material;
859,160✔
1511

1512
  handle.density_mult() = cell.density_mult(gs.cell_instance());
859,160✔
1513

1514
  // Store the mesh index (if any) assigned to this source region
1515
  handle.mesh() = mesh_idx;
859,160✔
1516

1517
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
859,160✔
1518
    // Determine if there are any volumetric sources, and apply them.
1519
    // Volumetric sources are specifc only to the base SR idx.
1520
    auto it_vol =
1521
      external_volumetric_source_map_.find(sr_key.base_source_region_id);
840,244✔
1522
    if (it_vol != external_volumetric_source_map_.end()) {
840,244✔
1523
      const vector<int>& vol_sources = it_vol->second;
1,664✔
1524
      for (int src_idx : vol_sources) {
3,328✔
1525
        apply_external_source_to_source_region(src_idx, handle);
1,664✔
1526
      }
1527
    }
1528

1529
    // Determine if there are any point sources, and apply them.
1530
    // Point sources are specific to the source region key.
1531
    auto it_point = external_point_source_map_.find(sr_key);
840,244✔
1532
    if (it_point != external_point_source_map_.end()) {
840,244✔
1533
      const vector<int>& point_sources = it_point->second;
4✔
1534
      for (int src_idx : point_sources) {
8✔
1535
        apply_external_source_to_source_region(src_idx, handle);
4✔
1536
      }
1537
    }
1538

1539
    // Divide external source term by sigma_t
1540
    if (material != C_NONE) {
840,244✔
1541
      for (int g = 0; g < negroups_; g++) {
1,681,128✔
1542
        double sigma_t =
1543
          sigma_t_[material * negroups_ + g] * handle.density_mult();
848,916✔
1544
        handle.external_source(g) /= sigma_t;
848,916✔
1545
      }
1546
    }
1547
  }
1548

1549
  // Compute the combined source term
1550
  update_single_neutron_source(handle);
859,160✔
1551

1552
  // Unlock the parallel map. Note: we may be tempted to release
1553
  // this lock earlier, and then just use the source region's lock to protect
1554
  // the flux/source initialization stages above. However, the rest of the code
1555
  // only protects updates to the new flux and volume fields, and assumes that
1556
  // the source is constant for the duration of transport. Thus, using just the
1557
  // source region's lock by itself would result in other threads potentially
1558
  // reading from the source before it is computed, as they won't use the lock
1559
  // when only reading from the SR's source. It would be expensive to protect
1560
  // those operations, whereas generating the SR is only done once, so we just
1561
  // hold the map's bucket lock until the source region is fully initialized.
1562
  discovered_source_regions_.unlock(sr_key);
859,160✔
1563

1564
  return handle;
859,160✔
1565
}
859,192✔
1566

1567
void FlatSourceDomain::finalize_discovered_source_regions()
4,480✔
1568
{
1569
  // Extract keys for entries with a valid volume.
1570
  vector<SourceRegionKey> keys;
4,480✔
1571
  for (const auto& pair : discovered_source_regions_) {
863,640✔
1572
    if (pair.second.volume_ > 0.0) {
859,160✔
1573
      keys.push_back(pair.first);
822,272✔
1574
    }
1575
  }
1576

1577
  if (!keys.empty()) {
4,480✔
1578
    // Sort the keys, so as to ensure reproducible ordering given that source
1579
    // regions may have been added to discovered_source_regions_ in an arbitrary
1580
    // order due to shared memory threading.
1581
    std::sort(keys.begin(), keys.end());
288✔
1582

1583
    // Remember the index of the first new source region
1584
    int64_t start_sr_id = source_regions_.n_source_regions();
288✔
1585

1586
    // Append the source regions in the sorted key order.
1587
    for (const auto& key : keys) {
822,560✔
1588
      const SourceRegion& sr = discovered_source_regions_[key];
822,272✔
1589
      source_region_map_[key] = source_regions_.n_source_regions();
822,272✔
1590
      source_regions_.push_back(sr);
822,272✔
1591
    }
1592

1593
    // Map all new source regions to tallies
1594
    convert_source_regions_to_tallies(start_sr_id);
288✔
1595
  }
1596

1597
  discovered_source_regions_.clear();
4,480✔
1598
}
4,480✔
1599

1600
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1601
//
1602
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1603
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1604
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1605
// https://doi.org/10.1016/j.anucene.2018.10.036.
1606
void FlatSourceDomain::apply_transport_stabilization()
4,480✔
1607
{
1608
  // Don't do anything if all in-group scattering
1609
  // cross sections are positive
1610
  if (!is_transport_stabilization_needed_) {
4,480✔
1611
    return;
4,400✔
1612
  }
1613

1614
  // Apply the stabilization factor to all source elements
1615
#pragma omp parallel for
1616
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,040✔
1617
    int material = source_regions_.material(sr);
960✔
1618
    double density_mult = source_regions_.density_mult(sr);
960✔
1619
    if (material == MATERIAL_VOID) {
960!
UNCOV
1620
      continue;
×
1621
    }
1622
    for (int g = 0; g < negroups_; g++) {
68,160✔
1623
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1624
      // negative
1625
      double sigma_s =
1626
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g] *
67,200✔
1627
        density_mult;
67,200✔
1628
      if (sigma_s < 0.0) {
67,200✔
1629
        double sigma_t = sigma_t_[material * negroups_ + g] * density_mult;
17,600✔
1630
        double phi_new = source_regions_.scalar_flux_new(sr, g);
17,600✔
1631
        double phi_old = source_regions_.scalar_flux_old(sr, g);
17,600✔
1632

1633
        // Equation 18 in the above Gunow et al. 2019 paper. For a default
1634
        // rho of 1.0, this ensures there are no negative diagonal elements
1635
        // in the iteration matrix. A lesser rho could be used (or exposed
1636
        // as a user input parameter) to reduce the negative impact on
1637
        // convergence rate though would need to be experimentally tested to see
1638
        // if it doesn't become unstable. rho = 1.0 is good as it gives the
1639
        // highest assurance of stability, and the impacts on convergence rate
1640
        // are pretty mild.
1641
        double D = diagonal_stabilization_rho_ * sigma_s / sigma_t;
17,600✔
1642

1643
        // Equation 16 in the above Gunow et al. 2019 paper
1644
        source_regions_.scalar_flux_new(sr, g) =
17,600✔
1645
          (phi_new - D * phi_old) / (1.0 - D);
17,600✔
1646
      }
1647
    }
1648
  }
1649
}
1650

1651
// Determines the base source region index (i.e., a material filled cell
1652
// instance) that corresponds to a particular location in the geometry. Requires
1653
// that the "gs" object passed in has already been initialized and has called
1654
// find_cell etc.
1655
int64_t FlatSourceDomain::lookup_base_source_region_idx(
294,346,338✔
1656
  const GeometryState& gs) const
1657
{
1658
  int i_cell = gs.lowest_coord().cell();
294,346,338✔
1659
  int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
294,346,338✔
1660
  return sr;
294,346,338✔
1661
}
1662

1663
// Determines the index of the mesh (if any) that has been applied
1664
// to a particular base source region index.
1665
int FlatSourceDomain::lookup_mesh_idx(int64_t sr) const
294,346,306✔
1666
{
1667
  int mesh_idx = C_NONE;
294,346,306✔
1668
  auto mesh_it = mesh_map_.find(sr);
294,346,306✔
1669
  if (mesh_it != mesh_map_.end()) {
294,346,306✔
1670
    mesh_idx = mesh_it->second;
162,887,078✔
1671
  }
1672
  return mesh_idx;
294,346,306✔
1673
}
1674

1675
// Determines the source region key that corresponds to a particular location in
1676
// the geometry. This takes into account both the base source region index as
1677
// well as the mesh bin if a mesh is applied to this source region for
1678
// subdivision.
1679
SourceRegionKey FlatSourceDomain::lookup_source_region_key(
702,406✔
1680
  const GeometryState& gs) const
1681
{
1682
  int64_t sr = lookup_base_source_region_idx(gs);
702,406✔
1683
  int64_t mesh_bin = lookup_mesh_bin(sr, gs.r());
702,406✔
1684
  return SourceRegionKey {sr, mesh_bin};
702,406✔
1685
}
1686

1687
// Determines the mesh bin that corresponds to a particular base source region
1688
// index and position.
1689
int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const
702,406✔
1690
{
1691
  int mesh_idx = lookup_mesh_idx(sr);
702,406✔
1692
  int mesh_bin = 0;
702,406✔
1693
  if (mesh_idx != C_NONE) {
702,406✔
1694
    mesh_bin = model::meshes[mesh_idx]->get_bin(r);
432,406✔
1695
  }
1696
  return mesh_bin;
702,406✔
1697
}
1698

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