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

openmc-dev / openmc / 21426188483

28 Jan 2026 05:22AM UTC coverage: 81.984% (-0.01%) from 81.998%
21426188483

Pull #3746

github

web-flow
Merge 2ab9e821e into db426b66c
Pull Request #3746: Warn users when setting undefined attributes in ```openmc.Settings```

17216 of 23970 branches covered (71.82%)

Branch coverage included in aggregate %.

7 of 11 new or added lines in 1 file covered. (63.64%)

373 existing lines in 10 files now uncovered.

55682 of 64947 relevant lines covered (85.73%)

44023040.97 hits per line

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

71.71
/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_)
721✔
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;
721✔
44
  for (const auto& c : model::cells) {
5,716✔
45
    if (c->type_ != Fill::MATERIAL) {
4,995✔
46
      source_region_offsets_.push_back(-1);
2,257✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
2,738✔
49
      base_source_regions += c->n_instances();
2,738✔
50
    }
51
  }
52

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

57
  // Initialize tally volumes
58
  if (volume_normalized_flux_tallies_) {
721✔
59
    tally_volumes_.resize(model::tallies.size());
480✔
60
    for (int i = 0; i < model::tallies.size(); i++) {
1,744✔
61
      //  Get the shape of the 3D result tensor
62
      auto shape = model::tallies[i]->results().shape();
1,264✔
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] =
1,264✔
67
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,528✔
68
    }
69
  }
70

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

79
void FlatSourceDomain::batch_reset()
12,662✔
80
{
81
// Reset scalar fluxes and iteration volume tallies to zero
82
#pragma omp parallel for
6,912✔
83
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,414,565✔
84
    source_regions_.volume(sr) = 0.0;
32,408,815✔
85
    source_regions_.volume_sq(sr) = 0.0;
32,408,815✔
86
  }
87

88
#pragma omp parallel for
6,912✔
89
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,725,445✔
90
    source_regions_.scalar_flux_new(se) = 0.0;
36,719,695✔
91
  }
92
}
12,662✔
93

94
void FlatSourceDomain::accumulate_iteration_flux()
5,231✔
95
{
96
#pragma omp parallel for
2,856✔
97
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,732,275✔
98
    source_regions_.scalar_flux_final(se) +=
16,729,900✔
99
      source_regions_.scalar_flux_new(se);
16,729,900✔
100
  }
101
}
5,231✔
102

103
void FlatSourceDomain::update_single_neutron_source(SourceRegionHandle& srh)
44,024,166✔
104
{
105
  // Reset all source regions to zero (important for void regions)
106
  for (int g = 0; g < negroups_; g++) {
93,478,470✔
107
    srh.source(g) = 0.0;
49,454,304✔
108
  }
109

110
  // Add scattering + fission source
111
  int material = srh.material();
44,024,166✔
112
  double density_mult = srh.density_mult();
44,024,166✔
113
  if (material != MATERIAL_VOID) {
44,024,166✔
114
    double inverse_k_eff = 1.0 / k_eff_;
43,582,518✔
115
    for (int g_out = 0; g_out < negroups_; g_out++) {
92,594,406✔
116
      double sigma_t = sigma_t_[material * negroups_ + g_out] * density_mult;
49,011,888✔
117
      double scatter_source = 0.0;
49,011,888✔
118
      double fission_source = 0.0;
49,011,888✔
119

120
      for (int g_in = 0; g_in < negroups_; g_in++) {
136,027,986✔
121
        double scalar_flux = srh.scalar_flux_old(g_in);
87,016,098✔
122
        double sigma_s = sigma_s_[material * negroups_ * negroups_ +
87,016,098✔
123
                                  g_out * negroups_ + g_in] *
87,016,098✔
124
                         density_mult;
87,016,098✔
125
        double nu_sigma_f =
126
          nu_sigma_f_[material * negroups_ + g_in] * density_mult;
87,016,098✔
127
        double chi = chi_[material * negroups_ + g_out];
87,016,098✔
128

129
        scatter_source += sigma_s * scalar_flux;
87,016,098✔
130
        if (settings::create_fission_neutrons) {
87,016,098!
131
          fission_source += nu_sigma_f * scalar_flux * chi;
87,016,098✔
132
        }
133
      }
134
      srh.source(g_out) =
49,011,888✔
135
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
49,011,888✔
136
    }
137
  }
138

139
  // Add external source if in fixed source mode
140
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
44,024,166✔
141
    for (int g = 0; g < negroups_; g++) {
89,955,038✔
142
      srh.source(g) += srh.external_source(g);
46,413,541✔
143
    }
144
  }
145
}
44,024,166✔
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()
12,662✔
150
{
151
  simulation::time_update_src.start();
12,662✔
152

153
#pragma omp parallel for
6,912✔
154
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,414,565✔
155
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
32,408,815✔
156
    update_single_neutron_source(srh);
32,408,815✔
157
  }
158

159
  simulation::time_update_src.stop();
12,662✔
160
}
12,662✔
161

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

