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

openmc-dev / openmc / 13973548701

20 Mar 2025 03:47PM UTC coverage: 85.129% (+0.006%) from 85.123%
13973548701

Pull #3360

github

web-flow
Merge 72b9aab8d into 277390b22
Pull Request #3360: Random Ray Point Source Locator

56 of 62 new or added lines in 2 files covered. (90.32%)

11 existing lines in 2 files now uncovered.

51606 of 60621 relevant lines covered (85.13%)

37002392.01 hits per line

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

78.35
/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_)
576✔
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;
576✔
43
  for (const auto& c : model::cells) {
5,200✔
44
    if (c->type_ != Fill::MATERIAL) {
4,624✔
45
      source_region_offsets_.push_back(-1);
2,320✔
46
    } else {
47
      source_region_offsets_.push_back(base_source_regions);
2,304✔
48
      base_source_regions += c->n_instances_;
2,304✔
49
    }
50
  }
51

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

58
  // Initialize materials
59
  int64_t source_region_id = 0;
576✔
60
  for (int i = 0; i < model::cells.size(); i++) {
5,200✔
61
    Cell& cell = *model::cells[i];
4,624✔
62
    if (cell.type_ == Fill::MATERIAL) {
4,624✔
63
      for (int j = 0; j < cell.n_instances_; j++) {
767,808✔
64
        source_regions_.material(source_region_id++) = cell.material(j);
765,504✔
65
      }
66
    }
67
  }
68

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

74
  // Initialize tally volumes
75
  if (volume_normalized_flux_tallies_) {
576✔
76
    tally_volumes_.resize(model::tallies.size());
512✔
77
    for (int i = 0; i < model::tallies.size(); i++) {
1,920✔
78
      //  Get the shape of the 3D result tensor
79
      auto shape = model::tallies[i]->results().shape();
1,408✔
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,408✔
84
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,816✔
85
    }
86
  }
87

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

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

105
#pragma omp parallel for
6,000✔
106
  for (int64_t se = 0; se < n_source_elements(); se++) {
36,656,995✔
107
    source_regions_.scalar_flux_new(se) = 0.0;
36,651,995✔
108
  }
109
}
11,000✔
110

111
void FlatSourceDomain::accumulate_iteration_flux()
4,455✔
112
{
113
#pragma omp parallel for
2,430✔
114
  for (int64_t se = 0; se < n_source_elements(); se++) {
16,568,625✔
115
    source_regions_.scalar_flux_final(se) +=
16,566,600✔
116
      source_regions_.scalar_flux_new(se);
16,566,600✔
117
  }
118
}
4,455✔
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)
5,115✔
123
{
124
  simulation::time_update_src.start();
5,115✔
125

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

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

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

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

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

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

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

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

180
// Normalize scalar flux to total distance travelled by all rays this
181
// iteration
182
#pragma omp parallel for
2,790✔
183
  for (int64_t se = 0; se < n_source_elements(); se++) {
22,191,335✔
184
    source_regions_.scalar_flux_new(se) *= normalization_factor;
22,189,010✔
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,790✔
190
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,796,795✔
191
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
19,794,470✔
192
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
19,794,470✔
193
    source_regions_.volume_naive(sr) =
39,588,940✔
194
      source_regions_.volume(sr) * normalization_factor;
19,794,470✔
195
    source_regions_.volume_sq(sr) =
39,588,940✔
196
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
19,794,470✔
197
    source_regions_.volume(sr) =
19,794,470✔
198
      source_regions_.volume_t(sr) * volume_normalization_factor;
19,794,470✔
199
  }
200
}
5,115✔
201

202
void FlatSourceDomain::set_flux_to_flux_plus_source(
43,220,045✔
203
  int64_t sr, double volume, int g)
204
{
205
  int material = source_regions_.material(sr);
43,220,045✔
206
  if (material == MATERIAL_VOID) {
43,220,045✔
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];
42,340,045✔
213
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
42,340,045✔
214
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
42,340,045✔
215
  }
216
}
43,220,045✔
217

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

