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

openmc-dev / openmc / 20886241544

10 Jan 2026 11:46PM UTC coverage: 82.205% (+0.007%) from 82.198%
20886241544

Pull #3720

github

web-flow
Merge 2a479dcac into 37e2feb34
Pull Request #3720: Support cell densities in the random ray solver

17112 of 23671 branches covered (72.29%)

Branch coverage included in aggregate %.

44 of 49 new or added lines in 6 files covered. (89.8%)

1 existing line in 1 file now uncovered.

55282 of 64394 relevant lines covered (85.85%)

43685814.8 hits per line

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

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

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

57
  // Initialize tally volumes
58
  if (volume_normalized_flux_tallies_) {
673✔
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());
673!
73
  SpatialDistribution* space_dist = is->space();
673✔
74
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
673!
75
  Position dims = sb->upper_right() - sb->lower_left();
673✔
76
  simulation_volume_ = dims.x * dims.y * dims.z;
673✔
77
}
673✔
78

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

88
#pragma omp parallel for
6,732✔
89
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,722,055✔
90
    source_regions_.scalar_flux_new(se) = 0.0;
36,716,455✔
91
  }
92
}
12,332✔
93

94
void FlatSourceDomain::accumulate_iteration_flux()
5,066✔
95
{
96
#pragma omp parallel for
2,766✔
97
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,730,400✔
98
    source_regions_.scalar_flux_final(se) +=
16,728,100✔
99
      source_regions_.scalar_flux_new(se);
16,728,100✔
100
  }
101
}
5,066✔
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,332✔
150
{
151
  simulation::time_update_src.start();
12,332✔
152

153
#pragma omp parallel for
6,732✔
154
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,412,795✔
155
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
32,407,195✔
156
    update_single_neutron_source(srh);
32,407,195✔
157
  }
158

159
  simulation::time_update_src.stop();