170
// Normalize scalar flux to total distance travelled by all rays this
171
// iteration
172
#pragma omp parallel for
2,982✔
173
  for (int64_t se = 0; se < n_source_elements(); se++) {
22,449,685✔
174
    source_regions_.scalar_flux_new(se) *= normalization_factor;
22,447,210✔
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
2,982✔
180
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,981,945✔
181
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
19,979,470✔
182
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
19,979,470✔
183
    source_regions_.volume_naive(sr) =
39,958,940✔
184
      source_regions_.volume(sr) * normalization_factor;
19,979,470✔
185
    source_regions_.volume_sq(sr) =
39,958,940✔
186
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
19,979,470✔
187
    source_regions_.volume(sr) =
19,979,470✔
188
      source_regions_.volume_t(sr) * volume_normalization_factor;
19,979,470✔
189
  }
190
}
5,457✔
191

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

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

217
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
8,927,547✔
218
{
219
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
8,927,547✔
220
}
8,927,547✔
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()
12,662✔
225
{
226
  int64_t n_hits = 0;
12,662✔
227
  double inverse_batch = 1.0 / simulation::current_batch;
12,662✔
228

229
#pragma omp parallel for reduction(+ : n_hits)
6,912✔
230
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,442,585✔
231

232
    double volume_simulation_avg = source_regions_.volume(sr);
33,436,835✔
233
    double volume_iteration = source_regions_.volume_naive(sr);
33,436,835✔
234

235
    // Increment the number of hits if cell was hit this iteration
236
    if (volume_iteration) {
33,436,835✔
237
      n_hits++;
29,377,680✔
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) {
33,436,835✔
243
      source_regions_.is_small(sr) = 1;
6,812,705✔
244
    } else {
245
      source_regions_.is_small(sr) = 0;
26,624,130✔
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_) {
33,436,835!
252
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
253
      volume = volume_iteration;
777,600✔
254
      break;
777,600✔
255
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
256
      volume = volume_simulation_avg;
432,000✔
257
      break;
432,000✔
258
    case RandomRayVolumeEstimator::HYBRID:
32,227,235✔
259
      if (source_regions_.external_source_present(sr) ||
60,266,070✔
260
          source_regions_.is_small(sr)) {
28,038,835✔
261
        volume = volume_iteration;
11,000,725✔
262
      } else {
263
        volume = volume_simulation_avg;
21,226,510✔
264
      }
265
      break;
32,227,235✔
266
    default:
267
      fatal_error("Invalid volume estimator type");
268
    }
269

270
    for (int g = 0; g < negroups_; g++) {
71,335,210✔
271
      // There are three scenarios we need to consider:
272
      if (volume_iteration > 0.0) {
37,898,375✔
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);
33,839,070✔
278
      } else if (volume_simulation_avg > 0.0) {
4,059,305✔
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)) {
4,059,295✔
292
          set_flux_to_old_flux(sr, g);
1,320✔
293
        } else {
294
          set_flux_to_source(sr, g);
4,057,975✔
295
        }
296
      }
297
      // Halt if NaN implosion is detected
298
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
37,898,375!
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;
12,662✔
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()
2,970✔
314
{
315
  double fission_rate_old = 0;
2,970✔
316
  double fission_rate_new = 0;
2,970✔
317

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

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

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

330
    int material = source_regions_.material(sr);
324,190✔
331
    if (material == MATERIAL_VOID) {
324,190!
332
      continue;
333
    }
334

335
    double sr_fission_source_old = 0;
324,190✔
336
    double sr_fission_source_new = 0;
324,190✔
337

338
    for (int g = 0; g < negroups_; g++) {
2,499,920✔
339
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g] *
2,175,730✔
340
                          source_regions_.density_mult(sr);
2,175,730✔
341
      sr_fission_source_old +=
2,175,730✔
342
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
2,175,730✔
343
      sr_fission_source_new +=
2,175,730✔
344
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
2,175,730✔
345
    }
346

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

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

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

359
  double k_eff_new = k_eff_ * (fission_rate_new / fission_rate_old);
2,970✔
360

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

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

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

379
  fission_rate_ = fission_rate_new;
2,970✔
380
  k_eff_ = k_eff_new;
2,970✔
381
}
2,970✔
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)
826✔
422
{
423
  openmc::simulation::time_tallies.start();
826✔
424

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

428
// Attempt to generate mapping for all source regions
429
#pragma omp parallel for
451✔
430
  for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) {
1,028,395✔
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)) {
1,028,020!
435
      all_source_regions_mapped = false;
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;
1,028,020✔
443
    p.r() = source_regions_.position(sr);
1,028,020✔
444
    p.r_last() = source_regions_.position(sr);
1,028,020✔
445
    p.u() = {1.0, 0.0, 0.0};
1,028,020✔
446
    bool found = exhaustive_find_cell(p);
1,028,020✔
447

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

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

457
      int64_t source_element = sr * negroups_ + g;
1,178,680✔
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) {
1,178,680!
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++) {
4,496,640✔
469
        Tally& tally {*model::tallies[i_tally]};
3,317,960✔
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);
3,317,960✔
475
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,317,960✔
476
        if (filter_iter == end)
3,317,960✔
477
          continue;
2,001,680✔
478

479
        // Loop over filter bins.
