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

openmc-dev / openmc / 13403808882

19 Feb 2025 01:54AM UTC coverage: 85.031% (+0.06%) from 84.969%
13403808882

Pull #3268

github

web-flow
Merge 795507cca into 3011a14a1
Pull Request #3268: Randomized Quasi-Monte Carlo Sampling in The Random Ray Method

54 of 62 new or added lines in 4 files covered. (87.1%)

389 existing lines in 14 files now uncovered.

50630 of 59543 relevant lines covered (85.03%)

35182857.82 hits per line

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

79.88
/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/eigenvalue.h"
5
#include "openmc/geometry.h"
6
#include "openmc/material.h"
7
#include "openmc/message_passing.h"
8
#include "openmc/mgxs_interface.h"
9
#include "openmc/output.h"
10
#include "openmc/plot.h"
11
#include "openmc/random_ray/random_ray.h"
12
#include "openmc/simulation.h"
13
#include "openmc/tallies/filter.h"
14
#include "openmc/tallies/tally.h"
15
#include "openmc/tallies/tally_scoring.h"
16
#include "openmc/timer.h"
17

18
#include <cstdio>
19

20
namespace openmc {
21

22
//==============================================================================
23
// FlatSourceDomain implementation
24
//==============================================================================
25

26
// Static Variable Declarations
27
RandomRayVolumeEstimator FlatSourceDomain::volume_estimator_ {
28
  RandomRayVolumeEstimator::HYBRID};
29
bool FlatSourceDomain::volume_normalized_flux_tallies_ {false};
30
bool FlatSourceDomain::adjoint_ {false};
31

32
FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_)
476✔
33
{
34
  // Count the number of source regions, compute the cell offset
35
  // indices, and store the material type The reason for the offsets is that
36
  // some cell types may not have material fills, and therefore do not
37
  // produce FSRs. Thus, we cannot index into the global arrays directly
38
  for (const auto& c : model::cells) {
4,505✔
39
    if (c->type_ != Fill::MATERIAL) {
4,029✔
40
      source_region_offsets_.push_back(-1);
2,057✔
41
    } else {
42
      source_region_offsets_.push_back(n_source_regions_);
1,972✔
43
      n_source_regions_ += c->n_instances_;
1,972✔
44
      n_source_elements_ += c->n_instances_ * negroups_;
1,972✔
45
    }
46
  }
47

48
  // Initialize cell-wise arrays
49
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
476✔
50
  source_regions_ = SourceRegionContainer(negroups_, is_linear);
476✔
51
  source_regions_.assign(n_source_regions_, SourceRegion(negroups_, is_linear));
476✔
52

53
  // Initialize materials
54
  int64_t source_region_id = 0;
476✔
55
  for (int i = 0; i < model::cells.size(); i++) {
4,505✔
56
    Cell& cell = *model::cells[i];
4,029✔
57
    if (cell.type_ == Fill::MATERIAL) {
4,029✔
58
      for (int j = 0; j < cell.n_instances_; j++) {
605,540✔
59
        source_regions_.material(source_region_id++) = cell.material(j);
603,568✔
60
      }
61
    }
62
  }
63

64
  // Sanity check
65
  if (source_region_id != n_source_regions_) {
476✔
66
    fatal_error("Unexpected number of source regions");
×
67
  }
68

69
  // Initialize tally volumes
70
  if (volume_normalized_flux_tallies_) {
476✔
71
    tally_volumes_.resize(model::tallies.size());
408✔
72
    for (int i = 0; i < model::tallies.size(); i++) {
1,462✔
73
      //  Get the shape of the 3D result tensor
74
      auto shape = model::tallies[i]->results().shape();
1,054✔
75

76
      // Create a new 2D tensor with the same size as the first
77
      // two dimensions of the 3D tensor
78
      tally_volumes_[i] =
1,054✔
79
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,108✔
80
    }
81
  }
82

83
  // Compute simulation domain volume based on ray source
84
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
476✔
85
  SpatialDistribution* space_dist = is->space();
476✔
86
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
476✔
87
  Position dims = sb->upper_right() - sb->lower_left();
476✔
88
  simulation_volume_ = dims.x * dims.y * dims.z;
476✔
89
}
476✔
90

91
void FlatSourceDomain::batch_reset()
13,260✔
92
{
93
// Reset scalar fluxes and iteration volume tallies to zero
94
#pragma omp parallel for
7,020✔
95
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
6,507,040✔
96
    source_regions_.volume(sr) = 0.0;
6,500,800✔
97
    source_regions_.volume_sq(sr) = 0.0;
6,500,800✔
98
  }
99
#pragma omp parallel for
7,020✔
100
  for (int64_t se = 0; se < n_source_elements_; se++) {
12,088,480✔
101
    source_regions_.scalar_flux_new(se) = 0.0;
12,082,240✔
102
  }
103
}
13,260✔
104

105
void FlatSourceDomain::accumulate_iteration_flux()
5,355✔
106
{
107
#pragma omp parallel for
2,835✔
108
  for (int64_t se = 0; se < n_source_elements_; se++) {
4,582,040✔
109
    source_regions_.scalar_flux_final(se) +=
4,579,520✔
110
      source_regions_.scalar_flux_new(se);
4,579,520✔
111
  }
112
}
5,355✔
113

