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

openmc-dev / openmc / 21320116805

24 Jan 2026 07:07PM UTC coverage: 82.098% (+0.1%) from 81.977%
21320116805

Pull #3737

github

web-flow
Merge 1f0e9b3cc into 3e2f1f521
Pull Request #3737: Temperature feedback support in the random ray solver.

17248 of 23973 branches covered (71.95%)

Branch coverage included in aggregate %.

338 of 364 new or added lines in 11 files covered. (92.86%)

3 existing lines in 2 files now uncovered.

55905 of 65131 relevant lines covered (85.83%)

45689909.79 hits per line

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

72.45
/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_)
785✔
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;
785✔
44
  for (const auto& c : model::cells) {
6,196✔
45
    if (c->type_ != Fill::MATERIAL) {
5,411✔
46
      source_region_offsets_.push_back(-1);
2,417✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
2,994✔
49
      base_source_regions += c->n_instances();
2,994✔
50
    }
51
  }
52

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

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

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

79
void FlatSourceDomain::batch_reset()
13,102✔
80
{
81
// Reset scalar fluxes and iteration volume tallies to zero
82
#pragma omp parallel for
7,152✔
83
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,427,365✔
84
    source_regions_.volume(sr) = 0.0;
32,421,415✔
85
    source_regions_.volume_sq(sr) = 0.0;
32,421,415✔
86
  }
87

88
#pragma omp parallel for
7,152✔
89
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,805,745✔
90
    source_regions_.scalar_flux_new(se) = 0.0;
36,799,795✔
91
  }
92
}
13,102✔
93

94
void FlatSourceDomain::accumulate_iteration_flux()
5,451✔
95
{
96
#pragma omp parallel for
2,976✔
97
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,776,875✔
98
    source_regions_.scalar_flux_final(se) +=
16,774,400✔
99
      source_regions_.scalar_flux_new(se);
16,774,400✔
100
  }
101
}
5,451✔
102

103
void FlatSourceDomain::update_single_neutron_source(SourceRegionHandle& srh)
44,051,006✔
104
{
105
  // Reset all source regions to zero (important for void regions)
106
  for (int g = 0; g < negroups_; g++) {
93,693,190✔
107
    srh.source(g) = 0.0;
49,642,184✔
108
  }
109

110
  // Add scattering + fission source
111
  int material = srh.material();
44,051,006✔
112
  int temp = srh.temperature_idx();
44,051,006✔
113
  double density_mult = srh.density_mult();
44,051,006✔
114
  if (material != MATERIAL_VOID) {
44,051,006✔
115
    double inverse_k_eff = 1.0 / k_eff_;
43,609,358✔
116
    for (int g_out = 0; g_out < negroups_; g_out++) {
92,809,126✔
117
      double sigma_t =
118
        sigma_t_[(material * ntemperature_ + temp) * negroups_ + g_out] *
49,199,768✔
119
        density_mult;
49,199,768✔
120
      double scatter_source = 0.0;
49,199,768✔
121
      double fission_source = 0.0;
49,199,768✔
122

123
      for (int g_in = 0; g_in < negroups_; g_in++) {
137,531,026✔
124
        double scalar_flux = srh.scalar_flux_old(g_in);
88,331,258✔
125
        double sigma_s =
126
          sigma_s_[((material * ntemperature_ + temp) * negroups_ + g_out) *
88,331,258✔
127
                     negroups_ +
88,331,258✔
128
                   g_in] *
88,331,258✔
129
          density_mult;
88,331,258✔
130
        double nu_sigma_f =
131
          nu_sigma_f_[(material * ntemperature_ + temp) * negroups_ + g_in] *
88,331,258✔
132
          density_mult;
88,331,258✔
133
        double chi =
134
          chi_[(material * ntemperature_ + temp) * negroups_ + g_out];
88,331,258✔
135

136
        scatter_source += sigma_s * scalar_flux;
88,331,258✔
137
        if (settings::create_fission_neutrons) {
88,331,258!
138
          fission_source += nu_sigma_f * scalar_flux * chi;
88,331,258✔
139
        }
140
      }
141
      srh.source(g_out) =
49,199,768✔
142
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
49,199,768✔
143
    }
144
  }
145

146
  // Add external source if in fixed source mode
147
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
44,051,006✔
148
    for (int g = 0; g < negroups_; g++) {
89,955,038✔
149
      srh.source(g) += srh.external_source(g);
46,413,541✔
150
    }
151
  }
152
}
44,051,006✔
153

154
// Compute new estimate of scattering + fission sources in each source region
155
// based on the flux estimate from the previous iteration.
156
void FlatSourceDomain::update_all_neutron_sources()
13,102✔
157
{
158
  simulation::time_update_src.start();
13,102✔
159

160
#pragma omp parallel for
7,152✔
161
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,427,365✔
162
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
32,421,415✔
163
    update_single_neutron_source(srh);
32,421,415✔
164
  }
165

166
  simulation::time_update_src.stop();
13,102✔
167
}
13,102✔
168

169
// Normalizes flux and updates simulation-averaged volume estimate
170
void FlatSourceDomain::normalize_scalar_flux_and_volumes(
5,567✔
171
  double total_active_distance_per_iteration)
172
{
173
  double normalization_factor = 1.0 / total_active_distance_per_iteration;
5,567✔
174
  double volume_normalization_factor =
5,567✔
175
    1.0 / (total_active_distance_per_iteration * simulation::current_batch);
5,567✔
176

177
// Normalize scalar flux to total distance travelled by all rays this
178
// iteration
179
#pragma omp parallel for
3,042✔
180
  for (int64_t se = 0; se < n_source_elements(); se++) {
22,535,135✔
181
    source_regions_.scalar_flux_new(se) *= normalization_factor;
22,532,610✔
182
  }
183

184
// Accumulate cell-wise ray length tallies collected this iteration, then
185
// update the simulation-averaged cell-wise volume estimates
186
#pragma omp parallel for
3,042✔
187
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,994,195✔
188
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
19,991,670✔
189
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
19,991,670✔
190
    source_regions_.volume_naive(sr) =
39,983,340✔
191
      source_regions_.volume(sr) * normalization_factor;
19,991,670✔
192
    source_regions_.volume_sq(sr) =
39,983,340✔
193
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
19,991,670✔
194
    source_regions_.volume(sr) =
19,991,670✔
195
      source_regions_.volume_t(sr) * volume_normalization_factor;
19,991,670✔
196
  }
197
}
5,567✔
198

199
void FlatSourceDomain::set_flux_to_flux_plus_source(
43,978,049✔
200
  int64_t sr, double volume, int g)
201
{
202
  int material = source_regions_.material(sr);
43,978,049✔
203
  int temp = source_regions_.temperature_idx(sr);
43,978,049✔
204
  if (material == MATERIAL_VOID) {
43,978,049✔
205
    source_regions_.scalar_flux_new(sr, g) /= volume;
882,416✔
206
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
882,416!
207
      source_regions_.scalar_flux_new(sr, g) +=
882,416✔
208
        0.5f * source_regions_.external_source(sr, g) *
882,416✔
209
        source_regions_.volume_sq(sr);
882,416✔
210
    }
211
  } else {
212
    double sigma_t =
213
      sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
43,095,633✔
214
      source_regions_.density_mult(sr);
43,095,633✔
215
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
43,095,633✔
216
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
43,095,633✔
217
  }
218
}
43,978,049✔
219

220
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
1,542✔
221
{
222
  source_regions_.scalar_flux_new(sr, g) =
3,084✔
223
    source_regions_.scalar_flux_old(sr, g);
1,542✔
224
}
1,542✔
225

226
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
8,927,547✔
227
{
228
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
8,927,547✔
229
}
8,927,547✔
230