224
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
8,928,293✔
225
{
226
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
8,928,293✔
227
}
8,928,293✔
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()
11,000✔
232
{
233
  int64_t n_hits = 0;
11,000✔
234
  double inverse_batch = 1.0 / simulation::current_batch;
11,000✔
235

236
#pragma omp parallel for reduction(+ : n_hits)
6,000✔
237
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
33,249,635✔
238

239
    double volume_simulation_avg = source_regions_.volume(sr);
33,244,635✔
240
    double volume_iteration = source_regions_.volume_naive(sr);
33,244,635✔
241

242
    // Increment the number of hits if cell was hit this iteration
243
    if (volume_iteration) {
33,244,635✔
244
      n_hits++;
29,185,480✔
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) {
33,244,635✔
250
      source_regions_.is_small(sr) = 1;
6,812,705✔
251
    } else {
252
      source_regions_.is_small(sr) = 0;
26,431,930✔
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_) {
33,244,635✔
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:
32,035,035✔
266
      if (source_regions_.external_source_present(sr) ||
59,882,470✔
267
          source_regions_.is_small(sr)) {
27,847,435✔
268
        volume = volume_iteration;
10,999,925✔
269
      } else {
270
        volume = volume_simulation_avg;
21,035,110✔
271
      }
272
      break;
32,035,035✔
273
    default:
274
      fatal_error("Invalid volume estimator type");
275
    }
276

277
    for (int g = 0; g < negroups_; g++) {
70,774,410✔
278
      // There are three scenarios we need to consider:
279
      if (volume_iteration > 0.0) {
37,529,775✔
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);
33,470,470✔
285
      } else if (volume_simulation_avg > 0.0) {
4,059,305✔
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_) {
4,059,295✔
299
          set_flux_to_old_flux(sr, g);
980✔
300
        } else {
301
          set_flux_to_source(sr, g);
4,058,315✔
302
        }
303
      }
304
    }
305
  }
306

307
  // Return the number of source regions that were hit this iteration
308
  return n_hits;
11,000✔
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()
396✔
415
{
416
  openmc::simulation::time_tallies.start();
396✔
417

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

421
// Attempt to generate mapping for all source regions
422
#pragma omp parallel for
216✔
423
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,165,780✔
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)) {
1,165,600✔
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;
1,165,600✔
436
    p.r() = source_regions_.position(sr);
1,165,600✔
437
    p.r_last() = source_regions_.position(sr);
1,165,600✔
438
    p.u() = {1.0, 0.0, 0.0};
1,165,600✔
439
    bool found = exhaustive_find_cell(p);
1,165,600✔
440

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

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

450
      int64_t source_element = sr * negroups_ + g;
1,310,080✔
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,310,080✔
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) {
5,189,280✔
462
        Tally& tally {*model::tallies[i_tally]};
3,879,200✔
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,879,200✔
468
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,879,200✔
469
        if (filter_iter == end)
3,879,200✔
470
          continue;
2,277,920✔
471

472
        // Loop over filter bins.
473
        for (; filter_iter != end; ++filter_iter) {
3,202,560✔
474
          auto filter_index = filter_iter.index_;
1,601,280✔
475
          auto filter_weight = filter_iter.weight_;
1,601,280✔
476

477
          // Loop over scores
478
          for (int score = 0; score < tally.scores_.size(); score++) {
3,539,680✔
479
            auto score_bin = tally.scores_[score];
1,938,400✔
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,938,400✔
483
            source_regions_.tally_task(sr, g).push_back(task);
1,938,400✔
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,938,400✔
488
          }
489
        }
490
      }
491
      // Reset all the filter matches for the next tally event.
492
      for (auto& match : p.filter_matches())
5,945,360✔
493
        match.bins_present_ = false;
4,635,280✔
494
    }
495
  }
1,165,600✔
496
  openmc::simulation::time_tallies.stop();
396✔
497

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

501
// Set the volume accumulators to zero for all tallies
502
void FlatSourceDomain::reset_tally_volumes()
4,455✔
503
{
504
  if (volume_normalized_flux_tallies_) {
4,455✔
505
#pragma omp parallel for
2,070✔
506
    for (int i = 0; i < tally_volumes_.size(); i++) {
6,500✔
507
      auto& tensor = tally_volumes_[i];
4,775✔
508
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
4,775✔
509
    }
510
  }
511
}
4,455✔
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,951✔
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,951✔
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,739✔
532
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
2,046✔
533
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
14,651,837✔
534
    int material = source_regions_.material(sr);
14,650,144✔
535
    double volume = source_regions_.volume(sr) * simulation_volume_;