114
// Compute new estimate of scattering + fission sources in each source region
115
// based on the flux estimate from the previous iteration.
116
void FlatSourceDomain::update_neutron_source(double k_eff)
5,695✔
117
{
118
  simulation::time_update_src.start();
5,695✔
119

120
  double inverse_k_eff = 1.0 / k_eff;
5,695✔
121

122
// Reset all source regions to zero (important for void regions)
123
#pragma omp parallel for
3,015✔
124
  for (int64_t se = 0; se < n_source_elements_; se++) {
5,238,040✔
125
    source_regions_.source(se) = 0.0;
5,235,360✔
126
  }
127

128
  // Add scattering + fission source
129
#pragma omp parallel for
3,015✔
130
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
2,681,560✔
131
    int material = source_regions_.material(sr);
2,678,880✔
132
    if (material == MATERIAL_VOID) {
2,678,880✔
133
      continue;
320,000✔
134
    }
135
    for (int g_out = 0; g_out < negroups_; g_out++) {
7,274,240✔
136
      double sigma_t = sigma_t_[material * negroups_ + g_out];
4,915,360✔
137
      double scatter_source = 0.0;
4,915,360✔
138
      double fission_source = 0.0;
4,915,360✔
139

140
      for (int g_in = 0; g_in < negroups_; g_in++) {
27,726,080✔
141
        double scalar_flux = source_regions_.scalar_flux_old(sr, g_in);
22,810,720✔
142
        double sigma_s =
143
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
22,810,720✔
144
        double nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
22,810,720✔
145
        double chi = chi_[material * negroups_ + g_out];
22,810,720✔
146

147
        scatter_source += sigma_s * scalar_flux;
22,810,720✔
148
        fission_source += nu_sigma_f * scalar_flux * chi;
22,810,720✔
149
      }
150
      source_regions_.source(sr, g_out) =
4,915,360✔
151
        (scatter_source + fission_source * inverse_k_eff) / sigma_t;
4,915,360✔
152
    }
153
  }
154

155
  // Add external source if in fixed source mode
156
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
5,695✔
157
#pragma omp parallel for
2,565✔
158
    for (int64_t se = 0; se < n_source_elements_; se++) {
4,650,120✔
159
      source_regions_.source(se) += source_regions_.external_source(se);
4,647,840✔
160
    }
161
  }
162

163
  simulation::time_update_src.stop();
5,695✔
164
}
5,695✔
165

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

174
// Normalize scalar flux to total distance travelled by all rays this
175
// iteration
176
#pragma omp parallel for
3,015✔
177
  for (int64_t se = 0; se < n_source_elements_; se++) {
5,238,040✔
178
    source_regions_.scalar_flux_new(se) *= normalization_factor;
5,235,360✔
179
  }
180

181
// Accumulate cell-wise ray length tallies collected this iteration, then
182
// update the simulation-averaged cell-wise volume estimates
183
#pragma omp parallel for
3,015✔
184
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
2,681,560✔
185
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
2,678,880✔
186
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
2,678,880✔
187
    source_regions_.volume_naive(sr) =
5,357,760✔
188
      source_regions_.volume(sr) * normalization_factor;
2,678,880✔
189
    source_regions_.volume_sq(sr) =
5,357,760✔
190
      (source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr)) *
2,678,880✔
191
      volume_normalization_factor;
192
    source_regions_.volume(sr) =
2,678,880✔
193
      source_regions_.volume_t(sr) * volume_normalization_factor;
2,678,880✔
194
  }
195
}
5,695✔
196

197
void FlatSourceDomain::set_flux_to_flux_plus_source(
11,805,106✔
198
  int64_t sr, double volume, int g)
199
{
200
  int material = source_regions_.material(sr);
11,805,106✔
201
  if (material == MATERIAL_VOID) {
11,805,106✔
202
    source_regions_.scalar_flux_new(sr, g) /= volume;
1,360,000✔
203
    source_regions_.scalar_flux_new(sr, g) +=
1,360,000✔
204
      0.5f * source_regions_.external_source(sr, g) *
1,360,000✔
205
      source_regions_.volume_sq(sr);
1,360,000✔
206
  } else {
207
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
10,445,106✔
208
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
10,445,106✔
209
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
10,445,106✔
210
  }
211
}
11,805,106✔
212

UNCOV
213
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
×
214
{
UNCOV
215
  source_regions_.scalar_flux_new(sr, g) =
×
UNCOV
216
    source_regions_.scalar_flux_old(sr, g);
×
217
}
218

219
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
34✔
220
{
221
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
34✔
222
}
34✔
223

