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

openmc-dev / openmc / 15914061027

26 Jun 2025 10:49PM UTC coverage: 85.241% (+0.002%) from 85.239%
15914061027

Pull #3461

github

web-flow
Merge 09b49b487 into 5c1021446
Pull Request #3461: Refactor and Harden Configuration Management

48 of 56 new or added lines in 1 file covered. (85.71%)

280 existing lines in 11 files now uncovered.

52596 of 61703 relevant lines covered (85.24%)

36708109.72 hits per line

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

78.62
/src/random_ray/flat_source_domain.cpp
1
#include "openmc/random_ray/flat_source_domain.h"
2

3
#include "openmc/cell.h"
4
#include "openmc/constants.h"
5
#include "openmc/eigenvalue.h"
6
#include "openmc/geometry.h"
7
#include "openmc/material.h"
8
#include "openmc/message_passing.h"
9
#include "openmc/mgxs_interface.h"
10
#include "openmc/output.h"
11
#include "openmc/plot.h"
12
#include "openmc/random_ray/random_ray.h"
13
#include "openmc/simulation.h"
14
#include "openmc/tallies/filter.h"
15
#include "openmc/tallies/tally.h"
16
#include "openmc/tallies/tally_scoring.h"
17
#include "openmc/timer.h"
18
#include "openmc/weight_windows.h"
19

20
#include <cstdio>
21

22
namespace openmc {
23

24
//==============================================================================
25
// FlatSourceDomain implementation
26
//==============================================================================
27

28
// Static Variable Declarations
29
RandomRayVolumeEstimator FlatSourceDomain::volume_estimator_ {
30
  RandomRayVolumeEstimator::HYBRID};
31
bool FlatSourceDomain::volume_normalized_flux_tallies_ {false};
32
bool FlatSourceDomain::adjoint_ {false};
33
double FlatSourceDomain::diagonal_stabilization_rho_ {1.0};
34
std::unordered_map<int, vector<std::pair<Source::DomainType, int>>>
35
  FlatSourceDomain::mesh_domain_map_;
36

37
FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_)
640✔
38
{
39
  // Count the number of source regions, compute the cell offset
40
  // indices, and store the material type The reason for the offsets is that
41
  // some cell types may not have material fills, and therefore do not
42
  // produce FSRs. Thus, we cannot index into the global arrays directly
43
  int base_source_regions = 0;
640✔
44
  for (const auto& c : model::cells) {
5,456✔
45
    if (c->type_ != Fill::MATERIAL) {
4,816✔
46
      source_region_offsets_.push_back(-1);
2,320✔
47
    } else {
48
      source_region_offsets_.push_back(base_source_regions);
2,496✔
49
      base_source_regions += c->n_instances_;
2,496✔
50
    }
51
  }
52

53
  // Initialize source regions.
54
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
640✔
55
  source_regions_ = SourceRegionContainer(negroups_, is_linear);
640✔
56
  source_regions_.assign(
640✔
57
    base_source_regions, SourceRegion(negroups_, is_linear));
1,280✔
58

59
  // Initialize materials
60
  int64_t source_region_id = 0;
640✔
61
  for (int i = 0; i < model::cells.size(); i++) {
5,456✔
62
    Cell& cell = *model::cells[i];
4,816✔
63
    if (cell.type_ == Fill::MATERIAL) {
4,816✔
64
      for (int j = 0; j < cell.n_instances_; j++) {
768,192✔
65
        source_regions_.material(source_region_id++) = cell.material(j);
765,696✔
66
      }
67
    }
68
  }
69

70
  // Sanity check
71
  if (source_region_id != base_source_regions) {
640✔
72
    fatal_error("Unexpected number of source regions");
×
73
  }
74

75
  // Initialize tally volumes
76
  if (volume_normalized_flux_tallies_) {
640✔
77
    tally_volumes_.resize(model::tallies.size());
512✔
78
    for (int i = 0; i < model::tallies.size(); i++) {
1,920✔
79
      //  Get the shape of the 3D result tensor
80
      auto shape = model::tallies[i]->results().shape();
1,408✔
81

82
      // Create a new 2D tensor with the same size as the first
83
      // two dimensions of the 3D tensor
84
      tally_volumes_[i] =
1,408✔
85
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,816✔
86
    }
87
  }
88

89
  // Compute simulation domain volume based on ray source
90
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
640✔
91
  SpatialDistribution* space_dist = is->space();
640✔
92
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
640✔
93
  Position dims = sb->upper_right() - sb->lower_left();
640✔
94
  simulation_volume_ = dims.x * dims.y * dims.z;
640✔
95
}
640✔
96