14,650,144✔
536
    for (int g = 0; g < negroups_; g++) {
29,851,520✔
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;
15,201,376✔
541
      if (material != MATERIAL_VOID) {
15,201,376✔
542
        sigma_t = sigma_t_[material * negroups_ + g];
14,987,376✔
543
      }
544
      simulation_external_source_strength +=
15,201,376✔
545
        source_regions_.external_source(sr, g) * sigma_t * volume;
15,201,376✔
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,739✔
551
  for (auto& ext_source : model::external_sources) {
7,478✔
552
    user_external_source_strength += ext_source->strength();
3,739✔
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,739✔
558
    user_external_source_strength / simulation_external_source_strength;
559

560
  return source_normalization_factor;
3,739✔
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,455✔
573
{
574
  openmc::simulation::time_tallies.start();
4,455✔
575

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

579
  double source_normalization_factor =
580
    compute_fixed_source_normalization_factor();
4,455✔
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,430✔
586
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
15,209,025✔
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_;
15,207,000✔
597

598
    double material = source_regions_.material(sr);
15,207,000✔
599
    for (int g = 0; g < negroups_; g++) {
31,773,600✔
600
      double flux =
601
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
16,566,600✔
602

603
      // Determine numerical score value
604
      for (auto& task : source_regions_.tally_task(sr, g)) {
39,144,000✔
605
        double score = 0.0;
22,577,400✔
606
        switch (task.score_type) {
22,577,400✔
607

608
        case SCORE_FLUX:
19,405,000✔
609
          score = flux * volume;
19,405,000✔
610
          break;
19,405,000✔
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]};
22,577,400✔
643
#pragma omp atomic
644
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
22,577,400✔
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_) {
15,207,000✔
653
      for (const auto& task : source_regions_.volume_task(sr)) {
35,771,200✔
654
        if (task.score_type == SCORE_FLUX) {
20,707,200✔
655
#pragma omp atomic
656
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
18,752,800✔
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,455✔
669
    for (int i = 0; i < model::tallies.size(); i++) {
14,300✔
670
      Tally& tally {*model::tallies[i]};
10,505✔
671
#pragma omp parallel for
5,730✔
672
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
703,875✔
673
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
1,416,400✔
674
          auto score_type = tally.scores_[score_idx];
717,300✔
675
          if (score_type == SCORE_FLUX) {
717,300✔
676
            double vol = tally_volumes_[i](bin, score_idx);
699,100✔
677
            if (vol > 0.0) {
699,100✔
678
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
699,100✔
679
            }
680
          }
681
        }
682
      }
683
    }
684
  }
685

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

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);
×
757
    vector<double> weight_windows(Nx * Ny * Nz);
×
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);
×
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

832
    int64_t num_neg = 0;
×
833
    int64_t num_samples = 0;
×
834
    float min_flux = 0.0;
×
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;
×
843
        float flux = 0;
×
844
        if (fsr >= 0) {
×
845
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
846
          if (flux < 0.0)
×
847
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
848
              voxel_positions[i], fsr, g);
×
849
        }
850
        if (flux < 0.0) {
×
851
          num_neg++;
×
852
          if (flux < min_flux) {
×
853
            min_flux = flux;
×
854
          }
855
        }
856
        if (flux > max_flux)
×
857
          max_flux = flux;
×
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.
867
    if (num_neg > 0) {
×
868
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
869
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
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) {
×
886
      int mat = -1;
×
887
      if (fsr >= 0)
×
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];
×
899
        float total_fission = 0.0;