224
// Combine transport flux contributions and flat source contributions from the
225
// previous iteration to generate this iteration's estimate of scalar flux.
226
int64_t FlatSourceDomain::add_source_to_scalar_flux()
13,260✔
227
{
228
  int64_t n_hits = 0;
13,260✔
229

230
#pragma omp parallel for reduction(+ : n_hits)
7,020✔
231
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
6,507,040✔
232

233
    double volume_simulation_avg = source_regions_.volume(sr);
6,500,800✔
234
    double volume_iteration = source_regions_.volume_naive(sr);
6,500,800✔
235

236
    // Increment the number of hits if cell was hit this iteration
237
    if (volume_iteration) {
6,500,800✔
238
      n_hits++;
6,500,784✔
239
    }
240

241
    // The volume treatment depends on the volume estimator type
242
    // and whether or not an external source is present in the cell.
243
    double volume;
244
    switch (volume_estimator_) {
6,500,800✔
245
    case RandomRayVolumeEstimator::NAIVE:
967,680✔
246
      volume = volume_iteration;
967,680✔
247
      break;
967,680✔
248
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
691,200✔
249
      volume = volume_simulation_avg;
691,200✔
250
      break;
691,200✔
251
    case RandomRayVolumeEstimator::HYBRID:
4,841,920✔
252
      if (source_regions_.external_source_present(sr)) {
4,841,920✔
253
        volume = volume_iteration;
19,280✔
254
      } else {
255
        volume = volume_simulation_avg;
4,822,640✔
256
      }
257
      break;
4,841,920✔
258
    default:
259
      fatal_error("Invalid volume estimator type");
260
    }
261

262
    for (int g = 0; g < negroups_; g++) {
18,583,040✔
263
      // There are three scenarios we need to consider:
264
      if (volume_iteration > 0.0) {
12,082,240✔
265
        // 1. If the FSR was hit this iteration, then the new flux is equal to
266
        // the flat source from the previous iteration plus the contributions
267
        // from rays passing through the source region (computed during the
268
        // transport sweep)
269
        set_flux_to_flux_plus_source(sr, volume, g);
12,082,224✔
270
      } else if (volume_simulation_avg > 0.0) {
16✔
271
        // 2. If the FSR was not hit this iteration, but has been hit some
272
        // previous iteration, then we need to make a choice about what
273
        // to do. Naively we will usually want to set the flux to be equal
274
        // to the reduced source. However, in fixed source problems where
275
        // there is a strong external source present in the cell, and where
276
        // the cell has a very low cross section, this approximation will
277
        // cause a huge upward bias in the flux estimate of the cell (in these
278
        // conditions, the flux estimate can be orders of magnitude too large).
279
        // Thus, to avoid this bias, if any external source is present
280
        // in the cell we will use the previous iteration's flux estimate. This
281
        // injects a small degree of correlation into the simulation, but this
282
        // is going to be trivial when the miss rate is a few percent or less.
283
        if (source_regions_.external_source_present(sr)) {
16✔
284
          set_flux_to_old_flux(sr, g);
285
        } else {
286
          set_flux_to_source(sr, g);
16✔
287
        }
288
      }
289
      // If the FSR was not hit this iteration, and it has never been hit in
290
      // any iteration (i.e., volume is zero), then we want to set this to 0
291
      // to avoid dividing anything by a zero volume. This happens implicitly
292
      // given that the new scalar flux arrays are set to zero each iteration.
293
    }
294
  }
295

296
  // Return the number of source regions that were hit this iteration
297
  return n_hits;
13,260✔
298
}
299

300
// Generates new estimate of k_eff based on the differences between this
301
// iteration's estimate of the scalar flux and the last iteration's estimate.
302
double FlatSourceDomain::compute_k_eff(double k_eff_old) const
2,210✔
303
{
304
  double fission_rate_old = 0;
2,210✔
305
  double fission_rate_new = 0;
2,210✔
306

307
  // Vector for gathering fission source terms for Shannon entropy calculation
308
  vector<float> p(n_source_regions_, 0.0f);
2,210✔
309

310
#pragma omp parallel for reduction(+ : fission_rate_old, fission_rate_new)
1,170✔
311
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
276,240✔
312

313
    // If simulation averaged volume is zero, don't include this cell
314
    double volume = source_regions_.volume(sr);
275,200✔
315
    if (volume == 0.0) {
275,200✔
316
      continue;
317
    }
318

319
    int material = source_regions_.material(sr);
275,200✔
320
    if (material == MATERIAL_VOID) {
275,200✔
321
      continue;
322
    }
323

324
    double sr_fission_source_old = 0;
275,200✔
325
    double sr_fission_source_new = 0;
275,200✔
326

327
    for (int g = 0; g < negroups_; g++) {
1,955,840✔
328
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
1,680,640✔
329
      sr_fission_source_old +=
1,680,640✔
330
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
1,680,640✔
331
      sr_fission_source_new +=
1,680,640✔
332
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
1,680,640✔
333
    }
334

335
    // Compute total fission rates in FSR
336
    sr_fission_source_old *= volume;
275,200✔
337
    sr_fission_source_new *= volume;
275,200✔
338

339
    // Accumulate totals
340
    fission_rate_old += sr_fission_source_old;
275,200✔
341
    fission_rate_new += sr_fission_source_new;
275,200✔
342

343
    // Store total fission rate in the FSR for Shannon calculation
344
    p[sr] = sr_fission_source_new;
275,200✔
345
  }
346

347
  double k_eff_new = k_eff_old * (fission_rate_new / fission_rate_old);
2,210✔
348

349
  double H = 0.0;
2,210✔
350
  // defining an inverse sum for better performance
351
  double inverse_sum = 1 / fission_rate_new;
2,210✔
352

353
#pragma omp parallel for reduction(+ : H)
1,170✔
354
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
276,240✔
355
    // Only if FSR has non-negative and non-zero fission source
356
    if (p[sr] > 0.0f) {
275,200✔
357
      // Normalize to total weight of bank sites. p_i for better performance
358
      float p_i = p[sr] * inverse_sum;
110,080✔
359
      // Sum values to obtain Shannon entropy.
360
      H -= p_i * std::log2(p_i);
110,080✔
361
    }
362
  }
363

364
  // Adds entropy value to shared entropy vector in openmc namespace.