97
void FlatSourceDomain::batch_reset()
11,550✔
98
{
99
// Reset scalar fluxes and iteration volume tallies to zero
100
#pragma omp parallel for
6,300✔
101
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
32,447,285✔
102
    source_regions_.volume(sr) = 0.0;
32,442,035✔
103
    source_regions_.volume_sq(sr) = 0.0;
32,442,035✔
104
  }
105

106
#pragma omp parallel for
6,300✔
107
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,741,425✔
108
    source_regions_.scalar_flux_new(se) = 0.0;
36,736,175✔
109
  }
110
}
11,550✔
111

112
void FlatSourceDomain::accumulate_iteration_flux()
4,675✔
113
{
114
#pragma omp parallel for
2,550✔
115
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,591,525✔
116
    source_regions_.scalar_flux_final(se) +=
16,589,400✔
117
      source_regions_.scalar_flux_new(se);
16,589,400✔
118
  }
119
}
4,675✔
120

121
// Compute new estimate of scattering + fission sources in each source region
122
// based on the flux estimate from the previous iteration.
123
void FlatSourceDomain::update_neutron_source(double k_eff)
5,115✔
124
{
125
  simulation::time_update_src.start();
5,115✔
126

127
  double inverse_k_eff = 1.0 / k_eff;
5,115✔
128

129
// Reset all source regions to zero (important for void regions)
130
#pragma omp parallel for
2,790✔
131
  for (int64_t se = 0; se < n_source_elements(); se++) {
21,597,915✔
132
    source_regions_.source(se) = 0.0;
21,595,590✔
133
  }
134

135
  // Add scattering + fission source
136
#pragma omp parallel for
2,790✔
137
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,275,735✔
138
    int material = source_regions_.material(sr);
19,273,410✔
139
    if (material == MATERIAL_VOID) {
19,273,410✔
140
      continue;
200,000✔
141
    }
142
    for (int g_out = 0; g_out < negroups_; g_out++) {
40,469,000✔
143
      double sigma_t = sigma_t_[material * negroups_ + g_out];
21,395,590✔
144
      double scatter_source = 0.0;
21,395,590✔
145
      double fission_source = 0.0;
21,395,590✔
146

147
      for (int g_in = 0; g_in < negroups_; g_in++) {
59,046,440✔
148
        double scalar_flux = source_regions_.scalar_flux_old(sr, g_in);
37,650,850✔
149
        double sigma_s =
150
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
37,650,850✔
151
        double nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
37,650,850✔
152
        double chi = chi_[material * negroups_ + g_out];
37,650,850✔
153

154
        scatter_source += sigma_s * scalar_flux;
37,650,850✔
155
        fission_source += nu_sigma_f * scalar_flux * chi;
37,650,850✔
156
      }
157
      source_regions_.source(sr, g_out) =
21,395,590✔
158
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
21,395,590✔
159
    }
160
  }
161

162
  // Add external source if in fixed source mode
163
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,115✔
164
#pragma omp parallel for
2,430✔
165
    for (int64_t se = 0; se < n_source_elements(); se++) {
20,385,305✔
166
      source_regions_.source(se) += source_regions_.external_source(se);
20,383,280✔
167
    }
168
  }
169

170
  simulation::time_update_src.stop();
5,115✔
171
}
5,115✔
172

173
// Normalizes flux and updates simulation-averaged volume estimate
174
void FlatSourceDomain::normalize_scalar_flux_and_volumes(
5,115✔
175
  double total_active_distance_per_iteration)
176
{
177
  double normalization_factor = 1.0 / total_active_distance_per_iteration;
5,115✔
178
  double volume_normalization_factor =
5,115✔
179
    1.0 / (total_active_distance_per_iteration * simulation::current_batch);
5,115✔
180

181
// Normalize scalar flux to total distance travelled by all rays this
182
// iteration
183
#pragma omp parallel for
2,790✔
184
  for (int64_t se = 0; se < n_source_elements(); se++) {
22,191,335✔
185
    source_regions_.scalar_flux_new(se) *= normalization_factor;
22,189,010✔
186
  }
187

188
// Accumulate cell-wise ray length tallies collected this iteration, then
189
// update the simulation-averaged cell-wise volume estimates
190
#pragma omp parallel for
2,790✔
191
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,796,795✔
192
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
19,794,470✔
193
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
19,794,470✔
194
    source_regions_.volume_naive(sr) =
39,588,940✔
195
      source_regions_.volume(sr) * normalization_factor;
19,794,470✔
196
    source_regions_.volume_sq(sr) =
39,588,940✔
197
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
19,794,470✔
198
    source_regions_.volume(sr) =
19,794,470✔
199
      source_regions_.volume_t(sr) * volume_normalization_factor;
19,794,470✔
200
  }