12,332✔
160
}
12,332✔
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,332✔
225
{
226
  int64_t n_hits = 0;
12,332✔
227
  double inverse_batch = 1.0 / simulation::current_batch;
12,332✔
228

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

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

235
    // Increment the number of hits if cell was hit this iteration
236
    if (volume_iteration) {
33,435,035✔
237
      n_hits++;
29,375,880✔
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,435,035✔
243
      source_regions_.is_small(sr) = 1;
6,812,705✔
244
    } else {
245
      source_regions_.is_small(sr) = 0;
26,622,330✔
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,435,035!
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,225,435✔
259
      if (source_regions_.external_source_present(sr) ||
60,262,470✔
260
          source_regions_.is_small(sr)) {
28,037,035✔
261
        volume = volume_iteration;
11,000,725✔
262
      } else {
263
        volume = volume_simulation_avg;
21,224,710✔
264
      }
265
      break;
32,225,435✔
266
    default:
267
      fatal_error("Invalid volume estimator type");
268
    }
269

270
    for (int g = 0; g < negroups_; g++) {
71,329,810✔
271
      // There are three scenarios we need to consider:
272
      if (volume_iteration > 0.0) {
37,894,775✔
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,835,470✔
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,894,775!
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,332✔
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,640✔
314
{
315
  double fission_rate_old = 0;
2,640✔
316
  double fission_rate_new = 0;
2,640✔
317

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

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

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

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

335
    double sr_fission_source_old = 0;
322,390✔
336
    double sr_fission_source_new = 0;
322,390✔
337

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

508
// Set the volume accumulators to zero for all tallies
509
void FlatSourceDomain::reset_tally_volumes()
5,066✔
510
{
511
  if (volume_normalized_flux_tallies_) {
5,066✔
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,066✔
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
5,739✔
529
{
530
  // Eigenvalue mode normalization
531
  if (settings::run_mode == RunMode::EIGENVALUE) {
5,739✔
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,521✔
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,218✔
552
    return 1.0;
333✔
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,066✔
602
{
603
  openmc::simulation::time_tallies.start();
5,066✔
604

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

608
  double source_normalization_factor =
609
    compute_fixed_source_normalization_factor();
5,066✔
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,766✔
615
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,304,200✔
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,301,900✔
626

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

630
    for (int g = 0; g < negroups_; g++) {
32,030,000✔
631
      double flux =
632
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,728,100✔
633

634
      // Determine numerical score value
635
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,520,000✔
636
        double score = 0.0;
22,791,900✔
637
        switch (task.score_type) {
22,791,900!
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
        default:
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]};
22,791,900✔
676
#pragma omp atomic
677
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,791,900✔
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_) {
15,301,900✔
686
      for (const auto& task : source_regions_.volume_task(sr)) {
36,078,200✔
687
        if (task.score_type == SCORE_FLUX) {
20,921,700✔
688
#pragma omp atomic
689
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
18,881,900✔
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_) {
5,066✔
702
    for (int i = 0; i < model::tallies.size(); i++) {
14,850✔
703
      Tally& tally {*model::tallies[i]};
10,890✔
704
#pragma omp parallel for
5,940✔
705
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
704,900✔
706
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,419,500✔
707
          auto score_type = tally.scores_[score_idx];
719,550✔
708
          if (score_type == SCORE_FLUX) {
719,550✔
709
            double vol = tally_volumes_[i](bin, score_idx);
699,950✔
710
            if (vol > 0.0) {
699,950!
711
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
699,950✔
712
            }
713
          }
714
        }
715
      }
716
    }
717
  }
718

719
  openmc::simulation::time_tallies.stop();
5,066✔
720
}
5,066✔
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)
793
    for (int z = 0; z < Nz; z++) {
×
794
      for (int y = 0; y < Ny; y++) {
×
795
        for (int x = 0; x < Nx; x++) {
×
796
          Position sample;
797
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
798
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
799
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
800
          Particle p;
×
801
          p.r() = sample;
802
          p.r_last() = sample;
803
          p.E() = 1.0;
804
          p.E_last() = 1.0;
805
          p.u() = {1.0, 0.0, 0.0};
806

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

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

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

825
          if (variance_reduction::weight_windows.size() == 1) {
×
826
            WeightWindow ww =
827
              variance_reduction::weight_windows[0]->get_weight_window(p);
×
828
            float weight = ww.lower_weight;
829
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
830
            if (weight < min_weight)
×
831
              min_weight = weight;
832
          }
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);
×
NEW
927
              double sigma_f = sigma_f_[mat * negroups_ + g] *
×
NEW
928
                               source_regions_.density_mult(fsr);
×
UNCOV
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) {
×
NEW
949
              sigma_t = sigma_t_[mat * negroups_ + g] *
×
NEW
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(
4,588✔
978
  int src_idx, SourceRegionHandle& srh)
979
{
980
  auto s = model::external_sources[src_idx].get();
4,588✔
981
  auto is = dynamic_cast<IndependentSource*>(s);
4,588!
982
  auto discrete = dynamic_cast<Discrete*>(is->energy());
4,588!
983
  double strength_factor = is->strength();
4,588✔
984
  const auto& discrete_energies = discrete->x();
4,588✔
985
  const auto& discrete_probs = discrete->prob();
4,588✔
986

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

989
  for (int i = 0; i < discrete_energies.size(); i++) {
9,308✔
990
    int g = data::mg.get_group_index(discrete_energies[i]);
4,720✔
991
    srh.external_source(g) += discrete_probs[i] * strength_factor;
4,720✔
992
  }
993
}
4,588✔
994

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

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

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

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

1024
  if (cell.type_ == Fill::MATERIAL) {
464✔
1025
    vector<int> instances(cell.n_instances());
432✔
1026
    std::iota(instances.begin(), instances.end(), 0);
432✔
1027
    apply_external_source_to_cell_instances(
432✔
1028
      i_cell, src_idx, target_material_id, instances);
1029
  } else if (target_material_id == C_NONE) {
464!
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
}
464✔
1039

1040
void FlatSourceDomain::count_external_source_regions()
1,171✔
1041
{
1042
  n_external_source_regions_ = 0;
1,171✔
1043
#pragma omp parallel for reduction(+ : n_external_source_regions_)
660✔
1044
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,185,091✔
1045
    if (source_regions_.external_source_present(sr)) {
1,184,580✔
1046
      n_external_source_regions_++;
157,250✔
1047
    }
1048
  }
1049
}
1,171✔
1050

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

1056
    // Extract source information
1057
    Source* s = model::external_sources[es].get();
417✔
1058
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
417!
1059
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
417!
1060
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
417✔
1061
    double strength_factor = is->strength();
417✔
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) {
417✔
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());
17!
1071
      GeometryState gs;
17✔
1072
      gs.r() = sp->r();
17✔
1073
      gs.r_last() = sp->r();
17✔
1074
      gs.u() = {1.0, 0.0, 0.0};
17✔
1075
      bool found = exhaustive_find_cell(gs);
17✔
1076
      if (!found) {
17!
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);
17✔
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);
17✔
1092

1093
    } else {
17✔
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) {
400✔
1097
        for (int32_t material_id : domain_ids) {
32✔
1098
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1099
            apply_external_source_to_cell_and_children(i_cell, es, material_id);
80✔
1100
          }
1101
        }
1102
      } else if (is->domain_type() == Source::DomainType::CELL) {
384✔
1103
        for (int32_t cell_id : domain_ids) {
32✔
1104
          int32_t i_cell = model::cell_map[cell_id];
16✔
1105
          apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
16✔
1106
        }
1107
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
368!
1108
        for (int32_t universe_id : domain_ids) {
736✔
1109
          int32_t i_universe = model::universe_map[universe_id];
368✔
1110
          Universe& universe = *model::universes[i_universe];
368✔
1111
          for (int32_t i_cell : universe.cells_) {
736✔
1112
            apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
368✔
1113
          }
1114
        }
1115
      }
1116
    }
1117
  } // End loop over external sources
1118
}
417✔
1119

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