480
        for (; filter_iter != end; ++filter_iter) {
2,632,560✔
481
          auto filter_index = filter_iter.index_;
1,316,280✔
482
          auto filter_weight = filter_iter.weight_;
1,316,280✔
483

484
          // Loop over scores
485
          for (int score = 0; score < tally.scores_.size(); score++) {
2,969,680✔
486
            auto score_bin = tally.scores_[score];
1,653,400✔
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,653,400✔
490
            source_regions_.tally_task(sr, g).push_back(task);
1,653,400✔
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,653,400✔
495
          }
496
        }
497
      }
498
      // Reset all the filter matches for the next tally event.
499
      for (auto& match : p.filter_matches())
4,958,960✔
500
        match.bins_present_ = false;
3,780,280✔
501
    }
502
  }
1,028,020✔
503
  openmc::simulation::time_tallies.stop();
826✔
504

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

508
// Set the volume accumulators to zero for all tallies
509
void FlatSourceDomain::reset_tally_volumes()
5,231✔
510
{
511
  if (volume_normalized_flux_tallies_) {
5,231✔
512
#pragma omp parallel for
2,160✔
513
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,750✔
514
      auto& tensor = tally_volumes_[i];
4,950✔
515
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,950✔
516
    }
517
  }
518
}
5,231✔
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
6,033✔
529
{
530
  // Eigenvalue mode normalization
531
  if (settings::run_mode == RunMode::EIGENVALUE) {
6,033✔
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_);
1,750✔
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_) {
4,283✔
552
    return 1.0;
398✔
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;
3,885✔
560
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
2,128✔
561
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
14,678,157✔
562
    int material = source_regions_.material(sr);
14,676,400✔
563
    double volume = source_regions_.volume(sr) * simulation_volume_;
14,676,400✔
564
    for (int g = 0; g < negroups_; g++) {
29,895,680✔
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;
15,219,280✔
569
      if (material != MATERIAL_VOID) {
15,219,280✔
570
        sigma_t =
15,009,040✔
571
          sigma_t_[material * negroups_ + g] * source_regions_.density_mult(sr);
15,009,040✔
572
      }
573
      simulation_external_source_strength +=
15,219,280✔
574
        source_regions_.external_source(sr, g) * sigma_t * volume;
15,219,280✔
575
    }
576
  }
577

578
  // Step 2 is to determine the total user-specified external source strength
579
  double user_external_source_strength = 0.0;
3,885✔
580
  for (auto& ext_source : model::external_sources) {
7,770✔
581
    user_external_source_strength += ext_source->strength();
3,885✔
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 =
3,885✔
587
    user_external_source_strength / simulation_external_source_strength;
588

589
  return source_normalization_factor;
3,885✔
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()
5,231✔
602
{
603
  openmc::simulation::time_tallies.start();
5,231✔
604

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

608
  double source_normalization_factor =
609
    compute_fixed_source_normalization_factor();
5,231✔
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
2,856✔
615
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,305,175✔
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_;
15,302,800✔
626

627
    int material = source_regions_.material(sr);
15,302,800✔
628
    double density_mult = source_regions_.density_mult(sr);
15,302,800✔
629

630
    for (int g = 0; g < negroups_; g++) {
32,032,700✔
631
      double flux =
632
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,729,900✔
633

634
      // Determine numerical score value
635
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,522,400✔
636
        double score = 0.0;
22,792,500✔
637
        switch (task.score_type) {
22,792,500!
638

639
        case SCORE_FLUX:
19,534,100✔
640
          score = flux * volume;
19,534,100✔
641
          break;
19,534,100✔
642

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

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

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

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

668
        case SCORE_KAPPA_FISSION:
600✔
669
          score = flux * volume * kappa_fission_[material * negroups_ + g] *
600✔
670
                  density_mult;
671
          break;
600✔
672

673
        default:
674
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
675
                      "total, fission, nu-fission, kappa-fission, and events "
676
                      "are supported in random ray mode.");
677
          break;
678
        }
679
        // Apply score to the appropriate tally bin
680
        Tally& tally {*model::tallies[task.tally_idx]};
22,792,500✔
681
#pragma omp atomic
682
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,792,500✔
683
          score;
684
      }
685
    }
686

687
    // For flux tallies, the total volume of the spatial region is needed
688
    // for normalizing the flux. We store this volume in a separate tensor.
689
    // We only contribute to each volume tally bin once per FSR.
690
    if (volume_normalized_flux_tallies_) {
15,302,800✔
691
      for (const auto& task : source_regions_.volume_task(sr)) {
36,078,200✔
692
        if (task.score_type == SCORE_FLUX) {
20,921,700✔
693
#pragma omp atomic
694
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
18,881,900✔
695
            volume;
696
        }
697
      }
698
    }
699
  } // end FSR loop
700

701
  // Normalize any flux scores by the total volume of the FSRs scoring to that
702
  // bin. To do this, we loop over all tallies, and then all filter bins,
703
  // and then scores. For each score, we check the tally data structure to
704
  // see what index that score corresponds to. If that score is a flux score,
705
  // then we divide it by volume.
706
  if (volume_normalized_flux_tallies_) {
5,231✔
707
    for (int i = 0; i < model::tallies.size(); i++) {
14,850✔
708
      Tally& tally {*model::tallies[i]};
10,890✔
709
#pragma omp parallel for
5,940✔
710
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
704,900✔
711
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,419,500✔
712
          auto score_type = tally.scores_[score_idx];
719,550✔
713
          if (score_type == SCORE_FLUX) {
719,550✔
714
            double vol = tally_volumes_[i](bin, score_idx);
699,950✔
715
            if (vol > 0.0) {
699,950!
716
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
699,950✔
717
            }
718
          }
719
        }
720
      }