365
  simulation::entropy.push_back(H);
2,210✔
366

367
  return k_eff_new;
2,210✔
368
}
2,210✔
369

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

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

393
// Besides generating the mapping structure, this function also keeps track
394
// of whether or not all flat source regions have been hit yet. This is
395
// required, as there is no guarantee that all flat source regions will
396
// be hit every iteration, such that in the first few iterations some FSRs
397
// may not have a known position within them yet to facilitate mapping to
398
// spatial tally filters. However, after several iterations, if all FSRs
399
// have been hit and have had a tally map generated, then this status will
400
// be passed back to the caller to alert them that this function doesn't
401
// need to be called for the remainder of the simulation.
402

403
void FlatSourceDomain::convert_source_regions_to_tallies()
336✔
404
{
405
  openmc::simulation::time_tallies.start();
336✔
406

407
  // Tracks if we've generated a mapping yet for all source regions.
408
  bool all_source_regions_mapped = true;
336✔
409

410
// Attempt to generate mapping for all source regions
411
#pragma omp parallel for
168✔
412
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
213,192✔
413

414
    // If this source region has not been hit by a ray yet, then
415
    // we aren't going to be able to map it, so skip it.
416
    if (!source_regions_.position_recorded(sr)) {
213,024✔
417
      all_source_regions_mapped = false;
418
      continue;
419
    }
420

421
    // A particle located at the recorded midpoint of a ray
422
    // crossing through this source region is used to estabilish
423
    // the spatial location of the source region
424
    Particle p;
213,024✔
425
    p.r() = source_regions_.position(sr);
213,024✔
426
    p.r_last() = source_regions_.position(sr);
213,024✔
427
    bool found = exhaustive_find_cell(p);
213,024✔
428

429
    // Loop over energy groups (so as to support energy filters)
430
    for (int g = 0; g < negroups_; g++) {
503,808✔
431

432
      // Set particle to the current energy
433
      p.g() = g;
290,784✔
434
      p.g_last() = g;
290,784✔
435
      p.E() = data::mg.energy_bin_avg_[p.g()];
290,784✔
436
      p.E_last() = p.E();
290,784✔
437

438
      int64_t source_element = sr * negroups_ + g;
290,784✔
439

440
      // If this task has already been populated, we don't need to do
441
      // it again.
442
      if (source_regions_.tally_task(sr, g).size() > 0) {
290,784✔
443
        continue;
444
      }
445

446
      // Loop over all active tallies. This logic is essentially identical
447
      // to what happens when scanning for applicable tallies during
448
      // MC transport.
449
      for (auto i_tally : model::active_tallies) {
993,216✔
450
        Tally& tally {*model::tallies[i_tally]};
702,432✔
451

452
        // Initialize an iterator over valid filter bin combinations.
453
        // If there are no valid combinations, use a continue statement
454
        // to ensure we skip the assume_separate break below.
455
        auto filter_iter = FilterBinIter(tally, p);
702,432✔
456
        auto end = FilterBinIter(tally, true, &p.filter_matches());
702,432✔
457
        if (filter_iter == end)
702,432✔
458
          continue;
393,984✔
459

460
        // Loop over filter bins.
461
        for (; filter_iter != end; ++filter_iter) {
616,896✔
462
          auto filter_index = filter_iter.index_;
308,448✔
463
          auto filter_weight = filter_iter.weight_;
308,448✔
464

465
          // Loop over scores
466
          for (auto score_index = 0; score_index < tally.scores_.size();
798,336✔
467
               score_index++) {
468
            auto score_bin = tally.scores_[score_index];
489,888✔
469
            // If a valid tally, filter, and score combination has been found,
470
            // then add it to the list of tally tasks for this source element.
471
            TallyTask task(i_tally, filter_index, score_index, score_bin);
489,888✔
472
            source_regions_.tally_task(sr, g).push_back(task);
489,888✔
473

474
            // Also add this task to the list of volume tasks for this source
475
            // region.
476
            source_regions_.volume_task(sr).insert(task);
489,888✔
477
          }
478
        }
479
      }
480
      // Reset all the filter matches for the next tally event.
481
      for (auto& match : p.filter_matches())
1,125,408✔
482
        match.bins_present_ = false;
834,624✔
483
    }
484
  }
213,024✔
485
  openmc::simulation::time_tallies.stop();
336✔
486

487
  mapped_all_tallies_ = all_source_regions_mapped;
336✔
488
}
336✔
489

490
// Set the volume accumulators to zero for all tallies
491
void FlatSourceDomain::reset_tally_volumes()
3,780✔
492
{
493
  if (volume_normalized_flux_tallies_) {
3,780✔
494
#pragma omp parallel for
1,530✔
495
    for (int i = 0; i < tally_volumes_.size(); i++) {
5,460✔
496
      auto& tensor = tally_volumes_[i];
3,930✔
497
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
3,930✔
498
    }
499
  }
500
}
3,780✔
501

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

518
  // Step 1 is to sum over all source regions and energy groups to get the
519
  // total external source strength in the simulation.
520
  double simulation_external_source_strength = 0.0;
3,203✔
521
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
1,611✔
522
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
2,316,488✔
523
    int material = source_regions_.material(sr);
2,314,896✔
524
    double volume = source_regions_.volume(sr) * simulation_volume_;