231
// Combine transport flux contributions and flat source contributions from the
232
// previous iteration to generate this iteration's estimate of scalar flux.
233
int64_t FlatSourceDomain::add_source_to_scalar_flux()
13,102✔
234
{
235
  int64_t n_hits = 0;
13,102✔
236
  double inverse_batch = 1.0 / simulation::current_batch;
13,102✔
237

238
#pragma omp parallel for reduction(+ : n_hits)
7,152✔
239
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,456,785✔
240

241
    double volume_simulation_avg = source_regions_.volume(sr);
33,450,835✔
242
    double volume_iteration = source_regions_.volume_naive(sr);
33,450,835✔
243

244
    // Increment the number of hits if cell was hit this iteration
245
    if (volume_iteration) {
33,450,835✔
246
      n_hits++;
29,391,680✔
247
    }
248

249
    // Set the SR to small status if its expected number of hits
250
    // per iteration is less than 1.5
251
    if (source_regions_.n_hits(sr) * inverse_batch < MIN_HITS_PER_BATCH) {
33,450,835✔
252
      source_regions_.is_small(sr) = 1;
6,812,705✔
253
    } else {
254
      source_regions_.is_small(sr) = 0;
26,638,130✔
255
    }
256

257
    // The volume treatment depends on the volume estimator type
258
    // and whether or not an external source is present in the cell.
259
    double volume;
260
    switch (volume_estimator_) {
33,450,835!
261
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
262
      volume = volume_iteration;
777,600✔
263
      break;
777,600✔
264
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
265
      volume = volume_simulation_avg;
432,000✔
266
      break;
432,000✔
267
    case RandomRayVolumeEstimator::HYBRID:
32,241,235✔
268
      if (source_regions_.external_source_present(sr) ||
60,294,070✔
269
          source_regions_.is_small(sr)) {
28,052,835✔
270
        volume = volume_iteration;
11,000,725✔
271
      } else {
272
        volume = volume_simulation_avg;
21,240,510✔
273
      }
274
      break;
32,241,235✔
275
    default:
276
      fatal_error("Invalid volume estimator type");
277
    }
278

279
    for (int g = 0; g < negroups_; g++) {
71,438,210✔
280
      // There are three scenarios we need to consider:
281
      if (volume_iteration > 0.0) {
37,987,375✔
282
        // 1. If the FSR was hit this iteration, then the new flux is equal to
283
        // the flat source from the previous iteration plus the contributions
284
        // from rays passing through the source region (computed during the
285
        // transport sweep)
286
        set_flux_to_flux_plus_source(sr, volume, g);
33,928,070✔
287
      } else if (volume_simulation_avg > 0.0) {
4,059,305✔
288
        // 2. If the FSR was not hit this iteration, but has been hit some
289
        // previous iteration, then we need to make a choice about what
290
        // to do. Naively we will usually want to set the flux to be equal
291
        // to the reduced source. However, in fixed source problems where
292
        // there is a strong external source present in the cell, and where
293
        // the cell has a very low cross section, this approximation will
294
        // cause a huge upward bias in the flux estimate of the cell (in these
295
        // conditions, the flux estimate can be orders of magnitude too large).
296
        // Thus, to avoid this bias, if any external source is present
297
        // in the cell we will use the previous iteration's flux estimate. This
298
        // injects a small degree of correlation into the simulation, but this
299
        // is going to be trivial when the miss rate is a few percent or less.
300
        if (source_regions_.external_source_present(sr)) {
4,059,295✔
301
          set_flux_to_old_flux(sr, g);
1,320✔
302
        } else {
303
          set_flux_to_source(sr, g);
4,057,975✔
304
        }
305
      }
306
      // Halt if NaN implosion is detected
307
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
37,987,375!
308
        fatal_error("A source region scalar flux is not finite. "
309
                    "This indicates a numerical instability in the "
310
                    "simulation. Consider increasing ray density or adjusting "
311
                    "the source region mesh.");
312
      }
313
    }
314
  }
315

316
  // Return the number of source regions that were hit this iteration
317
  return n_hits;
13,102✔
318
}
319

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

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

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

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

339
    int material = source_regions_.material(sr);
338,190✔
340
    int temp = source_regions_.temperature_idx(sr);
338,190✔
341
    if (material == MATERIAL_VOID) {
338,190!
342
      continue;
343
    }
344

345
    double sr_fission_source_old = 0;
338,190✔
346
    double sr_fission_source_new = 0;
338,190✔
347

348
    for (int g = 0; g < negroups_; g++) {
2,602,920✔
349
      double nu_sigma_f =
350
        nu_sigma_f_[(material * ntemperature_ + temp) * negroups_ + g] *
2,264,730✔
351
        source_regions_.density_mult(sr);
2,264,730✔
352
      sr_fission_source_old +=
2,264,730✔
353
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
2,264,730✔
354
      sr_fission_source_new +=
2,264,730✔
355
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
2,264,730✔
356
    }
357

358
    // Compute total fission rates in FSR
359
    sr_fission_source_old *= volume;
338,190✔
360
    sr_fission_source_new *= volume;
338,190✔
361

362
    // Accumulate totals
363
    fission_rate_old += sr_fission_source_old;
338,190✔
364
    fission_rate_new += sr_fission_source_new;
338,190✔
365

366
    // Store total fission rate in the FSR for Shannon calculation
367
    p[sr] = sr_fission_source_new;
338,190✔
368
  }
369

370
  double k_eff_new = k_eff_ * (fission_rate_new / fission_rate_old);
3,410✔
371

372
  double H = 0.0;
3,410✔
373
  // defining an inverse sum for better performance
374
  double inverse_sum = 1 / fission_rate_new;
3,410✔
375

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

387
  // Adds entropy value to shared entropy vector in openmc namespace.
388
  simulation::entropy.push_back(H);
3,410✔
389

390
  fission_rate_ = fission_rate_new;
3,410✔
391
  k_eff_ = k_eff_new;
3,410✔
392
}
3,410✔
393

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

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

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

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

432
void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id)
870✔
433
{
434
  openmc::simulation::time_tallies.start();
870✔
435

436
  // Tracks if we've generated a mapping yet for all source regions.
437
  bool all_source_regions_mapped = true;
870✔
438

439
// Attempt to generate mapping for all source regions
440
#pragma omp parallel for
475✔
441
  for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) {
1,029,815✔
442

443
    // If this source region has not been hit by a ray yet, then
444
    // we aren't going to be able to map it, so skip it.
445
    if (!source_regions_.position_recorded(sr)) {
1,029,420!
446
      all_source_regions_mapped = false;
447
      continue;
448
    }
449

450
    // A particle located at the recorded midpoint of a ray
451
    // crossing through this source region is used to estabilish
452
    // the spatial location of the source region
453
    Particle p;
1,029,420✔
454
    p.r() = source_regions_.position(sr);
1,029,420✔
455
    p.r_last() = source_regions_.position(sr);
1,029,420✔
456
    p.u() = {1.0, 0.0, 0.0};
1,029,420✔
457
    bool found = exhaustive_find_cell(p);
1,029,420✔
458

459
    // Loop over energy groups (so as to support energy filters)
460
    for (int g = 0; g < negroups_; g++) {
2,217,000✔
461

462
      // Set particle to the current energy
463
      p.g() = g;
1,187,580✔
464
      p.g_last() = g;
1,187,580✔
465
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,187,580✔
466
      p.E_last() = p.E();
1,187,580✔
467

468
      int64_t source_element = sr * negroups_ + g;
1,187,580✔
469

470
      // If this task has already been populated, we don't need to do
471
      // it again.
472
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,187,580!
473
        continue;
474
      }
475

476
      // Loop over all active tallies. This logic is essentially identical
477
      // to what happens when scanning for applicable tallies during
478
      // MC transport.
479
      for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) {
4,514,080✔
480
        Tally& tally {*model::tallies[i_tally]};
3,326,500✔
481

482
        // Initialize an iterator over valid filter bin combinations.
483
        // If there are no valid combinations, use a continue statement
484
        // to ensure we skip the assume_separate break below.
485
        auto filter_iter = FilterBinIter(tally, p);
3,326,500✔
486
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,326,500✔
487
        if (filter_iter == end)
3,326,500✔
488
          continue;
2,001,680✔
489

490
        // Loop over filter bins.
491
        for (; filter_iter != end; ++filter_iter) {
2,649,640✔
492
          auto filter_index = filter_iter.index_;
1,324,820✔
493
          auto filter_weight = filter_iter.weight_;
1,324,820✔
494

495
          // Loop over scores
496
          for (int score = 0; score < tally.scores_.size(); score++) {
3,003,840✔
497
            auto score_bin = tally.scores_[score];
1,679,020✔
498
            // If a valid tally, filter, and score combination has been found,
499
            // then add it to the list of tally tasks for this source element.
500
            TallyTask task(i_tally, filter_index, score, score_bin);
1,679,020✔
501
            source_regions_.tally_task(sr, g).push_back(task);
1,679,020✔
502

503
            // Also add this task to the list of volume tasks for this source
504
            // region.
505
            source_regions_.volume_task(sr).insert(task);
1,679,020✔
506
          }
507
        }
508
      }
509
      // Reset all the filter matches for the next tally event.
510
      for (auto& match : p.filter_matches())
4,984,940✔
511
        match.bins_present_ = false;
3,797,360✔
512
    }