201
}
5,115✔
202

203
void FlatSourceDomain::set_flux_to_flux_plus_source(
43,220,045✔
204
  int64_t sr, double volume, int g)
205
{
206
  int material = source_regions_.material(sr);
43,220,045✔
207
  if (material == MATERIAL_VOID) {
43,220,045✔
208
    source_regions_.scalar_flux_new(sr, g) /= volume;
880,000✔
209
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
880,000✔
210
      source_regions_.scalar_flux_new(sr, g) +=
880,000✔
211
        0.5f * source_regions_.external_source(sr, g) *
880,000✔
212
        source_regions_.volume_sq(sr);
880,000✔
213
    }
214
  } else {
215
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
42,340,045✔
216
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
42,340,045✔
217
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
42,340,045✔
218
  }
219
}
43,220,045✔
220

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

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

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

239
#pragma omp parallel for reduction(+ : n_hits)
6,300✔
240
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,252,885✔
241

242
    double volume_simulation_avg = source_regions_.volume(sr);
33,247,635✔
243
    double volume_iteration = source_regions_.volume_naive(sr);
33,247,635✔
244

245
    // Increment the number of hits if cell was hit this iteration
246
    if (volume_iteration) {
33,247,635✔
247
      n_hits++;
29,188,480✔
248
    }
249

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

258
    // The volume treatment depends on the volume estimator type
259
    // and whether or not an external source is present in the cell.
260
    double volume;
261
    switch (volume_estimator_) {
33,247,635✔
262
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
263
      volume = volume_iteration;
777,600✔
264
      break;
777,600✔
265
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
266
      volume = volume_simulation_avg;
432,000✔
267
      break;
432,000✔
268
    case RandomRayVolumeEstimator::HYBRID:
32,038,035✔
269
      if (source_regions_.external_source_present(sr) ||
59,888,470✔
270
          source_regions_.is_small(sr)) {
27,850,435✔
271
        volume = volume_iteration;
10,999,925✔
272
      } else {
273
        volume = volume_simulation_avg;
21,038,110✔
274
      }
275
      break;
32,038,035✔
276
    default:
277
      fatal_error("Invalid volume estimator type");
278
    }
279

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

429
void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id)
748✔
430
{
431
  openmc::simulation::time_tallies.start();
748✔
432

433
  // Tracks if we've generated a mapping yet for all source regions.
434
  bool all_source_regions_mapped = true;
748✔
435

436
// Attempt to generate mapping for all source regions
437
#pragma omp parallel for
408✔
438
  for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) {
1,027,940✔
439

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

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

456
    // Loop over energy groups (so as to support energy filters)
457
    for (int g = 0; g < negroups_; g++) {
2,204,000✔
458

459
      // Set particle to the current energy
460
      p.g() = g;
1,176,400✔
461
      p.g_last() = g;
1,176,400✔
462
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,176,400✔
463
      p.E_last() = p.E();
1,176,400✔
464

465
      int64_t source_element = sr * negroups_ + g;
1,176,400✔
466

467
      // If this task has already been populated, we don't need to do
468
      // it again.
469
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,176,400✔
470
        continue;
471
      }
472

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

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

487
        // Loop over filter bins.
488
        for (; filter_iter != end; ++filter_iter) {
2,649,600✔
489
          auto filter_index = filter_iter.index_;
1,324,800✔
490
          auto filter_weight = filter_iter.weight_;
1,324,800✔
491

492
          // Loop over scores
493
          for (int score = 0; score < tally.scores_.size(); score++) {
2,986,720✔
494
            auto score_bin = tally.scores_[score];
1,661,920✔
495
            // If a valid tally, filter, and score combination has been found,
496
            // then add it to the list of tally tasks for this source element.
497
            TallyTask task(i_tally, filter_index, score, score_bin);
1,661,920✔
498
            source_regions_.tally_task(sr, g).push_back(task);
1,661,920✔
499

500
            // Also add this task to the list of volume tasks for this source
501
            // region.
502
            source_regions_.volume_task(sr).insert(task);
1,661,920✔
503
          }
504
        }
505
      }