2,314,896✔
525
    for (int g = 0; g < negroups_; g++) {
5,289,600✔
526
      // For non-void regions, we store the external source pre-divided by
527
      // sigma_t. We need to multiply non-void regions back up by sigma_t
528
      // to get the total source strength in the expected units.
529
      double sigma_t = 1.0;
2,974,704✔
530
      if (material != MATERIAL_VOID) {
2,974,704✔
531
        sigma_t = sigma_t_[material * negroups_ + g];
2,718,704✔
532
      }
533
      simulation_external_source_strength +=
2,974,704✔
534
        source_regions_.external_source(sr, g) * sigma_t * volume;
2,974,704✔
535
    }
536
  }
537

538
  // Step 2 is to determine the total user-specified external source strength
539
  double user_external_source_strength = 0.0;
3,203✔
540
  for (auto& ext_source : model::external_sources) {
6,406✔
541
    user_external_source_strength += ext_source->strength();
3,203✔
542
  }
543

544
  // The correction factor is the ratio of the user-specified external source
545
  // strength to the simulation external source strength.
546
  double source_normalization_factor =
3,203✔
547
    user_external_source_strength / simulation_external_source_strength;
548

549
  return source_normalization_factor;
3,203✔
550
}
551

552
// Tallying in random ray is not done directly during transport, rather,
553
// it is done only once after each power iteration. This is made possible
554
// by way of a mapping data structure that relates spatial source regions
555
// (FSRs) to tally/filter/score combinations. The mechanism by which the
556
// mapping is done (and the limitations incurred) is documented in the
557
// "convert_source_regions_to_tallies()" function comments above. The present
558
// tally function simply traverses the mapping data structure and executes
559
// the scoring operations to OpenMC's native tally result arrays.
560

561
void FlatSourceDomain::random_ray_tally()
3,780✔
562
{
563
  openmc::simulation::time_tallies.start();
3,780✔
564

565
  // Reset our tally volumes to zero
566
  reset_tally_volumes();
3,780✔
567

568
  double source_normalization_factor =
569
    compute_fixed_source_normalization_factor();
3,780✔
570

571
// We loop over all source regions and energy groups. For each
572
// element, we check if there are any scores needed and apply
573
// them.
574
#pragma omp parallel for
1,890✔
575
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
2,283,090✔
576
    // The fsr.volume_ is the unitless fractional simulation averaged volume
577
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
578
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
579
    // entire global simulation domain (as defined by the ray source box).
580
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
581
    // its fraction of the total volume by the total volume. Not important in
582
    // eigenvalue solves, but useful in fixed source solves for returning the
583
    // flux shape with a magnitude that makes sense relative to the fixed
584
    // source strength.
585
    double volume = source_regions_.volume(sr) * simulation_volume_;
2,281,200✔
586

587
    double material = source_regions_.material(sr);
2,281,200✔
588
    for (int g = 0; g < negroups_; g++) {
5,715,840✔
589
      double flux =
590
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
3,434,640✔
591

592
      // Determine numerical score value
593
      for (auto& task : source_regions_.tally_task(sr, g)) {
9,648,960✔
594
        double score = 0.0;
6,214,320✔
595
        switch (task.score_type) {
6,214,320✔
596

597
        case SCORE_FLUX:
3,522,960✔
598
          score = flux * volume;
3,522,960✔
599
          break;
3,522,960✔
600

601
        case SCORE_TOTAL:
602
          if (material != MATERIAL_VOID) {
603
            score = flux * volume * sigma_t_[material * negroups_ + g];
604
          }
605
          break;
606

607
        case SCORE_FISSION:
1,345,680✔
608
          if (material != MATERIAL_VOID) {
1,345,680✔
609
            score = flux * volume * sigma_f_[material * negroups_ + g];
1,345,680✔
610
          }
611
          break;
1,345,680✔
612

613
        case SCORE_NU_FISSION:
1,345,680✔
614
          if (material != MATERIAL_VOID) {
1,345,680✔
615
            score = flux * volume * nu_sigma_f_[material * negroups_ + g];
1,345,680✔
616
          }
617
          break;
1,345,680✔
618

619
        case SCORE_EVENTS:
620
          score = 1.0;
621
          break;
622

623
        default:
624
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
625
                      "total, fission, nu-fission, and events are supported in "
626
                      "random ray mode.");
627
          break;
628
        }
629

630
        // Apply score to the appropriate tally bin
631
        Tally& tally {*model::tallies[task.tally_idx]};
6,214,320✔
632
#pragma omp atomic
633
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
6,214,320✔
634
          score;
635
      }
636
    }
637

638
    // For flux tallies, the total volume of the spatial region is needed
639
    // for normalizing the flux. We store this volume in a separate tensor.
640
    // We only contribute to each volume tally bin once per FSR.
641
    if (volume_normalized_flux_tallies_) {
2,281,200✔
642
      for (const auto& task : source_regions_.volume_task(sr)) {
6,079,680✔
643
        if (task.score_type == SCORE_FLUX) {
3,970,080✔
644
#pragma omp atomic
645
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
2,740,320✔
646
            volume;
647
        }
648
      }
649
    }
650
  } // end FSR loop
651

652
  // Normalize any flux scores by the total volume of the FSRs scoring to that
653
  // bin. To do this, we loop over all tallies, and then all filter bins,
654
  // and then scores. For each score, we check the tally data structure to
655
  // see what index that score corresponds to. If that score is a flux score,
656
  // then we divide it by volume.