513
  }
1,029,420✔
514
  openmc::simulation::time_tallies.stop();
870✔
515

516
  mapped_all_tallies_ = all_source_regions_mapped;
870✔
517
}
870✔
518

519
// Set the volume accumulators to zero for all tallies
520
void FlatSourceDomain::reset_tally_volumes()
5,451✔
521
{
522
  if (volume_normalized_flux_tallies_) {
5,451✔
523
#pragma omp parallel for
2,190✔
524
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,800✔
525
      auto& tensor = tally_volumes_[i];
4,975✔
526
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,975✔
527
    }
528
  }
529
}
5,451✔
530

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

559
  // If we are in adjoint mode of a fixed source problem, the external
560
  // source is already normalized, such that all resulting fluxes are
561
  // also normalized.
562
  if (adjoint_) {
4,283✔
563
    return 1.0;
398✔
564
  }
565

566
  // Fixed source mode normalization
567

568
  // Step 1 is to sum over all source regions and energy groups to get the
569
  // total external source strength in the simulation.
570
  double simulation_external_source_strength = 0.0;
3,885✔
571
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
2,128✔
572
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
14,678,157✔
573
    int material = source_regions_.material(sr);
14,676,400✔
574
    int temp = source_regions_.temperature_idx(sr);
14,676,400✔
575
    double volume = source_regions_.volume(sr) * simulation_volume_;
14,676,400✔
576
    for (int g = 0; g < negroups_; g++) {
29,895,680✔
577
      // For non-void regions, we store the external source pre-divided by
578
      // sigma_t. We need to multiply non-void regions back up by sigma_t
579
      // to get the total source strength in the expected units.
580
      double sigma_t = 1.0;
15,219,280✔
581
      if (material != MATERIAL_VOID) {
15,219,280✔
582
        sigma_t = sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
30,018,080✔
583
                  source_regions_.density_mult(sr);
15,009,040✔
584
      }
585
      simulation_external_source_strength +=
15,219,280✔
586
        source_regions_.external_source(sr, g) * sigma_t * volume;
15,219,280✔
587
    }
588
  }
589

590
  // Step 2 is to determine the total user-specified external source strength
591
  double user_external_source_strength = 0.0;
3,885✔
592
  for (auto& ext_source : model::external_sources) {
7,770✔
593
    user_external_source_strength += ext_source->strength();
3,885✔
594
  }
595

596
  // The correction factor is the ratio of the user-specified external source
597
  // strength to the simulation external source strength.
598
  double source_normalization_factor =
3,885✔
599
    user_external_source_strength / simulation_external_source_strength;
600

601
  return source_normalization_factor;
3,885✔
602
}
603

604
// Tallying in random ray is not done directly during transport, rather,
605
// it is done only once after each power iteration. This is made possible
606
// by way of a mapping data structure that relates spatial source regions
607
// (FSRs) to tally/filter/score combinations. The mechanism by which the
608
// mapping is done (and the limitations incurred) is documented in the
609
// "convert_source_regions_to_tallies()" function comments above. The present
610
// tally function simply traverses the mapping data structure and executes
611
// the scoring operations to OpenMC's native tally result arrays.
612

613
void FlatSourceDomain::random_ray_tally()
5,451✔
614
{
615
  openmc::simulation::time_tallies.start();
5,451✔
616

617
  // Reset our tally volumes to zero
618
  reset_tally_volumes();
5,451✔
619

620
  double source_normalization_factor =
621
    compute_fixed_source_normalization_factor();
5,451✔
622

623
// We loop over all source regions and energy groups. For each
624
// element, we check if there are any scores needed and apply
625
// them.
626
#pragma omp parallel for
2,976✔
627
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,312,275✔
628
    // The fsr.volume_ is the unitless fractional simulation averaged volume
629
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
630
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
631
    // entire global simulation domain (as defined by the ray source box).
632
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
633
    // its fraction of the total volume by the total volume. Not important in
634
    // eigenvalue solves, but useful in fixed source solves for returning the
635
    // flux shape with a magnitude that makes sense relative to the fixed
636
    // source strength.
637
    double volume = source_regions_.volume(sr) * simulation_volume_;
15,309,800✔
638

639
    double material = source_regions_.material(sr);
15,309,800✔
640
    int temp = source_regions_.temperature_idx(sr);
15,309,800✔
641
    double density_mult = source_regions_.density_mult(sr);
15,309,800✔
642
    for (int g = 0; g < negroups_; g++) {
32,084,200✔
643
      double flux =
644
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,774,400✔
645

646
      // Determine numerical score value
647
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,695,000✔
648
        double score = 0.0;
22,920,600✔
649
        switch (task.score_type) {
22,920,600!
650

651
        case SCORE_FLUX:
19,576,800✔
652
          score = flux * volume;
19,576,800✔
653
          break;
19,576,800✔
654

655
        case SCORE_TOTAL:
656
          if (material != MATERIAL_VOID) {
×
657
            score =
658
              flux * volume *
659
              sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
660
              density_mult;
661
          }
662
          break;
663

664
        case SCORE_FISSION:
1,671,600✔
665
          if (material != MATERIAL_VOID) {
1,671,600!
666
            score =
1,671,600✔
667
              flux * volume *
1,671,600✔
668
              sigma_f_[(material * ntemperature_ + temp) * negroups_ + g] *
1,671,600✔
669
              density_mult;
670
          }
671
          break;
1,671,600✔
672

673
        case SCORE_NU_FISSION:
1,671,600✔
674
          if (material != MATERIAL_VOID) {
1,671,600!
675
            score =
1,671,600✔
676
              flux * volume *
1,671,600✔
677
              nu_sigma_f_[(material * ntemperature_ + temp) * negroups_ + g] *
1,671,600✔
678
              density_mult;
679
          }
680
          break;
1,671,600✔
681

682
        case SCORE_EVENTS:
683
          score = 1.0;
684
          break;
685

686
        case SCORE_KAPPA_FISSION:
600✔
687
          score =
600✔
688
            flux * volume *
1,200✔
689
            kappa_fission_[(material * ntemperature_ + temp) * negroups_ + g] *
600✔
690
            density_mult;
691
          break;
600✔
692

693
        default:
694
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
695
                      "total, fission, nu-fission, kappa-fission, and events "
696
                      "are supported in random ray mode.");
697
          break;
698
        }
699
        // Apply score to the appropriate tally bin
700
        Tally& tally {*model::tallies[task.tally_idx]};
22,920,600✔
701
#pragma omp atomic
702
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,920,600✔
703
          score;
704
      }
705
    }
706

707
    // For flux tallies, the total volume of the spatial region is needed
708
    // for normalizing the flux. We store this volume in a separate tensor.
709
    // We only contribute to each volume tally bin once per FSR.
710
    if (volume_normalized_flux_tallies_) {
15,309,800✔
711
      for (const auto& task : source_regions_.volume_task(sr)) {
36,212,400✔
712
        if (task.score_type == SCORE_FLUX) {
21,049,800✔
713
#pragma omp atomic
714
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
18,924,600✔
715
            volume;
716
        }
717
      }
718
    }
719
  } // end FSR loop
720

721
  // Normalize any flux scores by the total volume of the FSRs scoring to that
722
  // bin. To do this, we loop over all tallies, and then all filter bins,
723
  // and then scores. For each score, we check the tally data structure to
724
  // see what index that score corresponds to. If that score is a flux score,
725
  // then we divide it by volume.
726
  if (volume_normalized_flux_tallies_) {
5,451✔
727
    for (int i = 0; i < model::tallies.size(); i++) {
14,960✔
728
      Tally& tally {*model::tallies[i]};
10,945✔
729
#pragma omp parallel for
5,970✔
730
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
705,625✔
731
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,422,300✔
732
          auto score_type = tally.scores_[score_idx];
721,650✔
733
          if (score_type == SCORE_FLUX) {
721,650✔
734
            double vol = tally_volumes_[i](bin, score_idx);
700,650✔
735
            if (vol > 0.0) {
700,650!
736
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
700,650✔
737
            }
738
          }
739
        }
740
      }
741
    }
742
  }
743

744
  openmc::simulation::time_tallies.stop();
5,451✔
745
}
5,451✔
746

747
double FlatSourceDomain::evaluate_flux_at_point(
×
748
  Position r, int64_t sr, int g) const
749
{
750
  return source_regions_.scalar_flux_final(sr, g) /
×
751
         (settings::n_batches - settings::n_inactive);
×
752
}
753

