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

openmc-dev / openmc / 13712674732

07 Mar 2025 02:48AM UTC coverage: 85.126% (-0.001%) from 85.127%
13712674732

push

github

web-flow
Random Ray Source Region Mesh Subdivision (Cell-Under-Voxel Geometry) (#3333)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

550 of 637 new or added lines in 12 files covered. (86.34%)

7 existing lines in 3 files now uncovered.

51572 of 60583 relevant lines covered (85.13%)

36891325.97 hits per line

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

77.93
/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
std::unordered_map<int, vector<std::pair<Source::DomainType, int>>>
34
  FlatSourceDomain::mesh_domain_map_;
35

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

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

58
  // Initialize materials
59
  int64_t source_region_id = 0;
560✔
60
  for (int i = 0; i < model::cells.size(); i++) {
5,104✔
61
    Cell& cell = *model::cells[i];
4,544✔
62
    if (cell.type_ == Fill::MATERIAL) {
4,544✔
63
      for (int j = 0; j < cell.n_instances_; j++) {
740,112✔
64
        source_regions_.material(source_region_id++) = cell.material(j);
737,856✔
65
      }
66
    }
67
  }
68

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

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

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

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

96
void FlatSourceDomain::batch_reset()
10,670✔
97
{
98
// Reset scalar fluxes and iteration volume tallies to zero
99
#pragma omp parallel for
5,820✔
100
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
25,742,790✔
101
    source_regions_.volume(sr) = 0.0;
25,737,940✔
102
    source_regions_.volume_sq(sr) = 0.0;
25,737,940✔
103
  }
104

105
#pragma omp parallel for
5,820✔
106
  for (int64_t se = 0; se < n_source_elements(); se++) {
29,955,570✔
107
    source_regions_.scalar_flux_new(se) = 0.0;
29,950,720✔
108
  }
109
}
10,670✔
110

111
void FlatSourceDomain::accumulate_iteration_flux()
4,290✔
112
{
113
#pragma omp parallel for
2,340✔
114
  for (int64_t se = 0; se < n_source_elements(); se++) {
13,069,350✔
115
    source_regions_.scalar_flux_final(se) +=
13,067,400✔
116
      source_regions_.scalar_flux_new(se);
13,067,400✔
117
  }
118
}
4,290✔
119

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

126
  double inverse_k_eff = 1.0 / k_eff;
4,785✔
127

128
// Reset all source regions to zero (important for void regions)
129
#pragma omp parallel for
2,610✔
130
  for (int64_t se = 0; se < n_source_elements(); se++) {
14,896,490✔
131
    source_regions_.source(se) = 0.0;
14,894,315✔
132
  }
133

134
  // Add scattering + fission source
135
#pragma omp parallel for
2,610✔
136
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
12,574,310✔
137
    int material = source_regions_.material(sr);
12,572,135✔
138
    if (material == MATERIAL_VOID) {
12,572,135✔
139
      continue;
200,000✔
140
    }
141
    for (int g_out = 0; g_out < negroups_; g_out++) {
27,066,450✔
142
      double sigma_t = sigma_t_[material * negroups_ + g_out];
14,694,315✔
143
      double scatter_source = 0.0;
14,694,315✔
144
      double fission_source = 0.0;
14,694,315✔
145

146
      for (int g_in = 0; g_in < negroups_; g_in++) {
45,643,890✔
147
        double scalar_flux = source_regions_.scalar_flux_old(sr, g_in);
30,949,575✔
148
        double sigma_s =
149
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
30,949,575✔
150
        double nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
30,949,575✔
151
        double chi = chi_[material * negroups_ + g_out];
30,949,575✔
152

153
        scatter_source += sigma_s * scalar_flux;
30,949,575✔
154
        fission_source += nu_sigma_f * scalar_flux * chi;
30,949,575✔
155
      }
156
      source_regions_.source(sr, g_out) =
14,694,315✔
157
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
14,694,315✔
158
    }
159
  }
160

161
  // Add external source if in fixed source mode
162
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
4,785✔
163
#pragma omp parallel for
2,250✔
164
    for (int64_t se = 0; se < n_source_elements(); se++) {
13,683,880✔
165
      source_regions_.source(se) += source_regions_.external_source(se);
13,682,005✔
166
    }
167
  }
168

169
  simulation::time_update_src.stop();
4,785✔
170
}
4,785✔
171

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

180
// Normalize scalar flux to total distance travelled by all rays this
181
// iteration
182
#pragma omp parallel for
2,610✔
183
  for (int64_t se = 0; se < n_source_elements(); se++) {
15,265,270✔
184
    source_regions_.scalar_flux_new(se) *= normalization_factor;
15,263,095✔
185
  }
186

187
// Accumulate cell-wise ray length tallies collected this iteration, then
188
// update the simulation-averaged cell-wise volume estimates
189
#pragma omp parallel for
2,610✔
190
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
12,870,730✔
191
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
12,868,555✔
192
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
12,868,555✔
193
    source_regions_.volume_naive(sr) =
25,737,110✔
194
      source_regions_.volume(sr) * normalization_factor;
12,868,555✔
195
    source_regions_.volume_sq(sr) =
25,737,110✔
196
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
12,868,555✔
197
    source_regions_.volume(sr) =
12,868,555✔
198
      source_regions_.volume_t(sr) * volume_normalization_factor;
12,868,555✔
199
  }
200
}
4,785✔
201

202
void FlatSourceDomain::set_flux_to_flux_plus_source(
31,123,708✔
203
  int64_t sr, double volume, int g)
204
{
205
  int material = source_regions_.material(sr);
31,123,708✔
206
  if (material == MATERIAL_VOID) {
31,123,708✔
207
    source_regions_.scalar_flux_new(sr, g) /= volume;
880,000✔
208
    source_regions_.scalar_flux_new(sr, g) +=
880,000✔
209
      0.5f * source_regions_.external_source(sr, g) *
880,000✔
210
      source_regions_.volume_sq(sr);
880,000✔
211
  } else {
212
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
30,243,708✔
213
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
30,243,708✔
214
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
30,243,708✔
215
  }
216
}
31,123,708✔
217

218
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
990✔
219
{
220
  source_regions_.scalar_flux_new(sr, g) =
1,980✔
221
    source_regions_.scalar_flux_old(sr, g);
990✔
222
}
990✔
223

224
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
5,787,793✔
225
{
226
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
5,787,793✔
227
}
5,787,793✔
228

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

236
#pragma omp parallel for reduction(+ : n_hits)
5,820✔
237
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
26,323,570✔
238

239
    double volume_simulation_avg = source_regions_.volume(sr);