721
    }
722
  }
723

724
  openmc::simulation::time_tallies.stop();
5,231✔
725
}
5,231✔
726

UNCOV
727
double FlatSourceDomain::evaluate_flux_at_point(
×
728
  Position r, int64_t sr, int g) const
729
{
UNCOV
730
  return source_regions_.scalar_flux_final(sr, g) /
×
UNCOV
731
         (settings::n_batches - settings::n_inactive);
×
732
}
733

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

748
  // Print header information
UNCOV
749
  print_plot();
×
750

751
  // Outer loop over plots
UNCOV
752
  for (int plt = 0; plt < model::plots.size(); plt++) {
×
753

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

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

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

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

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

812
          bool found = exhaustive_find_cell(p);
×
813
          if (!found) {
×
814
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
815
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
816
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
817
            continue;
818
          }
819

820
          SourceRegionKey sr_key = lookup_source_region_key(p);
×
821
          int64_t sr = -1;
822
          auto it = source_region_map_.find(sr_key);
×
823
          if (it != source_region_map_.end()) {
×
824
            sr = it->second;
825
          }
826

827
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
828
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
829

830
          if (variance_reduction::weight_windows.size() == 1) {
×
831
            WeightWindow ww =
832
              variance_reduction::weight_windows[0]->get_weight_window(p);
×
833
            float weight = ww.lower_weight;
834
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
835
            if (weight < min_weight)
×
836
              min_weight = weight;
837
          }
838
        }
×
839
      }
840
    }
841

842
    double source_normalization_factor =
UNCOV
843
      compute_fixed_source_normalization_factor();
×
844

845
    // Open file for writing
846
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
847

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

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

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

899
    // Plot FSRs
900
    std::fprintf(plot, "SCALARS FSRs float\n");
×
UNCOV
901
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
UNCOV
902
    for (int fsr : voxel_indices) {
×
UNCOV
903
      float value = future_prn(10, fsr);
×
904
      value = convert_to_big_endian<float>(value);
×
905
      std::fwrite(&value, sizeof(float), 1, plot);
×
906
    }
907

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

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

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

UNCOV
978
    std::fclose(plot);
×
UNCOV
979
  }
×
UNCOV
980
}
×
981

982
void FlatSourceDomain::apply_external_source_to_source_region(
4,588✔
983
  int src_idx, SourceRegionHandle& srh)
984
{
985
  auto s = model::external_sources[src_idx].get();
4,588✔
986
  auto is = dynamic_cast<IndependentSource*>(s);
4,588!
987
  auto discrete = dynamic_cast<Discrete*>(is->energy());
4,588!
988
  double strength_factor = is->strength();
4,588✔
989
  const auto& discrete_energies = discrete->x();
4,588✔
990
  const auto& discrete_probs = discrete->prob();
4,588✔
991

992
  srh.external_source_present() = 1;
4,588✔
993

994
  for (int i = 0; i < discrete_energies.size(); i++) {
9,308✔
995
    int g = data::mg.get_group_index(discrete_energies[i]);
4,720✔
996
    srh.external_source(g) += discrete_probs[i] * strength_factor;
4,720✔
997
  }
998
}
4,588✔
999

1000
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
432✔
1001
  int src_idx, int target_material_id, const vector<int32_t>& instances)
1002
{
1003
  Cell& cell = *model::cells[i_cell];
432✔
1004

1005
  if (cell.type_ != Fill::MATERIAL)
432!
UNCOV
1006
    return;
×
1007

1008
  for (int j : instances) {
30,928✔
1009
    int cell_material_idx = cell.material(j);
30,496✔
1010
    int cell_material_id;
1011
    if (cell_material_idx == MATERIAL_VOID) {
30,496✔
1012
      cell_material_id = MATERIAL_VOID;
256✔
1013
    } else {
1014
      cell_material_id = model::materials[cell_material_idx]->id();
30,240✔
1015
    }
1016
    if (target_material_id == C_NONE ||
30,496✔
1017
        cell_material_id == target_material_id) {
1018
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,976✔
1019
      external_volumetric_source_map_[source_region].push_back(src_idx);
2,976✔
1020
    }
1021
  }
1022
}
1023

1024
void FlatSourceDomain::apply_external_source_to_cell_and_children(
464✔
1025
  int32_t i_cell, int src_idx, int32_t target_material_id)
1026
{
1027
  Cell& cell = *model::cells[i_cell];
464✔
1028

1029
  if (cell.type_ == Fill::MATERIAL) {
464✔
1030
    vector<int> instances(cell.n_instances());
432✔
1031
    std::iota(instances.begin(), instances.end(), 0);
432✔
1032
    apply_external_source_to_cell_instances(
432✔
1033
      i_cell, src_idx, target_material_id, instances);
1034
  } else if (target_material_id == C_NONE) {
464!
1035
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
UNCOV
1036
      cell.get_contained_cells(0, nullptr);
×
1037
    for (const auto& pair : cell_instance_list) {
×
UNCOV
1038
      int32_t i_child_cell = pair.first;
×
UNCOV
1039
      apply_external_source_to_cell_instances(
×
UNCOV
1040
        i_child_cell, src_idx, target_material_id, pair.second);
×
1041
    }
UNCOV
1042
  }
×
1043
}
464✔
1044