657
  if (volume_normalized_flux_tallies_) {
3,780✔
658
    for (int i = 0; i < model::tallies.size(); i++) {
10,920✔
659
      Tally& tally {*model::tallies[i]};
7,860✔
660
#pragma omp parallel for
3,930✔
661
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
30,480✔
662
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
73,260✔
663
          auto score_type = tally.scores_[score_idx];
46,710✔
664
          if (score_type == SCORE_FLUX) {
46,710✔
665
            double vol = tally_volumes_[i](bin, score_idx);
26,550✔
666
            if (vol > 0.0) {
26,550✔
667
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
26,550✔
668
            }
669
          }
670
        }
671
      }
672
    }
673
  }
674

675
  openmc::simulation::time_tallies.stop();
3,780✔
676
}
3,780✔
677

678
void FlatSourceDomain::all_reduce_replicated_source_regions()
13,260✔
679
{
680
#ifdef OPENMC_MPI
681
  // If we only have 1 MPI rank, no need
682
  // to reduce anything.
683
  if (mpi::n_procs <= 1)
7,800✔
684
    return;
685

686
  simulation::time_bank_sendrecv.start();
7,800✔
687

688
  // First, we broadcast the fully mapped tally status variable so that
689
  // all ranks are on the same page
690
  int mapped_all_tallies_i = static_cast<int>(mapped_all_tallies_);
7,800✔
691
  MPI_Bcast(&mapped_all_tallies_i, 1, MPI_INT, 0, mpi::intracomm);
7,800✔
692

693
  bool reduce_position =
7,800✔
694
    simulation::current_batch > settings::n_inactive && !mapped_all_tallies_i;
7,800✔
695

696
  source_regions_.mpi_sync_ranks(reduce_position);
7,800✔
697

698
  simulation::time_bank_sendrecv.stop();
7,800✔
699
#endif
700
}
5,460✔
701

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

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

723
  // Print header information
724
  print_plot();
×
725

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

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

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

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

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

767
    // Relate voxel spatial locations to random ray source regions
768
    vector<int> voxel_indices(Nx * Ny * Nz);
×
769
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
770

771
#pragma omp parallel for collapse(3)
772
    for (int z = 0; z < Nz; z++) {
773
      for (int y = 0; y < Ny; y++) {
774
        for (int x = 0; x < Nx; x++) {
775
          Position sample;
776
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
777
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
778
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
779
          Particle p;
780
          p.r() = sample;
781
          bool found = exhaustive_find_cell(p);
782
          int i_cell = p.lowest_coord().cell;
783
          int64_t source_region_idx =
784
            source_region_offsets_[i_cell] + p.cell_instance();
785
          voxel_indices[z * Ny * Nx + y * Nx + x] = source_region_idx;
786
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
787
        }
788
      }
789
    }
790

791
    double source_normalization_factor =
UNCOV
792
      compute_fixed_source_normalization_factor();
×
793

794
    // Open file for writing
795
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
796

797
    // Write vtk metadata
798
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
799
    std::fprintf(plot, "Dataset File\n");
×
UNCOV
800
    std::fprintf(plot, "BINARY\n");
×
UNCOV
801
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
UNCOV
802
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
803
    std::fprintf(plot, "ORIGIN 0 0 0\n");
×
804
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
805
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
806

807
    // Plot multigroup flux data
808
    for (int g = 0; g < negroups_; g++) {
×
809
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
810
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
811
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
812
        int64_t fsr = voxel_indices[i];
×
813
        int64_t source_element = fsr * negroups_ + g;
×
814
        float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
UNCOV
815
        flux = convert_to_big_endian<float>(flux);
×
816
        std::fwrite(&flux, sizeof(float), 1, plot);
×
817
      }
818
    }
819

820
    // Plot FSRs
UNCOV
821
    std::fprintf(plot, "SCALARS FSRs float\n");
×
UNCOV
822
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
UNCOV
823
    for (int fsr : voxel_indices) {
×
UNCOV
824
      float value = future_prn(10, fsr);
×
UNCOV
825
      value = convert_to_big_endian<float>(value);
×
UNCOV
826
      std::fwrite(&value, sizeof(float), 1, plot);
×
827
    }
828

829
    // Plot Materials
UNCOV
830
    std::fprintf(plot, "SCALARS Materials int\n");
×
UNCOV
831
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
UNCOV
832
    for (int fsr : voxel_indices) {
×
UNCOV
833
      int mat = source_regions_.material(fsr);
×
UNCOV
834
      mat = convert_to_big_endian<int>(mat);
×
UNCOV
835
      std::fwrite(&mat, sizeof(int), 1, plot);
×
836
    }
837

838
    // Plot fission source
UNCOV
839
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
UNCOV
840
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
UNCOV
841
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
UNCOV
842
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
UNCOV
843
        int64_t fsr = voxel_indices[i];
×
844

UNCOV
845
        float total_fission = 0.0;
×
846
        int mat = source_regions_.material(fsr);
×
UNCOV
847
        if (mat != MATERIAL_VOID) {
×
UNCOV
848
          for (int g = 0; g < negroups_; g++) {
×
UNCOV
849
            int64_t source_element = fsr * negroups_ + g;
×
UNCOV
850
            float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
UNCOV
851
            double sigma_f = sigma_f_[mat * negroups_ + g];
×
UNCOV
852
            total_fission += sigma_f * flux;
×
853
          }
854
        }