1125
void FlatSourceDomain::flatten_xs()
673✔
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;
673✔
1131
  const int a = 0;
673✔
1132

1133
  n_materials_ = data::mg.macro_xs_.size();
673✔
1134
  for (int i = 0; i < n_materials_; i++) {
2,514✔
1135
    auto& m = data::mg.macro_xs_[i];
1,841✔
1136
    for (int g_out = 0; g_out < negroups_; g_out++) {
10,211✔
1137
      if (m.exists_in_model) {
8,370✔
1138
        double sigma_t =
1139
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
8,306✔
1140
        sigma_t_.push_back(sigma_t);
8,306✔
1141

1142
        if (sigma_t < MINIMUM_MACRO_XS) {
8,306✔
1143
          Material* mat = model::materials[i].get();
16✔
1144
          warning(fmt::format(
16✔
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));
32✔
1149
        }
1150

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

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

1159
        double chi =
1160
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
8,306✔
1161
        if (!std::isfinite(chi)) {
8,306✔
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;
576✔
1165
        }
1166
        chi_.push_back(chi);
8,306✔
1167

1168
        for (int g_in = 0; g_in < negroups_; g_in++) {
271,590✔
1169
          double sigma_s =
1170
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
263,284✔
1171
          sigma_s_.push_back(sigma_s);
263,284✔
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)
263,284✔
1176
            is_transport_stabilization_needed_ = true;
880✔
1177
        }
1178
      } else {
1179
        sigma_t_.push_back(0);
64✔
1180
        nu_sigma_f_.push_back(0);
64✔
1181
        sigma_f_.push_back(0);
64✔
1182
        chi_.push_back(0);
64✔
1183
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1184
          sigma_s_.push_back(0);
64✔
1185
        }
1186
      }
1187
    }
1188
  }
1189
}
673✔
1190