1045
void FlatSourceDomain::count_external_source_regions()
1,219✔
1046
{
1047
  n_external_source_regions_ = 0;
1,219✔
1048
#pragma omp parallel for reduction(+ : n_external_source_regions_)
687✔
1049
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,185,292✔
1050
    if (source_regions_.external_source_present(sr)) {
1,184,760✔
1051
      n_external_source_regions_++;
157,250✔
1052
    }
1053
  }
1054
}
1,219✔
1055

1056
void FlatSourceDomain::convert_external_sources()
417✔
1057
{
1058
  // Loop over external sources
1059
  for (int es = 0; es < model::external_sources.size(); es++) {
834✔
1060

1061
    // Extract source information
1062
    Source* s = model::external_sources[es].get();
417✔
1063
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
417!
1064
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
417!
1065
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
417✔
1066
    double strength_factor = is->strength();
417✔
1067

1068
    // If there is no domain constraint specified, then this must be a point
1069
    // source. In this case, we need to find the source region that contains the
1070
    // point source and apply or relate it to the external source.
1071
    if (is->domain_ids().size() == 0) {
417✔
1072

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

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

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

1125
void FlatSourceDomain::flux_swap()
12,662✔
1126
{
1127
  source_regions_.flux_swap();
12,662✔
1128
}
12,662✔
1129

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

1138
  n_materials_ = data::mg.macro_xs_.size();
721✔
1139
  for (int i = 0; i < n_materials_; i++) {
2,706✔
1140
    auto& m = data::mg.macro_xs_[i];
1,985✔
1141
    for (int g_out = 0; g_out < negroups_; g_out++) {
10,643✔
1142
      if (m.exists_in_model) {
8,658✔
1143
        double sigma_t =
1144
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
8,594✔
1145
        sigma_t_.push_back(sigma_t);
8,594✔
1146

1147
        if (sigma_t < MINIMUM_MACRO_XS) {
8,594✔
1148
          Material* mat = model::materials[i].get();
16✔
1149
          warning(fmt::format(
16✔
1150
            "Material \"{}\" (id: {}) has a group {} total cross section "
1151
            "({:.3e}) below the minimum threshold "
1152
            "({:.3e}). Material will be treated as pure void.",
1153
            mat->name(), mat->id(), g_out, sigma_t, MINIMUM_MACRO_XS));
32✔
1154
        }
1155

1156
        double nu_sigma_f =
1157
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
8,594✔
1158
        nu_sigma_f_.push_back(nu_sigma_f);
8,594✔
1159

1160
        double sigma_f =
1161
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
8,594✔
1162
        sigma_f_.push_back(sigma_f);
8,594✔
1163

1164
        double chi =
1165
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
8,594✔
1166
        if (!std::isfinite(chi)) {
8,594✔
1167
          // MGXS interface may return NaN in some cases, such as when material
1168
          // is fissionable but has very small sigma_f.
1169
          chi = 0.0;
640✔
1170
        }
1171
        chi_.push_back(chi);
8,594✔
1172

1173
        double kappa_fission =
1174
          m.get_xs(MgxsType::KAPPA_FISSION, g_out, NULL, NULL, NULL, t, a);
8,594✔
1175
        kappa_fission_.push_back(kappa_fission);
8,594✔
1176

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

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

1211
  // First, find the maximum forward flux value
1212
  double max_flux = 0.0;
65✔
1213
#pragma omp parallel for reduction(max : max_flux)
37✔
1214
  for (int64_t se = 0; se < n_source_elements(); se++) {
155,548✔
1215
    double flux = source_regions_.scalar_flux_final(se);
155,520✔
1216
    if (flux > max_flux) {
155,520✔
1217
      max_flux = flux;
25✔
1218
    }
1219
  }
1220

1221
  // Then, compute the adjoint source for each source region
1222
#pragma omp parallel for
37✔
1223
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1224
    for (int g = 0; g < negroups_; g++) {
311,040✔
1225
      double flux = source_regions_.scalar_flux_final(sr, g);
155,520✔
1226
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
155,520✔
1227
        source_regions_.external_source(sr, g) = 0.0;
325✔
1228
      } else {
1229
        source_regions_.external_source(sr, g) = 1.0 / flux;
155,195✔
1230
      }
1231
      if (flux > 0.0) {
155,520✔
1232
        source_regions_.external_source_present(sr) = 1;
155,195✔
1233
      }
1234
      source_regions_.scalar_flux_final(sr, g) = 0.0;
155,520✔
1235
    }
1236
  }
1237

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

1277
void FlatSourceDomain::transpose_scattering_matrix()
81✔
1278
{
1279
  // Transpose the inner two dimensions for each material
1280
  for (int m = 0; m < n_materials_; ++m) {
306✔
1281
    int material_offset = m * negroups_ * negroups_;
225✔
1282
    for (int i = 0; i < negroups_; ++i) {
643✔
1283
      for (int j = i + 1; j < negroups_; ++j) {
1,091✔
1284
        // Calculate indices of the elements to swap
1285
        int idx1 = material_offset + i * negroups_ + j;
673✔
1286
        int idx2 = material_offset + j * negroups_ + i;
673✔
1287

1288
        // Swap the elements to transpose the matrix
1289
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
673✔
1290
      }
1291
    }
1292
  }
1293
}
81✔
1294

UNCOV
1295
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
×
1296
{
1297
  // Ensure array is correct size
UNCOV
1298
  flux.resize(n_source_regions() * negroups_);
×
1299
// Serialize the final fluxes for output
1300
#pragma omp parallel for
1301
  for (int64_t se = 0; se < n_source_elements(); se++) {
×
1302
    flux[se] = source_regions_.scalar_flux_final(se);
1303
  }
UNCOV
1304
}
×
1305

1306
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
946✔
1307
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1308
  bool is_target_void)
1309
{
1310
  Cell& cell = *model::cells[i_cell];
946✔
1311
  if (cell.type_ != Fill::MATERIAL)
946!
UNCOV
1312
    return;
×
1313
  for (int32_t j : instances) {
175,620✔
1314
    int cell_material_idx = cell.material(j);
174,674✔
1315
    int cell_material_id = (cell_material_idx == C_NONE)
1316
                             ? C_NONE
174,674✔
1317
                             : model::materials[cell_material_idx]->id();
174,673✔
1318

1319
    if ((target_material_id == C_NONE && !is_target_void) ||
174,674!
1320
        cell_material_id == target_material_id) {
1321
      int64_t sr = source_region_offsets_[i_cell] + j;
142,674✔
1322
      // Check if the key is already present in the mesh_map_
1323
      if (mesh_map_.find(sr) != mesh_map_.end()) {
142,674!
UNCOV
1324
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1325
                                "applied, but trying to apply mesh idx {}",
UNCOV
1326
          sr, mesh_map_[sr], mesh_idx));
×
1327
      }
1328
      // If the SR has not already been assigned, then we can write to it
1329
      mesh_map_[sr] = mesh_idx;
142,674✔
1330
    }
1331
  }
1332
}
1333

1334
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
817✔
1335
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1336
{
1337
  Cell& cell = *model::cells[i_cell];
817✔
1338

1339
  if (cell.type_ == Fill::MATERIAL) {
817✔
1340
    vector<int> instances(cell.n_instances());
688✔
1341
    std::iota(instances.begin(), instances.end(), 0);
688✔
1342
    apply_mesh_to_cell_instances(
688✔
1343
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1344
  } else if (target_material_id == C_NONE && !is_target_void) {
817!
1345
    for (int j = 0; j < cell.n_instances(); j++) {
130✔
1346
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1347
        cell.get_contained_cells(j, nullptr);
65✔
1348
      for (const auto& pair : cell_instance_list) {
323✔
1349
        int32_t i_child_cell = pair.first;
258✔
1350
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
258✔
1351
          pair.second, is_target_void);
258✔
1352
      }
1353
    }
65✔
1354
  }
1355
}
817✔
1356

1357
void FlatSourceDomain::apply_meshes()
721✔
1358
{
1359
  // Skip if there are no mappings between mesh IDs and domains
1360
  if (mesh_domain_map_.empty())
721✔
1361
    return;
448✔
1362

1363
  // Loop over meshes
1364
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
626✔
1365
    Mesh* mesh = model::meshes[mesh_idx].get();
353✔
1366
    int mesh_id = mesh->id();
353✔
1367

1368
    // Skip if mesh id is not present in the map
1369
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
353✔
1370
      continue;
16✔
1371

1372
    // Loop over domains associated with the mesh
1373
    for (auto& domain : mesh_domain_map_[mesh_id]) {
674✔
1374
      Source::DomainType domain_type = domain.first;
337✔
1375
      int domain_id = domain.second;
337✔
1376

1377
      if (domain_type == Source::DomainType::MATERIAL) {
337✔
1378
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1379
          if (domain_id == C_NONE) {
160!
UNCOV
1380
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1381
          } else {
1382
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1383
          }
1384
        }
1385
      } else if (domain_type == Source::DomainType::CELL) {
305✔
1386
        int32_t i_cell = model::cell_map[domain_id];
32✔
1387
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1388
      } else if (domain_type == Source::DomainType::UNIVERSE) {
273!
1389
        int32_t i_universe = model::universe_map[domain_id];
273✔
1390
        Universe& universe = *model::universes[i_universe];
273✔
1391
        for (int32_t i_cell : universe.cells_) {
898✔
1392
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
625✔
1393
        }
1394
      }
1395
    }
1396
  }