UNCOV
855
        total_fission = convert_to_big_endian<float>(total_fission);
×
UNCOV
856
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
857
      }
858
    } else {
UNCOV
859
      std::fprintf(plot, "SCALARS external_source float\n");
×
UNCOV
860
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
UNCOV
861
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
UNCOV
862
        int64_t fsr = voxel_indices[i];
×
UNCOV
863
        float total_external = 0.0f;
×
UNCOV
864
        for (int g = 0; g < negroups_; g++) {
×
UNCOV
865
          total_external += source_regions_.external_source(fsr, g);
×
866
        }
UNCOV
867
        total_external = convert_to_big_endian<float>(total_external);
×
UNCOV
868
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
869
      }
870
    }
871

UNCOV
872
    std::fclose(plot);
×
873
  }
874
}
875

876
void FlatSourceDomain::apply_external_source_to_source_region(
2,346✔
877
  Discrete* discrete, double strength_factor, int64_t sr)
878
{
879
  source_regions_.external_source_present(sr) = 1;
2,346✔
880

881
  const auto& discrete_energies = discrete->x();
2,346✔
882
  const auto& discrete_probs = discrete->prob();
2,346✔
883

884
  for (int i = 0; i < discrete_energies.size(); i++) {
4,896✔
885
    int g = data::mg.get_group_index(discrete_energies[i]);
2,550✔
886
    source_regions_.external_source(sr, g) +=
2,550✔
887
      discrete_probs[i] * strength_factor;
2,550✔
888
  }
889
}
2,346✔
890

891
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
357✔
892
  Discrete* discrete, double strength_factor, int target_material_id,
893
  const vector<int32_t>& instances)
894
{
895
  Cell& cell = *model::cells[i_cell];
357✔
896

897
  if (cell.type_ != Fill::MATERIAL)
357✔
UNCOV
898
    return;
×
899

900
  for (int j : instances) {
31,943✔
901
    int cell_material_idx = cell.material(j);
31,586✔
902
    int cell_material_id;
903
    if (cell_material_idx == MATERIAL_VOID) {
31,586✔
904
      cell_material_id = MATERIAL_VOID;
272✔
905
    } else {
906
      cell_material_id = model::materials[cell_material_idx]->id();
31,314✔
907
    }
908
    if (target_material_id == C_NONE ||
31,586✔
909
        cell_material_id == target_material_id) {
910
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,346✔
911
      apply_external_source_to_source_region(
2,346✔
912
        discrete, strength_factor, source_region);
913
    }
914
  }
915
}
916

917
void FlatSourceDomain::apply_external_source_to_cell_and_children(
391✔
918
  int32_t i_cell, Discrete* discrete, double strength_factor,
919
  int32_t target_material_id)
920
{
921
  Cell& cell = *model::cells[i_cell];
391✔
922

923
  if (cell.type_ == Fill::MATERIAL) {
391✔
924
    vector<int> instances(cell.n_instances_);
357✔
925
    std::iota(instances.begin(), instances.end(), 0);
357✔
926
    apply_external_source_to_cell_instances(
357✔
927
      i_cell, discrete, strength_factor, target_material_id, instances);
928
  } else if (target_material_id == C_NONE) {
391✔
929
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
UNCOV
930
      cell.get_contained_cells(0, nullptr);
×
UNCOV
931
    for (const auto& pair : cell_instance_list) {
×
UNCOV
932
      int32_t i_child_cell = pair.first;
×
UNCOV
933
      apply_external_source_to_cell_instances(i_child_cell, discrete,
×
UNCOV
934
        strength_factor, target_material_id, pair.second);
×
935
    }
936
  }
937
}
391✔
938

939
void FlatSourceDomain::count_external_source_regions()
323✔
940
{
941
  n_external_source_regions_ = 0;
323✔
942
#pragma omp parallel for reduction(+ : n_external_source_regions_)
171✔
943
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
240,728✔
944
    if (source_regions_.external_source_present(sr)) {
240,576✔
945
      n_external_source_regions_++;
1,104✔
946
    }
947
  }
948
}
323✔
949

950
void FlatSourceDomain::convert_external_sources()
323✔
951
{
952
  // Loop over external sources
953
  for (int es = 0; es < model::external_sources.size(); es++) {
646✔
954
    Source* s = model::external_sources[es].get();
323✔
955
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
323✔
956
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
323✔
957
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
323✔
958

959
    double strength_factor = is->strength();
323✔
960

961
    if (is->domain_type() == Source::DomainType::MATERIAL) {
323✔
962
      for (int32_t material_id : domain_ids) {
34✔
963
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
102✔
964
          apply_external_source_to_cell_and_children(
85✔
965
            i_cell, energy, strength_factor, material_id);
966
        }
967
      }
968
    } else if (is->domain_type() == Source::DomainType::CELL) {
306✔
969
      for (int32_t cell_id : domain_ids) {
34✔
970
        int32_t i_cell = model::cell_map[cell_id];
17✔
971
        apply_external_source_to_cell_and_children(
17✔
972
          i_cell, energy, strength_factor, C_NONE);
973
      }
974
    } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
289✔
975
      for (int32_t universe_id : domain_ids) {
578✔
976
        int32_t i_universe = model::universe_map[universe_id];
289✔
977
        Universe& universe = *model::universes[i_universe];
289✔
978
        for (int32_t i_cell : universe.cells_) {
578✔
979
          apply_external_source_to_cell_and_children(
289✔
980
            i_cell, energy, strength_factor, C_NONE);
981
        }
982
      }
983
    }