26,318,720✔
240
    double volume_iteration = source_regions_.volume_naive(sr);
26,318,720✔
241

242
    // Increment the number of hits if cell was hit this iteration
243
    if (volume_iteration) {
26,318,720✔
244
      n_hits++;
23,687,145✔
245
    }
246

247
    // Set the SR to small status if its expected number of hits
248
    // per iteration is less than 1.5
249
    if (source_regions_.n_hits(sr) * inverse_batch < MIN_HITS_PER_BATCH) {
26,318,720✔
250
      source_regions_.is_small(sr) = 1;
4,172,940✔
251
    } else {
252
      source_regions_.is_small(sr) = 0;
22,145,780✔
253
    }
254

255
    // The volume treatment depends on the volume estimator type
256
    // and whether or not an external source is present in the cell.
257
    double volume;
258
    switch (volume_estimator_) {
26,318,720✔
259
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
260
      volume = volume_iteration;
777,600✔
261
      break;
777,600✔
262
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
263
      volume = volume_simulation_avg;
432,000✔
264
      break;
432,000✔
265
    case RandomRayVolumeEstimator::HYBRID:
25,109,120✔
266
      if (source_regions_.external_source_present(sr) ||
46,030,780✔
267
          source_regions_.is_small(sr)) {
20,921,660✔
268
        volume = volume_iteration;
8,360,160✔
269
      } else {
270
        volume = volume_simulation_avg;
16,748,960✔
271
      }
272
      break;
25,109,120✔
273
    default:
274
      fatal_error("Invalid volume estimator type");
275
    }
276

277
    for (int g = 0; g < negroups_; g++) {
56,922,580✔
278
      // There are three scenarios we need to consider:
279
      if (volume_iteration > 0.0) {
30,603,860✔
280
        // 1. If the FSR was hit this iteration, then the new flux is equal to
281
        // the flat source from the previous iteration plus the contributions
282
        // from rays passing through the source region (computed during the
283
        // transport sweep)
284
        set_flux_to_flux_plus_source(sr, volume, g);
27,972,135✔
285
      } else if (volume_simulation_avg > 0.0) {
2,631,725✔
286
        // 2. If the FSR was not hit this iteration, but has been hit some
287
        // previous iteration, then we need to make a choice about what
288
        // to do. Naively we will usually want to set the flux to be equal
289
        // to the reduced source. However, in fixed source problems where
290
        // there is a strong external source present in the cell, and where
291
        // the cell has a very low cross section, this approximation will
292
        // cause a huge upward bias in the flux estimate of the cell (in these
293
        // conditions, the flux estimate can be orders of magnitude too large).
294
        // Thus, to avoid this bias, if any external source is present
295
        // in the cell we will use the previous iteration's flux estimate. This
296
        // injects a small degree of correlation into the simulation, but this
297
        // is going to be trivial when the miss rate is a few percent or less.
298
        if (source_regions_.external_source_present(sr) && !adjoint_) {
2,631,715✔
299
          set_flux_to_old_flux(sr, g);
900✔
300
        } else {
301
          set_flux_to_source(sr, g);
2,630,815✔
302
        }
303
      }
304
    }
305
  }
306

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

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

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

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

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

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

335
    double sr_fission_source_old = 0;
304,790✔
336
    double sr_fission_source_new = 0;
304,790✔
337

338
    for (int g = 0; g < negroups_; g++) {
2,284,720✔
339
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
1,979,930✔
340
      sr_fission_source_old +=
1,979,930✔
341
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
1,979,930✔
342
      sr_fission_source_new +=
1,979,930✔
343
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
1,979,930✔
344
    }
345

346
    // Compute total fission rates in FSR
347
    sr_fission_source_old *= volume;
304,790✔
348
    sr_fission_source_new *= volume;
304,790✔
349

350
    // Accumulate totals
351
    fission_rate_old += sr_fission_source_old;
304,790✔
352
    fission_rate_new += sr_fission_source_new;
304,790✔
353

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

358
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
1,540✔
359

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

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

375
  // Adds entropy value to shared entropy vector in openmc namespace.
376
  simulation::entropy.push_back(H);
1,540✔
377

378
  return k_eff_new;
1,540✔
379
}
1,540✔
380

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

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

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

414
void FlatSourceDomain::convert_source_regions_to_tallies()
385✔
415
{
416
  openmc::simulation::time_tallies.start();
385✔
417

418
  // Tracks if we've generated a mapping yet for all source regions.
419
  bool all_source_regions_mapped = true;
385✔
420

421
// Attempt to generate mapping for all source regions
422
#pragma omp parallel for
210✔
423
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
932,495✔
424

425
    // If this source region has not been hit by a ray yet, then
426
    // we aren't going to be able to map it, so skip it.
427
    if (!source_regions_.position_recorded(sr)) {
932,320✔
428
      all_source_regions_mapped = false;
429
      continue;
430
    }
431

432
    // A particle located at the recorded midpoint of a ray
433
    // crossing through this source region is used to estabilish
434
    // the spatial location of the source region
435
    Particle p;
932,320✔
436
    p.r() = source_regions_.position(sr);
932,320✔
437
    p.r_last() = source_regions_.position(sr);
932,320✔
438
    p.u() = {1.0, 0.0, 0.0};
932,320✔
439
    bool found = exhaustive_find_cell(p);
932,320✔
440

441
    // Loop over energy groups (so as to support energy filters)
442
    for (int g = 0; g < negroups_; g++) {
2,009,120✔
443

444
      // Set particle to the current energy
445
      p.g() = g;
1,076,800✔
446
      p.g_last() = g;
1,076,800✔
447
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,076,800✔
448
      p.E_last() = p.E();
1,076,800✔
449

450
      int64_t source_element = sr * negroups_ + g;
1,076,800✔
451

452
      // If this task has already been populated, we don't need to do
453
      // it again.
454
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,076,800✔
455
        continue;
456
      }
457

458
      // Loop over all active tallies. This logic is essentially identical
459
      // to what happens when scanning for applicable tallies during
460
      // MC transport.
461
      for (auto i_tally : model::active_tallies) {
4,256,160✔
462
        Tally& tally {*model::tallies[i_tally]};
3,179,360✔
463

464
        // Initialize an iterator over valid filter bin combinations.
465
        // If there are no valid combinations, use a continue statement
466
        // to ensure we skip the assume_separate break below.
467
        auto filter_iter = FilterBinIter(tally, p);
3,179,360✔
468
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,179,360✔
469
        if (filter_iter == end)
3,179,360✔
470
          continue;
1,811,360✔
471

472
        // Loop over filter bins.
473
        for (; filter_iter != end; ++filter_iter) {
2,736,000✔
474
          auto filter_index = filter_iter.index_;
1,368,000✔
475
          auto filter_weight = filter_iter.weight_;
1,368,000✔
476

477
          // Loop over scores
478
          for (int score = 0; score < tally.scores_.size(); score++) {
3,073,120✔
479
            auto score_bin = tally.scores_[score];
1,705,120✔
480
            // If a valid tally, filter, and score combination has been found,
481
            // then add it to the list of tally tasks for this source element.
482
            TallyTask task(i_tally, filter_index, score, score_bin);
1,705,120✔
483
            source_regions_.tally_task(sr, g).push_back(task);
1,705,120✔
484

485
            // Also add this task to the list of volume tasks for this source
486
            // region.
487
            source_regions_.volume_task(sr).insert(task);
1,705,120✔
488
          }
489
        }
490
      }
491
      // Reset all the filter matches for the next tally event.
492
      for (auto& match : p.filter_matches())
5,012,240✔
493
        match.bins_present_ = false;
3,935,440✔
494
    }