1397
}
1398

1399
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
1,278,155,423✔
1400
  SourceRegionKey sr_key, Position r, Direction u)
1401
{
1402
  // Case 1: Check if the source region key is already present in the permanent
1403
  // map. This is the most common condition, as any source region visited in a
1404
  // previous power iteration will already be present in the permanent map. If
1405
  // the source region key is found, we translate the key into a specific 1D
1406
  // source region index and return a handle its position in the
1407
  // source_regions_ vector.
1408
  auto it = source_region_map_.find(sr_key);
1,278,155,423✔
1409
  if (it != source_region_map_.end()) {
1,278,155,423✔
1410
    int64_t sr = it->second;
1,237,803,278✔
1411
    return source_regions_.get_source_region_handle(sr);
1,237,803,278✔
1412
  }
1413

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

1422
  // If the key is found in the temporary map, then we return a handle to the
1423
  // source region that is stored in the temporary map.
1424
  if (discovered_source_regions_.contains(sr_key)) {
40,352,145✔
1425
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
37,988,884✔
1426
    discovered_source_regions_.unlock(sr_key);
37,988,884✔
1427
    return handle;
37,988,884✔
1428
  }
1429

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

1458
  // Sanity check on source region id
1459
  GeometryState gs;
2,363,261✔
1460
  gs.r() = r + TINY_BIT * u;
2,363,261✔
1461
  gs.u() = {1.0, 0.0, 0.0};
2,363,261✔
1462
  exhaustive_find_cell(gs);
2,363,261✔
1463
  int64_t sr_found = lookup_base_source_region_idx(gs);
2,363,261✔
1464
  if (sr_found != sr_key.base_source_region_id) {
2,363,261✔
1465
    discovered_source_regions_.unlock(sr_key);
88✔
1466
    SourceRegionHandle handle;
88✔
1467
    handle.is_numerical_fp_artifact_ = true;
88✔
1468
    return handle;
88✔
1469
  }
1470

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

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

1498
  // Call the basic constructor for the source region and store in the parallel
1499
  // map.
1500
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
2,363,173✔
1501
  SourceRegion* sr_ptr =
1502
    discovered_source_regions_.emplace(sr_key, {negroups_, is_linear});
2,363,173✔
1503
  SourceRegionHandle handle {*sr_ptr};
2,363,173✔
1504

1505
  // Determine the material
1506
  int gs_i_cell = gs.lowest_coord().cell();
2,363,173✔
1507
  Cell& cell = *model::cells[gs_i_cell];
2,363,173✔
1508
  int material = cell.material(gs.cell_instance());
2,363,173✔
1509

1510
  // If material total XS is extremely low, just set it to void to avoid
1511
  // problems with 1/Sigma_t
1512
  for (int g = 0; g < negroups_; g++) {
5,035,735✔
1513
    double sigma_t = sigma_t_[material * negroups_ + g];
2,694,714✔
1514
    if (sigma_t < MINIMUM_MACRO_XS) {
2,694,714✔
1515
      material = MATERIAL_VOID;
22,152✔
1516
      break;
22,152✔
1517
    }
1518
  }
1519

1520
  handle.material() = material;
2,363,173✔
1521

1522
  handle.density_mult() = cell.density_mult(gs.cell_instance());
2,363,173✔
1523

1524
  // Store the mesh index (if any) assigned to this source region
1525
  handle.mesh() = mesh_idx;
2,363,173✔
1526

1527
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
2,363,173✔
1528
    // Determine if there are any volumetric sources, and apply them.
1529
    // Volumetric sources are specifc only to the base SR idx.
1530
    auto it_vol =
1531
      external_volumetric_source_map_.find(sr_key.base_source_region_id);
2,310,758✔
1532
    if (it_vol != external_volumetric_source_map_.end()) {
2,310,758✔
1533
      const vector<int>& vol_sources = it_vol->second;
4,576✔
1534
      for (int src_idx : vol_sources) {
9,152✔
1535
        apply_external_source_to_source_region(src_idx, handle);
4,576✔
1536
      }
1537
    }
1538

1539
    // Determine if there are any point sources, and apply them.
1540
    // Point sources are specific to the source region key.
1541
    auto it_point = external_point_source_map_.find(sr_key);
2,310,758✔
1542
    if (it_point != external_point_source_map_.end()) {
2,310,758✔
1543
      const vector<int>& point_sources = it_point->second;
12✔
1544
      for (int src_idx : point_sources) {
24✔
1545
        apply_external_source_to_source_region(src_idx, handle);
12✔
1546
      }
1547
    }
1548

1549
    // Divide external source term by sigma_t
1550
    if (material != C_NONE) {
2,310,758✔
1551
      for (int g = 0; g < negroups_; g++) {
4,623,171✔
1552
        double sigma_t =
1553
          sigma_t_[material * negroups_ + g] * handle.density_mult();
2,334,565✔
1554
        handle.external_source(g) /= sigma_t;
2,334,565✔
1555
      }
1556
    }
1557
  }