1191
void FlatSourceDomain::set_adjoint_sources()
65✔
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;
65✔
1203
#pragma omp parallel for reduction(max : max_flux)
37✔
1204
  for (int64_t se = 0; se < n_source_elements(); se++) {
155,548✔
1205
    double flux = source_regions_.scalar_flux_final(se);
155,520✔
1206
    if (flux > max_flux) {
155,520✔
1207
      max_flux = flux;
25✔
1208
    }
1209
  }
1210

1211
  // Then, compute the adjoint source for each source region
1212
#pragma omp parallel for
37✔
1213
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1214
    for (int g = 0; g < negroups_; g++) {
311,040✔
1215
      double flux = source_regions_.scalar_flux_final(sr, g);
155,520✔
1216
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
155,520✔
1217
        source_regions_.external_source(sr, g) = 0.0;
325✔
1218
      } else {
1219
        source_regions_.external_source(sr, g) = 1.0 / flux;
155,195✔
1220
      }
1221
      if (flux > 0.0) {
155,520✔
1222
        source_regions_.external_source_present(sr) = 1;
155,195✔
1223
      }
1224
      source_regions_.scalar_flux_final(sr, g) = 0.0;
155,520✔
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
37✔
1243
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1244
    if (source_regions_.is_small(sr)) {
155,520!
1245
      for (int g = 0; g < negroups_; g++) {
×
1246
        source_regions_.external_source(sr, g) = 0.0;
1247
      }
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
37✔
1254
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1255
    int material = source_regions_.material(sr);
155,520✔
1256
    if (material == MATERIAL_VOID) {
155,520!
1257
      continue;
1258
    }
1259
    for (int g = 0; g < negroups_; g++) {
311,040✔
1260
      double sigma_t =
1261
        sigma_t_[material * negroups_ + g] * source_regions_.density_mult(sr);
155,520✔
1262
      source_regions_.external_source(sr, g) /= sigma_t;
155,520✔
1263
    }
1264
  }
1265
}
65✔
1266

1267
void FlatSourceDomain::transpose_scattering_matrix()
81✔
1268
{
1269
  // Transpose the inner two dimensions for each material
1270
  for (int m = 0; m < n_materials_; ++m) {
306✔
1271
    int material_offset = m * negroups_ * negroups_;
225✔
1272
    for (int i = 0; i < negroups_; ++i) {
643✔
1273
      for (int j = i + 1; j < negroups_; ++j) {
1,091✔
1274
        // Calculate indices of the elements to swap
1275
        int idx1 = material_offset + i * negroups_ + j;
673✔
1276
        int idx2 = material_offset + j * negroups_ + i;
673✔
1277

1278
        // Swap the elements to transpose the matrix
1279
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
673✔
1280
      }
1281
    }
1282
  }
1283
}
81✔
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
1291
  for (int64_t se = 0; se < n_source_elements(); se++) {
×
1292
    flux[se] = source_regions_.scalar_flux_final(se);
1293
  }
1294
}
×
1295

1296
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
802✔
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];
802✔
1301
  if (cell.type_ != Fill::MATERIAL)
802!
1302
    return;
×
1303
  for (int32_t j : instances) {
175,332✔
1304
    int cell_material_idx = cell.material(j);
174,530✔
1305
    int cell_material_id = (cell_material_idx == C_NONE)
1306
                             ? C_NONE
174,530✔
1307
                             : model::materials[cell_material_idx]->id();
174,529✔
1308

1309
    if ((target_material_id == C_NONE && !is_target_void) ||
174,530!
1310
        cell_material_id == target_material_id) {
1311
      int64_t sr = source_region_offsets_[i_cell] + j;
142,530✔
1312
      // Check if the key is already present in the mesh_map_
1313
      if (mesh_map_.find(sr) != mesh_map_.end()) {
142,530!
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;
142,530✔
1320
    }
1321
  }
1322
}
1323

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

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

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

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

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

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

1367
      if (domain_type == Source::DomainType::MATERIAL) {
289✔
1368
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1369
          if (domain_id == C_NONE) {
160!
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);
160✔
1373
          }