×
900
        if (fsr >= 0) {
×
901
          int mat = source_regions_.material(fsr);
×
902
          if (mat != MATERIAL_VOID) {
×
903
            for (int g = 0; g < negroups_; g++) {
×
904
              int64_t source_element = fsr * negroups_ + g;
×
905
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
906
              double sigma_f = sigma_f_[mat * negroups_ + g];
×
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;
×
920
        if (fsr >= 0) {
×
921
          for (int g = 0; g < negroups_; g++) {
×
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
931
    if (variance_reduction::weight_windows.size() == 1) {
×
932
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
933
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
934
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
935
        float weight = weight_windows[i];
×
936
        if (weight == 0.0)
×
937
          weight = min_weight;
×
938
        weight = convert_to_big_endian<float>(weight);
×
939
        std::fwrite(&weight, sizeof(float), 1, plot);
×
940
      }
941
    }
942

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

947
void FlatSourceDomain::apply_external_source_to_source_region(
2,731✔
948
  Discrete* discrete, double strength_factor, SourceRegionHandle& srh)
949
{
950
  srh.external_source_present() = 1;
2,731✔
951

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

955
  for (int i = 0; i < discrete_energies.size(); i++) {
5,654✔
956
    int g = data::mg.get_group_index(discrete_energies[i]);
2,923✔
957
    srh.external_source(g) += discrete_probs[i] * strength_factor;
2,923✔
958
  }
959
}
2,731✔
960

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

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

970
  for (int j : instances) {
30,640✔
971
    int cell_material_idx = cell.material(j);
30,240✔
972
    int cell_material_id;
973
    if (cell_material_idx == MATERIAL_VOID) {
30,240✔
974
      cell_material_id = MATERIAL_VOID;
256✔
975
    } else {
976
      cell_material_id = model::materials[cell_material_idx]->id();
29,984✔
977
    }
978
    if (target_material_id == C_NONE ||
30,240✔
979
        cell_material_id == target_material_id) {
980
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,720✔
981
      SourceRegionHandle srh =
982
        source_regions_.get_source_region_handle(source_region);
2,720✔
983
      apply_external_source_to_source_region(discrete, strength_factor, srh);
2,720✔
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()
960✔
1011
{
1012
  n_external_source_regions_ = 0;
960✔
1013
#pragma omp parallel for reduction(+ : n_external_source_regions_)
540✔
1014
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,532,692✔
1015
    if (source_regions_.external_source_present(sr)) {
1,532,272✔
1016
      n_external_source_regions_++;
158,700✔
1017
    }
1018
  }
1019
}
960✔
1020

1021
void FlatSourceDomain::convert_external_sources()
384✔
1022
{
1023
  // Loop over external sources
1024
  for (int es = 0; es < model::external_sources.size(); es++) {
768✔
1025

1026
    // Extract source information
1027
    Source* s = model::external_sources[es].get();
384✔
1028
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
384✔
1029
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
384✔
1030
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
384✔
1031
    double strength_factor = is->strength();
384✔
1032

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

1038
      // Extract the point source coordinate and find the base source region
1039
      // at that point
1040
      SpatialDistribution* space_dist = is->space();
16✔
1041
      SpatialPoint* sp = dynamic_cast<SpatialPoint*>(space_dist);
16✔
1042
      GeometryState gs;
16✔
1043
      gs.r() = sp->r();
16✔
1044
      gs.r_last() = sp->r();
16✔
1045
      gs.u() = {1.0, 0.0, 0.0};
16✔
1046
      bool found = exhaustive_find_cell(gs);
16✔
1047
      if (!found) {
16✔
NEW
1048
        fatal_error(fmt::format("Could not find cell containing external "
×
1049
                                "point source at ({}, {}, {})",
NEW
1050
          sp->r().x, sp->r().y, sp->r().z));
×
1051
      }
1052
      int i_cell = gs.lowest_coord().cell;
16✔
1053
      int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
16✔
1054

1055
      if (RandomRay::mesh_subdivision_enabled_) {
16✔
1056
        // If mesh subdivision is enabled, we need to determine which
1057
        // subdivided mesh bin the point source coordinate is in as well
1058
        int mesh_idx = source_regions_.mesh(sr);
16✔
1059
        int mesh_bin;
1060
        if (mesh_idx == C_NONE) {
16✔
NEW
1061
          mesh_bin = 0;
×
1062
        } else {
1063
          mesh_bin = model::meshes[mesh_idx]->get_bin(gs.r());
16✔
1064
        }
1065
        // With the source region and mesh bin known, we can use the
1066
        // accompanying SourceRegionKey as a key into a map that stores
1067
        // the corresponding external source index for the point source.
1068
        // Notably, we do not actually apply the external source to any
1069
        // source regions here, as if mesh subdivision is enabled, they
1070
        // haven't actually been discovered & initilized yet. When discovered,
1071
        // they will read from the point_source_map to determine if there
1072
        // are any point source terms that should be applied.
1073
        SourceRegionKey key {sr, mesh_bin};
16✔
1074
        point_source_map_[key] = es;
16✔
1075
      } else {
1076
        // If we are not using mesh subdivision, we can apply the external
1077
        // source directly to the source region as we do for volumetric
1078
        // domain constraint sources.
NEW
1079
        SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
×
NEW
1080
        apply_external_source_to_source_region(energy, strength_factor, srh);
×
1081
      }
1082

1083
      // If not a point source, then use the volumetric domain constraints
1084
      // to determine which source regions to apply the external source to.
1085
    } else {
16✔
1086
      if (is->domain_type() == Source::DomainType::MATERIAL) {
368✔
1087
        for (int32_t material_id : domain_ids) {
32✔
1088
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1089
            apply_external_source_to_cell_and_children(
80✔
1090
              i_cell, energy, strength_factor, material_id);
1091
          }
1092
        }
1093
      } else if (is->domain_type() == Source::DomainType::CELL) {
352✔
1094
        for (int32_t cell_id : domain_ids) {
32✔
1095
          int32_t i_cell = model::cell_map[cell_id];
16✔
1096
          apply_external_source_to_cell_and_children(
16✔
1097
            i_cell, energy, strength_factor, C_NONE);
1098
        }
1099
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
336✔
1100
        for (int32_t universe_id : domain_ids) {
672✔
1101
          int32_t i_universe = model::universe_map[universe_id];
336✔
1102
          Universe& universe = *model::universes[i_universe];
336✔
1103
          for (int32_t i_cell : universe.cells_) {
672✔
1104
            apply_external_source_to_cell_and_children(
336✔
1105
              i_cell, energy, strength_factor, C_NONE);
1106
          }
1107
        }
1108
      }
1109
    }
1110
  } // End loop over external sources
1111

1112
// Divide the fixed source term by sigma t (to save time when applying each
1113
// iteration)
1114
#pragma omp parallel for
216✔
1115
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
271,152✔
1116
    int material = source_regions_.material(sr);
270,984✔
1117
    if (material == MATERIAL_VOID) {
270,984✔
1118
      continue;
14,000✔
1119
    }
1120
    for (int g = 0; g < negroups_; g++) {
543,200✔
1121
      double sigma_t = sigma_t_[material * negroups_ + g];
286,216✔
1122
      source_regions_.external_source(sr, g) /= sigma_t;
286,216✔
1123
    }
1124
  }
1125
}
384✔
1126

1127
void FlatSourceDomain::flux_swap()
11,000✔
1128
{
1129
  source_regions_.flux_swap();
11,000✔
1130
}
11,000✔
1131

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

1140
  n_materials_ = data::mg.macro_xs_.size();
576✔
1141
  for (auto& m : data::mg.macro_xs_) {
2,128✔
1142
    for (int g_out = 0; g_out < negroups_; g_out++) {
4,832✔
1143
      if (m.exists_in_model) {
3,280✔
1144
        double sigma_t =
1145
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
3,216✔
1146
        sigma_t_.push_back(sigma_t);
3,216✔
1147

1148
        double nu_Sigma_f =
1149
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
3,216✔
1150
        nu_sigma_f_.push_back(nu_Sigma_f);
3,216✔
1151

1152
        double sigma_f =
1153
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
3,216✔
1154
        sigma_f_.push_back(sigma_f);
3,216✔
1155

1156
        double chi =
1157
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
3,216✔
1158
        chi_.push_back(chi);
3,216✔
1159

1160
        for (int g_in = 0; g_in < negroups_; g_in++) {
18,528✔
1161
          double sigma_s =
1162
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
15,312✔
1163
          sigma_s_.push_back(sigma_s);
15,312✔
1164
        }
1165
      } else {
1166
        sigma_t_.push_back(0);
64✔
1167
        nu_sigma_f_.push_back(0);
64✔
1168
        sigma_f_.push_back(0);
64✔
1169
        chi_.push_back(0);
64✔
1170
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1171
          sigma_s_.push_back(0);
64✔
1172
        }
1173
      }
1174
    }
1175
  }
1176
}
576✔
1177