984
  } // End loop over external sources
985

986
// Divide the fixed source term by sigma t (to save time when applying each
987
// iteration)
988
#pragma omp parallel for
171✔
989
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
240,728✔
990
    int material = source_regions_.material(sr);
240,576✔
991
    if (material == MATERIAL_VOID) {
240,576✔
992
      continue;
16,000✔
993
    }
994
    for (int g = 0; g < negroups_; g++) {
482,560✔
995
      double sigma_t = sigma_t_[material * negroups_ + g];
257,984✔
996
      source_regions_.external_source(sr, g) /= sigma_t;
257,984✔
997
    }
998
  }
999
}
323✔
1000

1001
void FlatSourceDomain::flux_swap()
13,260✔
1002
{
1003
  source_regions_.flux_swap();
13,260✔
1004
}
13,260✔
1005

1006
void FlatSourceDomain::flatten_xs()
476✔
1007
{
1008
  // Temperature and angle indices, if using multiple temperature
1009
  // data sets and/or anisotropic data sets.
1010
  // TODO: Currently assumes we are only using single temp/single angle data.
1011
  const int t = 0;
476✔
1012
  const int a = 0;
476✔
1013

1014
  n_materials_ = data::mg.macro_xs_.size();
476✔
1015
  for (auto& m : data::mg.macro_xs_) {
1,734✔
1016
    for (int g_out = 0; g_out < negroups_; g_out++) {
4,148✔
1017
      if (m.exists_in_model) {
2,890✔
1018
        double sigma_t =
1019
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
2,822✔
1020
        sigma_t_.push_back(sigma_t);
2,822✔
1021

1022
        double nu_Sigma_f =
1023
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
2,822✔
1024
        nu_sigma_f_.push_back(nu_Sigma_f);
2,822✔
1025

1026
        double sigma_f =
1027
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
2,822✔
1028
        sigma_f_.push_back(sigma_f);
2,822✔
1029

1030
        double chi =
1031
          m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
2,822✔
1032
        chi_.push_back(chi);
2,822✔
1033

1034
        for (int g_in = 0; g_in < negroups_; g_in++) {
17,068✔
1035
          double sigma_s =
1036
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
14,246✔
1037
          sigma_s_.push_back(sigma_s);
14,246✔
1038
        }
1039
      } else {
1040
        sigma_t_.push_back(0);
68✔
1041
        nu_sigma_f_.push_back(0);
68✔
1042
        sigma_f_.push_back(0);
68✔
1043
        chi_.push_back(0);
68✔
1044
        for (int g_in = 0; g_in < negroups_; g_in++) {
136✔
1045
          sigma_s_.push_back(0);
68✔
1046
        }
1047
      }
1048
    }
1049
  }
1050
}
476✔
1051

1052
void FlatSourceDomain::set_adjoint_sources(const vector<double>& forward_flux)
34✔
1053
{
1054
  // Set the external source to 1/forward_flux
1055
  // The forward flux is given in terms of total for the forward simulation
1056
  // so we must convert it to a "per batch" quantity
1057
#pragma omp parallel for
18✔
1058
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
27,664✔
1059
    for (int g = 0; g < negroups_; g++) {
55,296✔
1060
      source_regions_.external_source(sr, g) =
27,648✔
1061
        1.0 / forward_flux[sr * negroups_ + g];
27,648✔
1062
    }
1063
  }
1064

1065
  // Divide the fixed source term by sigma t (to save time when applying each
1066
  // iteration)
1067
#pragma omp parallel for
18✔
1068
  for (int64_t sr = 0; sr < n_source_regions_; sr++) {
27,664✔
1069
    for (int g = 0; g < negroups_; g++) {
55,296✔
1070
      int material = source_regions_.material(sr);
27,648✔
1071
      if (material == MATERIAL_VOID) {
27,648✔
1072
        continue;
1073
      }
1074
      double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
27,648✔
1075
      source_regions_.external_source(sr, g) /= sigma_t;
27,648✔
1076
    }
1077
  }
1078
}
34✔
1079

1080
void FlatSourceDomain::transpose_scattering_matrix()
51✔
1081
{
1082
  // Transpose the inner two dimensions for each material
1083
  for (int m = 0; m < n_materials_; ++m) {
187✔
1084
    int material_offset = m * negroups_ * negroups_;
136✔
1085
    for (int i = 0; i < negroups_; ++i) {
476✔
1086
      for (int j = i + 1; j < negroups_; ++j) {
1,054✔
1087
        // Calculate indices of the elements to swap
1088
        int idx1 = material_offset + i * negroups_ + j;
714✔
1089
        int idx2 = material_offset + j * negroups_ + i;
714✔
1090

1091
        // Swap the elements to transpose the matrix
1092
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
714✔
1093
      }
1094
    }
1095
  }
1096
}
51✔
1097

1098
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
425✔
1099
{
1100
  // Ensure array is correct size
1101
  flux.resize(n_source_regions_ * negroups_);
425✔
1102
// Serialize the final fluxes for output
1103
#pragma omp parallel for
225✔
1104
  for (int64_t se = 0; se < n_source_elements_; se++) {
346,600✔
1105
    flux[se] = source_regions_.scalar_flux_final(se);
346,400✔
1106
  }
1107
}
425✔
1108

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