754
// Outputs all basic material, FSR ID, multigroup flux, and
755
// fission source data to .vtk file that can be directly
756
// loaded and displayed by Paraview. Note that .vtk binary
757
// files require big endian byte ordering, so endianness
758
// is checked and flipped if necessary.
759
void FlatSourceDomain::output_to_vtk() const
×
760
{
761
  // Rename .h5 plot filename(s) to .vtk filenames
762
  for (int p = 0; p < model::plots.size(); p++) {
×
763
    PlottableInterface* plot = model::plots[p].get();
×
764
    plot->path_plot() =
×
765
      plot->path_plot().substr(0, plot->path_plot().find_last_of('.')) + ".vtk";
×
766
  }
767

768
  // Print header information
769
  print_plot();
×
770

771
  // Outer loop over plots
772
  for (int plt = 0; plt < model::plots.size(); plt++) {
×
773

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

777
    // Random ray plots only support voxel plots
778
    if (!openmc_plot) {
×
779
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
780
                          "is allowed in random ray mode.",
781
        plt));
782
      continue;
×
783
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
784
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
785
                          "is allowed in random ray mode.",
786
        plt));
787
      continue;
×
788
    }
789

790
    int Nx = openmc_plot->pixels_[0];
×
791
    int Ny = openmc_plot->pixels_[1];
×
792
    int Nz = openmc_plot->pixels_[2];
×
793
    Position origin = openmc_plot->origin_;
×
794
    Position width = openmc_plot->width_;
×
795
    Position ll = origin - width / 2.0;
×
796
    double x_delta = width.x / Nx;
×
797
    double y_delta = width.y / Ny;
×
798
    double z_delta = width.z / Nz;
×
799
    std::string filename = openmc_plot->path_plot();
×
800

801
    // Perform sanity checks on file size
802
    uint64_t bytes = Nx * Ny * Nz * (negroups_ + 1 + 1 + 1) * sizeof(float);
×
803
    write_message(5, "Processing plot {}: {}... (Estimated size is {} MB)",
×
804
      openmc_plot->id(), filename, bytes / 1.0e6);
×
805
    if (bytes / 1.0e9 > 1.0) {
×
806
      warning("Voxel plot specification is very large (>1 GB). Plotting may be "
×
807
              "slow.");
808
    } else if (bytes / 1.0e9 > 100.0) {
×
809
      fatal_error("Voxel plot specification is too large (>100 GB). Exiting.");
×
810
    }
811

812
    // Relate voxel spatial locations to random ray source regions
813
    vector<int> voxel_indices(Nx * Ny * Nz);
×
814
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
815
    vector<double> weight_windows(Nx * Ny * Nz);
×
816
    float min_weight = 1e20;
×
817
#pragma omp parallel for collapse(3) reduction(min : min_weight)
818
    for (int z = 0; z < Nz; z++) {
×
819
      for (int y = 0; y < Ny; y++) {
×
820
        for (int x = 0; x < Nx; x++) {
×
821
          Position sample;
822
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
823
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
824
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
825
          Particle p;
×
826
          p.r() = sample;
827
          p.r_last() = sample;
828
          p.E() = 1.0;
829
          p.E_last() = 1.0;
830
          p.u() = {1.0, 0.0, 0.0};
831

832
          bool found = exhaustive_find_cell(p);
×
833
          if (!found) {
×
834
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
835
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
836
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
837
            continue;
838
          }
839

840
          SourceRegionKey sr_key = lookup_source_region_key(p);
×
841
          int64_t sr = -1;
842
          auto it = source_region_map_.find(sr_key);
×
843
          if (it != source_region_map_.end()) {
×
844
            sr = it->second;
845
          }
846

847
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
848
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
849

850
          if (variance_reduction::weight_windows.size() == 1) {
×
851
            WeightWindow ww =
852
              variance_reduction::weight_windows[0]->get_weight_window(p);
×
853
            float weight = ww.lower_weight;
854
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
855
            if (weight < min_weight)
×
856
              min_weight = weight;
857
          }
858
        }
×
859
      }
860
    }
861

862
    double source_normalization_factor =
863
      compute_fixed_source_normalization_factor();
×
864

865
    // Open file for writing
866
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
867

868
    // Write vtk metadata
869
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
870
    std::fprintf(plot, "Dataset File\n");
×
871
    std::fprintf(plot, "BINARY\n");
×
872
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
873
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
874
    std::fprintf(plot, "ORIGIN %lf %lf %lf\n", ll.x, ll.y, ll.z);
×
875
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
876
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
877

878
    int64_t num_neg = 0;
×
879
    int64_t num_samples = 0;
×
880
    float min_flux = 0.0;
×
881
    float max_flux = -1.0e20;
×
882
    // Plot multigroup flux data
883
    for (int g = 0; g < negroups_; g++) {
×
884
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
885
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
886
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
887
        int64_t fsr = voxel_indices[i];
×
888
        int64_t source_element = fsr * negroups_ + g;
×
889
        float flux = 0;
×
890
        if (fsr >= 0) {
×
891
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
892
          if (flux < 0.0)
×
893
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
894
              voxel_positions[i], fsr, g);
×
895
        }
896
        if (flux < 0.0) {
×
897
          num_neg++;
×
898
          if (flux < min_flux) {
×
899
            min_flux = flux;
×
900
          }
901
        }
902
        if (flux > max_flux)
×
903
          max_flux = flux;
×
904
        num_samples++;
×
905
        flux = convert_to_big_endian<float>(flux);
×
906
        std::fwrite(&flux, sizeof(float), 1, plot);
×
907
      }
908
    }
909

910
    // Slightly negative fluxes can be normal when sampling corners of linear
911
    // source regions. However, very common and high magnitude negative fluxes
912
    // may indicate numerical instability.
913
    if (num_neg > 0) {
×
914
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
915
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
916
        num_neg, (100.0 * num_neg) / num_samples, min_flux, max_flux));
×
917
    }
918

919
    // Plot FSRs
920
    std::fprintf(plot, "SCALARS FSRs float\n");
×
921
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
922
    for (int fsr : voxel_indices) {
×
923
      float value = future_prn(10, fsr);
×
924
      value = convert_to_big_endian<float>(value);
×
925
      std::fwrite(&value, sizeof(float), 1, plot);
×
926
    }
927

928
    // Plot Materials
929
    std::fprintf(plot, "SCALARS Materials int\n");
×
930
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
931
    for (int fsr : voxel_indices) {
×
932
      int mat = -1;
×
933
      if (fsr >= 0)
×
934
        mat = source_regions_.material(fsr);
×
935
      mat = convert_to_big_endian<int>(mat);
×
936
      std::fwrite(&mat, sizeof(int), 1, plot);
×
937
    }
938

939
    // Plot fission source
940
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
941
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
942
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
943
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
944
        int64_t fsr = voxel_indices[i];
×
945
        float total_fission = 0.0;
×
946
        if (fsr >= 0) {
×
947
          int mat = source_regions_.material(fsr);
×
NEW
948
          int temp = source_regions_.temperature_idx(fsr);
×
949
          if (mat != MATERIAL_VOID) {
×
950
            for (int g = 0; g < negroups_; g++) {
×
951
              int64_t source_element = fsr * negroups_ + g;
×
952
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
953
              double sigma_f =
NEW
954
                sigma_f_[(mat * ntemperature_ + temp) * negroups_ + g] *
×
NEW
955
                source_regions_.density_mult(fsr);
×
UNCOV
956
              total_fission += sigma_f * flux;
×
957
            }
958
          }
959
        }
960
        total_fission = convert_to_big_endian<float>(total_fission);
×
961
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
962
      }
963
    } else {
964
      std::fprintf(plot, "SCALARS external_source float\n");
×
965
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
966
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
967
        int64_t fsr = voxel_indices[i];
×
968
        int mat = source_regions_.material(fsr);
×
NEW
969
        int temp = source_regions_.temperature_idx(fsr);
×
970
        float total_external = 0.0f;
×
971
        if (fsr >= 0) {
×
972
          for (int g = 0; g < negroups_; g++) {
×
973
            // External sources are already divided by sigma_t, so we need to
974
            // multiply it back to get the true external source.
975
            double sigma_t = 1.0;
×
976
            if (mat != MATERIAL_VOID) {
×
NEW
977
              sigma_t = sigma_t_[(mat * ntemperature_ + temp) * negroups_ + g] *
×
978
                        source_regions_.density_mult(fsr);
×
979
            }
980
            total_external += source_regions_.external_source(fsr, g) * sigma_t;
×
981
          }
982
        }
983
        total_external = convert_to_big_endian<float>(total_external);
×
984
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
985
      }