495
  }
932,320✔
496
  openmc::simulation::time_tallies.stop();
385✔
497

498
  mapped_all_tallies_ = all_source_regions_mapped;
385✔
499
}
385✔
500

501
// Set the volume accumulators to zero for all tallies
502
void FlatSourceDomain::reset_tally_volumes()
4,290✔
503
{
504
  if (volume_normalized_flux_tallies_) {
4,290✔
505
#pragma omp parallel for
1,980✔
506
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,200✔
507
      auto& tensor = tally_volumes_[i];
4,550✔
508
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,550✔
509
    }
510
  }
511
}
4,290✔
512

513
// In fixed source mode, due to the way that volumetric fixed sources are
514
// converted and applied as volumetric sources in one or more source regions,
515
// we need to perform an additional normalization step to ensure that the
516
// reported scalar fluxes are in units per source neutron. This allows for
517
// direct comparison of reported tallies to Monte Carlo flux results.
518
// This factor needs to be computed at each iteration, as it is based on the
519
// volume estimate of each FSR, which improves over the course of the
520
// simulation
521
double FlatSourceDomain::compute_fixed_source_normalization_factor() const
4,770✔
522
{
523
  // If we are not in fixed source mode, then there are no external sources
524
  // so no normalization is needed.
525
  if (settings::run_mode != RunMode::FIXED_SOURCE || adjoint_) {
4,770✔
526
    return 1.0;
1,212✔
527
  }
528

529
  // Step 1 is to sum over all source regions and energy groups to get the
530
  // total external source strength in the simulation.
531
  double simulation_external_source_strength = 0.0;
3,558✔
532
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
1,947✔
533
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
10,915,819✔
534
    int material = source_regions_.material(sr);
10,914,208✔
535
    double volume = source_regions_.volume(sr) * simulation_volume_;
10,914,208✔
536
    for (int g = 0; g < negroups_; g++) {
22,379,648✔
537
      // For non-void regions, we store the external source pre-divided by
538
      // sigma_t. We need to multiply non-void regions back up by sigma_t
539
      // to get the total source strength in the expected units.
540
      double sigma_t = 1.0;
11,465,440✔
541
      if (material != MATERIAL_VOID) {
11,465,440✔
542
        sigma_t = sigma_t_[material * negroups_ + g];
11,251,440✔
543
      }
544
      simulation_external_source_strength +=
11,465,440✔
545
        source_regions_.external_source(sr, g) * sigma_t * volume;
11,465,440✔
546
    }
547
  }
548

549
  // Step 2 is to determine the total user-specified external source strength
550
  double user_external_source_strength = 0.0;
3,558✔
551
  for (auto& ext_source : model::external_sources) {
7,116✔
552
    user_external_source_strength += ext_source->strength();
3,558✔
553
  }
554

555
  // The correction factor is the ratio of the user-specified external source
556
  // strength to the simulation external source strength.
557
  double source_normalization_factor =
3,558✔
558
    user_external_source_strength / simulation_external_source_strength;
559

560
  return source_normalization_factor;
3,558✔
561
}
562

563
// Tallying in random ray is not done directly during transport, rather,
564
// it is done only once after each power iteration. This is made possible
565
// by way of a mapping data structure that relates spatial source regions
566
// (FSRs) to tally/filter/score combinations. The mechanism by which the
567
// mapping is done (and the limitations incurred) is documented in the
568
// "convert_source_regions_to_tallies()" function comments above. The present
569
// tally function simply traverses the mapping data structure and executes
570
// the scoring operations to OpenMC's native tally result arrays.
571

572
void FlatSourceDomain::random_ray_tally()
4,290✔
573
{
574
  openmc::simulation::time_tallies.start();
4,290✔
575

576
  // Reset our tally volumes to zero
577
  reset_tally_volumes();
4,290✔
578

579
  double source_normalization_factor =
580
    compute_fixed_source_normalization_factor();
4,290✔
581

582
// We loop over all source regions and energy groups. For each
583
// element, we check if there are any scores needed and apply
584
// them.
585
#pragma omp parallel for
2,340✔
586
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
11,709,750✔
587
    // The fsr.volume_ is the unitless fractional simulation averaged volume
588
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
589
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
590
    // entire global simulation domain (as defined by the ray source box).
591
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
592
    // its fraction of the total volume by the total volume. Not important in
593
    // eigenvalue solves, but useful in fixed source solves for returning the
594
    // flux shape with a magnitude that makes sense relative to the fixed
595
    // source strength.
596
    double volume = source_regions_.volume(sr) * simulation_volume_;
11,707,800✔
597

598
    double material = source_regions_.material(sr);
11,707,800✔
599
    for (int g = 0; g < negroups_; g++) {
24,775,200✔
600
      double flux =
601
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
13,067,400✔
602

603
      // Determine numerical score value
604
      for (auto& task : source_regions_.tally_task(sr, g)) {
32,145,600✔
605
        double score = 0.0;
19,078,200✔
606
        switch (task.score_type) {
19,078,200✔
607

608
        case SCORE_FLUX:
15,905,800✔
609
          score = flux * volume;
15,905,800✔
610
          break;
15,905,800✔
611

612
        case SCORE_TOTAL:
613
          if (material != MATERIAL_VOID) {
614
            score = flux * volume * sigma_t_[material * negroups_ + g];
615
          }
616
          break;
617

618
        case SCORE_FISSION:
1,586,200✔
619
          if (material != MATERIAL_VOID) {
1,586,200✔
620
            score = flux * volume * sigma_f_[material * negroups_ + g];
1,586,200✔
621
          }
622
          break;
1,586,200✔
623

624
        case SCORE_NU_FISSION:
1,586,200✔
625
          if (material != MATERIAL_VOID) {
1,586,200✔
626
            score = flux * volume * nu_sigma_f_[material * negroups_ + g];
1,586,200✔
627
          }
628
          break;
1,586,200✔
629

630
        case SCORE_EVENTS:
631
          score = 1.0;
632
          break;
633

634
        default:
635
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
636
                      "total, fission, nu-fission, and events are supported in "
637
                      "random ray mode.");
638
          break;
639
        }
640

641
        // Apply score to the appropriate tally bin
642
        Tally& tally {*model::tallies[task.tally_idx]};
19,078,200✔
643
#pragma omp atomic
644
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
19,078,200✔
645
          score;
646
      }
647
    }