1374
        }
1375
      } else if (domain_type == Source::DomainType::CELL) {
257✔
1376
        int32_t i_cell = model::cell_map[domain_id];
32✔
1377
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1378
      } else if (domain_type == Source::DomainType::UNIVERSE) {
225!
1379
        int32_t i_universe = model::universe_map[domain_id];
225✔
1380
        Universe& universe = *model::universes[i_universe];
225✔
1381
        for (int32_t i_cell : universe.cells_) {
706✔
1382
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
481✔
1383
        }
1384
      }
1385
    }
1386
  }
1387
}
1388

1389
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
1,258,680,209✔
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);
1,258,680,209✔
1399
  if (it != source_region_map_.end()) {
1,258,680,209✔
1400
    int64_t sr = it->second;
1,220,272,721✔
1401
    return source_regions_.get_source_region_handle(sr);
1,220,272,721✔
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);
38,407,488✔
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)) {
38,407,488✔
1415
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
36,044,623✔
1416
    discovered_source_regions_.unlock(sr_key);
36,044,623✔
1417
    return handle;
36,044,623✔
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;
2,362,865✔
1450
  gs.r() = r + TINY_BIT * u;
2,362,865✔
1451
  gs.u() = {1.0, 0.0, 0.0};
2,362,865✔
1452
  exhaustive_find_cell(gs);
2,362,865✔
1453
  int64_t sr_found = lookup_base_source_region_idx(gs);
2,362,865✔
1454
  if (sr_found != sr_key.base_source_region_id) {
2,362,865✔
1455
    discovered_source_regions_.unlock(sr_key);
88✔
1456
    SourceRegionHandle handle;
88✔
1457
    handle.is_numerical_fp_artifact_ = true;
88✔
1458
    return handle;
88✔
1459
  }
1460

1461
  // Sanity check on mesh bin
1462
  int mesh_idx = lookup_mesh_idx(sr_key.base_source_region_id);
2,362,777✔
1463
  if (mesh_idx == C_NONE) {
2,362,777✔
1464
    if (sr_key.mesh_bin != 0) {
390,544!
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();
1,972,233✔
1472
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,972,233✔
1473
    if (bin_found != sr_key.mesh_bin) {
1,972,233!
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;
2,362,777✔
1491
  SourceRegion* sr_ptr =
1492
    discovered_source_regions_.emplace(sr_key, {negroups_, is_linear});
2,362,777✔
1493
  SourceRegionHandle handle {*sr_ptr};
2,362,777✔
1494

1495
  // Determine the material
1496
  int gs_i_cell = gs.lowest_coord().cell();
2,362,777✔
1497
  Cell& cell = *model::cells[gs_i_cell];
2,362,777✔
1498
  int material = cell.material(gs.cell_instance());
2,362,777✔
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++) {
5,034,547✔
1503
    double sigma_t = sigma_t_[material * negroups_ + g];
2,693,922✔
1504
    if (sigma_t < MINIMUM_MACRO_XS) {
2,693,922✔
1505
      material = MATERIAL_VOID;
22,152✔
1506
      break;
22,152✔
1507
    }
1508
  }
1509

1510
  handle.material() = material;
2,362,777✔
1511

1512
  handle.density_mult() = cell.density_mult(gs.cell_instance());
2,362,777✔
1513

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

1517
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
2,362,777✔
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);
2,310,758✔
1522
    if (it_vol != external_volumetric_source_map_.end()) {
2,310,758✔
1523
      const vector<int>& vol_sources = it_vol->second;
4,576✔
1524
      for (int src_idx : vol_sources) {
9,152✔
1525
        apply_external_source_to_source_region(src_idx, handle);
4,576✔
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);
2,310,758✔
1532
    if (it_point != external_point_source_map_.end()) {
2,310,758✔
1533
      const vector<int>& point_sources = it_point->second;
12✔
1534
      for (int src_idx : point_sources) {
24✔
1535
        apply_external_source_to_source_region(src_idx, handle);
12✔
1536
      }
1537
    }
1538

1539
    // Divide external source term by sigma_t
1540
    if (material != C_NONE) {
2,310,758✔
1541
      for (int g = 0; g < negroups_; g++) {
4,623,171✔
1542
        double sigma_t =
1543
          sigma_t_[material * negroups_ + g] * handle.density_mult();
2,334,565✔
1544
        handle.external_source(g) /= sigma_t;
2,334,565✔
1545
      }
1546
    }
1547
  }
1548

1549
  // Compute the combined source term
1550
  update_single_neutron_source(handle);
2,362,777✔
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);
2,362,777✔
1563

1564
  return handle;
2,362,777✔
1565
}
2,362,865✔
1566