986
    }
987

988
    // Plot weight window data
989
    if (variance_reduction::weight_windows.size() == 1) {
×
990
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
991
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
992
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
993
        float weight = weight_windows[i];
×
994
        if (weight == 0.0)
×
995
          weight = min_weight;
×
996
        weight = convert_to_big_endian<float>(weight);
×
997
        std::fwrite(&weight, sizeof(float), 1, plot);
×
998
      }
999
    }
1000

1001
    std::fclose(plot);
×
1002
  }
×
1003
}
×
1004

1005
void FlatSourceDomain::apply_external_source_to_source_region(
4,588✔
1006
  int src_idx, SourceRegionHandle& srh)
1007
{
1008
  auto s = model::external_sources[src_idx].get();
4,588✔
1009
  auto is = dynamic_cast<IndependentSource*>(s);
4,588!
1010
  auto discrete = dynamic_cast<Discrete*>(is->energy());
4,588!
1011
  double strength_factor = is->strength();
4,588✔
1012
  const auto& discrete_energies = discrete->x();
4,588✔
1013
  const auto& discrete_probs = discrete->prob();
4,588✔
1014

1015
  srh.external_source_present() = 1;
4,588✔
1016

1017
  for (int i = 0; i < discrete_energies.size(); i++) {
9,308✔
1018
    int g = data::mg.get_group_index(discrete_energies[i]);
4,720✔
1019
    srh.external_source(g) += discrete_probs[i] * strength_factor;
4,720✔
1020
  }
1021
}
4,588✔
1022

1023
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
432✔
1024
  int src_idx, int target_material_id, const vector<int32_t>& instances)
1025
{
1026
  Cell& cell = *model::cells[i_cell];
432✔
1027

1028
  if (cell.type_ != Fill::MATERIAL)
432!
1029
    return;
×
1030

1031
  for (int j : instances) {
30,928✔
1032
    int cell_material_idx = cell.material(j);
30,496✔
1033
    int cell_material_id;
1034
    if (cell_material_idx == MATERIAL_VOID) {
30,496✔
1035
      cell_material_id = MATERIAL_VOID;
256✔
1036
    } else {
1037
      cell_material_id = model::materials[cell_material_idx]->id();
30,240✔
1038
    }
1039
    if (target_material_id == C_NONE ||
30,496✔
1040
        cell_material_id == target_material_id) {
1041
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,976✔
1042
      external_volumetric_source_map_[source_region].push_back(src_idx);
2,976✔
1043
    }
1044
  }
1045
}
1046

1047
void FlatSourceDomain::apply_external_source_to_cell_and_children(
464✔
1048
  int32_t i_cell, int src_idx, int32_t target_material_id)
1049
{
1050
  Cell& cell = *model::cells[i_cell];
464✔
1051

1052
  if (cell.type_ == Fill::MATERIAL) {
464✔
1053
    vector<int> instances(cell.n_instances());
432✔
1054
    std::iota(instances.begin(), instances.end(), 0);
432✔
1055
    apply_external_source_to_cell_instances(
432✔
1056
      i_cell, src_idx, target_material_id, instances);
1057
  } else if (target_material_id == C_NONE) {
464!
1058
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1059
      cell.get_contained_cells(0, nullptr);
×
1060
    for (const auto& pair : cell_instance_list) {
×
1061
      int32_t i_child_cell = pair.first;
×
1062
      apply_external_source_to_cell_instances(
×
1063
        i_child_cell, src_idx, target_material_id, pair.second);
×
1064
    }
1065
  }
×
1066
}
464✔
1067

1068
void FlatSourceDomain::count_external_source_regions()
1,283✔
1069
{
1070
  n_external_source_regions_ = 0;
1,283✔
1071
#pragma omp parallel for reduction(+ : n_external_source_regions_)
723✔
1072
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,186,720✔
1073
    if (source_regions_.external_source_present(sr)) {
1,186,160✔
1074
      n_external_source_regions_++;
157,250✔
1075
    }
1076
  }
1077
}
1,283✔
1078

1079
void FlatSourceDomain::convert_external_sources()
417✔
1080
{
1081
  // Loop over external sources
1082
  for (int es = 0; es < model::external_sources.size(); es++) {
834✔
1083

1084
    // Extract source information
1085
    Source* s = model::external_sources[es].get();
417✔
1086
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
417!
1087
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
417!
1088
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
417✔
1089
    double strength_factor = is->strength();
417✔
1090

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

1096
      // Extract the point source coordinate and find the base source region at
1097
      // that point
1098
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
17!
1099
      GeometryState gs;
17✔
1100
      gs.r() = sp->r();
17✔
1101
      gs.r_last() = sp->r();
17✔
1102
      gs.u() = {1.0, 0.0, 0.0};
17✔
1103
      bool found = exhaustive_find_cell(gs);
17✔
1104
      if (!found) {
17!
1105
        fatal_error(fmt::format("Could not find cell containing external "
×
1106
                                "point source at {}",
1107
          sp->r()));
×
1108
      }
1109
      SourceRegionKey key = lookup_source_region_key(gs);
17✔
1110

1111
      // With the source region and mesh bin known, we can use the
1112
      // accompanying SourceRegionKey as a key into a map that stores the
1113
      // corresponding external source index for the point source. Notably, we
1114
      // do not actually apply the external source to any source regions here,
1115
      // as if mesh subdivision is enabled, they haven't actually been
1116
      // discovered & initilized yet. When discovered, they will read from the
1117
      // external_source_map to determine if there are any external source
1118
      // terms that should be applied.
1119
      external_point_source_map_[key].push_back(es);
17✔
1120

1121
    } else {
17✔
1122
      // If not a point source, then use the volumetric domain constraints to
1123
      // determine which source regions to apply the external source to.
1124
      if (is->domain_type() == Source::DomainType::MATERIAL) {
400✔
1125
        for (int32_t material_id : domain_ids) {
32✔
1126
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1127
            apply_external_source_to_cell_and_children(i_cell, es, material_id);
80✔
1128
          }
1129
        }
1130
      } else if (is->domain_type() == Source::DomainType::CELL) {
384✔
1131
        for (int32_t cell_id : domain_ids) {
32✔
1132
          int32_t i_cell = model::cell_map[cell_id];
16✔
1133
          apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
16✔
1134
        }
1135
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
368!
1136
        for (int32_t universe_id : domain_ids) {
736✔
1137
          int32_t i_universe = model::universe_map[universe_id];
368✔
1138
          Universe& universe = *model::universes[i_universe];
368✔
1139
          for (int32_t i_cell : universe.cells_) {
736✔
1140
            apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
368✔
1141
          }
1142
        }
1143
      }
1144
    }
1145
  } // End loop over external sources
1146
}
417✔
1147

1148
void FlatSourceDomain::flux_swap()
13,102✔
1149
{
1150
  source_regions_.flux_swap();
13,102✔
1151
}
13,102✔
1152