648

649
    // For flux tallies, the total volume of the spatial region is needed
650
    // for normalizing the flux. We store this volume in a separate tensor.
651
    // We only contribute to each volume tally bin once per FSR.
652
    if (volume_normalized_flux_tallies_) {
11,707,800✔
653
      for (const auto& task : source_regions_.volume_task(sr)) {
28,772,800✔
654
        if (task.score_type == SCORE_FLUX) {
17,208,000✔
655
#pragma omp atomic
656
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
15,253,600✔
657
            volume;
658
        }
659
      }
660
    }
661
  } // end FSR loop
662

663
  // Normalize any flux scores by the total volume of the FSRs scoring to that
664
  // bin. To do this, we loop over all tallies, and then all filter bins,
665
  // and then scores. For each score, we check the tally data structure to
666
  // see what index that score corresponds to. If that score is a flux score,
667
  // then we divide it by volume.
668
  if (volume_normalized_flux_tallies_) {
4,290✔
669
    for (int i = 0; i < model::tallies.size(); i++) {
13,640✔
670
      Tally& tally {*model::tallies[i]};
10,010✔
671
#pragma omp parallel for
5,460✔
672
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
703,425✔
673
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,415,950✔
674
          auto score_type = tally.scores_[score_idx];
717,075✔
675
          if (score_type == SCORE_FLUX) {
717,075✔
676
            double vol = tally_volumes_[i](bin, score_idx);
698,875✔
677
            if (vol > 0.0) {
698,875✔
678
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
698,875✔
679
            }
680
          }
681
        }
682
      }
683
    }
684
  }
685

686
  openmc::simulation::time_tallies.stop();
4,290✔
687
}
4,290✔
688

UNCOV
689
double FlatSourceDomain::evaluate_flux_at_point(
×
690
  Position r, int64_t sr, int g) const
691
{
692
  return source_regions_.scalar_flux_final(sr, g) /
×
693
         (settings::n_batches - settings::n_inactive);
×
694
}
695

696
// Outputs all basic material, FSR ID, multigroup flux, and
697
// fission source data to .vtk file that can be directly
698
// loaded and displayed by Paraview. Note that .vtk binary
699
// files require big endian byte ordering, so endianness
700
// is checked and flipped if necessary.
701
void FlatSourceDomain::output_to_vtk() const
×
702
{
703
  // Rename .h5 plot filename(s) to .vtk filenames
704
  for (int p = 0; p < model::plots.size(); p++) {
×
705
    PlottableInterface* plot = model::plots[p].get();
×
706
    plot->path_plot() =
×
707
      plot->path_plot().substr(0, plot->path_plot().find_last_of('.')) + ".vtk";
×
708
  }
709

710
  // Print header information
711
  print_plot();
×
712

713
  // Outer loop over plots
714
  for (int p = 0; p < model::plots.size(); p++) {
×
715

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

719
    // Random ray plots only support voxel plots
720
    if (!openmc_plot) {
×
721
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
722
                          "is allowed in random ray mode.",
723
        p));
724
      continue;
×
725
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
726
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
727
                          "is allowed in random ray mode.",
728
        p));
729
      continue;
×
730
    }
731

732
    int Nx = openmc_plot->pixels_[0];
×
733
    int Ny = openmc_plot->pixels_[1];
×
734
    int Nz = openmc_plot->pixels_[2];
×
735
    Position origin = openmc_plot->origin_;
×
736
    Position width = openmc_plot->width_;
×
737
    Position ll = origin - width / 2.0;
×
738
    double x_delta = width.x / Nx;
×
739
    double y_delta = width.y / Ny;
×
740
    double z_delta = width.z / Nz;
×
741
    std::string filename = openmc_plot->path_plot();
×
742

743
    // Perform sanity checks on file size
744
    uint64_t bytes = Nx * Ny * Nz * (negroups_ + 1 + 1 + 1) * sizeof(float);
×
745
    write_message(5, "Processing plot {}: {}... (Estimated size is {} MB)",
×
746
      openmc_plot->id(), filename, bytes / 1.0e6);
×
747
    if (bytes / 1.0e9 > 1.0) {
×
748
      warning("Voxel plot specification is very large (>1 GB). Plotting may be "
×
749
              "slow.");
750
    } else if (bytes / 1.0e9 > 100.0) {
×
751
      fatal_error("Voxel plot specification is too large (>100 GB). Exiting.");
×
752
    }
753

754
    // Relate voxel spatial locations to random ray source regions
755
    vector<int> voxel_indices(Nx * Ny * Nz);
×
756
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
NEW
757
    vector<double> weight_windows(Nx * Ny * Nz);
×
NEW
758
    float min_weight = 1e20;
×
759
#pragma omp parallel for collapse(3) reduction(min : min_weight)
760
    for (int z = 0; z < Nz; z++) {
761
      for (int y = 0; y < Ny; y++) {
762
        for (int x = 0; x < Nx; x++) {
763
          Position sample;
764
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
765
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
766
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
767
          Particle p;
768
          p.r() = sample;
769
          p.r_last() = sample;
770
          p.E() = 1.0;
771
          p.E_last() = 1.0;
772
          p.u() = {1.0, 0.0, 0.0};
773

774
          bool found = exhaustive_find_cell(p);
775
          if (!found) {
776
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
777
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
778
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
779
            continue;
780
          }
781

782
          int i_cell = p.lowest_coord().cell;
783
          int64_t sr = source_region_offsets_[i_cell] + p.cell_instance();
784
          if (RandomRay::mesh_subdivision_enabled_) {
785
            int mesh_idx = base_source_regions_.mesh(sr);
786
            int mesh_bin;
787
            if (mesh_idx == C_NONE) {
788
              mesh_bin = 0;
789
            } else {
790
              mesh_bin = model::meshes[mesh_idx]->get_bin(p.r());
791
            }
792
            SourceRegionKey sr_key {sr, mesh_bin};
793
            auto it = source_region_map_.find(sr_key);
794
            if (it != source_region_map_.end()) {
795
              sr = it->second;
796
            } else {
797
              sr = -1;
798
            }
799
          }
800

801
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
802
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
803

804
          if (variance_reduction::weight_windows.size() == 1) {
805
            WeightWindow ww =
806
              variance_reduction::weight_windows[0]->get_weight_window(p);
807
            float weight = ww.lower_weight;
808
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
809
            if (weight < min_weight)
810
              min_weight = weight;
811
          }
812
        }
813
      }
814
    }