1558

1559
  // Compute the combined source term
1560
  update_single_neutron_source(handle);
2,363,173✔
1561

1562
  // Unlock the parallel map. Note: we may be tempted to release
1563
  // this lock earlier, and then just use the source region's lock to protect
1564
  // the flux/source initialization stages above. However, the rest of the code
1565
  // only protects updates to the new flux and volume fields, and assumes that
1566
  // the source is constant for the duration of transport. Thus, using just the
1567
  // source region's lock by itself would result in other threads potentially
1568
  // reading from the source before it is computed, as they won't use the lock
1569
  // when only reading from the SR's source. It would be expensive to protect
1570
  // those operations, whereas generating the SR is only done once, so we just
1571
  // hold the map's bucket lock until the source region is fully initialized.
1572
  discovered_source_regions_.unlock(sr_key);
2,363,173✔
1573

1574
  return handle;
2,363,173✔
1575
}
2,363,261✔
1576

1577
void FlatSourceDomain::finalize_discovered_source_regions()
12,662✔
1578
{
1579
  // Extract keys for entries with a valid volume.
1580
  vector<SourceRegionKey> keys;
12,662✔
1581
  for (const auto& pair : discovered_source_regions_) {
2,375,835✔
1582
    if (pair.second.volume_ > 0.0) {
2,363,173✔
1583
      keys.push_back(pair.first);
2,261,731✔
1584
    }
1585
  }
1586

1587
  if (!keys.empty()) {
12,662✔
1588
    // Sort the keys, so as to ensure reproducible ordering given that source
1589
    // regions may have been added to discovered_source_regions_ in an arbitrary
1590
    // order due to shared memory threading.
1591
    std::sort(keys.begin(), keys.end());
826✔
1592

1593
    // Remember the index of the first new source region
1594
    int64_t start_sr_id = source_regions_.n_source_regions();
826✔
1595

1596
    // Append the source regions in the sorted key order.
1597
    for (const auto& key : keys) {
2,262,557✔
1598
      const SourceRegion& sr = discovered_source_regions_[key];
2,261,731✔
1599
      source_region_map_[key] = source_regions_.n_source_regions();
2,261,731✔
1600
      source_regions_.push_back(sr);
2,261,731✔
1601
    }
1602

1603
    // Map all new source regions to tallies
1604
    convert_source_regions_to_tallies(start_sr_id);
826✔
1605
  }
1606

1607
  discovered_source_regions_.clear();
12,662✔
1608
}
12,662✔
1609