1153
void FlatSourceDomain::flatten_xs()
785✔
1154
{
1155
  // Temperature and angle indices, if using multiple temperature
1156
  // data sets and/or anisotropic data sets.
1157
  // TODO: Currently assumes we are only using single angle data.
1158
  const int a = 0;
785✔
1159

1160
  n_materials_ = data::mg.macro_xs_.size();
785✔
1161
  ntemperature_ = 1;
785✔
1162
  for (int i = 0; i < n_materials_; i++) {
2,946✔
1163
    ntemperature_ =
2,161✔
1164
      std::max(ntemperature_, data::mg.macro_xs_[i].n_temperature_points());
2,161✔
1165
  }
1166

1167
  for (int i = 0; i < n_materials_; i++) {
2,946✔
1168
    auto& m = data::mg.macro_xs_[i];
2,161✔
1169
    for (int t = 0; t < ntemperature_; t++) {
4,354✔
1170
      for (int g_out = 0; g_out < negroups_; g_out++) {
11,587✔
1171
        if (m.exists_in_model && t < m.n_temperature_points()) {
9,394✔
1172
          double sigma_t =
1173
            m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
9,218✔
1174
          sigma_t_.push_back(sigma_t);
9,218✔
1175

1176
          if (sigma_t < MINIMUM_MACRO_XS) {
9,218✔
1177
            Material* mat = model::materials[i].get();
16✔
1178
            warning(fmt::format(
16✔
1179
              "Material \"{}\" (id: {}) has a group {} total cross section "
1180
              "({:.3e}) below the minimum threshold "
1181
              "({:.3e}). Material will be treated as pure void.",
1182
              mat->name(), mat->id(), g_out, sigma_t, MINIMUM_MACRO_XS));
32✔
1183
          }
1184

1185
          double nu_sigma_f =
1186
            m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
9,218✔
1187
          nu_sigma_f_.push_back(nu_sigma_f);
9,218✔
1188

1189
          double sigma_f =
1190
            m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
9,218✔
1191
          sigma_f_.push_back(sigma_f);
9,218✔
1192

1193
          double chi =
1194
            m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
9,218✔
1195
          if (!std::isfinite(chi)) {
9,218✔
1196
            // MGXS interface may return NaN in some cases, such as when
1197
            // material is fissionable but has very small sigma_f.
1198
            chi = 0.0;
704✔
1199
          }
1200
          chi_.push_back(chi);
9,218✔
1201

1202
          double kappa_fission =
1203
            m.get_xs(MgxsType::KAPPA_FISSION, g_out, NULL, NULL, NULL, t, a);
9,218✔
1204
          kappa_fission_.push_back(kappa_fission);
9,218✔
1205

1206
          for (int g_in = 0; g_in < negroups_; g_in++) {
276,006✔
1207
            double sigma_s =
1208
              m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
266,788✔
1209
            sigma_s_.push_back(sigma_s);
266,788✔
1210
            // For transport corrected XS data, diagonal elements may be
1211
            // negative. In this case, set a flag to enable transport
1212
            // stabilization for the simulation.
1213
            if (g_out == g_in && sigma_s < 0.0)
266,788✔
1214
              is_transport_stabilization_needed_ = true;
880✔
1215
          }
1216
        } else {
1217
          sigma_t_.push_back(0);
176✔
1218
          nu_sigma_f_.push_back(0);
176✔
1219
          sigma_f_.push_back(0);
176✔
1220
          chi_.push_back(0);
176✔
1221
          kappa_fission_.push_back(0);
176✔
1222
          for (int g_in = 0; g_in < negroups_; g_in++) {
1,024✔
1223
            sigma_s_.push_back(0);
848✔
1224
          }
1225
        }
1226
      }
1227
    }
1228
  }
1229
}
785✔
1230

1231
void FlatSourceDomain::set_adjoint_sources()
65✔
1232
{
1233
  // Set the adjoint external source to 1/forward_flux. If the forward flux is
1234
  // negative, zero, or extremely close to zero, set the adjoint source to zero,
1235
  // as this is likely a very small source region that we don't need to bother
1236
  // trying to vector particles towards. In the case of flux "being extremely
1237
  // close to zero", we define this as being a fixed fraction of the maximum
1238
  // forward flux, below which we assume the flux would be physically
1239
  // undetectable.
1240

1241
  // First, find the maximum forward flux value
1242
  double max_flux = 0.0;
65✔
1243
#pragma omp parallel for reduction(max : max_flux)
37✔
1244
  for (int64_t se = 0; se < n_source_elements(); se++) {
155,548✔
1245
    double flux = source_regions_.scalar_flux_final(se);
155,520✔
1246
    if (flux > max_flux) {
155,520✔
1247
      max_flux = flux;
25✔
1248
    }
1249
  }
1250

1251
  // Then, compute the adjoint source for each source region
1252
#pragma omp parallel for
37✔
1253
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1254
    for (int g = 0; g < negroups_; g++) {
311,040✔
1255
      double flux = source_regions_.scalar_flux_final(sr, g);
155,520✔
1256
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
155,520✔
1257
        source_regions_.external_source(sr, g) = 0.0;
325✔
1258
      } else {
1259
        source_regions_.external_source(sr, g) = 1.0 / flux;
155,195✔
1260
      }
1261
      if (flux > 0.0) {
155,520✔
1262
        source_regions_.external_source_present(sr) = 1;
155,195✔
1263
      }
1264
      source_regions_.scalar_flux_final(sr, g) = 0.0;
155,520✔
1265
    }
1266
  }
1267

1268
  // "Small" source regions in OpenMC are defined as those that are hit by
1269
  // MIN_HITS_PER_BATCH rays or fewer each batch. These regions typically have
1270
  // very small volumes combined with a low aspect ratio, and are often
1271
  // generated when applying a source region mesh that clips the edge of a
1272
  // curved surface. As perhaps only a few rays will visit these regions over
1273
  // the entire forward simulation, the forward flux estimates are extremely
1274
  // noisy and unreliable. In some cases, the noise may make the forward fluxes
1275
  // extremely low, leading to unphysically large adjoint source terms,
1276
  // resulting in weight windows that aggressively try to drive particles
1277
  // towards these regions. To fix this, we simply filter out any "small" source
1278
  // regions from consideration. If a source region is "small", we
1279
  // set its adjoint source to zero. This adds negligible bias to the adjoint
1280
  // flux solution, as the true total adjoint source contribution from small
1281
  // regions is likely to be negligible.
1282
#pragma omp parallel for
37✔
1283
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1284
    if (source_regions_.is_small(sr)) {
155,520!
1285
      for (int g = 0; g < negroups_; g++) {
×
1286
        source_regions_.external_source(sr, g) = 0.0;
1287
      }
1288
      source_regions_.external_source_present(sr) = 0;
1289
    }
1290
  }
1291
  // Divide the fixed source term by sigma t (to save time when applying each
1292
  // iteration)
1293
#pragma omp parallel for
37✔
1294
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1295
    int material = source_regions_.material(sr);
155,520✔
1296
    int temp = source_regions_.temperature_idx(sr);
155,520✔
1297
    if (material == MATERIAL_VOID) {
155,520!
1298
      continue;
1299
    }
1300
    for (int g = 0; g < negroups_; g++) {
311,040✔
1301
      double sigma_t =
1302
        sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
155,520✔
1303
        source_regions_.density_mult(sr);
155,520✔
1304
      source_regions_.external_source(sr, g) /= sigma_t;
155,520✔
1305
    }
1306
  }
1307
}
65✔
1308

1309
void FlatSourceDomain::transpose_scattering_matrix()
81✔
1310
{
1311
  // Transpose the inner two dimensions for each material
1312
  for (int m = 0; m < n_materials_; ++m) {
306✔
1313
    for (int t = 0; t < ntemperature_; t++) {
450✔
1314
      int material_offset = (m * ntemperature_ + t) * negroups_ * negroups_;
225✔
1315
      for (int i = 0; i < negroups_; ++i) {
643✔
1316
        for (int j = i + 1; j < negroups_; ++j) {
1,091✔
1317
          // Calculate indices of the elements to swap
1318
          int idx1 = material_offset + i * negroups_ + j;
673✔
1319
          int idx2 = material_offset + j * negroups_ + i;
673✔
1320

1321
          // Swap the elements to transpose the matrix
1322
          std::swap(sigma_s_[idx1], sigma_s_[idx2]);
673✔
1323
        }
1324
      }
1325
    }
1326
  }
1327
}
81✔
1328

1329
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
×
1330
{
1331
  // Ensure array is correct size
1332
  flux.resize(n_source_regions() * negroups_);
×
1333
// Serialize the final fluxes for output
1334
#pragma omp parallel for
1335
  for (int64_t se = 0; se < n_source_elements(); se++) {
×
1336
    flux[se] = source_regions_.scalar_flux_final(se);
1337
  }
1338
}
×
1339

1340
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
1,090✔
1341
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1342
  bool is_target_void)
1343
{
1344
  Cell& cell = *model::cells[i_cell];
1,090✔
1345
  if (cell.type_ != Fill::MATERIAL)
1,090!
1346
    return;
×
1347
  for (int32_t j : instances) {
175,908✔
1348
    int cell_material_idx = cell.material(j);
174,818✔
1349
    int cell_material_id = (cell_material_idx == C_NONE)
1350
                             ? C_NONE
174,818✔
1351
                             : model::materials[cell_material_idx]->id();
174,817✔
1352

1353
    if ((target_material_id == C_NONE && !is_target_void) ||
174,818!
1354
        cell_material_id == target_material_id) {
1355
      int64_t sr = source_region_offsets_[i_cell] + j;
142,818✔
1356
      // Check if the key is already present in the mesh_map_
1357
      if (mesh_map_.find(sr) != mesh_map_.end()) {
142,818!
1358
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1359
                                "applied, but trying to apply mesh idx {}",
1360
          sr, mesh_map_[sr], mesh_idx));
×
1361
      }
1362
      // If the SR has not already been assigned, then we can write to it
1363
      mesh_map_[sr] = mesh_idx;
142,818✔
1364
    }
1365
  }