815

816
    double source_normalization_factor =
817
      compute_fixed_source_normalization_factor();
×
818

819
    // Open file for writing
820
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
821

822
    // Write vtk metadata
823
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
824
    std::fprintf(plot, "Dataset File\n");
×
825
    std::fprintf(plot, "BINARY\n");
×
826
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
827
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
NEW
828
    std::fprintf(plot, "ORIGIN %lf %lf %lf\n", ll.x, ll.y, ll.z);
×
829
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
830
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
831

NEW
832
    int64_t num_neg = 0;
×
NEW
833
    int64_t num_samples = 0;
×
NEW
834
    float min_flux = 0.0;
×
NEW
835
    float max_flux = -1.0e20;
×
836
    // Plot multigroup flux data
837
    for (int g = 0; g < negroups_; g++) {
×
838
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
839
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
840
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
841
        int64_t fsr = voxel_indices[i];
×
842
        int64_t source_element = fsr * negroups_ + g;
×
NEW
843
        float flux = 0;
×
NEW
844
        if (fsr >= 0) {
×
NEW
845
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
NEW
846
          if (flux < 0.0)
×
NEW
847
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
NEW
848
              voxel_positions[i], fsr, g);
×
849
        }
NEW
850
        if (flux < 0.0) {
×
NEW
851
          num_neg++;
×
NEW
852
          if (flux < min_flux) {
×
NEW
853
            min_flux = flux;
×
854
          }
855
        }
NEW
856
        if (flux > max_flux)
×
NEW
857
          max_flux = flux;
×
NEW
858
        num_samples++;
×
859
        flux = convert_to_big_endian<float>(flux);
×
860
        std::fwrite(&flux, sizeof(float), 1, plot);
×
861
      }
862
    }
863

864
    // Slightly negative fluxes can be normal when sampling corners of linear
865
    // source regions. However, very common and high magnitude negative fluxes
866
    // may indicate numerical instability.
NEW
867
    if (num_neg > 0) {
×
NEW
868
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
869
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
NEW
870
        num_neg, (100.0 * num_neg) / num_samples, min_flux, max_flux));
×
871
    }
872

873
    // Plot FSRs
874
    std::fprintf(plot, "SCALARS FSRs float\n");
×
875
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
876
    for (int fsr : voxel_indices) {
×
877
      float value = future_prn(10, fsr);
×
878
      value = convert_to_big_endian<float>(value);
×
879
      std::fwrite(&value, sizeof(float), 1, plot);
×
880
    }
881

882
    // Plot Materials
883
    std::fprintf(plot, "SCALARS Materials int\n");
×
884
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
885
    for (int fsr : voxel_indices) {
×
NEW
886
      int mat = -1;
×
NEW
887
      if (fsr >= 0)
×
NEW
888
        mat = source_regions_.material(fsr);
×
889
      mat = convert_to_big_endian<int>(mat);
×
890
      std::fwrite(&mat, sizeof(int), 1, plot);
×
891
    }
892

893
    // Plot fission source
894
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
895
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
896
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
897
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
898
        int64_t fsr = voxel_indices[i];
×
UNCOV
899
        float total_fission = 0.0;
×
NEW
900
        if (fsr >= 0) {
×
NEW
901
          int mat = source_regions_.material(fsr);
×
NEW
902
          if (mat != MATERIAL_VOID) {
×
NEW
903
            for (int g = 0; g < negroups_; g++) {
×
NEW
904
              int64_t source_element = fsr * negroups_ + g;
×
NEW
905
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
NEW
906
              double sigma_f = sigma_f_[mat * negroups_ + g];
×
NEW
907
              total_fission += sigma_f * flux;
×
908
            }
909
          }
910
        }
911
        total_fission = convert_to_big_endian<float>(total_fission);
×
912
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
913
      }
914
    } else {
915
      std::fprintf(plot, "SCALARS external_source float\n");
×
916
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
917
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
918
        int64_t fsr = voxel_indices[i];
×
919
        float total_external = 0.0f;
×
NEW
920
        if (fsr >= 0) {
×
NEW
921
          for (int g = 0; g < negroups_; g++) {
×
NEW
922
            total_external += source_regions_.external_source(fsr, g);
×
923
          }
924
        }
925
        total_external = convert_to_big_endian<float>(total_external);
×
926
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
927
      }
928
    }
929

930
    // Plot weight window data
NEW
931
    if (variance_reduction::weight_windows.size() == 1) {
×
NEW
932
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
NEW
933
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
NEW
934
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
NEW
935
        float weight = weight_windows[i];
×
NEW
936
        if (weight == 0.0)
×
NEW
937
          weight = min_weight;
×
NEW
938
        weight = convert_to_big_endian<float>(weight);
×
NEW
939
        std::fwrite(&weight, sizeof(float), 1, plot);
×
940
      }
941
    }
942

UNCOV
943
    std::fclose(plot);
×
944
  }
945
}
946

947
void FlatSourceDomain::apply_external_source_to_source_region(
2,720✔
948
  Discrete* discrete, double strength_factor, int64_t sr)
949
{
950
  source_regions_.external_source_present(sr) = 1;
2,720✔
951

952
  const auto& discrete_energies = discrete->x();
2,720✔
953
  const auto& discrete_probs = discrete->prob();
2,720✔
954

955
  for (int i = 0; i < discrete_energies.size(); i++) {
5,632✔
956
    int g = data::mg.get_group_index(discrete_energies[i]);
2,912✔
957
    source_regions_.external_source(sr, g) +=
2,912✔
958
      discrete_probs[i] * strength_factor;
2,912✔
959
  }
960
}
2,720✔
961

962
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
400✔
963
  Discrete* discrete, double strength_factor, int target_material_id,
964
  const vector<int32_t>& instances)