1178
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
64✔
1179
{
1180
  // Set the external source to 1/forward_flux. If the forward flux is negative
1181
  // or zero, set the adjoint source to zero, as this is likely a very small
1182
  // source region that we don't need to bother trying to vector particles
1183
  // towards. Flux negativity in random ray is not related to the flux being
1184
  // small in magnitude, but rather due to the source region being physically
1185
  // small in volume and thus having a noisy flux estimate.
1186
#pragma omp parallel for
36✔
1187
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1188
    for (int g = 0; g < negroups_; g++) {
338,688✔
1189
      double flux = forward_flux[sr * negroups_ + g];
169,344✔
1190
      if (flux <= 0.0) {
169,344✔
1191
        source_regions_.external_source(sr, g) = 0.0;
325✔
1192
      } else {
1193
        source_regions_.external_source(sr, g) = 1.0 / flux;
169,019✔
1194
      }
1195
      if (flux > 0.0) {
169,344✔
1196
        source_regions_.external_source_present(sr) = 1;
155,195✔
1197
      }
1198
    }
1199
  }
1200

1201
  // Divide the fixed source term by sigma t (to save time when applying each
1202
  // iteration)
1203
#pragma omp parallel for
36✔
1204
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
169,372✔
1205
    int material = source_regions_.material(sr);
169,344✔
1206
    if (material == MATERIAL_VOID) {
169,344✔
1207
      continue;
1208
    }