1366
}
1367

1368
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
961✔
1369
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1370
{
1371
  Cell& cell = *model::cells[i_cell];
961✔
1372

1373
  if (cell.type_ == Fill::MATERIAL) {
961✔
1374
    vector<int> instances(cell.n_instances());
832✔
1375
    std::iota(instances.begin(), instances.end(), 0);
832✔
1376
    apply_mesh_to_cell_instances(
832✔
1377
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1378
  } else if (target_material_id == C_NONE && !is_target_void) {
961!
1379
    for (int j = 0; j < cell.n_instances(); j++) {
130✔
1380
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1381
        cell.get_contained_cells(j, nullptr);
65✔
1382
      for (const auto& pair : cell_instance_list) {
323✔
1383
        int32_t i_child_cell = pair.first;
258✔
1384
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
258✔
1385
          pair.second, is_target_void);
258✔
1386
      }
1387
    }
65✔
1388
  }
1389
}
961✔
1390

1391
void FlatSourceDomain::apply_meshes()
785✔
1392
{
1393
  // Skip if there are no mappings between mesh IDs and domains
1394
  if (mesh_domain_map_.empty())
785✔
1395
    return;
464✔
1396

1397
  // Loop over meshes
1398
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
722✔
1399
    Mesh* mesh = model::meshes[mesh_idx].get();
401✔
1400
    int mesh_id = mesh->id();
401✔
1401

1402
    // Skip if mesh id is not present in the map
1403
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
401✔
1404
      continue;
16✔
1405

1406
    // Loop over domains associated with the mesh
1407
    for (auto& domain : mesh_domain_map_[mesh_id]) {
770✔
1408
      Source::DomainType domain_type = domain.first;
385✔
1409
      int domain_id = domain.second;
385✔
1410

1411
      if (domain_type == Source::DomainType::MATERIAL) {
385✔
1412
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1413
          if (domain_id == C_NONE) {
160!
1414
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1415
          } else {
1416
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1417
          }
1418
        }
1419
      } else if (domain_type == Source::DomainType::CELL) {
353✔
1420
        int32_t i_cell = model::cell_map[domain_id];
32✔
1421
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1422
      } else if (domain_type == Source::DomainType::UNIVERSE) {
321!
1423
        int32_t i_universe = model::universe_map[domain_id];
321✔
1424
        Universe& universe = *model::universes[i_universe];
321✔
1425
        for (int32_t i_cell : universe.cells_) {
1,090✔
1426
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
769✔
1427
        }
1428
      }
1429
    }
1430
  }
1431
}
1432

1433
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
1,307,352,393✔
1434
  SourceRegionKey sr_key, Position r, Direction u)
1435
{
1436
  // Case 1: Check if the source region key is already present in the permanent
1437
  // map. This is the most common condition, as any source region visited in a
1438
  // previous power iteration will already be present in the permanent map. If
1439
  // the source region key is found, we translate the key into a specific 1D
1440
  // source region index and return a handle its position in the
1441
  // source_regions_ vector.
1442
  auto it = source_region_map_.find(sr_key);
1,307,352,393✔
1443
  if (it != source_region_map_.end()) {
1,307,352,393✔
1444
    int64_t sr = it->second;
1,264,079,055✔
1445
    return source_regions_.get_source_region_handle(sr);
1,264,079,055✔
1446
  }
1447

1448
  // Case 2: Check if the source region key is present in the temporary (thread
1449
  // safe) map. This is a common occurrence in the first power iteration when
1450
  // the source region has already been visited already by some other ray. We
1451
  // begin by locking the temporary map before any operations are performed. The
1452
  // lock is not global over the full data structure -- it will be dependent on
1453
  // which key is used.
1454
  discovered_source_regions_.lock(sr_key);
43,273,338✔
1455

1456
  // If the key is found in the temporary map, then we return a handle to the
1457
  // source region that is stored in the temporary map.
1458
  if (discovered_source_regions_.contains(sr_key)) {
43,273,338✔
1459
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
40,906,997✔
1460
    discovered_source_regions_.unlock(sr_key);
40,906,997✔
1461
    return handle;
40,906,997✔
1462
  }
1463

1464
  // Case 3: The source region key is not present anywhere, but it is only due
1465
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1466
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1467
  // result in the ray tracer detecting an additional (very short) segment
1468
  // though a mesh bin that is actually past the physical source region
1469
  // boundary. This is a result of the the multi-level ray tracing treatment in
1470
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1471
  // result in the wrong surface being selected as the nearest. This can happen
1472
  // in a lattice when there are two directions that both are very close in
1473
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1474
  // treated as being equivalent so alternative logic is used. However, when we
1475
  // go and ray trace on this with the mesh tracer we may go past the surface
1476
  // bounding the current source region.
1477
  //
1478
  // To filter out this case, before we create the new source region, we double
1479
  // check that the actual starting point of this segment (r) is still in the
1480
  // same geometry source region that we started in. If an artifact is detected,
1481
  // we discard the segment (and attenuation through it) as it is not really a
1482
  // valid source region and will have only an infinitessimally small cell
1483
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1484
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1485
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1486
  // consequences for the general ray tracer, so for now we do the below sanity
1487
  // checks before generating phantom source regions. A significant extra cost
1488
  // is incurred in instantiating the GeometryState object and doing a cell
1489
  // lookup, but again, this is going to be an extremely rare thing to check
1490
  // after the first power iteration has completed.
1491

1492
  // Sanity check on source region id
1493
  GeometryState gs;
2,366,341✔
1494
  gs.r() = r + TINY_BIT * u;
2,366,341✔
1495
  gs.u() = {1.0, 0.0, 0.0};
2,366,341✔
1496
  exhaustive_find_cell(gs);
2,366,341✔
1497
  int64_t sr_found = lookup_base_source_region_idx(gs);
2,366,341✔
1498
  if (sr_found != sr_key.base_source_region_id) {
2,366,341✔
1499
    discovered_source_regions_.unlock(sr_key);
88✔
1500
    SourceRegionHandle handle;
88✔
1501
    handle.is_numerical_fp_artifact_ = true;
88✔
1502
    return handle;
88✔
1503
  }
1504

1505
  // Sanity check on mesh bin
1506
  int mesh_idx = lookup_mesh_idx(sr_key.base_source_region_id);
2,366,253✔
1507
  if (mesh_idx == C_NONE) {
2,366,253✔
1508
    if (sr_key.mesh_bin != 0) {
393,228!
1509
      discovered_source_regions_.unlock(sr_key);
×
1510
      SourceRegionHandle handle;
×
1511
      handle.is_numerical_fp_artifact_ = true;
×
1512
      return handle;
×
1513
    }
1514
  } else {
1515
    Mesh* mesh = model::meshes[mesh_idx].get();
1,973,025✔
1516
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,973,025✔
1517
    if (bin_found != sr_key.mesh_bin) {
1,973,025!
1518
      discovered_source_regions_.unlock(sr_key);
×
1519
      SourceRegionHandle handle;
×
1520
      handle.is_numerical_fp_artifact_ = true;
×
1521
      return handle;
×
1522
    }
1523
  }
1524

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

1532
  // Call the basic constructor for the source region and store in the parallel
1533
  // map.
1534
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
2,366,253✔
1535
  SourceRegion* sr_ptr =
1536
    discovered_source_regions_.emplace(sr_key, {negroups_, is_linear});
2,366,253✔
1537
  SourceRegionHandle handle {*sr_ptr};
2,366,253✔
1538

1539
  // Determine the material
1540
  int gs_i_cell = gs.lowest_coord().cell();
2,366,253✔
1541
  Cell& cell = *model::cells[gs_i_cell];
2,366,253✔
1542
  int material = cell.material(gs.cell_instance());
2,366,253✔
1543
  int temp = 0;
2,366,253✔
1544

1545
  // If material total XS is extremely low, just set it to void to avoid
1546
  // problems with 1/Sigma_t
1547
  if (material != MATERIAL_VOID) {
2,366,253✔
1548
    temp = data::mg.macro_xs_[material].get_temperature_index(
4,688,378✔
1549
      cell.sqrtkT(gs.cell_instance()));
2,344,189✔
1550
    for (int g = 0; g < negroups_; g++) {
5,036,331✔
1551
      double sigma_t =
1552
        sigma_t_[(material * ntemperature_ + temp) * negroups_ + g];
2,692,230✔
1553
      if (sigma_t < MINIMUM_MACRO_XS) {
2,692,230✔
1554
        material = MATERIAL_VOID;
88✔
1555
        temp = 0;
88✔
1556
        break;
88✔
1557
      }
1558
    }
1559
  }
1560

1561
  handle.material() = material;
2,366,253✔
1562
  handle.temperature_idx() = temp;
2,366,253✔
1563

1564
  handle.density_mult() = cell.density_mult(gs.cell_instance());
2,366,253✔
1565

1566
  // Store the mesh index (if any) assigned to this source region
1567
  handle.mesh() = mesh_idx;
2,366,253✔
1568

1569
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
2,366,253✔
1570
    // Determine if there are any volumetric sources, and apply them.
1571
    // Volumetric sources are specifc only to the base SR idx.
1572
    auto it_vol =
1573
      external_volumetric_source_map_.find(sr_key.base_source_region_id);
2,310,758✔
1574
    if (it_vol != external_volumetric_source_map_.end()) {
2,310,758✔
1575
      const vector<int>& vol_sources = it_vol->second;
4,576✔
1576
      for (int src_idx : vol_sources) {
9,152✔
1577
        apply_external_source_to_source_region(src_idx, handle);
4,576✔
1578
      }
1579
    }
1580

1581
    // Determine if there are any point sources, and apply them.
1582
    // Point sources are specific to the source region key.
1583
    auto it_point = external_point_source_map_.find(sr_key);
2,310,758✔
1584
    if (it_point != external_point_source_map_.end()) {
2,310,758✔
1585
      const vector<int>& point_sources = it_point->second;
12✔
1586
      for (int src_idx : point_sources) {
24✔
1587
        apply_external_source_to_source_region(src_idx, handle);
12✔
1588
      }
1589
    }
1590

1591
    // Divide external source term by sigma_t
1592
    if (material != C_NONE) {
2,310,758✔
1593
      for (int g = 0; g < negroups_; g++) {
4,623,171✔
1594
        double sigma_t =
1595
          sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
2,334,565✔
1596
          handle.density_mult();
2,334,565✔
1597
        handle.external_source(g) /= sigma_t;
2,334,565✔
1598
      }
1599
    }
1600
  }