1567
void FlatSourceDomain::finalize_discovered_source_regions()
12,332✔
1568
{
1569
  // Extract keys for entries with a valid volume.
1570
  vector<SourceRegionKey> keys;
12,332✔
1571
  for (const auto& pair : discovered_source_regions_) {
2,375,109✔
1572
    if (pair.second.volume_ > 0.0) {
2,362,777✔
1573
      keys.push_back(pair.first);
2,261,335✔
1574
    }
1575
  }
1576

1577
  if (!keys.empty()) {
12,332✔
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());
793✔
1582

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

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

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

1597
  discovered_source_regions_.clear();
12,332✔
1598
}
12,332✔
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()
12,332✔
1607
{
1608
  // Don't do anything if all in-group scattering
1609
  // cross sections are positive
1610
  if (!is_transport_stabilization_needed_) {
12,332✔
1611
    return;
12,112✔
1612
  }
1613

1614
  // Apply the stabilization factor to all source elements
1615
#pragma omp parallel for
120✔
1616
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1617
    int material = source_regions_.material(sr);
1,200✔
1618
    double density_mult = source_regions_.density_mult(sr);
1,200✔
1619
    if (material == MATERIAL_VOID) {
1,200!
1620
      continue;
1621
    }
1622
    for (int g = 0; g < negroups_; g++) {
85,200✔
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] *
84,000✔
1627
        density_mult;
84,000✔
1628
      if (sigma_s < 0.0) {
84,000✔
1629
        double sigma_t = sigma_t_[material * negroups_ + g] * density_mult;
22,000✔
1630
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1631
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
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;
22,000✔
1642

1643
        // Equation 16 in the above Gunow et al. 2019 paper
1644
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1645
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
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(
809,479,335✔
1656
  const GeometryState& gs) const
1657
{
1658
  int i_cell = gs.lowest_coord().cell();
809,479,335✔
1659
  int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
809,479,335✔
1660
  return sr;
809,479,335✔
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
809,479,247✔
1666
{
1667
  int mesh_idx = C_NONE;
809,479,247✔
1668
  auto mesh_it = mesh_map_.find(sr);
809,479,247✔
1669
  if (mesh_it != mesh_map_.end()) {
809,479,247✔
1670
    mesh_idx = mesh_it->second;
447,966,370✔
1671
  }
1672
  return mesh_idx;
809,479,247✔
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(
1,932,337✔
1680
  const GeometryState& gs) const
1681
{
1682
  int64_t sr = lookup_base_source_region_idx(gs);
1,932,337✔
1683
  int64_t mesh_bin = lookup_mesh_bin(sr, gs.r());
1,932,337✔
1684
  return SourceRegionKey {sr, mesh_bin};
1,932,337✔
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
1,932,337✔
1690
{
1691
  int mesh_idx = lookup_mesh_idx(sr);
1,932,337✔
1692
  int mesh_bin = 0;
1,932,337✔
1693
  if (mesh_idx != C_NONE) {
1,932,337✔
1694
    mesh_bin = model::meshes[mesh_idx]->get_bin(r);
1,189,837✔
1695
  }
1696
  return mesh_bin;
1,932,337✔
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