1610
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1611
//
1612
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1613
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1614
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1615
// https://doi.org/10.1016/j.anucene.2018.10.036.
1616
void FlatSourceDomain::apply_transport_stabilization()
12,662✔
1617
{
1618
  // Don't do anything if all in-group scattering
1619
  // cross sections are positive
1620
  if (!is_transport_stabilization_needed_) {
12,662✔
1621
    return;
12,442✔
1622
  }
1623

1624
  // Apply the stabilization factor to all source elements
1625
#pragma omp parallel for
120✔
1626
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1627
    int material = source_regions_.material(sr);
1,200✔
1628
    double density_mult = source_regions_.density_mult(sr);
1,200✔
1629
    if (material == MATERIAL_VOID) {
1,200!
1630
      continue;
1631
    }
1632
    for (int g = 0; g < negroups_; g++) {
85,200✔
1633
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1634
      // negative
1635
      double sigma_s =
1636
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g] *
84,000✔
1637
        density_mult;
84,000✔
1638
      if (sigma_s < 0.0) {
84,000✔
1639
        double sigma_t = sigma_t_[material * negroups_ + g] * density_mult;
22,000✔
1640
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1641
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
1642

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

1653
        // Equation 16 in the above Gunow et al. 2019 paper
1654
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1655
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1656
      }
1657
    }
1658
  }
1659
}
1660

1661
// Determines the base source region index (i.e., a material filled cell
1662
// instance) that corresponds to a particular location in the geometry. Requires
1663
// that the "gs" object passed in has already been initialized and has called
1664
// find_cell etc.
1665
int64_t FlatSourceDomain::lookup_base_source_region_idx(
824,255,052✔
1666
  const GeometryState& gs) const
1667
{
1668
  int i_cell = gs.lowest_coord().cell();
824,255,052✔
1669
  int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
824,255,052✔
1670
  return sr;
824,255,052✔
1671
}
1672

1673
// Determines the index of the mesh (if any) that has been applied
1674
// to a particular base source region index.
1675
int FlatSourceDomain::lookup_mesh_idx(int64_t sr) const
824,254,964✔
1676
{
1677
  int mesh_idx = C_NONE;
824,254,964✔
1678
  auto mesh_it = mesh_map_.find(sr);
824,254,964✔
1679
  if (mesh_it != mesh_map_.end()) {
824,254,964✔
1680
    mesh_idx = mesh_it->second;
462,742,087✔
1681
  }
1682
  return mesh_idx;
824,254,964✔
1683
}
1684

1685
// Determines the source region key that corresponds to a particular location in
1686
// the geometry. This takes into account both the base source region index as
1687
// well as the mesh bin if a mesh is applied to this source region for
1688
// subdivision.
1689
SourceRegionKey FlatSourceDomain::lookup_source_region_key(
1,965,337✔
1690
  const GeometryState& gs) const
1691
{
1692
  int64_t sr = lookup_base_source_region_idx(gs);
1,965,337✔
1693
  int64_t mesh_bin = lookup_mesh_bin(sr, gs.r());
1,965,337✔
1694
  return SourceRegionKey {sr, mesh_bin};
1,965,337✔
1695
}
1696

1697
// Determines the mesh bin that corresponds to a particular base source region
1698
// index and position.
1699
int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const
1,965,337✔
1700
{
1701
  int mesh_idx = lookup_mesh_idx(sr);
1,965,337✔
1702
  int mesh_bin = 0;
1,965,337✔
1703
  if (mesh_idx != C_NONE) {
1,965,337✔
1704
    mesh_bin = model::meshes[mesh_idx]->get_bin(r);
1,222,837✔
1705
  }
1706
  return mesh_bin;
1,965,337✔
1707
}
1708

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