1601

1602
  // Compute the combined source term
1603
  update_single_neutron_source(handle);
2,366,253✔
1604

1605
  // Unlock the parallel map. Note: we may be tempted to release
1606
  // this lock earlier, and then just use the source region's lock to protect
1607
  // the flux/source initialization stages above. However, the rest of the code
1608
  // only protects updates to the new flux and volume fields, and assumes that
1609
  // the source is constant for the duration of transport. Thus, using just the
1610
  // source region's lock by itself would result in other threads potentially
1611
  // reading from the source before it is computed, as they won't use the lock
1612
  // when only reading from the SR's source. It would be expensive to protect
1613
  // those operations, whereas generating the SR is only done once, so we just
1614
  // hold the map's bucket lock until the source region is fully initialized.
1615
  discovered_source_regions_.unlock(sr_key);
2,366,253✔
1616

1617
  return handle;
2,366,253✔
1618
}
2,366,341✔
1619

1620
void FlatSourceDomain::finalize_discovered_source_regions()
13,102✔
1621
{
1622
  // Extract keys for entries with a valid volume.
1623
  vector<SourceRegionKey> keys;
13,102✔
1624
  for (const auto& pair : discovered_source_regions_) {
2,379,355✔
1625
    if (pair.second.volume_ > 0.0) {
2,366,253✔
1626
      keys.push_back(pair.first);
2,264,811✔
1627
    }
1628
  }
1629

1630
  if (!keys.empty()) {
13,102✔
1631
    // Sort the keys, so as to ensure reproducible ordering given that source
1632
    // regions may have been added to discovered_source_regions_ in an arbitrary
1633
    // order due to shared memory threading.
1634
    std::sort(keys.begin(), keys.end());
870✔
1635

1636
    // Remember the index of the first new source region
1637
    int64_t start_sr_id = source_regions_.n_source_regions();
870✔
1638

1639
    // Append the source regions in the sorted key order.
1640
    for (const auto& key : keys) {
2,265,681✔
1641
      const SourceRegion& sr = discovered_source_regions_[key];
2,264,811✔
1642
      source_region_map_[key] = source_regions_.n_source_regions();
2,264,811✔
1643
      source_regions_.push_back(sr);
2,264,811✔
1644
    }
1645

1646
    // Map all new source regions to tallies
1647
    convert_source_regions_to_tallies(start_sr_id);
870✔
1648
  }
1649

1650
  discovered_source_regions_.clear();
13,102✔
1651
}
13,102✔
1652

1653
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1654
//
1655
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1656
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1657
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1658
// https://doi.org/10.1016/j.anucene.2018.10.036.
1659
void FlatSourceDomain::apply_transport_stabilization()
13,102✔
1660
{
1661
  // Don't do anything if all in-group scattering
1662
  // cross sections are positive
1663
  if (!is_transport_stabilization_needed_) {
13,102✔
1664
    return;
12,882✔
1665
  }
1666

1667
  // Apply the stabilization factor to all source elements
1668
#pragma omp parallel for
120✔
1669
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,300✔
1670
    int material = source_regions_.material(sr);
1,200✔
1671
    int temp = source_regions_.temperature_idx(sr);
1,200✔
1672
    double density_mult = source_regions_.density_mult(sr);
1,200✔
1673
    if (material == MATERIAL_VOID) {
1,200!
1674
      continue;
1675
    }
1676
    for (int g = 0; g < negroups_; g++) {
85,200✔
1677
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1678
      // negative
1679
      double sigma_s =
1680
        sigma_s_[((material * ntemperature_ + temp) * negroups_ + g) *
84,000✔
1681
                   negroups_ +
84,000✔
1682
                 g] *
84,000✔
1683
        density_mult;
84,000✔
1684
      if (sigma_s < 0.0) {
84,000✔
1685
        double sigma_t =
1686
          sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
22,000✔
1687
          density_mult;
22,000✔
1688
        double phi_new = source_regions_.scalar_flux_new(sr, g);
22,000✔
1689
        double phi_old = source_regions_.scalar_flux_old(sr, g);
22,000✔
1690

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

1701
        // Equation 16 in the above Gunow et al. 2019 paper
1702
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1703
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1704
      }
1705
    }
1706
  }
1707
}
1708

1709
// Determines the base source region index (i.e., a material filled cell
1710
// instance) that corresponds to a particular location in the geometry. Requires
1711
// that the "gs" object passed in has already been initialized and has called
1712
// find_cell etc.
1713
int64_t FlatSourceDomain::lookup_base_source_region_idx(
848,755,209✔
1714
  const GeometryState& gs) const
1715
{
1716
  int i_cell = gs.lowest_coord().cell();
848,755,209✔
1717
  int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
848,755,209✔
1718
  return sr;
848,755,209✔
1719
}
1720

1721
// Determines the index of the mesh (if any) that has been applied
1722
// to a particular base source region index.
1723
int FlatSourceDomain::lookup_mesh_idx(int64_t sr) const
848,755,121✔
1724
{
1725
  int mesh_idx = C_NONE;
848,755,121✔
1726
  auto mesh_it = mesh_map_.find(sr);
848,755,121✔
1727
  if (mesh_it != mesh_map_.end()) {
848,755,121✔
1728
    mesh_idx = mesh_it->second;
477,517,804✔
1729
  }
1730
  return mesh_idx;
848,755,121✔
1731
}
1732

1733
// Determines the source region key that corresponds to a particular location in
1734
// the geometry. This takes into account both the base source region index as
1735
// well as the mesh bin if a mesh is applied to this source region for
1736
// subdivision.
1737
SourceRegionKey FlatSourceDomain::lookup_source_region_key(
2,009,337✔
1738
  const GeometryState& gs) const
1739
{
1740
  int64_t sr = lookup_base_source_region_idx(gs);
2,009,337✔
1741
  int64_t mesh_bin = lookup_mesh_bin(sr, gs.r());
2,009,337✔
1742
  return SourceRegionKey {sr, mesh_bin};
2,009,337✔
1743
}
1744

1745
// Determines the mesh bin that corresponds to a particular base source region
1746
// index and position.
1747
int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const
2,009,337✔
1748
{
1749
  int mesh_idx = lookup_mesh_idx(sr);
2,009,337✔
1750
  int mesh_bin = 0;
2,009,337✔
1751
  if (mesh_idx != C_NONE) {
2,009,337✔
1752
    mesh_bin = model::meshes[mesh_idx]->get_bin(r);
1,255,837✔
1753
  }
1754
  return mesh_bin;
2,009,337✔
1755
}
1756

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