965
{
966
  Cell& cell = *model::cells[i_cell];
400✔
967

968
  if (cell.type_ != Fill::MATERIAL)
400✔
969
    return;
×
970

971
  for (int j : instances) {
30,640✔
972
    int cell_material_idx = cell.material(j);
30,240✔
973
    int cell_material_id;
974
    if (cell_material_idx == MATERIAL_VOID) {
30,240✔
975
      cell_material_id = MATERIAL_VOID;
256✔
976
    } else {
977
      cell_material_id = model::materials[cell_material_idx]->id();
29,984✔
978
    }
979
    if (target_material_id == C_NONE ||
30,240✔
980
        cell_material_id == target_material_id) {
981
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,720✔
982
      apply_external_source_to_source_region(
2,720✔
983
        discrete, strength_factor, source_region);
984
    }
985
  }
986
}
987

988
void FlatSourceDomain::apply_external_source_to_cell_and_children(
432✔
989
  int32_t i_cell, Discrete* discrete, double strength_factor,
990
  int32_t target_material_id)
991
{
992
  Cell& cell = *model::cells[i_cell];
432✔
993

994
  if (cell.type_ == Fill::MATERIAL) {
432✔
995
    vector<int> instances(cell.n_instances_);
400✔
996
    std::iota(instances.begin(), instances.end(), 0);
400✔
997
    apply_external_source_to_cell_instances(
400✔
998
      i_cell, discrete, strength_factor, target_material_id, instances);
999
  } else if (target_material_id == C_NONE) {
432✔
1000
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1001
      cell.get_contained_cells(0, nullptr);
×
1002
    for (const auto& pair : cell_instance_list) {
×
1003
      int32_t i_child_cell = pair.first;
×
1004
      apply_external_source_to_cell_instances(i_child_cell, discrete,
×
1005
        strength_factor, target_material_id, pair.second);
×
1006
    }
1007
  }
1008
}
432✔
1009

1010
void FlatSourceDomain::count_external_source_regions()
368✔
1011
{
1012
  n_external_source_regions_ = 0;
368✔
1013
#pragma omp parallel for reduction(+ : n_external_source_regions_)
207✔
1014
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
259,049✔
1015
    if (source_regions_.external_source_present(sr)) {
258,888✔
1016
      n_external_source_regions_++;
1,190✔
1017
    }
1018
  }
1019
}
368✔
1020

1021
void FlatSourceDomain::convert_external_sources()
368✔
1022
{
1023
  // Loop over external sources
1024
  for (int es = 0; es < model::external_sources.size(); es++) {
736✔
1025
    Source* s = model::external_sources[es].get();
368✔
1026
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
368✔
1027
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
368✔
1028
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
368✔
1029

1030
    double strength_factor = is->strength();
368✔
1031

1032
    if (is->domain_type() == Source::DomainType::MATERIAL) {
368✔
1033
      for (int32_t material_id : domain_ids) {
32✔
1034
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1035
          apply_external_source_to_cell_and_children(
80✔
1036
            i_cell, energy, strength_factor, material_id);
1037
        }
1038
      }
1039
    } else if (is->domain_type() == Source::DomainType::CELL) {
352✔
1040
      for (int32_t cell_id : domain_ids) {
32✔
1041
        int32_t i_cell = model::cell_map[cell_id];
16✔
1042
        apply_external_source_to_cell_and_children(
16✔
1043
          i_cell, energy, strength_factor, C_NONE);
1044
      }
1045
    } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
336✔
1046
      for (int32_t universe_id : domain_ids) {
672✔
1047
        int32_t i_universe = model::universe_map[universe_id];
336✔
1048
        Universe& universe = *model::universes[i_universe];
336✔
1049
        for (int32_t i_cell : universe.cells_) {
672✔
1050
          apply_external_source_to_cell_and_children(
336✔
1051
            i_cell, energy, strength_factor, C_NONE);
1052
        }
1053
      }
1054
    }
1055
  } // End loop over external sources
1056

1057
// Divide the fixed source term by sigma t (to save time when applying each
1058
// iteration)
1059
#pragma omp parallel for
207✔
1060
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
259,049✔
1061
    int material = source_regions_.material(sr);
258,888✔
1062
    if (material == MATERIAL_VOID) {
258,888✔
1063
      continue;
14,000✔
1064
    }
1065
    for (int g = 0; g < negroups_; g++) {
519,008✔
1066
      double sigma_t = sigma_t_[material * negroups_ + g];
274,120✔
1067
      source_regions_.external_source(sr, g) /= sigma_t;
274,120✔
1068
    }
1069
  }
1070
}
368✔
1071

1072
void FlatSourceDomain::flux_swap()
10,670✔
1073
{
1074
  source_regions_.flux_swap();
10,670✔
1075
}
10,670✔
1076

1077
void FlatSourceDomain::flatten_xs()
560✔
1078
{
1079
  // Temperature and angle indices, if using multiple temperature
1080
  // data sets and/or anisotropic data sets.
1081
  // TODO: Currently assumes we are only using single temp/single angle data.
1082
  const int t = 0;
560✔
1083
  const int a = 0;
560✔
1084

1085
  n_materials_ = data::mg.macro_xs_.size();
560✔
1086
  for (auto& m : data::mg.macro_xs_) {
2,064✔
1087
    for (int g_out = 0; g_out < negroups_; g_out++) {
4,736✔
1088
      if (m.exists_in_model) {
3,232✔
1089
        double sigma_t =
1090
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
3,168✔
1091
        sigma_t_.push_back(sigma_t);
3,168✔
1092

1093
        double nu_Sigma_f =
1094
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
3,168✔
1095
        nu_sigma_f_.push_back(nu_Sigma_f);
3,168✔
1096

1097
        double sigma_f =
1098
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
3,168✔
1099
        sigma_f_.push_back(sigma_f);
3,168✔
1100

1101
        double chi =
1102
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
3,168✔
1103
        chi_.push_back(chi);
3,168✔
1104

1105
        for (int g_in = 0; g_in < negroups_; g_in++) {
18,432✔
1106
          double sigma_s =
1107
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
15,264✔
1108
          sigma_s_.push_back(sigma_s);
15,264✔
1109
        }
1110
      } else {
1111
        sigma_t_.push_back(0);
64✔
1112
        nu_sigma_f_.push_back(0);
64✔
1113
        sigma_f_.push_back(0);
64✔
1114
        chi_.push_back(0);
64✔
1115
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1116
          sigma_s_.push_back(0);
64✔
1117
        }
1118
      }
1119
    }
1120
  }
1121
}
560✔
1122