506
      // Reset all the filter matches for the next tally event.
507
      for (auto& match : p.filter_matches())
4,982,240✔
508
        match.bins_present_ = false;
3,805,840✔
509
    }
510
  }
1,027,600✔
511
  openmc::simulation::time_tallies.stop();
748✔
512

513
  mapped_all_tallies_ = all_source_regions_mapped;
748✔
514
}
748✔
515

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

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

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

564
  // Step 2 is to determine the total user-specified external source strength
565
  double user_external_source_strength = 0.0;
3,739✔
566
  for (auto& ext_source : model::external_sources) {
7,478✔
567
    user_external_source_strength += ext_source->strength();
3,739✔
568
  }
569

570
  // The correction factor is the ratio of the user-specified external source
571
  // strength to the simulation external source strength.
572
  double source_normalization_factor =
3,739✔
573
    user_external_source_strength / simulation_external_source_strength;
574

575
  return source_normalization_factor;
3,739✔
576
}
577

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

587
void FlatSourceDomain::random_ray_tally()
4,675✔
588
{
589
  openmc::simulation::time_tallies.start();
4,675✔
590

591
  // Reset our tally volumes to zero
592
  reset_tally_volumes();
4,675✔
593

594
  double source_normalization_factor =
595
    compute_fixed_source_normalization_factor();
4,675✔
596

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

613
    double material = source_regions_.material(sr);
15,208,200✔
614
    for (int g = 0; g < negroups_; g++) {
31,797,600✔
615
      double flux =
616
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,589,400✔
617

618
      // Determine numerical score value
619
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,166,800✔
620
        double score = 0.0;
22,577,400✔
621
        switch (task.score_type) {
22,577,400✔
622

623
        case SCORE_FLUX:
19,405,000✔
624
          score = flux * volume;
19,405,000✔
625
          break;
19,405,000✔
626

627
        case SCORE_TOTAL:
628
          if (material != MATERIAL_VOID) {
629
            score = flux * volume * sigma_t_[material * negroups_ + g];
630
          }
631
          break;
632

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

639
        case SCORE_NU_FISSION:
1,586,200✔
640
          if (material != MATERIAL_VOID) {
1,586,200✔
641
            score = flux * volume * nu_sigma_f_[material * negroups_ + g];
1,586,200✔
642
          }
643
          break;
1,586,200✔
644

645
        case SCORE_EVENTS:
646
          score = 1.0;
647
          break;
648

649
        default:
650
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
651
                      "total, fission, nu-fission, and events are supported in "
652
                      "random ray mode.");
653
          break;
654
        }
655

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

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

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

701
  openmc::simulation::time_tallies.stop();
4,675✔
702
}
4,675✔
703

UNCOV
704
double FlatSourceDomain::evaluate_flux_at_point(
×
705
  Position r, int64_t sr, int g) const
706
{
UNCOV
707
  return source_regions_.scalar_flux_final(sr, g) /
×
UNCOV
708
         (settings::n_batches - settings::n_inactive);
×
709
}
710

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

725
  // Print header information
UNCOV
726
  print_plot();
×
727

728
  // Outer loop over plots
UNCOV
729
  for (int p = 0; p < model::plots.size(); p++) {
×
730

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

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

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

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

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

789
          bool found = exhaustive_find_cell(p);
790
          if (!found) {
791
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
792
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
793
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
794
            continue;
795
          }
796

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

816
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
817
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
818

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

831
    double source_normalization_factor =
UNCOV
832
      compute_fixed_source_normalization_factor();
×
833

834
    // Open file for writing
835
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
836

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

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

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

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

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

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

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

UNCOV
965
    std::fclose(plot);
×
966
  }
967
}
968

969
void FlatSourceDomain::apply_external_source_to_source_region(
2,731✔
970
  Discrete* discrete, double strength_factor, SourceRegionHandle& srh)
971
{
972
  srh.external_source_present() = 1;
2,731✔
973

974
  const auto& discrete_energies = discrete->x();
2,731✔
975
  const auto& discrete_probs = discrete->prob();
2,731✔
976

977
  for (int i = 0; i < discrete_energies.size(); i++) {
5,654✔
978
    int g = data::mg.get_group_index(discrete_energies[i]);
2,923✔
979
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,923✔
980
  }
981
}
2,731✔
982