1209
    for (int g = 0; g < negroups_; g++) {
338,688✔
1210
      double sigma_t = sigma_t_[material * negroups_ + g];
169,344✔
1211
      source_regions_.external_source(sr, g) /= sigma_t;
169,344✔
1212
    }
1213
  }
1214
}
64✔
1215

1216
void FlatSourceDomain::transpose_scattering_matrix()
80✔
1217
{
1218
  // Transpose the inner two dimensions for each material
1219
  for (int m = 0; m < n_materials_; ++m) {
304✔
1220
    int material_offset = m * negroups_ * negroups_;
224✔
1221
    for (int i = 0; i < negroups_; ++i) {
640✔
1222
      for (int j = i + 1; j < negroups_; ++j) {
1,088✔
1223
        // Calculate indices of the elements to swap
1224
        int idx1 = material_offset + i * negroups_ + j;
672✔
1225
        int idx2 = material_offset + j * negroups_ + i;
672✔
1226

1227
        // Swap the elements to transpose the matrix
1228
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
672✔
1229
      }
1230
    }
1231
  }
1232
}
80✔
1233

1234
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
496✔
1235
{
1236
  // Ensure array is correct size
1237
  flux.resize(n_source_regions() * negroups_);
496✔
1238
// Serialize the final fluxes for output
1239
#pragma omp parallel for
279✔
1240
  for (int64_t se = 0; se < n_source_elements(); se++) {
1,253,533✔
1241
    flux[se] = source_regions_.scalar_flux_final(se);
1,253,316✔
1242
  }
1243
}
496✔
1244

1245
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
416✔
1246
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1247
  bool is_target_void)
1248
{
1249
  Cell& cell = *model::cells[i_cell];
416✔
1250
  if (cell.type_ != Fill::MATERIAL)
416✔
UNCOV
1251
    return;
×
1252
  for (int32_t j : instances) {
174,560✔
1253
    int cell_material_idx = cell.material(j);
174,144✔
1254
    int cell_material_id = (cell_material_idx == C_NONE)
1255
                             ? C_NONE
174,144✔
1256
                             : model::materials[cell_material_idx]->id();
174,144✔
1257

1258
    if ((target_material_id == C_NONE && !is_target_void) ||
174,144✔
1259
        cell_material_id == target_material_id) {
1260
      int64_t sr = source_region_offsets_[i_cell] + j;
142,144✔
1261
      if (source_regions_.mesh(sr) != C_NONE) {
142,144✔
1262
        // print out the source region that is broken:
UNCOV
1263
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1264
                                "applied, but trying to apply mesh idx {}",
1265
          sr, source_regions_.mesh(sr), mesh_idx));
1266
      }
1267
      source_regions_.mesh(sr) = mesh_idx;
142,144✔
1268
    }
1269
  }
1270
}
1271

1272
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
288✔
1273
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1274
{
1275
  Cell& cell = *model::cells[i_cell];
288✔
1276

1277
  if (cell.type_ == Fill::MATERIAL) {
288✔
1278
    vector<int> instances(cell.n_instances_);
160✔
1279
    std::iota(instances.begin(), instances.end(), 0);
160✔
1280
    apply_mesh_to_cell_instances(
160✔
1281
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1282
  } else if (target_material_id == C_NONE && !is_target_void) {
288✔
1283
    for (int j = 0; j < cell.n_instances_; j++) {
128✔
1284
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1285
        cell.get_contained_cells(j, nullptr);
64✔
1286
      for (const auto& pair : cell_instance_list) {
320✔
1287
        int32_t i_child_cell = pair.first;
256✔
1288
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
256✔
1289
          pair.second, is_target_void);
256✔
1290
      }
1291
    }
64✔
1292
  }
1293
}
288✔
1294

1295
void FlatSourceDomain::apply_meshes()
496✔
1296
{
1297
  // Skip if there are no mappings between mesh IDs and domains
1298
  if (mesh_domain_map_.empty())
496✔
1299
    return;
400✔
1300

1301
  // Loop over meshes
1302
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
272✔
1303
    Mesh* mesh = model::meshes[mesh_idx].get();
176✔
1304
    int mesh_id = mesh->id();
176✔
1305

1306
    // Skip if mesh id is not present in the map
1307
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
176✔
1308
      continue;
16✔
1309

1310
    // Loop over domains associated with the mesh
1311
    for (auto& domain : mesh_domain_map_[mesh_id]) {
320✔
1312
      Source::DomainType domain_type = domain.first;
160✔
1313
      int domain_id = domain.second;
160✔
1314

1315
      if (domain_type == Source::DomainType::MATERIAL) {
160✔
1316
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1317
          if (domain_id == C_NONE) {
160✔
UNCOV
1318
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1319
          } else {
1320
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1321
          }
1322
        }
1323
      } else if (domain_type == Source::DomainType::CELL) {
128✔
1324
        int32_t i_cell = model::cell_map[domain_id];
32✔
1325
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1326
      } else if (domain_type == Source::DomainType::UNIVERSE) {
96✔
1327
        int32_t i_universe = model::universe_map[domain_id];
96✔
1328
        Universe& universe = *model::universes[i_universe];
96✔
1329
        for (int32_t i_cell : universe.cells_) {
192✔
1330
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
96✔
1331
        }
1332
      }
1333
    }