1123
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
64✔
1124
{
1125
  // Set the external source to 1/forward_flux. If the forward flux is negative
1126
  // or zero, set the adjoint source to zero, as this is likely a very small
1127
  // source region that we don't need to bother trying to vector particles
1128
  // towards. Flux negativity in random ray is not related to the flux being
1129
  // small in magnitude, but rather due to the source region being physically
1130
  // small in volume and thus having a noisy flux estimate.
1131
#pragma omp parallel for
36✔
1132
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1133
    for (int g = 0; g < negroups_; g++) {
338,688✔
1134
      double flux = forward_flux[sr * negroups_ + g];
169,344✔
1135
      if (flux <= 0.0) {
169,344✔
1136
        source_regions_.external_source(sr, g) = 0.0;
325✔
1137
      } else {
1138
        source_regions_.external_source(sr, g) = 1.0 / flux;
169,019✔
1139
      }
1140
      if (flux > 0.0) {
169,344✔
1141
        source_regions_.external_source_present(sr) = 1;
155,195✔
1142
      }
1143
    }
1144
  }
1145

1146
  // Divide the fixed source term by sigma t (to save time when applying each
1147
  // iteration)
1148
#pragma omp parallel for
36✔
1149
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1150
    int material = source_regions_.material(sr);
169,344✔
1151
    if (material == MATERIAL_VOID) {
169,344✔
1152
      continue;
1153
    }
1154
    for (int g = 0; g < negroups_; g++) {
338,688✔
1155
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1156
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1157
    }
1158
  }
1159
}
64✔
1160

1161
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1162
{
1163
  // Transpose the inner two dimensions for each material
1164
  for (int m = 0; m < n_materials_; ++m) {
304✔
1165
    int material_offset = m * negroups_ * negroups_;
224✔
1166
    for (int i = 0; i < negroups_; ++i) {
640✔
1167
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1168
        // Calculate indices of the elements to swap
1169
        int idx1 = material_offset + i * negroups_ + j;
672✔
1170
        int idx2 = material_offset + j * negroups_ + i;
672✔
1171

1172
        // Swap the elements to transpose the matrix
1173
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1174
      }
1175
    }
1176
  }
1177
}
80✔
1178

1179
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
480✔
1180
{
1181
  // Ensure array is correct size
1182
  flux.resize(n_source_regions() * negroups_);
480✔
1183
// Serialize the final fluxes for output
1184
#pragma omp parallel for
270✔
1185
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,016,790✔
1186
    flux[se] = source_regions_.scalar_flux_final(se);
1,016,580✔
1187
  }
1188
}
480✔
1189

1190
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
368✔
1191
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1192
  bool is_target_void)
1193
{
1194
  Cell& cell = *model::cells[i_cell];
368✔
1195
  if (cell.type_ != Fill::MATERIAL)
368✔
NEW
1196
    return;
×
1197
  for (int32_t j : instances) {
146,864✔
1198
    int cell_material_idx = cell.material(j);
146,496✔
1199
    int cell_material_id = (cell_material_idx == C_NONE)
1200
                             ? C_NONE
146,496✔
1201
                             : model::materials[cell_material_idx]->id();
146,496✔
1202

1203
    if ((target_material_id == C_NONE && !is_target_void) ||
146,496✔
1204
        cell_material_id == target_material_id) {
1205
      int64_t sr = source_region_offsets_[i_cell] + j;
114,496✔
1206
      if (source_regions_.mesh(sr) != C_NONE) {
114,496✔
1207
        // print out the source region that is broken:
NEW
1208
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1209
                                "applied, but trying to apply mesh idx {}",
1210
          sr, source_regions_.mesh(sr), mesh_idx));
1211
      }
1212
      source_regions_.mesh(sr) = mesh_idx;
114,496✔
1213
    }
1214
  }
1215
}
1216

1217
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
272✔
1218
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1219
{
1220
  Cell& cell = *model::cells[i_cell];
272✔
1221

1222
  if (cell.type_ == Fill::MATERIAL) {
272✔
1223
    vector<int> instances(cell.n_instances_);
160✔
1224
    std::iota(instances.begin(), instances.end(), 0);
160✔
1225
    apply_mesh_to_cell_instances(
160✔
1226
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1227
  } else if (target_material_id == C_NONE && !is_target_void) {
272✔
1228
    for (int j = 0; j < cell.n_instances_; j++) {
96✔
1229
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1230
        cell.get_contained_cells(j, nullptr);
48✔
1231
      for (const auto& pair : cell_instance_list) {
256✔
1232
        int32_t i_child_cell = pair.first;
208✔
1233
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
208✔
1234
          pair.second, is_target_void);
208✔
1235
      }
1236
    }
48✔
1237
  }
1238
}
272✔
1239

1240
void FlatSourceDomain::apply_meshes()
480✔
1241
{
1242
  // Skip if there are no mappings between mesh IDs and domains
1243
  if (mesh_domain_map_.empty())
480✔
1244
    return;
400✔
1245

1246
  // Loop over meshes
1247
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
240✔
1248
    Mesh* mesh = model::meshes[mesh_idx].get();
160✔
1249
    int mesh_id = mesh->id();
160✔
1250

1251
    // Skip if mesh id is not present in the map
1252
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
160✔
1253
      continue;
16✔
1254

1255
    // Loop over domains associated with the mesh
1256
    for (auto& domain : mesh_domain_map_[mesh_id]) {
288✔
1257
      Source::DomainType domain_type = domain.first;
144✔
1258
      int domain_id = domain.second;
144✔
1259

1260
      if (domain_type == Source::DomainType::MATERIAL) {
144✔
1261
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1262
          if (domain_id == C_NONE) {
160✔
NEW
1263
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1264
          } else {
1265
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1266
          }
1267
        }
1268
      } else if (domain_type == Source::DomainType::CELL) {
112✔
1269
        int32_t i_cell = model::cell_map[domain_id];
32✔
1270
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1271
      } else if (domain_type == Source::DomainType::UNIVERSE) {
80✔
1272
        int32_t i_universe = model::universe_map[domain_id];
80✔
1273
        Universe& universe = *model::universes[i_universe];
80✔
1274
        for (int32_t i_cell : universe.cells_) {
160✔
1275
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
80✔
1276
        }
1277
      }
1278
    }
1279
  }
1280
}
1281

1282
void FlatSourceDomain::prepare_base_source_regions()
55✔
1283
{
1284
  std::swap(source_regions_, base_source_regions_);
55✔
1285
  source_regions_.negroups() = base_source_regions_.negroups();
55✔
1286
  source_regions_.is_linear() = base_source_regions_.is_linear();
55✔
1287
}
55✔
1288

1289
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
806,904,131✔
1290
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1291
{
1292
  SourceRegionKey sr_key {sr, mesh_bin};
806,904,131✔
1293

1294
  // Case 1: Check if the source region key is already present in the permanent
1295
  // map. This is the most common condition, as any source region visited in a
1296
  // previous power iteration will already be present in the permanent map. If
1297
  // the source region key is found, we translate the key into a specific 1D
1298
  // source region index and return a handle its position in the
1299
  // source_regions_ vector.
1300
  auto it = source_region_map_.find(sr_key);
806,904,131✔
1301
  if (it != source_region_map_.end()) {
806,904,131✔
1302
    int64_t sr = it->second;
789,751,963✔
1303
    return source_regions_.get_source_region_handle(sr);
789,751,963✔
1304
  }
1305

1306
  // Case 2: Check if the source region key is present in the temporary (thread
1307
  // safe) map. This is a common occurrence in the first power iteration when
1308
  // the source region has already been visited already by some other ray. We
1309
  // begin by locking the temporary map before any operations are performed. The
1310
  // lock is not global over the full data structure -- it will be dependent on
1311
  // which key is used.
1312
  discovered_source_regions_.lock(sr_key);
17,152,168✔
1313

1314
  // If the key is found in the temporary map, then we return a handle to the
1315
  // source region that is stored in the temporary map.
1316
  if (discovered_source_regions_.contains(sr_key)) {
17,152,168✔
1317
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
15,729,329✔
1318
    discovered_source_regions_.unlock(sr_key);
15,729,329✔
1319
    return handle;
15,729,329✔
1320
  }
1321

1322
  // Case 3: The source region key is not present anywhere, but it is only due
1323
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1324
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1325
  // result in the ray tracer detecting an additional (very short) segment
1326
  // though a mesh bin that is actually past the physical source region
1327
  // boundary. This is a result of the the multi-level ray tracing treatment in
1328
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1329
  // result in the wrong surface being selected as the nearest. This can happen
1330
  // in a lattice when there are two directions that both are very close in
1331
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1332
  // treated as being equivalent so alternative logic is used. However, when we
1333
  // go and ray trace on this with the mesh tracer we may go past the surface
1334
  // bounding the current source region.
1335
  //
1336
  // To filter out this case, before we create the new source region, we double
1337
  // check that the actual starting point of this segment (r) is still in the
1338
  // same geometry source region that we started in. If an artifact is detected,
1339
  // we discard the segment (and attenuation through it) as it is not really a
1340
  // valid source region and will have only an infinitessimally small cell
1341
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1342
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1343
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1344
  // consequences for the general ray tracer, so for now we do the below sanity
1345
  // checks before generating phantom source regions. A significant extra cost
1346
  // is incurred in instantiating the GeometryState object and doing a cell
1347
  // lookup, but again, this is going to be an extremely rare thing to check
1348
  // after the first power iteration has completed.
1349

1350
  // Sanity check on source region id
1351
  GeometryState gs;
1,422,839✔
1352
  gs.r() = r + TINY_BIT * u;
1,422,839✔
1353
  gs.u() = {1.0, 0.0, 0.0};
1,422,839✔
1354
  exhaustive_find_cell(gs);
1,422,839✔
1355
  int gs_i_cell = gs.lowest_coord().cell;
1,422,839✔
1356
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,422,839✔
1357
  if (sr_found != sr) {
1,422,839✔
1358
    discovered_source_regions_.unlock(sr_key);
88✔
1359
    SourceRegionHandle handle;
88✔
1360
    handle.is_numerical_fp_artifact_ = true;
88✔
1361
    return handle;
88✔
1362
  }
1363

1364
  // Sanity check on mesh bin
1365
  int mesh_idx = base_source_regions_.mesh(sr);
1,422,751✔
1366
  if (mesh_idx == C_NONE) {
1,422,751✔
NEW
1367
    if (mesh_bin != 0) {
×
NEW
1368
      discovered_source_regions_.unlock(sr_key);
×
NEW
1369
      SourceRegionHandle handle;
×
NEW
1370
      handle.is_numerical_fp_artifact_ = true;
×
NEW
1371
      return handle;
×
1372
    }
1373
  } else {
1374
    Mesh* mesh = model::meshes[mesh_idx].get();
1,422,751✔
1375
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,422,751✔
1376
    if (bin_found != mesh_bin) {
1,422,751✔
NEW
1377
      discovered_source_regions_.unlock(sr_key);
×
NEW
1378
      SourceRegionHandle handle;
×
NEW
1379
      handle.is_numerical_fp_artifact_ = true;
×
NEW
1380
      return handle;
×
1381
    }
1382
  }
1383

1384
  // Case 4: The source region key is valid, but is not present anywhere. This
1385
  // condition only occurs the first time the source region is discovered
1386
  // (typically in the first power iteration). In this case, we need to handle
1387
  // creation of the new source region and its storage into the parallel map.
1388
  // The new source region is created by copying the base source region, so as
1389
  // to inherit material, external source, and some flux properties etc. We
1390
  // also pass the base source region id to allow the new source region to
1391
  // know which base source region it is derived from.
1392
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
1,422,751✔
1393
    sr_key, {base_source_regions_.get_source_region_handle(sr), sr});
1,422,751✔
1394
  discovered_source_regions_.unlock(sr_key);
1,422,751✔
1395
  SourceRegionHandle handle {*sr_ptr};
1,422,751✔
1396
  return handle;
1,422,751✔
1397
}
1,422,839✔
1398

1399
void FlatSourceDomain::finalize_discovered_source_regions()
2,090✔
1400
{
1401
  // Extract keys for entries with a valid volume.
1402
  vector<SourceRegionKey> keys;
2,090✔
1403
  for (const auto& pair : discovered_source_regions_) {
1,424,841✔
1404
    if (pair.second.volume_ > 0.0) {
1,422,751✔
1405
      keys.push_back(pair.first);
1,356,432✔
1406
    }
1407
  }
1408

1409
  if (!keys.empty()) {
2,090✔
1410
    // Sort the keys, so as to ensure reproducible ordering given that source
1411
    // regions may have been added to discovered_source_regions_ in an arbitrary
1412
    // order due to shared memory threading.
1413
    std::sort(keys.begin(), keys.end());
286✔
1414

1415
    // Append the source regions in the sorted key order.
1416
    for (const auto& key : keys) {
1,356,718✔
1417
      const SourceRegion& sr = discovered_source_regions_[key];
1,356,432✔
1418
      source_region_map_[key] = source_regions_.n_source_regions();
1,356,432✔
1419
      source_regions_.push_back(sr);
1,356,432✔
1420
    }
1421

1422
    // If any new source regions were discovered, we need to update the
1423
    // tally mapping between source regions and tally bins.
1424
    mapped_all_tallies_ = false;
286✔
1425
  }
1426

1427
  discovered_source_regions_.clear();
2,090✔
1428
}
2,090✔
1429

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