983
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
400✔
984
  Discrete* discrete, double strength_factor, int target_material_id,
985
  const vector<int32_t>& instances)
986
{
987
  Cell& cell = *model::cells[i_cell];
400✔
988

989
  if (cell.type_ != Fill::MATERIAL)
400✔
UNCOV
990
    return;
×
991

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

1010
void FlatSourceDomain::apply_external_source_to_cell_and_children(
432✔
1011
  int32_t i_cell, Discrete* discrete, double strength_factor,
1012
  int32_t target_material_id)
1013
{
1014
  Cell& cell = *model::cells[i_cell];
432✔
1015

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

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

1043
void FlatSourceDomain::convert_external_sources()
384✔
1044
{
1045
  // Loop over external sources
1046
  for (int es = 0; es < model::external_sources.size(); es++) {
768✔
1047

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

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

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

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

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

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

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

1153
void FlatSourceDomain::flatten_xs()
640✔
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 temp/single angle data.
1158
  const int t = 0;
640✔
1159
  const int a = 0;
640✔
1160

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

1169
        double nu_sigma_f =
1170
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1171
        nu_sigma_f_.push_back(nu_sigma_f);
6,864✔
1172

1173
        double sigma_f =
1174
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
6,864✔
1175
        sigma_f_.push_back(sigma_f);
6,864✔
1176

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

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

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

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

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

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

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

1271
        // Swap the elements to transpose the matrix
1272
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1273
      }
1274
    }
1275
  }
1276
}
80✔
1277

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

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

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

1316
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
480✔
1317
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1318
{
1319
  Cell& cell = *model::cells[i_cell];
480✔
1320

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

1339
void FlatSourceDomain::apply_meshes()
560✔
1340
{
1341
  // Skip if there are no mappings between mesh IDs and domains
1342
  if (mesh_domain_map_.empty())
560✔
1343
    return;
400✔
1344

1345
  // Loop over meshes
1346
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
400✔
1347
    Mesh* mesh = model::meshes[mesh_idx].get();
240✔
1348
    int mesh_id = mesh->id();
240✔
1349

1350
    // Skip if mesh id is not present in the map
1351
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
240✔
1352
      continue;
16✔
1353

1354
    // Loop over domains associated with the mesh
1355
    for (auto& domain : mesh_domain_map_[mesh_id]) {
448✔
1356
      Source::DomainType domain_type = domain.first;
224✔
1357
      int domain_id = domain.second;
224✔
1358

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

1381
void FlatSourceDomain::prepare_base_source_regions()
110✔
1382
{
1383
  std::swap(source_regions_, base_source_regions_);
110✔
1384
  source_regions_.negroups() = base_source_regions_.negroups();
110✔
1385
  source_regions_.is_linear() = base_source_regions_.is_linear();
110✔
1386
}
110✔
1387

1388
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
871,515,854✔
1389
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1390
{
1391
  SourceRegionKey sr_key {sr, mesh_bin};
871,515,854✔
1392

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

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

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

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

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

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

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

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

1514
  return handle;
1,971,618✔
1515
}
1,971,706✔
1516

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

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

1533
    // Remember the index of the first new source region
1534
    int64_t start_sr_id = source_regions_.n_source_regions();
440✔
1535

1536
    // Append the source regions in the sorted key order.
1537
    for (const auto& key : keys) {
1,870,616✔
1538
      const SourceRegion& sr = discovered_source_regions_[key];
1,870,176✔
1539
      source_region_map_[key] = source_regions_.n_source_regions();
1,870,176✔
1540
      source_regions_.push_back(sr);
1,870,176✔
1541
    }
1542

1543
    // Map all new source regions to tallies
1544
    convert_source_regions_to_tallies(start_sr_id);
440✔
1545
  }
1546

1547
  discovered_source_regions_.clear();
2,970✔
1548
}
2,970✔
1549

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

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

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

1591
        // Equation 16 in the above Gunow et al. 2019 paper
1592
        source_regions_.scalar_flux_new(sr, g) =
22,000✔
1593
          (phi_new - D * phi_old) / (1.0 - D);
22,000✔
1594
      }
1595
    }
1596
  }
1597
}
1598

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

© 2025 Coveralls, Inc