1334
  }
1335
}
1336

1337
void FlatSourceDomain::prepare_base_source_regions()
66✔
1338
{
1339
  std::swap(source_regions_, base_source_regions_);
66✔
1340
  source_regions_.negroups() = base_source_regions_.negroups();
66✔
1341
  source_regions_.is_linear() = base_source_regions_.is_linear();
66✔
1342
}
66✔
1343

1344
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
839,080,506✔
1345
  int64_t sr, int mesh_bin, Position r, double dist, Direction u)
1346
{
1347
  SourceRegionKey sr_key {sr, mesh_bin};
839,080,506✔
1348

1349
  // Case 1: Check if the source region key is already present in the permanent
1350
  // map. This is the most common condition, as any source region visited in a
1351
  // previous power iteration will already be present in the permanent map. If
1352
  // the source region key is found, we translate the key into a specific 1D
1353
  // source region index and return a handle its position in the
1354
  // source_regions_ vector.
1355
  auto it = source_region_map_.find(sr_key);
839,080,506✔
1356
  if (it != source_region_map_.end()) {
839,080,506✔
1357
    int64_t sr = it->second;
820,602,673✔
1358
    return source_regions_.get_source_region_handle(sr);
820,602,673✔
1359
  }
1360

1361
  // Case 2: Check if the source region key is present in the temporary (thread
1362
  // safe) map. This is a common occurrence in the first power iteration when
1363
  // the source region has already been visited already by some other ray. We
1364
  // begin by locking the temporary map before any operations are performed. The
1365
  // lock is not global over the full data structure -- it will be dependent on
1366
  // which key is used.
1367
  discovered_source_regions_.lock(sr_key);
18,477,833✔
1368

1369
  // If the key is found in the temporary map, then we return a handle to the
1370
  // source region that is stored in the temporary map.
1371
  if (discovered_source_regions_.contains(sr_key)) {
18,477,833✔
1372
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
16,506,655✔
1373
    discovered_source_regions_.unlock(sr_key);
16,506,655✔
1374
    return handle;
16,506,655✔
1375
  }
1376

1377
  // Case 3: The source region key is not present anywhere, but it is only due
1378
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1379
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1380
  // result in the ray tracer detecting an additional (very short) segment
1381
  // though a mesh bin that is actually past the physical source region
1382
  // boundary. This is a result of the the multi-level ray tracing treatment in
1383
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1384
  // result in the wrong surface being selected as the nearest. This can happen
1385
  // in a lattice when there are two directions that both are very close in
1386
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1387
  // treated as being equivalent so alternative logic is used. However, when we
1388
  // go and ray trace on this with the mesh tracer we may go past the surface
1389
  // bounding the current source region.
1390
  //
1391
  // To filter out this case, before we create the new source region, we double
1392
  // check that the actual starting point of this segment (r) is still in the
1393
  // same geometry source region that we started in. If an artifact is detected,
1394
  // we discard the segment (and attenuation through it) as it is not really a
1395
  // valid source region and will have only an infinitessimally small cell
1396
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1397
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1398
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1399
  // consequences for the general ray tracer, so for now we do the below sanity
1400
  // checks before generating phantom source regions. A significant extra cost
1401
  // is incurred in instantiating the GeometryState object and doing a cell
1402
  // lookup, but again, this is going to be an extremely rare thing to check
1403
  // after the first power iteration has completed.
1404

1405
  // Sanity check on source region id
1406
  GeometryState gs;
1,971,178✔
1407
  gs.r() = r + TINY_BIT * u;
1,971,178✔
1408
  gs.u() = {1.0, 0.0, 0.0};
1,971,178✔
1409
  exhaustive_find_cell(gs);
1,971,178✔
1410
  int gs_i_cell = gs.lowest_coord().cell;
1,971,178✔
1411
  int64_t sr_found = source_region_offsets_[gs_i_cell] + gs.cell_instance();
1,971,178✔
1412
  if (sr_found != sr) {
1,971,178✔
1413
    discovered_source_regions_.unlock(sr_key);
88✔
1414
    SourceRegionHandle handle;
88✔
1415
    handle.is_numerical_fp_artifact_ = true;
88✔
1416
    return handle;
88✔
1417
  }
1418

1419
  // Sanity check on mesh bin
1420
  int mesh_idx = base_source_regions_.mesh(sr);
1,971,090✔
1421
  if (mesh_idx == C_NONE) {
1,971,090✔
1422
    if (mesh_bin != 0) {
×
1423
      discovered_source_regions_.unlock(sr_key);
×
1424
      SourceRegionHandle handle;
×
1425
      handle.is_numerical_fp_artifact_ = true;
×
UNCOV
1426
      return handle;
×
1427
    }
1428
  } else {
1429
    Mesh* mesh = model::meshes[mesh_idx].get();
1,971,090✔
1430
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
1,971,090✔
1431
    if (bin_found != mesh_bin) {
1,971,090✔
1432
      discovered_source_regions_.unlock(sr_key);
×
1433
      SourceRegionHandle handle;
×
1434
      handle.is_numerical_fp_artifact_ = true;
×
UNCOV
1435
      return handle;
×
1436
    }
1437
  }
1438

1439
  // Case 4: The source region key is valid, but is not present anywhere. This
1440
  // condition only occurs the first time the source region is discovered
1441
  // (typically in the first power iteration). In this case, we need to handle
1442
  // creation of the new source region and its storage into the parallel map.
1443
  // The new source region is created by copying the base source region, so as
1444
  // to inherit material, external source, and some flux properties etc. We
1445
  // also pass the base source region id to allow the new source region to
1446
  // know which base source region it is derived from.
1447
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
1,971,090✔
1448
    sr_key, {base_source_regions_.get_source_region_handle(sr), sr});
1,971,090✔
1449
  discovered_source_regions_.unlock(sr_key);
1,971,090✔
1450
  SourceRegionHandle handle {*sr_ptr};
1,971,090✔
1451

1452
  // Check if the new source region contains a point source and apply it if so
1453
  auto it2 = point_source_map_.find(sr_key);
1,971,090✔
1454
  if (it2 != point_source_map_.end()) {
1,971,090✔
1455
    int es = it2->second;
11✔
1456
    Source* s = model::external_sources[es].get();
11✔
1457
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
11✔
1458
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
11✔
1459
    double strength_factor = is->strength();
11✔
1460
    apply_external_source_to_source_region(energy, strength_factor, handle);
11✔
1461
    int material = handle.material();
11✔
1462
    if (material != MATERIAL_VOID) {
11✔
1463
      for (int g = 0; g < negroups_; g++) {
22✔
1464
        double sigma_t = sigma_t_[material * negroups_ + g];
11✔
1465
        handle.external_source(g) /= sigma_t;
11✔
1466
      }
1467
    }
1468
  }
1469

1470
  return handle;
1,971,090✔
1471
}
1,971,178✔
1472

1473
void FlatSourceDomain::finalize_discovered_source_regions()
2,420✔
1474
{
1475
  // Extract keys for entries with a valid volume.
1476
  vector<SourceRegionKey> keys;
2,420✔
1477
  for (const auto& pair : discovered_source_regions_) {
1,973,510✔
1478
    if (pair.second.volume_ > 0.0) {
1,971,090✔
1479
      keys.push_back(pair.first);
1,869,648✔
1480
    }
1481
  }
1482

1483
  if (!keys.empty()) {
2,420✔
1484
    // Sort the keys, so as to ensure reproducible ordering given that source
1485
    // regions may have been added to discovered_source_regions_ in an arbitrary
1486
    // order due to shared memory threading.
1487
    std::sort(keys.begin(), keys.end());
396✔
1488

1489
    // Append the source regions in the sorted key order.
1490
    for (const auto& key : keys) {
1,870,044✔
1491
      const SourceRegion& sr = discovered_source_regions_[key];
1,869,648✔
1492
      source_region_map_[key] = source_regions_.n_source_regions();
1,869,648✔
1493
      source_regions_.push_back(sr);
1,869,648✔
1494
    }
1495

1496
    // If any new source regions were discovered, we need to update the
1497
    // tally mapping between source regions and tally bins.
1498
    mapped_all_tallies_ = false;
396✔
1499
  }
1500

1501
  discovered_source_regions_.clear();
2,420✔
1502
}
2,420✔
1503

1504
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc