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

openmc-dev / openmc / 20738722922

06 Jan 2026 05:08AM UTC coverage: 81.963% (-0.2%) from 82.154%
20738722922

Pull #3702

github

web-flow
Merge 22474d132 into 60ddafa9b
Pull Request #3702: Random Ray Kinetic Simulation Mode

17516 of 24331 branches covered (71.99%)

Branch coverage included in aggregate %.

903 of 1114 new or added lines in 20 files covered. (81.06%)

89 existing lines in 8 files now uncovered.

55907 of 65250 relevant lines covered (85.68%)

50718943.59 hits per line

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

73.25
/src/random_ray/flat_source_domain.cpp
1
#include "openmc/random_ray/flat_source_domain.h"
2
#include "openmc/random_ray/bd_utilities.h"
3

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

21
#include <cmath>
22
#include <cstdio>
23
#include <deque>
24

25
namespace openmc {
26

27
//==============================================================================
28
// FlatSourceDomain implementation
29
//==============================================================================
30

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

40
FlatSourceDomain::FlatSourceDomain()
753✔
41
  : negroups_(data::mg.num_energy_groups_),
753✔
42
    ndgroups_(data::mg.num_delayed_groups_)
753✔
43

44
{
45
  // Count the number of source regions, compute the cell offset
46
  // indices, and store the material type The reason for the offsets is that
47
  // some cell types may not have material fills, and therefore do not
48
  // produce FSRs. Thus, we cannot index into the global arrays directly
49
  int base_source_regions = 0;
753✔
50
  for (const auto& c : model::cells) {
6,196✔
51
    if (c->type_ != Fill::MATERIAL) {
5,443✔
52
      source_region_offsets_.push_back(-1);
2,513✔
53
    } else {
54
      source_region_offsets_.push_back(base_source_regions);
2,930✔
55
      base_source_regions += c->n_instances();
2,930✔
56
    }
57
  }
58

59
  // Initialize source regions.
60
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
753✔
61
  source_regions_ = SourceRegionContainer(negroups_, ndgroups_, is_linear);
753✔
62

63
  // Initialize tally volumes
64
  if (volume_normalized_flux_tallies_) {
753✔
65
    tally_volumes_.resize(model::tallies.size());
496✔
66
    for (int i = 0; i < model::tallies.size(); i++) {
1,792✔
67
      //  Get the shape of the 3D result tensor
68
      auto shape = model::tallies[i]->results().shape();
1,296✔
69

70
      // Create a new 2D tensor with the same size as the first
71
      // two dimensions of the 3D tensor
72
      tally_volumes_[i] =
1,296✔
73
        xt::xtensor<double, 2>::from_shape({shape[0], shape[1]});
2,592✔
74
    }
75
  }
76

77
  // Compute simulation domain volume based on ray source
78
  auto* is = dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get());
753!
79
  SpatialDistribution* space_dist = is->space();
753✔
80
  SpatialBox* sb = dynamic_cast<SpatialBox*>(space_dist);
753!
81
  Position dims = sb->upper_right() - sb->lower_left();
753✔
82
  simulation_volume_ = dims.x * dims.y * dims.z;
753✔
83
}
753✔
84

85
void FlatSourceDomain::batch_reset()
108,362✔
86
{
87
// Reset scalar fluxes and iteration volume tallies to zero
88
#pragma omp parallel for
59,112✔
89
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
71,061,855✔
90
    source_regions_.volume(sr) = 0.0;
71,012,605✔
91
    source_regions_.volume_sq(sr) = 0.0;
71,012,605✔
92
  }
93

94
#pragma omp parallel for
59,112✔
95
  for (int64_t se = 0; se < n_source_elements(); se++) {
311,485,575✔
96
    source_regions_.scalar_flux_new(se) = 0.0;
311,436,325✔
97
  }
98

99
  if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
108,362!
100
#pragma omp parallel for
52,500✔
101
    for (int64_t de = 0; de < n_delay_elements(); de++)
309,237,110✔
102
      source_regions_.precursors_new(de) = 0.0;
309,193,360✔
103
  }
104
}
108,362✔
105

106
void FlatSourceDomain::accumulate_iteration_flux()
52,696✔
107
{
108
#pragma omp parallel for
28,746✔
109
  for (int64_t se = 0; se < n_source_elements(); se++) {
152,897,350✔
110
    source_regions_.scalar_flux_final(se) +=
152,873,400✔
111
      source_regions_.scalar_flux_new(se);
152,873,400✔
112
  }
113
}
52,696✔
114

115
void FlatSourceDomain::update_single_neutron_source(SourceRegionHandle& srh)
128,969,235✔
116
{
117
  // Reset all source regions to zero (important for void regions)
118
  for (int g = 0; g < negroups_; g++) {
783,068,382✔
119
    srh.source(g) = 0.0;
654,099,147✔
120
  }
121

122
  // Add scattering + fission source
123
  int material = srh.material();
128,969,235✔
124
  if (material != MATERIAL_VOID) {
128,969,235✔
125
    double inverse_k_eff = 1.0 / k_eff_;
128,527,587✔
126
    for (int g_out = 0; g_out < negroups_; g_out++) {
782,184,318✔
127
      double sigma_t = sigma_t_[material * negroups_ + g_out];
653,656,731✔
128
      double scatter_source = 0.0;
653,656,731✔
129
      double fission_source = 0.0;
653,656,731✔
130
      double total_source = 0.0;
653,656,731✔
131

132
      for (int g_in = 0; g_in < negroups_; g_in++) {
2,147,483,647✔
133
        double scalar_flux = srh.scalar_flux_old(g_in);
2,147,483,647✔
134
        double sigma_s =
135
          sigma_s_[material * negroups_ * negroups_ + g_out * negroups_ + g_in];
2,147,483,647✔
136
        double nu_sigma_f;
137
        double chi;
138
        if (settings::kinetic_simulation && !simulation::is_initial_condition) {
2,147,483,647✔
139
          nu_sigma_f = nu_p_sigma_f_[material * negroups_ + g_in];
2,147,483,647✔
140
          chi = chi_p_[material * negroups_ + g_out];
2,147,483,647✔
141
        } else {
142
          nu_sigma_f = nu_sigma_f_[material * negroups_ + g_in];
1,496,671,279✔
143
          chi = chi_[material * negroups_ + g_out];
1,496,671,279✔
144
        }
145
        scatter_source += sigma_s * scalar_flux;
2,147,483,647✔
146
        if (settings::create_fission_neutrons) {
2,147,483,647!
147
          fission_source += nu_sigma_f * scalar_flux * chi;
2,147,483,647✔
148
        }
149
      }
150
      total_source = (scatter_source + fission_source * inverse_k_eff);
653,656,731✔
151

152
      if (settings::kinetic_simulation && !simulation::is_initial_condition) {
653,656,731✔
153
        // Add delayed source for kinetic simulation if delayed neutrons are
154
        // turned on
155
        if (settings::create_delayed_neutrons) {
432,159,200!
156
          double delayed_source = 0.0;
432,159,200✔
157
          for (int dg = 0; dg < ndgroups_; dg++) {
2,147,483,647✔
158
            double chi_d =
159
              chi_d_[material * negroups_ * ndgroups_ + dg * negroups_ + g_out];
2,147,483,647✔
160
            double lambda = lambda_[material * ndgroups_ + dg];
2,147,483,647✔
161
            double precursors = srh.precursors_old(dg);
2,147,483,647✔
162
            delayed_source += chi_d * precursors * lambda;
2,147,483,647✔
163
          }
164
          total_source += delayed_source;
432,159,200✔
165
        }
166
        // Add derivative of scalar flux to source (only works for isotropic
167
        // method)
168
        if (RandomRay::time_method_ == RandomRayTimeMethod::ISOTROPIC) {
432,159,200!
169
          double inverse_vbar = inverse_vbar_[material * negroups_ + g_out];
432,159,200✔
170
          double scalar_flux_rhs_bd = srh.scalar_flux_rhs_bd(g_out);
432,159,200✔
171
          double A0 =
172
            (bd_coefficients_first_order_.at(RandomRay::bd_order_))[0] /
432,159,200✔
173
            settings::dt;
432,159,200✔
174
          double scalar_flux = srh.scalar_flux_old(g_out);
432,159,200✔
175
          double scalar_flux_time_derivative =
432,159,200✔
176
            A0 * scalar_flux + scalar_flux_rhs_bd;
432,159,200✔
177
          total_source -= scalar_flux_time_derivative * inverse_vbar;
432,159,200✔
178
        }
179
      }
180
      srh.source(g_out) = total_source / sigma_t;
653,656,731✔
181
    }
182
  }
183

184
  // TODO: Add control flow for k-eigenvalue forward-weighted adjoint
185
  // Add external source if in fixed source mode
186
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
128,969,235✔
187
    for (int g = 0; g < negroups_; g++) {
89,574,878✔
188
      srh.source(g) += srh.external_source(g);
46,223,461✔
189
    }
190
  }
191
}
128,969,235✔
192

193
// Compute new estimate of scattering + fission sources in each source region
194
// based on the flux estimate from the previous iteration.
195
void FlatSourceDomain::update_all_neutron_sources()
108,362✔
196
{
197
  simulation::time_update_src.start();
108,362✔
198

199
#pragma omp parallel for
59,112✔
200
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
71,061,855✔
201
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
71,012,605✔
202
    update_single_neutron_source(srh);
71,012,605✔
203
    if (settings::kinetic_simulation && !simulation::is_initial_condition &&
71,012,605✔
204
        RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
27,650,000!
205
      compute_single_T1(srh);
×
206
    }
207
  }
208

209
  simulation::time_update_src.stop();
108,362✔
210
}
108,362✔
211

212
// Normalizes flux and updates simulation-averaged volume estimate
213
void FlatSourceDomain::normalize_scalar_flux_and_volumes(
101,487✔
214
  double total_active_distance_per_iteration)
215
{
216
  double normalization_factor = 1.0 / total_active_distance_per_iteration;
101,487✔
217
  double volume_normalization_factor =
101,487✔
218
    1.0 / (total_active_distance_per_iteration * simulation::current_batch);
101,487✔
219

220
// Normalize scalar flux to total distance travelled by all rays this
221
// iteration
222
#pragma omp parallel for
55,362✔
223
  for (int64_t se = 0; se < n_source_elements(); se++) {
297,331,865✔
224
    source_regions_.scalar_flux_new(se) *= normalization_factor;
297,285,740✔
225
  }
226

227
// Accumulate cell-wise ray length tallies collected this iteration, then
228
// update the simulation-averaged cell-wise volume estimates
229
#pragma omp parallel for
55,362✔
230
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
58,636,985✔
231
    source_regions_.volume_t(sr) += source_regions_.volume(sr);
58,590,860✔
232
    source_regions_.volume_sq_t(sr) += source_regions_.volume_sq(sr);
58,590,860✔
233
    source_regions_.volume_naive(sr) =
117,181,720✔
234
      source_regions_.volume(sr) * normalization_factor;
58,590,860✔
235
    source_regions_.volume_sq(sr) =
117,181,720✔
236
      source_regions_.volume_sq_t(sr) / source_regions_.volume_t(sr);
58,590,860✔
237
    source_regions_.volume(sr) =
58,590,860✔
238
      source_regions_.volume_t(sr) * volume_normalization_factor;
58,590,860✔
239
  }
240
}
101,487✔
241

242
void FlatSourceDomain::set_flux_to_flux_plus_source(
648,243,205✔
243
  int64_t sr, double volume, int g)
244
{
245
  int material = source_regions_.material(sr);
648,243,205✔
246
  // TODO: Implement support for time-dependent void transport
247
  if (material == MATERIAL_VOID) {
648,243,205✔
248
    source_regions_.scalar_flux_new(sr, g) /= volume;
882,416✔
249
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
882,416!
250
      source_regions_.scalar_flux_new(sr, g) +=
882,416✔
251
        0.5f * source_regions_.external_source(sr, g) *
882,416✔
252
        source_regions_.volume_sq(sr);
882,416✔
253
    }
254
  } else {
255
    double sigma_t = sigma_t_[source_regions_.material(sr) * negroups_ + g];
647,360,789✔
256
    source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume);
647,360,789✔
257
    source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g);
647,360,789✔
258
    if (settings::kinetic_simulation && !simulation::is_initial_condition &&
647,360,789✔
259
        RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
432,022,140!
260
      double inverse_vbar =
NEW
261
        inverse_vbar_[source_regions_.material(sr) * negroups_ + g];
×
NEW
262
      double scalar_flux_rhs_bd = source_regions_.scalar_flux_rhs_bd(sr, g);
×
NEW
263
      double A0 = (bd_coefficients_first_order_.at(RandomRay::bd_order_))[0] /
×
NEW
264
                  settings::dt;
×
NEW
265
      source_regions_.scalar_flux_new(sr, g) -=
×
NEW
266
        scalar_flux_rhs_bd * inverse_vbar / sigma_t;
×
NEW
267
      source_regions_.scalar_flux_new(sr, g) /= 1 + A0 * inverse_vbar / sigma_t;
×
268
    }
269
  }
270
}
648,243,205✔
271

272
void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g)
1,542✔
273
{
274
  source_regions_.scalar_flux_new(sr, g) =
3,084✔
275
    source_regions_.scalar_flux_old(sr, g);
1,542✔
276
}
1,542✔
277

278
void FlatSourceDomain::set_flux_to_source(int64_t sr, int g)
9,118,353✔
279
{
280
  source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g);
9,118,353✔
281
}
9,118,353✔
282

283
// Combine transport flux contributions and flat source contributions from the
284
// previous iteration to generate this iteration's estimate of scalar flux.
285
int64_t FlatSourceDomain::add_source_to_scalar_flux()
108,362✔
286
{
287
  int64_t n_hits = 0;
108,362✔
288
  double inverse_batch = 1.0 / simulation::current_batch;
108,362✔
289

290
#pragma omp parallel for reduction(+ : n_hits)
59,112✔
291
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
72,095,675✔
292

293
    double volume_simulation_avg = source_regions_.volume(sr);
72,046,425✔
294
    double volume_iteration = source_regions_.volume_naive(sr);
72,046,425✔
295

296
    // Increment the number of hits if cell was hit this iteration
297
    if (volume_iteration) {
72,046,425✔
298
      n_hits++;
67,974,820✔
299
    }
300

301
    // Set the SR to small status if its expected number of hits
302
    // per iteration is less than 1.5
303
    if (source_regions_.n_hits(sr) * inverse_batch < MIN_HITS_PER_BATCH) {
72,046,425✔
304
      source_regions_.is_small(sr) = 1;
6,812,940✔
305
    } else {
306
      source_regions_.is_small(sr) = 0;
65,233,485✔
307
    }
308

309
    // The volume treatment depends on the volume estimator type
310
    // and whether or not an external source is present in the cell.
311
    double volume;
312
    switch (volume_estimator_) {
72,046,425!
313
    case RandomRayVolumeEstimator::NAIVE:
777,600✔
314
      volume = volume_iteration;
777,600✔
315
      break;
777,600✔
316
    case RandomRayVolumeEstimator::SIMULATION_AVERAGED:
432,000✔
317
      volume = volume_simulation_avg;
432,000✔
318
      break;
432,000✔
319
    case RandomRayVolumeEstimator::HYBRID:
70,836,825✔
320
      if (source_regions_.external_source_present(sr) ||
137,485,650✔
321
          source_regions_.is_small(sr)) {
66,648,825✔
322
        volume = volume_iteration;
11,000,560✔
323
      } else {
324
        volume = volume_simulation_avg;
59,836,265✔
325
      }
326
      break;
70,836,825✔
327
    default:
328
      fatal_error("Invalid volume estimator type");
329
    }
330

331
    for (int g = 0; g < negroups_; g++) {
384,779,730✔
332
      // There are three scenarios we need to consider:
333
      if (volume_iteration > 0.0) {
312,733,305✔
334
        // 1. If the FSR was hit this iteration, then the new flux is equal to
335
        // the flat source from the previous iteration plus the contributions
336
        // from rays passing through the source region (computed during the
337
        // transport sweep)
338
        set_flux_to_flux_plus_source(sr, volume, g);
308,586,850✔
339
      } else if (volume_simulation_avg > 0.0) {
4,146,455✔
340
        // 2. If the FSR was not hit this iteration, but has been hit some
341
        // previous iteration, then we need to make a choice about what
342
        // to do. Naively we will usually want to set the flux to be equal
343
        // to the reduced source. However, in fixed source problems where
344
        // there is a strong external source present in the cell, and where
345
        // the cell has a very low cross section, this approximation will
346
        // cause a huge upward bias in the flux estimate of the cell (in these
347
        // conditions, the flux estimate can be orders of magnitude too large).
348
        // Thus, to avoid this bias, if any external source is present
349
        // in the cell we will use the previous iteration's flux estimate. This
350
        // injects a small degree of correlation into the simulation, but this
351
        // is going to be trivial when the miss rate is a few percent or less.
352
        if (source_regions_.external_source_present(sr)) {
4,146,025✔
353
          set_flux_to_old_flux(sr, g);
1,320✔
354
        } else {
355
          set_flux_to_source(sr, g);
4,144,705✔
356
        }
357
      }
358
      // Halt if NaN implosion is detected
359
      if (!std::isfinite(source_regions_.scalar_flux_new(sr, g))) {
312,733,305!
360
        fatal_error("A source region scalar flux is not finite. "
361
                    "This indicates a numerical instability in the "
362
                    "simulation. Consider increasing ray density or adjusting "
363
                    "the source region mesh.");
364
      }
365
    }
366
  }
367

368
  // Return the number of source regions that were hit this iteration
369
  return n_hits;
108,362✔
370
}
371

372
// Generates new estimate of k_eff based on the differences between this
373
// iteration's estimate of the scalar flux and the last iteration's estimate.
374
void FlatSourceDomain::compute_k_eff()
30,030✔
375
{
376
  double fission_rate_old = 0;
30,030✔
377
  double fission_rate_new = 0;
30,030✔
378

379
  // Vector for gathering fission source terms for Shannon entropy calculation
380
  vector<float> p(n_source_regions(), 0.0f);
30,030✔
381

382
#pragma omp parallel for reduction(+ : fission_rate_old, fission_rate_new)
16,380✔
383
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
11,383,830✔
384

385
    // If simulation averaged volume is zero, don't include this cell
386
    double volume = source_regions_.volume(sr);
11,370,180✔
387
    if (volume == 0.0) {
11,370,180✔
388
      continue;
10✔
389
    }
390

391
    int material = source_regions_.material(sr);
11,370,170✔
392
    if (material == MATERIAL_VOID) {
11,370,170!
393
      continue;
394
    }
395

396
    double sr_fission_source_old = 0;
11,370,170✔
397
    double sr_fission_source_new = 0;
11,370,170✔
398

399
    for (int g = 0; g < negroups_; g++) {
92,031,160✔
400
      double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
80,660,990✔
401
      sr_fission_source_old +=
80,660,990✔
402
        nu_sigma_f * source_regions_.scalar_flux_old(sr, g);
80,660,990✔
403
      sr_fission_source_new +=
80,660,990✔
404
        nu_sigma_f * source_regions_.scalar_flux_new(sr, g);
80,660,990✔
405
    }
406

407
    // Compute total fission rates in FSR
408
    sr_fission_source_old *= volume;
11,370,170✔
409
    sr_fission_source_new *= volume;
11,370,170✔
410

411
    // Accumulate totals
412
    fission_rate_old += sr_fission_source_old;
11,370,170✔
413
    fission_rate_new += sr_fission_source_new;
11,370,170✔
414

415
    // Store total fission rate in the FSR for Shannon calculation
416
    p[sr] = sr_fission_source_new;
11,370,170✔
417
  }
418

419
  double k_eff_new = k_eff_ * (fission_rate_new / fission_rate_old);
30,030✔
420

421
  double H = 0.0;
30,030✔
422
  // defining an inverse sum for better performance
423
  double inverse_sum = 1 / fission_rate_new;
30,030✔
424

425
#pragma omp parallel for reduction(+ : H)
16,380✔
426
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
11,383,830✔
427
    // Only if FSR has non-negative and non-zero fission source
428
    if (p[sr] > 0.0f) {
11,370,180✔
429
      // Normalize to total weight of bank sites. p_i for better performance
430
      float p_i = p[sr] * inverse_sum;
5,235,775✔
431
      // Sum values to obtain Shannon entropy.
432
      H -= p_i * std::log2(p_i);
5,235,775✔
433
    }
434
  }
435

436
  // Adds entropy value to shared entropy vector in openmc namespace.
437
  simulation::entropy.push_back(H);
30,030✔
438

439
  fission_rate_ = fission_rate_new;
30,030✔
440
  k_eff_ = k_eff_new;
30,030✔
441
}
30,030✔
442

443
// This function is responsible for generating a mapping between random
444
// ray flat source regions (cell instances) and tally bins. The mapping
445
// takes the form of a "TallyTask" object, which accounts for one single
446
// score being applied to a single tally. Thus, a single source region
447
// may have anywhere from zero to many tally tasks associated with it ---
448
// meaning that the global "tally_task" data structure is in 2D. The outer
449
// dimension corresponds to the source element (i.e., each entry corresponds
450
// to a specific energy group within a specific source region), and the
451
// inner dimension corresponds to the tallying task itself. Mechanically,
452
// the mapping between FSRs and spatial filters is done by considering
453
// the location of a single known ray midpoint that passed through the
454
// FSR. I.e., during transport, the first ray to pass through a given FSR
455
// will write down its midpoint for use with this function. This is a cheap
456
// and easy way of mapping FSRs to spatial tally filters, but comes with
457
// the downside of adding the restriction that spatial tally filters must
458
// share boundaries with the physical geometry of the simulation (so as
459
// not to subdivide any FSR). It is acceptable for a spatial tally region
460
// to contain multiple FSRs, but not the other way around.
461

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

466
// Besides generating the mapping structure, this function also keeps track
467
// of whether or not all flat source regions have been hit yet. This is
468
// required, as there is no guarantee that all flat source regions will
469
// be hit every iteration, such that in the first few iterations some FSRs
470
// may not have a known position within them yet to facilitate mapping to
471
// spatial tally filters. However, after several iterations, if all FSRs
472
// have been hit and have had a tally map generated, then this status will
473
// be passed back to the caller to alert them that this function doesn't
474
// need to be called for the remainder of the simulation.
475

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

481
void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id)
859✔
482
{
483
  openmc::simulation::time_tallies.start();
859✔
484

485
  // Tracks if we've generated a mapping yet for all source regions.
486
  bool all_source_regions_mapped = true;
859✔
487

488
// Attempt to generate mapping for all source regions
489
#pragma omp parallel for
469✔
490
  for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) {
1,034,210✔
491

492
    // If this source region has not been hit by a ray yet, then
493
    // we aren't going to be able to map it, so skip it.
494
    if (!source_regions_.position_recorded(sr)) {
1,033,820!
495
      all_source_regions_mapped = false;
496
      continue;
497
    }
498

499
    // A particle located at the recorded midpoint of a ray
500
    // crossing through this source region is used to estabilish
501
    // the spatial location of the source region
502
    Particle p;
1,033,820✔
503
    p.r() = source_regions_.position(sr);
1,033,820✔
504
    p.r_last() = source_regions_.position(sr);
1,033,820✔
505
    p.u() = {1.0, 0.0, 0.0};
1,033,820✔
506
    bool found = exhaustive_find_cell(p);
1,033,820✔
507

508
    // Loop over energy groups (so as to support energy filters)
509
    for (int g = 0; g < negroups_; g++) {
2,330,800✔
510

511
      // Set particle to the current energy
512
      p.g() = g;
1,296,980✔
513
      p.g_last() = g;
1,296,980✔
514
      p.E() = data::mg.energy_bin_avg_[p.g()];
1,296,980✔
515
      p.E_last() = p.E();
1,296,980✔
516

517
      int64_t source_element = sr * negroups_ + g;
1,296,980✔
518

519
      // If this task has already been populated, we don't need to do
520
      // it again.
521
      if (source_regions_.tally_task(sr, g).size() > 0) {
1,296,980!
522
        continue;
523
      }
524

525
      // Loop over all active tallies. This logic is essentially identical
526
      // to what happens when scanning for applicable tallies during
527
      // MC transport.
528
      for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) {
4,772,760✔
529
        Tally& tally {*model::tallies[i_tally]};
3,475,780✔
530

531
        // Initialize an iterator over valid filter bin combinations.
532
        // If there are no valid combinations, use a continue statement
533
        // to ensure we skip the assume_separate break below.
534
        auto filter_iter = FilterBinIter(tally, p);
3,475,780✔
535
        auto end = FilterBinIter(tally, true, &p.filter_matches());
3,475,780✔
536
        if (filter_iter == end)
3,475,780✔
537
          continue;
1,984,160✔
538

539
        // Loop over filter bins.
540
        for (; filter_iter != end; ++filter_iter) {
2,983,240✔
541
          auto filter_index = filter_iter.index_;
1,491,620✔
542
          auto filter_weight = filter_iter.weight_;
1,491,620✔
543

544
          // Loop over scores
545
          for (int score = 0; score < tally.scores_.size(); score++) {
3,399,600✔
546
            auto score_bin = tally.scores_[score];
2,004,300✔
547
            // Skip precursor score. These must be scored by delay group via
548
            // tally_delay_task.
549
            if (score_bin == SCORE_PRECURSORS)
2,004,300✔
550
              break;
96,320✔
551
            // If a valid tally, filter, and score combination has been found,
552
            // then add it to the list of tally tasks for this source element.
553
            TallyTask task(i_tally, filter_index, score, score_bin);
1,907,980✔
554
            source_regions_.tally_task(sr, g).push_back(task);
1,907,980✔
555

556
            // Also add this task to the list of volume tasks for this source
557
            // region.
558
            source_regions_.volume_task(sr).insert(task);
1,907,980✔
559
          }
560
        }
561
      }
562
      // Reset all the filter matches for the next tally event.
563
      for (auto& match : p.filter_matches())
5,316,140✔
564
        match.bins_present_ = false;
4,019,160✔
565
    }
566
    // Loop over delayed groups (so as to support tallying delayed quantities)
567
    if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
1,033,820!
568
      for (int dg = 0; dg < ndgroups_; dg++) {
138,400✔
569

570
        // Set particle to the current delay group
571
        p.delayed_group() = dg;
122,560✔
572

573
        int64_t delay_element = sr * ndgroups_ + dg;
122,560✔
574

575
        // If this task has already been populated, we don't need to do
576
        // it again.
577
        if (source_regions_.tally_delay_task(sr, dg).size() > 0) {
122,560!
578
          continue;
579
        }
580

581
        // Loop over all active tallies. This logic is essentially identical
582
        // to what happens when scanning for applicable tallies during
583
        // MC transport.
584
        // Loop over all active tallies. This logic is essentially identical
585
        for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) {
342,720✔
586
          Tally& tally {*model::tallies[i_tally]};
220,160✔
587

588
          // Initialize an iterator over valid filter bin combinations.
589
          // If there are no valid combinations, use a continue statement
590
          // to ensure we skip the assume_separate break below.
591
          auto filter_iter = FilterBinIter(tally, p);
220,160✔
592
          auto end = FilterBinIter(tally, true, &p.filter_matches());
220,160✔
593
          if (filter_iter == end)
220,160!
594
            continue;
595

596
          // Loop over filter bins.
597
          for (; filter_iter != end; ++filter_iter) {
440,320✔
598
            auto filter_index = filter_iter.index_;
220,160✔
599
            auto filter_weight = filter_iter.weight_;
220,160✔
600

601
            // Loop over scores
602
            for (int score = 0; score < tally.scores_.size(); score++) {
330,240✔
603
              auto score_bin = tally.scores_[score];
220,160✔
604
              // We only want to score precursors
605
              if (score_bin != SCORE_PRECURSORS)
220,160✔
606
                break;
110,080✔
607
              // If a valid tally, filter, and score combination has been found,
608
              // then add it to the list of tally tasks for this source element.
609
              TallyTask task(i_tally, filter_index + dg, score, score_bin);
110,080✔
610
              source_regions_.tally_delay_task(sr, dg).push_back(task);
110,080✔
611

612
              // Also add this task to the list of volume tasks for this source
613
              // region.
614
              source_regions_.volume_task(sr).insert(task);
110,080✔
615
            }
616
          }
617
        }
618
        // Reset all the filter matches for the next tally event.
619
        for (auto& match : p.filter_matches())
445,120✔
620
          match.bins_present_ = false;
322,560✔
621
      }
622
    }
623
  }
1,033,820✔
624
  openmc::simulation::time_tallies.stop();
859✔
625

626
  mapped_all_tallies_ = all_source_regions_mapped;
859✔
627
}
859✔
628

629
// Set the volume accumulators to zero for all tallies
630
void FlatSourceDomain::reset_tally_volumes()
52,696✔
631
{
632
  if (volume_normalized_flux_tallies_) {
52,696✔
633
#pragma omp parallel for
27,300✔
634
    for (int i = 0; i < tally_volumes_.size(); i++) {
69,600✔
635
      auto& tensor = tally_volumes_[i];
46,850✔
636
      tensor.fill(0.0); // Set all elements of the tensor to 0.0
46,850✔
637
    }
638
  }
639
}
52,696✔
640

641
// In fixed source mode, due to the way that volumetric fixed sources are
642
// converted and applied as volumetric sources in one or more source regions,
643
// we need to perform an additional normalization step to ensure that the
644
// reported scalar fluxes are in units per source neutron. This allows for
645
// direct comparison of reported tallies to Monte Carlo flux results.
646
// This factor needs to be computed at each iteration, as it is based on the
647
// volume estimate of each FSR, which improves over the course of the
648
// simulation
649
double FlatSourceDomain::compute_fixed_source_normalization_factor() const
53,530✔
650
{
651
  // Eigenvalue mode normalization
652
  if (settings::run_mode == RunMode::EIGENVALUE) {
53,530✔
653
    // Normalize fluxes by total number of fission neutrons produced. This
654
    // ensures consistent scaling of the eigenvector such that its magnitude is
655
    // comparable to the eigenvector produced by the Monte Carlo solver.
656
    // Multiplying by the eigenvalue is unintuitive, but it is necessary.
657
    // If the eigenvalue is 1.2, per starting source neutron, you will
658
    // generate 1.2 neutrons. Thus if we normalize to generating only ONE
659
    // neutron in total for the whole domain, then we don't actually have enough
660
    // flux to generate the required 1.2 neutrons. We only know the flux
661
    // required to generate 1 neutron (which would have required less than one
662
    // starting neutron). Thus, you have to scale the flux up by the eigenvalue
663
    // such that 1.2 neutrons are generated, so as to be consistent with the
664
    // bookkeeping in MC which is all done per starting source neutron (not per
665
    // neutron produced).
666
    return k_eff_ / (fission_rate_ * simulation_volume_);
49,318✔
667
  }
668

669
  // If we are in adjoint mode of a fixed source problem, the external
670
  // source is already normalized, such that all resulting fluxes are
671
  // also normalized.
672
  if (adjoint_) {
4,212✔
673
    return 1.0;
398✔
674
  }
675

676
  // Fixed source mode normalization
677

678
  // Step 1 is to sum over all source regions and energy groups to get the
679
  // total external source strength in the simulation.
680
  double simulation_external_source_strength = 0.0;
3,814✔
681
#pragma omp parallel for reduction(+ : simulation_external_source_strength)
2,089✔
682
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
14,626,285✔
683
    int material = source_regions_.material(sr);
14,624,560✔
684
    double volume = source_regions_.volume(sr) * simulation_volume_;
14,624,560✔
685
    for (int g = 0; g < negroups_; g++) {
29,792,000✔
686
      // For non-void regions, we store the external source pre-divided by
687
      // sigma_t. We need to multiply non-void regions back up by sigma_t
688
      // to get the total source strength in the expected units.
689
      double sigma_t = 1.0;
15,167,440✔
690
      if (material != MATERIAL_VOID) {
15,167,440✔
691
        sigma_t = sigma_t_[material * negroups_ + g];
14,957,200✔
692
      }
693
      simulation_external_source_strength +=
15,167,440✔
694
        source_regions_.external_source(sr, g) * sigma_t * volume;
15,167,440✔
695
    }
696
  }
697

698
  // Step 2 is to determine the total user-specified external source strength
699
  double user_external_source_strength = 0.0;
3,814✔
700
  for (auto& ext_source : model::external_sources) {
7,628✔
701
    user_external_source_strength += ext_source->strength();
3,814✔
702
  }
703

704
  // The correction factor is the ratio of the user-specified external source
705
  // strength to the simulation external source strength.
706
  double source_normalization_factor =
3,814✔
707
    user_external_source_strength / simulation_external_source_strength;
708

709
  return source_normalization_factor;
3,814✔
710
}
711

712
// Tallying in random ray is not done directly during transport, rather,
713
// it is done only once after each power iteration. This is made possible
714
// by way of a mapping data structure that relates spatial source regions
715
// (FSRs) to tally/filter/score combinations. The mechanism by which the
716
// mapping is done (and the limitations incurred) is documented in the
717
// "convert_source_regions_to_tallies()" function comments above. The present
718
// tally function simply traverses the mapping data structure and executes
719
// the scoring operations to OpenMC's native tally result arrays.
720

721
// TODO: Add support for prompt and delayed nu fission tallies
722
void FlatSourceDomain::random_ray_tally()
52,696✔
723
{
724
  openmc::simulation::time_tallies.start();
52,696✔
725

726
  // Reset our tally volumes to zero
727
  reset_tally_volumes();
52,696✔
728

729
  double source_normalization_factor =
730
    compute_fixed_source_normalization_factor();
52,696✔
731

732
// We loop over all source regions and energy groups. For each
733
// element, we check if there are any scores needed and apply
734
// them.
735
#pragma omp parallel for
28,746✔
736
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
34,613,350✔
737
    // The fsr.volume_ is the unitless fractional simulation averaged volume
738
    // (i.e., it is the FSR's fraction of the overall simulation volume). The
739
    // simulation_volume_ is the total 3D physical volume in cm^3 of the
740
    // entire global simulation domain (as defined by the ray source box).
741
    // Thus, the FSR's true 3D spatial volume in cm^3 is found by multiplying
742
    // its fraction of the total volume by the total volume. Not important in
743
    // eigenvalue solves, but useful in fixed source solves for returning the
744
    // flux shape with a magnitude that makes sense relative to the fixed
745
    // source strength.
746
    double volume = source_regions_.volume(sr) * simulation_volume_;
34,589,400✔
747

748
    double material = source_regions_.material(sr);
34,589,400✔
749
    for (int g = 0; g < negroups_; g++) {
187,462,800✔
750
      double flux =
751
        source_regions_.scalar_flux_new(sr, g) * source_normalization_factor;
152,873,400✔
752

753
      // Determine numerical score value
754
      for (auto& task : source_regions_.tally_task(sr, g)) {
580,038,000✔
755
        double score = 0.0;
427,164,600✔
756
        switch (task.score_type) {
427,164,600!
757

758
        case SCORE_FLUX:
154,296,200✔
759
          score = flux * volume;
154,296,200✔
760
          break;
154,296,200✔
761

762
        case SCORE_TOTAL:
763
          if (material != MATERIAL_VOID) {
×
764
            double sigma_t = sigma_t_[material * negroups_ + g];
765
            score = flux * volume * sigma_t_[material * negroups_ + g];
766
          }
767
          break;
768

769
        case SCORE_FISSION:
136,434,200✔
770
          if (material != MATERIAL_VOID) {
136,434,200!
771
            double sigma_f = sigma_f_[material * negroups_ + g];
136,434,200✔
772
            score = flux * volume * sigma_f_[material * negroups_ + g];
136,434,200✔
773
          }
774
          break;
136,434,200✔
775

776
        case SCORE_NU_FISSION:
136,434,200✔
777
          if (material != MATERIAL_VOID) {
136,434,200!
778
            double nu_sigma_f = nu_sigma_f_[material * negroups_ + g];
136,434,200✔
779
            score = flux * volume * nu_sigma_f_[material * negroups_ + g];
136,434,200✔
780
          }
781
          break;
136,434,200✔
782

783
        case SCORE_EVENTS:
784
          score = 1.0;
785
          break;
786

787
        case SCORE_PRECURSORS:
788
          // Score precursors in tally_delay_tasks
789
          if (settings::kinetic_simulation &&
×
790
              settings::create_delayed_neutrons) {
791
            break;
792
          } else {
793
            fatal_error("Invalid score specified in tallies.xml. Precursors "
794
                        "are only supported in random ray mode for kinetic "
795
                        "simulations when delayed neutrons are turned on.");
796
          }
797

798
        default:
799
          fatal_error("Invalid score specified in tallies.xml. Only flux, "
800
                      "total, fission, nu-fission, and events are supported in "
801
                      "random ray mode (precursors are supported in kinetic "
802
                      "simulations when delayed neutrons are turned on).");
803
          break;
804
        }
805
        // Apply score to the appropriate tally bin
806
        Tally& tally {*model::tallies[task.tally_idx]};
427,164,600✔
807
#pragma omp atomic
808
        tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
427,164,600✔
809
          score;
810
      }
811
    }
812
    if (settings::kinetic_simulation && settings::create_delayed_neutrons) {
34,589,400!
813
      for (int dg = 0; dg < ndgroups_; dg++) {
173,885,600✔
814
        // Determine numerical score value
815
        for (auto& task : source_regions_.tally_delay_task(sr, dg)) {
308,660,800✔
816
          double score = 0.0;
154,112,000✔
817
          switch (task.score_type) {
154,112,000!
818

819
          // Certain scores already tallied
820
          case SCORE_FLUX:
821
          case SCORE_TOTAL:
822
          case SCORE_FISSION:
823
          case SCORE_NU_FISSION:
824
          case SCORE_EVENTS:
825
            break;
826

827
          case SCORE_PRECURSORS:
154,112,000✔
828
            score = source_regions_.precursors_new(sr, dg) *
154,112,000✔
829
                    source_normalization_factor * volume;
830
            break;
154,112,000✔
831

832
          default:
833
            fatal_error(
834
              "Invalid score specified in tallies.xml. Only flux, "
835
              "total, fission, nu-fission, and events are supported in "
836
              "random ray mode (precursors are supported in kinetic "
837
              "simulations when delayed neutrons are turned on).");
838
            break;
839
          }
840

841
          // Apply score to the appropriate tally bin
842
          Tally& tally {*model::tallies[task.tally_idx]};
154,112,000✔
843
#pragma omp atomic
844
          tally.results_(task.filter_idx, task.score_idx, TallyResult::VALUE) +=
154,112,000✔
845
            score;
846
        }
847
      }
848
    }
849

850
    // For flux and precursor tallies, the total volume of the spatial region is
851
    // needed for normalizing the tally. We store this volume in a separate
852
    // tensor. We only contribute to each volume tally bin once per FSR.
853
    if (volume_normalized_flux_tallies_) {
34,589,400✔
854
      for (const auto& task : source_regions_.volume_task(sr)) {
601,681,600✔
855
        if (task.score_type == SCORE_FLUX ||
567,310,400✔
856
            task.score_type == SCORE_PRECURSORS) {
417,698,400✔
857
#pragma omp atomic
858
          tally_volumes_[task.tally_idx](task.filter_idx, task.score_idx) +=
303,724,000✔
859
            volume;
860
        }
861
      }
862
    }
863
  } // end FSR loop
864

865
  // Normalize any flux or precursor scores by the total volume of the FSRs
866
  // scoring to that bin. To do this, we loop over all tallies, and then all
867
  // filter bins, and then scores. For each score, we check the tally data
868
  // structure to see what index that score corresponds to. If that score is a
869
  // flux or precursor score, then we divide it by volume.
870
  if (volume_normalized_flux_tallies_) {
52,696✔
871
    for (int i = 0; i < model::tallies.size(); i++) {
153,120✔
872
      Tally& tally {*model::tallies[i]};
103,070✔
873
#pragma omp parallel for
56,220✔
874
      for (int bin = 0; bin < tally.n_filter_bins(); bin++) {
1,292,025✔
875
        for (int score_idx = 0; score_idx < tally.n_scores(); score_idx++) {
2,928,550✔
876
          auto score_type = tally.scores_[score_idx];
1,683,375✔
877
          if (score_type == SCORE_FLUX || score_type == SCORE_PRECURSORS) {
1,683,375✔
878
            double vol = tally_volumes_[i](bin, score_idx);
1,245,175✔
879
            if (vol > 0.0) {
1,245,175!
880
              tally.results_(bin, score_idx, TallyResult::VALUE) /= vol;
1,245,175✔
881
            }
882
          }
883
        }
884
      }
885
    }
886
  }
887

888
  openmc::simulation::time_tallies.stop();
52,696✔
889
}
52,696✔
890

891
double FlatSourceDomain::evaluate_flux_at_point(
×
892
  Position r, int64_t sr, int g) const
893
{
894
  return source_regions_.scalar_flux_final(sr, g) /
×
895
         (settings::n_batches - settings::n_inactive);
×
896
}
897

898
// Outputs all basic material, FSR ID, multigroup flux, and
899
// fission source data to .vtk file that can be directly
900
// loaded and displayed by Paraview. Note that .vtk binary
901
// files require big endian byte ordering, so endianness
902
// is checked and flipped if necessary.
903
void FlatSourceDomain::output_to_vtk() const
×
904
{
905
  // Rename .h5 plot filename(s) to .vtk filenames
906
  for (int p = 0; p < model::plots.size(); p++) {
×
907
    PlottableInterface* plot = model::plots[p].get();
×
908
    plot->path_plot() =
×
909
      plot->path_plot().substr(0, plot->path_plot().find_last_of('.')) + ".vtk";
×
910
  }
911

912
  // Print header information
913
  print_plot();
×
914

915
  // Outer loop over plots
916
  for (int plt = 0; plt < model::plots.size(); plt++) {
×
917

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

921
    // Random ray plots only support voxel plots
922
    if (!openmc_plot) {
×
923
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
924
                          "is allowed in random ray mode.",
925
        plt));
926
      continue;
×
927
    } else if (openmc_plot->type_ != Plot::PlotType::voxel) {
×
928
      warning(fmt::format("Plot {} is invalid plot type -- only voxel plotting "
×
929
                          "is allowed in random ray mode.",
930
        plt));
931
      continue;
×
932
    }
933

934
    int Nx = openmc_plot->pixels_[0];
×
935
    int Ny = openmc_plot->pixels_[1];
×
936
    int Nz = openmc_plot->pixels_[2];
×
937
    Position origin = openmc_plot->origin_;
×
938
    Position width = openmc_plot->width_;
×
939
    Position ll = origin - width / 2.0;
×
940
    double x_delta = width.x / Nx;
×
941
    double y_delta = width.y / Ny;
×
942
    double z_delta = width.z / Nz;
×
943
    std::string filename = openmc_plot->path_plot();
×
944

945
    // Perform sanity checks on file size
946
    uint64_t bytes = Nx * Ny * Nz * (negroups_ + 1 + 1 + 1) * sizeof(float);
×
947
    write_message(5, "Processing plot {}: {}... (Estimated size is {} MB)",
×
948
      openmc_plot->id(), filename, bytes / 1.0e6);
×
949
    if (bytes / 1.0e9 > 1.0) {
×
950
      warning("Voxel plot specification is very large (>1 GB). Plotting may be "
×
951
              "slow.");
952
    } else if (bytes / 1.0e9 > 100.0) {
×
953
      fatal_error("Voxel plot specification is too large (>100 GB). Exiting.");
×
954
    }
955

956
    // Relate voxel spatial locations to random ray source regions
957
    vector<int> voxel_indices(Nx * Ny * Nz);
×
958
    vector<Position> voxel_positions(Nx * Ny * Nz);
×
959
    vector<double> weight_windows(Nx * Ny * Nz);
×
960
    float min_weight = 1e20;
×
961
#pragma omp parallel for collapse(3) reduction(min : min_weight)
962
    for (int z = 0; z < Nz; z++) {
×
963
      for (int y = 0; y < Ny; y++) {
×
964
        for (int x = 0; x < Nx; x++) {
×
965
          Position sample;
966
          sample.z = ll.z + z_delta / 2.0 + z * z_delta;
967
          sample.y = ll.y + y_delta / 2.0 + y * y_delta;
968
          sample.x = ll.x + x_delta / 2.0 + x * x_delta;
969
          Particle p;
×
970
          p.r() = sample;
971
          p.r_last() = sample;
972
          p.E() = 1.0;
973
          p.E_last() = 1.0;
974
          p.u() = {1.0, 0.0, 0.0};
975

976
          bool found = exhaustive_find_cell(p);
×
977
          if (!found) {
×
978
            voxel_indices[z * Ny * Nx + y * Nx + x] = -1;
979
            voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
980
            weight_windows[z * Ny * Nx + y * Nx + x] = 0.0;
981
            continue;
982
          }
983

984
          SourceRegionKey sr_key = lookup_source_region_key(p);
×
985
          int64_t sr = -1;
986
          auto it = source_region_map_.find(sr_key);
×
987
          if (it != source_region_map_.end()) {
×
988
            sr = it->second;
989
          }
990

991
          voxel_indices[z * Ny * Nx + y * Nx + x] = sr;
992
          voxel_positions[z * Ny * Nx + y * Nx + x] = sample;
993

994
          if (variance_reduction::weight_windows.size() == 1) {
×
995
            WeightWindow ww =
996
              variance_reduction::weight_windows[0]->get_weight_window(p);
×
997
            float weight = ww.lower_weight;
998
            weight_windows[z * Ny * Nx + y * Nx + x] = weight;
999
            if (weight < min_weight)
×
1000
              min_weight = weight;
1001
          }
1002
        }
×
1003
      }
1004
    }
1005

1006
    double source_normalization_factor =
1007
      compute_fixed_source_normalization_factor();
×
1008

1009
    // Open file for writing
1010
    std::FILE* plot = std::fopen(filename.c_str(), "wb");
×
1011

1012
    // Write vtk metadata
1013
    std::fprintf(plot, "# vtk DataFile Version 2.0\n");
×
1014
    std::fprintf(plot, "Dataset File\n");
×
1015
    std::fprintf(plot, "BINARY\n");
×
1016
    std::fprintf(plot, "DATASET STRUCTURED_POINTS\n");
×
1017
    std::fprintf(plot, "DIMENSIONS %d %d %d\n", Nx, Ny, Nz);
×
1018
    std::fprintf(plot, "ORIGIN %lf %lf %lf\n", ll.x, ll.y, ll.z);
×
1019
    std::fprintf(plot, "SPACING %lf %lf %lf\n", x_delta, y_delta, z_delta);
×
1020
    std::fprintf(plot, "POINT_DATA %d\n", Nx * Ny * Nz);
×
1021

1022
    int64_t num_neg = 0;
×
1023
    int64_t num_samples = 0;
×
1024
    float min_flux = 0.0;
×
1025
    float max_flux = -1.0e20;
×
1026
    // Plot multigroup flux data
1027
    for (int g = 0; g < negroups_; g++) {
×
1028
      std::fprintf(plot, "SCALARS flux_group_%d float\n", g);
×
1029
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1030
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
1031
        int64_t fsr = voxel_indices[i];
×
1032
        int64_t source_element = fsr * negroups_ + g;
×
1033
        float flux = 0;
×
1034
        if (fsr >= 0) {
×
1035
          flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
1036
          if (flux < 0.0)
×
1037
            flux = FlatSourceDomain::evaluate_flux_at_point(
×
1038
              voxel_positions[i], fsr, g);
×
1039
        }
1040
        if (flux < 0.0) {
×
1041
          num_neg++;
×
1042
          if (flux < min_flux) {
×
1043
            min_flux = flux;
×
1044
          }
1045
        }
1046
        if (flux > max_flux)
×
1047
          max_flux = flux;
×
1048
        num_samples++;
×
1049
        flux = convert_to_big_endian<float>(flux);
×
1050
        std::fwrite(&flux, sizeof(float), 1, plot);
×
1051
      }
1052
    }
1053

1054
    // Slightly negative fluxes can be normal when sampling corners of linear
1055
    // source regions. However, very common and high magnitude negative fluxes
1056
    // may indicate numerical instability.
1057
    if (num_neg > 0) {
×
1058
      warning(fmt::format("{} plot samples ({:.4f}%) contained negative fluxes "
×
1059
                          "(minumum found = {:.2e} maximum_found = {:.2e})",
1060
        num_neg, (100.0 * num_neg) / num_samples, min_flux, max_flux));
×
1061
    }
1062

1063
    // Plot FSRs
1064
    std::fprintf(plot, "SCALARS FSRs float\n");
×
1065
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1066
    for (int fsr : voxel_indices) {
×
1067
      float value = future_prn(10, fsr);
×
1068
      value = convert_to_big_endian<float>(value);
×
1069
      std::fwrite(&value, sizeof(float), 1, plot);
×
1070
    }
1071

1072
    // Plot Materials
1073
    std::fprintf(plot, "SCALARS Materials int\n");
×
1074
    std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1075
    for (int fsr : voxel_indices) {
×
1076
      int mat = -1;
×
1077
      if (fsr >= 0)
×
1078
        mat = source_regions_.material(fsr);
×
1079
      mat = convert_to_big_endian<int>(mat);
×
1080
      std::fwrite(&mat, sizeof(int), 1, plot);
×
1081
    }
1082

1083
    // Plot fission source
1084
    if (settings::run_mode == RunMode::EIGENVALUE) {
×
1085
      std::fprintf(plot, "SCALARS total_fission_source float\n");
×
1086
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1087
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
1088
        int64_t fsr = voxel_indices[i];
×
1089
        float total_fission = 0.0;
×
1090
        if (fsr >= 0) {
×
1091
          int mat = source_regions_.material(fsr);
×
1092
          if (mat != MATERIAL_VOID) {
×
1093
            for (int g = 0; g < negroups_; g++) {
×
1094
              int64_t source_element = fsr * negroups_ + g;
×
1095
              float flux = evaluate_flux_at_point(voxel_positions[i], fsr, g);
×
1096
              double sigma_f = sigma_f_[mat * negroups_ + g];
×
1097
              total_fission += sigma_f * flux;
×
1098
            }
1099
          }
1100
        }
1101
        total_fission = convert_to_big_endian<float>(total_fission);
×
1102
        std::fwrite(&total_fission, sizeof(float), 1, plot);
×
1103
      }
1104
    } else {
1105
      std::fprintf(plot, "SCALARS external_source float\n");
×
1106
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1107
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
1108
        int64_t fsr = voxel_indices[i];
×
1109
        int mat = source_regions_.material(fsr);
×
1110
        float total_external = 0.0f;
×
1111
        if (fsr >= 0) {
×
1112
          for (int g = 0; g < negroups_; g++) {
×
1113
            // External sources are already divided by sigma_t, so we need to
1114
            // multiply it back to get the true external source.
1115
            double sigma_t = 1.0;
×
1116
            if (mat != MATERIAL_VOID) {
×
1117
              sigma_t = sigma_t_[mat * negroups_ + g];
×
1118
            }
1119
            total_external += source_regions_.external_source(fsr, g) * sigma_t;
×
1120
          }
1121
        }
1122
        total_external = convert_to_big_endian<float>(total_external);
×
1123
        std::fwrite(&total_external, sizeof(float), 1, plot);
×
1124
      }
1125
    }
1126

1127
    // Plot weight window data
1128
    if (variance_reduction::weight_windows.size() == 1) {
×
1129
      std::fprintf(plot, "SCALARS weight_window_lower float\n");
×
1130
      std::fprintf(plot, "LOOKUP_TABLE default\n");
×
1131
      for (int i = 0; i < Nx * Ny * Nz; i++) {
×
1132
        float weight = weight_windows[i];
×
1133
        if (weight == 0.0)
×
1134
          weight = min_weight;
×
1135
        weight = convert_to_big_endian<float>(weight);
×
1136
        std::fwrite(&weight, sizeof(float), 1, plot);
×
1137
      }
1138
    }
1139

1140
    std::fclose(plot);
×
1141
  }
×
1142
}
×
1143

1144
void FlatSourceDomain::apply_external_source_to_source_region(
4,500✔
1145
  int src_idx, SourceRegionHandle& srh)
1146
{
1147
  auto s = model::external_sources[src_idx].get();
4,500✔
1148
  auto is = dynamic_cast<IndependentSource*>(s);
4,500!
1149
  auto discrete = dynamic_cast<Discrete*>(is->energy());
4,500!
1150
  double strength_factor = is->strength();
4,500✔
1151
  const auto& discrete_energies = discrete->x();
4,500✔
1152
  const auto& discrete_probs = discrete->prob();
4,500✔
1153

1154
  srh.external_source_present() = 1;
4,500✔
1155

1156
  for (int i = 0; i < discrete_energies.size(); i++) {
9,132✔
1157
    int g = data::mg.get_group_index(discrete_energies[i]);
4,632✔
1158
    srh.external_source(g) += discrete_probs[i] * strength_factor;
4,632✔
1159
  }
1160
}
4,500✔
1161

1162
void FlatSourceDomain::apply_external_source_to_cell_instances(int32_t i_cell,
416✔
1163
  int src_idx, int target_material_id, const vector<int32_t>& instances)
1164
{
1165
  Cell& cell = *model::cells[i_cell];
416✔
1166

1167
  if (cell.type_ != Fill::MATERIAL)
416!
1168
    return;
×
1169

1170
  for (int j : instances) {
30,784✔
1171
    int cell_material_idx = cell.material(j);
30,368✔
1172
    int cell_material_id;
1173
    if (cell_material_idx == MATERIAL_VOID) {
30,368✔
1174
      cell_material_id = MATERIAL_VOID;
256✔
1175
    } else {
1176
      cell_material_id = model::materials[cell_material_idx]->id();
30,112✔
1177
    }
1178
    if (target_material_id == C_NONE ||
30,368✔
1179
        cell_material_id == target_material_id) {
1180
      int64_t source_region = source_region_offsets_[i_cell] + j;
2,848✔
1181
      external_volumetric_source_map_[source_region].push_back(src_idx);
2,848✔
1182
    }
1183
  }
1184
}
1185

1186
void FlatSourceDomain::apply_external_source_to_cell_and_children(
448✔
1187
  int32_t i_cell, int src_idx, int32_t target_material_id)
1188
{
1189
  Cell& cell = *model::cells[i_cell];
448✔
1190

1191
  if (cell.type_ == Fill::MATERIAL) {
448✔
1192
    vector<int> instances(cell.n_instances());
416✔
1193
    std::iota(instances.begin(), instances.end(), 0);
416✔
1194
    apply_external_source_to_cell_instances(
416✔
1195
      i_cell, src_idx, target_material_id, instances);
1196
  } else if (target_material_id == C_NONE) {
448!
1197
    std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1198
      cell.get_contained_cells(0, nullptr);
×
1199
    for (const auto& pair : cell_instance_list) {
×
1200
      int32_t i_child_cell = pair.first;
×
1201
      apply_external_source_to_cell_instances(
×
1202
        i_child_cell, src_idx, target_material_id, pair.second);
×
1203
    }
1204
  }
×
1205
}
448✔
1206

1207
void FlatSourceDomain::count_external_source_regions()
1,907✔
1208
{
1209
  n_external_source_regions_ = 0;
1,907✔
1210
#pragma omp parallel for reduction(+ : n_external_source_regions_)
1,074✔
1211
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,286,433✔
1212
    if (source_regions_.external_source_present(sr)) {
1,285,600✔
1213
      n_external_source_regions_++;
157,210✔
1214
    }
1215
  }
1216
}
1,907✔
1217

1218
void FlatSourceDomain::convert_external_sources()
401✔
1219
{
1220
  // Loop over external sources
1221
  for (int es = 0; es < model::external_sources.size(); es++) {
802✔
1222

1223
    // Extract source information
1224
    Source* s = model::external_sources[es].get();
401✔
1225
    IndependentSource* is = dynamic_cast<IndependentSource*>(s);
401!
1226
    Discrete* energy = dynamic_cast<Discrete*>(is->energy());
401!
1227
    const std::unordered_set<int32_t>& domain_ids = is->domain_ids();
401✔
1228
    double strength_factor = is->strength();
401✔
1229

1230
    // If there is no domain constraint specified, then this must be a point
1231
    // source. In this case, we need to find the source region that contains the
1232
    // point source and apply or relate it to the external source.
1233
    if (is->domain_ids().size() == 0) {
401✔
1234

1235
      // Extract the point source coordinate and find the base source region at
1236
      // that point
1237
      auto sp = dynamic_cast<SpatialPoint*>(is->space());
17!
1238
      GeometryState gs;
17✔
1239
      gs.r() = sp->r();
17✔
1240
      gs.r_last() = sp->r();
17✔
1241
      gs.u() = {1.0, 0.0, 0.0};
17✔
1242
      bool found = exhaustive_find_cell(gs);
17✔
1243
      if (!found) {
17!
1244
        fatal_error(fmt::format("Could not find cell containing external "
×
1245
                                "point source at {}",
1246
          sp->r()));
×
1247
      }
1248
      SourceRegionKey key = lookup_source_region_key(gs);
17✔
1249

1250
      // With the source region and mesh bin known, we can use the
1251
      // accompanying SourceRegionKey as a key into a map that stores the
1252
      // corresponding external source index for the point source. Notably, we
1253
      // do not actually apply the external source to any source regions here,
1254
      // as if mesh subdivision is enabled, they haven't actually been
1255
      // discovered & initilized yet. When discovered, they will read from the
1256
      // external_source_map to determine if there are any external source
1257
      // terms that should be applied.
1258
      external_point_source_map_[key].push_back(es);
17✔
1259

1260
    } else {
17✔
1261
      // If not a point source, then use the volumetric domain constraints to
1262
      // determine which source regions to apply the external source to.
1263
      if (is->domain_type() == Source::DomainType::MATERIAL) {
384✔
1264
        for (int32_t material_id : domain_ids) {
32✔
1265
          for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
96✔
1266
            apply_external_source_to_cell_and_children(i_cell, es, material_id);
80✔
1267
          }
1268
        }
1269
      } else if (is->domain_type() == Source::DomainType::CELL) {
368✔
1270
        for (int32_t cell_id : domain_ids) {
32✔
1271
          int32_t i_cell = model::cell_map[cell_id];
16✔
1272
          apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
16✔
1273
        }
1274
      } else if (is->domain_type() == Source::DomainType::UNIVERSE) {
352!
1275
        for (int32_t universe_id : domain_ids) {
704✔
1276
          int32_t i_universe = model::universe_map[universe_id];
352✔
1277
          Universe& universe = *model::universes[i_universe];
352✔
1278
          for (int32_t i_cell : universe.cells_) {
704✔
1279
            apply_external_source_to_cell_and_children(i_cell, es, C_NONE);
352✔
1280
          }
1281
        }
1282
      }
1283
    }
1284
  } // End loop over external sources
1285
}
401✔
1286

1287
void FlatSourceDomain::flux_swap()
108,362✔
1288
{
1289
  source_regions_.flux_swap();
108,362✔
1290
}
108,362✔
1291

1292
void FlatSourceDomain::flatten_xs()
753✔
1293
{
1294
  // Temperature and angle indices, if using multiple temperature
1295
  // data sets and/or anisotropic data sets.
1296
  // TODO: Currently assumes we are only using single temp/single angle data.
1297
  const int t = 0;
753✔
1298
  const int a = 0;
753✔
1299

1300
  n_materials_ = data::mg.macro_xs_.size();
753✔
1301
  for (int i = 0; i < n_materials_; i++) {
2,818✔
1302
    auto& m = data::mg.macro_xs_[i];
2,065✔
1303
    for (int g_out = 0; g_out < negroups_; g_out++) {
14,595✔
1304
      if (m.exists_in_model) {
12,530✔
1305
        double sigma_t =
1306
          m.get_xs(MgxsType::TOTAL, g_out, NULL, NULL, NULL, t, a);
12,466✔
1307
        sigma_t_.push_back(sigma_t);
12,466✔
1308

1309
        if (sigma_t < MINIMUM_MACRO_XS) {
12,466✔
1310
          Material* mat = model::materials[i].get();
16✔
1311
          warning(fmt::format(
16✔
1312
            "Material \"{}\" (id: {}) has a group {} total cross section "
1313
            "({:.3e}) below the minimum threshold "
1314
            "({:.3e}). Material will be treated as pure void.",
1315
            mat->name(), mat->id(), g_out, sigma_t, MINIMUM_MACRO_XS));
32✔
1316
        }
1317

1318
        double nu_sigma_f =
1319
          m.get_xs(MgxsType::NU_FISSION, g_out, NULL, NULL, NULL, t, a);
12,466✔
1320
        nu_sigma_f_.push_back(nu_sigma_f);
12,466✔
1321

1322
        double sigma_f =
1323
          m.get_xs(MgxsType::FISSION, g_out, NULL, NULL, NULL, t, a);
12,466✔
1324
        sigma_f_.push_back(sigma_f);
12,466✔
1325

1326
        double chi = m.get_xs(MgxsType::CHI, g_out, &g_out, NULL, NULL, t, a);
12,466✔
1327
        if (!std::isfinite(chi)) {
12,466!
1328
          // MGXS interface may return NaN in some cases, such as when material
1329
          // is fissionable but has very small sigma_f.
UNCOV
1330
          chi = 0.0;
×
1331
        }
1332
        chi_.push_back(chi);
12,466✔
1333

1334
        for (int g_in = 0; g_in < negroups_; g_in++) {
515,398✔
1335
          double sigma_s =
1336
            m.get_xs(MgxsType::NU_SCATTER, g_in, &g_out, NULL, NULL, t, a);
502,932✔
1337
          sigma_s_.push_back(sigma_s);
502,932✔
1338
          // For transport corrected XS data, diagonal elements may be negative.
1339
          // In this case, set a flag to enable transport stabilization for the
1340
          // simulation.
1341
          if (g_out == g_in && sigma_s < 0.0)
502,932✔
1342
            is_transport_stabilization_needed_ = true;
1,728✔
1343
        }
1344
        // Prompt cross-sections for kinetic simulations
1345
        if (settings::kinetic_simulation) {
12,466✔
1346
          double chi_p =
1347
            m.get_xs(MgxsType::CHI_PROMPT, g_out, &g_out, NULL, NULL, t, a);
4,432✔
1348
          if (!std::isfinite(chi_p)) {
4,432!
1349
            // MGXS interface may return NaN in some cases, such as when
1350
            // material is fissionable but has very small sigma_f.
NEW
1351
            chi_p = 0.0;
×
1352
          }
1353
          chi_p_.push_back(chi_p);
4,432✔
1354

1355
          double inverse_vbar =
1356
            m.get_xs(MgxsType::INVERSE_VELOCITY, g_out, NULL, NULL, NULL, t, a);
4,432✔
1357
          inverse_vbar_.push_back(inverse_vbar);
4,432✔
1358

1359
          double nu_p_Sigma_f = m.get_xs(
4,432✔
1360
            MgxsType::PROMPT_NU_FISSION, g_out, NULL, NULL, NULL, t, a);
4,432✔
1361
          nu_p_sigma_f_.push_back(nu_p_Sigma_f);
4,432✔
1362
        }
1363
      } else {
1364
        sigma_t_.push_back(0);
64✔
1365
        nu_sigma_f_.push_back(0);
64✔
1366
        sigma_f_.push_back(0);
64✔
1367
        chi_.push_back(0);
64✔
1368
        for (int g_in = 0; g_in < negroups_; g_in++) {
128✔
1369
          sigma_s_.push_back(0);
64✔
1370
        }
1371
        if (settings::kinetic_simulation) {
64!
NEW
1372
          chi_p_.push_back(0);
×
NEW
1373
          inverse_vbar_.push_back(0);
×
NEW
1374
          nu_p_sigma_f_.push_back(0);
×
1375
        }
1376
      }
1377
    }
1378
    // Delayed cross sections for time-dependent simulations
1379
    if (settings::kinetic_simulation) {
2,065✔
1380
      for (int dg = 0; dg < ndgroups_; dg++) {
2,352✔
1381
        if (m.exists_in_model) {
2,048!
1382
          double lambda =
1383
            m.get_xs(MgxsType::DECAY_RATE, 0, NULL, NULL, &dg, t, a);
2,048✔
1384
          lambda_.push_back(lambda);
2,048✔
1385
          for (int g_out = 0; g_out < negroups_; g_out++) {
30,208✔
1386
            double nu_d_Sigma_f = m.get_xs(
28,160✔
1387
              MgxsType::DELAYED_NU_FISSION, g_out, NULL, NULL, &dg, t, a);
28,160✔
1388
            nu_d_sigma_f_.push_back(nu_d_Sigma_f);
28,160✔
1389
            double chi_d =
1390
              m.get_xs(MgxsType::CHI_DELAYED, g_out, &g_out, NULL, &dg, t, a);
28,160✔
1391
            if (!std::isfinite(chi_d)) {
28,160!
1392
              // MGXS interface may return NaN in some cases, such as when
1393
              // material is fissionable but has very small sigma_f.
NEW
1394
              chi_d = 0.0;
×
1395
            }
1396
            chi_d_.push_back(chi_d);
28,160✔
1397
          }
1398
        } else {
NEW
1399
          lambda_.push_back(0);
×
NEW
1400
          for (int g_out = 0; g_out < negroups_; g_out++) {
×
NEW
1401
            nu_d_sigma_f_.push_back(0);
×
NEW
1402
            chi_d_.push_back(0);
×
1403
          }
1404
        }
1405
      }
1406
    }
1407
  }
1408
}
753✔
1409

1410
void FlatSourceDomain::set_adjoint_sources()
65✔
1411
{
1412
  // Set the adjoint external source to 1/forward_flux. If the forward flux is
1413
  // negative, zero, or extremely close to zero, set the adjoint source to zero,
1414
  // as this is likely a very small source region that we don't need to bother
1415
  // trying to vector particles towards. In the case of flux "being extremely
1416
  // close to zero", we define this as being a fixed fraction of the maximum
1417
  // forward flux, below which we assume the flux would be physically
1418
  // undetectable.
1419

1420
  // First, find the maximum forward flux value
1421
  double max_flux = 0.0;
65✔
1422
#pragma omp parallel for reduction(max : max_flux)
37✔
1423
  for (int64_t se = 0; se < n_source_elements(); se++) {
155,548✔
1424
    double flux = source_regions_.scalar_flux_final(se);
155,520✔
1425
    if (flux > max_flux) {
155,520✔
1426
      max_flux = flux;
25✔
1427
    }
1428
  }
1429

1430
  // Then, compute the adjoint source for each source region
1431
#pragma omp parallel for
37✔
1432
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1433
    for (int g = 0; g < negroups_; g++) {
311,040✔
1434
      double flux = source_regions_.scalar_flux_final(sr, g);
155,520✔
1435
      if (flux <= ZERO_FLUX_CUTOFF * max_flux) {
155,520✔
1436
        source_regions_.external_source(sr, g) = 0.0;
325✔
1437
      } else {
1438
        source_regions_.external_source(sr, g) = 1.0 / flux;
155,195✔
1439
      }
1440
      if (flux > 0.0) {
155,520✔
1441
        source_regions_.external_source_present(sr) = 1;
155,195✔
1442
      }
1443
      source_regions_.scalar_flux_final(sr, g) = 0.0;
155,520✔
1444
    }
1445
  }
1446

1447
  // "Small" source regions in OpenMC are defined as those that are hit by
1448
  // MIN_HITS_PER_BATCH rays or fewer each batch. These regions typically have
1449
  // very small volumes combined with a low aspect ratio, and are often
1450
  // generated when applying a source region mesh that clips the edge of a
1451
  // curved surface. As perhaps only a few rays will visit these regions over
1452
  // the entire forward simulation, the forward flux estimates are extremely
1453
  // noisy and unreliable. In some cases, the noise may make the forward fluxes
1454
  // extremely low, leading to unphysically large adjoint source terms,
1455
  // resulting in weight windows that aggressively try to drive particles
1456
  // towards these regions. To fix this, we simply filter out any "small" source
1457
  // regions from consideration. If a source region is "small", we
1458
  // set its adjoint source to zero. This adds negligible bias to the adjoint
1459
  // flux solution, as the true total adjoint source contribution from small
1460
  // regions is likely to be negligible.
1461
#pragma omp parallel for
37✔
1462
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1463
    if (source_regions_.is_small(sr)) {
155,520!
1464
      for (int g = 0; g < negroups_; g++) {
×
1465
        source_regions_.external_source(sr, g) = 0.0;
1466
      }
1467
      source_regions_.external_source_present(sr) = 0;
1468
    }
1469
  }
1470
  // Divide the fixed source term by sigma t (to save time when applying each
1471
  // iteration)
1472
#pragma omp parallel for
37✔
1473
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
155,548✔
1474
    int material = source_regions_.material(sr);
155,520✔
1475
    if (material == MATERIAL_VOID) {
155,520!
1476
      continue;
1477
    }
1478
    for (int g = 0; g < negroups_; g++) {
311,040✔
1479
      double sigma_t = sigma_t_[material * negroups_ + g];
155,520✔
1480
      source_regions_.external_source(sr, g) /= sigma_t;
155,520✔
1481
    }
1482
  }
1483
}
65✔
1484

1485
void FlatSourceDomain::transpose_scattering_matrix()
81✔
1486
{
1487
  // Transpose the inner two dimensions for each material
1488
  for (int m = 0; m < n_materials_; ++m) {
306✔
1489
    int material_offset = m * negroups_ * negroups_;
225✔
1490
    for (int i = 0; i < negroups_; ++i) {
643✔
1491
      for (int j = i + 1; j < negroups_; ++j) {
1,091✔
1492
        // Calculate indices of the elements to swap
1493
        int idx1 = material_offset + i * negroups_ + j;
673✔
1494
        int idx2 = material_offset + j * negroups_ + i;
673✔
1495

1496
        // Swap the elements to transpose the matrix
1497
        std::swap(sigma_s_[idx1], sigma_s_[idx2]);
673✔
1498
      }
1499
    }
1500
  }
1501
}
81✔
1502

1503
void FlatSourceDomain::serialize_final_fluxes(vector<double>& flux)
×
1504
{
1505
  // Ensure array is correct size
1506
  flux.resize(n_source_regions() * negroups_);
×
1507
// Serialize the final fluxes for output
1508
#pragma omp parallel for
1509
  for (int64_t se = 0; se < n_source_elements(); se++) {
×
1510
    flux[se] = source_regions_.scalar_flux_final(se);
1511
  }
1512
}
×
1513

NEW
1514
void FlatSourceDomain::serialize_final_sources(vector<double>& source)
×
1515
{
1516
  // Ensure array is correct size
NEW
1517
  source.resize(n_source_regions() * negroups_);
×
1518
  // Serialize the final sources for output
1519
#pragma omp parallel for
1520
  for (int64_t se = 0; se < n_source_elements(); se++) {
×
1521
    source[se] = source_regions_.source_final(se);
1522
  }
NEW
1523
}
×
1524

1525
void FlatSourceDomain::apply_mesh_to_cell_instances(int32_t i_cell,
1,106✔
1526
  int32_t mesh_idx, int target_material_id, const vector<int32_t>& instances,
1527
  bool is_target_void)
1528
{
1529
  Cell& cell = *model::cells[i_cell];
1,106✔
1530
  if (cell.type_ != Fill::MATERIAL)
1,106!
1531
    return;
×
1532
  for (int32_t j : instances) {
179,732✔
1533
    int cell_material_idx = cell.material(j);
178,626✔
1534
    int cell_material_id = (cell_material_idx == C_NONE)
1535
                             ? C_NONE
178,626✔
1536
                             : model::materials[cell_material_idx]->id();
178,625✔
1537

1538
    if ((target_material_id == C_NONE && !is_target_void) ||
178,626!
1539
        cell_material_id == target_material_id) {
1540
      int64_t sr = source_region_offsets_[i_cell] + j;
146,626✔
1541
      // Check if the key is already present in the mesh_map_
1542
      if (mesh_map_.find(sr) != mesh_map_.end()) {
146,626!
1543
        fatal_error(fmt::format("Source region {} already has mesh idx {} "
×
1544
                                "applied, but trying to apply mesh idx {}",
1545
          sr, mesh_map_[sr], mesh_idx));
×
1546
      }
1547
      // If the SR has not already been assigned, then we can write to it
1548
      mesh_map_[sr] = mesh_idx;
146,626✔
1549
    }
1550
  }
1551
}
1552

1553
void FlatSourceDomain::apply_mesh_to_cell_and_children(int32_t i_cell,
881✔
1554
  int32_t mesh_idx, int32_t target_material_id, bool is_target_void)
1555
{
1556
  Cell& cell = *model::cells[i_cell];
881✔
1557

1558
  if (cell.type_ == Fill::MATERIAL) {
881✔
1559
    vector<int> instances(cell.n_instances());
736✔
1560
    std::iota(instances.begin(), instances.end(), 0);
736✔
1561
    apply_mesh_to_cell_instances(
736✔
1562
      i_cell, mesh_idx, target_material_id, instances, is_target_void);
1563
  } else if (target_material_id == C_NONE && !is_target_void) {
881!
1564
    for (int j = 0; j < cell.n_instances(); j++) {
162✔
1565
      std::unordered_map<int32_t, vector<int32_t>> cell_instance_list =
1566
        cell.get_contained_cells(j, nullptr);
81✔
1567
      for (const auto& pair : cell_instance_list) {
451✔
1568
        int32_t i_child_cell = pair.first;
370✔
1569
        apply_mesh_to_cell_instances(i_child_cell, mesh_idx, target_material_id,
370✔
1570
          pair.second, is_target_void);
370✔
1571
      }
1572
    }
81✔
1573
  }
1574
}
881✔
1575

1576
void FlatSourceDomain::apply_meshes()
753✔
1577
{
1578
  // Skip if there are no mappings between mesh IDs and domains
1579
  if (mesh_domain_map_.empty())
753✔
1580
    return;
448✔
1581

1582
  // Loop over meshes
1583
  for (int mesh_idx = 0; mesh_idx < model::meshes.size(); mesh_idx++) {
706✔
1584
    Mesh* mesh = model::meshes[mesh_idx].get();
401✔
1585
    int mesh_id = mesh->id();
401✔
1586

1587
    // Skip if mesh id is not present in the map
1588
    if (mesh_domain_map_.find(mesh_id) == mesh_domain_map_.end())
401✔
1589
      continue;
32✔
1590

1591
    // Loop over domains associated with the mesh
1592
    for (auto& domain : mesh_domain_map_[mesh_id]) {
738✔
1593
      Source::DomainType domain_type = domain.first;
369✔
1594
      int domain_id = domain.second;
369✔
1595

1596
      if (domain_type == Source::DomainType::MATERIAL) {
369✔
1597
        for (int i_cell = 0; i_cell < model::cells.size(); i_cell++) {
192✔
1598
          if (domain_id == C_NONE) {
160!
1599
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, true);
×
1600
          } else {
1601
            apply_mesh_to_cell_and_children(i_cell, mesh_idx, domain_id, false);
160✔
1602
          }
1603
        }
1604
      } else if (domain_type == Source::DomainType::CELL) {
337✔
1605
        int32_t i_cell = model::cell_map[domain_id];
32✔
1606
        apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
32✔
1607
      } else if (domain_type == Source::DomainType::UNIVERSE) {
305!
1608
        int32_t i_universe = model::universe_map[domain_id];
305✔
1609
        Universe& universe = *model::universes[i_universe];
305✔
1610
        for (int32_t i_cell : universe.cells_) {
994✔
1611
          apply_mesh_to_cell_and_children(i_cell, mesh_idx, C_NONE, false);
689✔
1612
        }
1613
      }
1614
    }
1615
  }
1616
}
1617

1618
SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle(
2,147,483,647✔
1619
  SourceRegionKey sr_key, Position r, Direction u)
1620
{
1621
  // Case 1: Check if the source region key is already present in the permanent
1622
  // map. This is the most common condition, as any source region visited in a
1623
  // previous power iteration will already be present in the permanent map. If
1624
  // the source region key is found, we translate the key into a specific 1D
1625
  // source region index and return a handle its position in the
1626
  // source_regions_ vector.
1627
  auto it = source_region_map_.find(sr_key);
2,147,483,647✔
1628
  if (it != source_region_map_.end()) {
2,147,483,647✔
1629
    int64_t sr = it->second;
2,147,483,647✔
1630
    return source_regions_.get_source_region_handle(sr);
2,147,483,647✔
1631
  }
1632

1633
  // Case 2: Check if the source region key is present in the temporary (thread
1634
  // safe) map. This is a common occurrence in the first power iteration when
1635
  // the source region has already been visited already by some other ray. We
1636
  // begin by locking the temporary map before any operations are performed. The
1637
  // lock is not global over the full data structure -- it will be dependent on
1638
  // which key is used.
1639
  discovered_source_regions_.lock(sr_key);
47,968,259✔
1640

1641
  // If the key is found in the temporary map, then we return a handle to the
1642
  // source region that is stored in the temporary map.
1643
  if (discovered_source_regions_.contains(sr_key)) {
47,968,259✔
1644
    SourceRegionHandle handle {discovered_source_regions_[sr_key]};
45,591,842✔
1645
    discovered_source_regions_.unlock(sr_key);
45,591,842✔
1646
    return handle;
45,591,842✔
1647
  }
1648

1649
  // Case 3: The source region key is not present anywhere, but it is only due
1650
  // to floating point artifacts. These artifacts occur when the overlaid mesh
1651
  // overlaps with actual geometry surfaces. In these cases, roundoff error may
1652
  // result in the ray tracer detecting an additional (very short) segment
1653
  // though a mesh bin that is actually past the physical source region
1654
  // boundary. This is a result of the the multi-level ray tracing treatment in
1655
  // OpenMC, which depending on the number of universes in the hierarchy etc can
1656
  // result in the wrong surface being selected as the nearest. This can happen
1657
  // in a lattice when there are two directions that both are very close in
1658
  // distance, within the tolerance of FP_REL_PRECISION, and the are thus
1659
  // treated as being equivalent so alternative logic is used. However, when we
1660
  // go and ray trace on this with the mesh tracer we may go past the surface
1661
  // bounding the current source region.
1662
  //
1663
  // To filter out this case, before we create the new source region, we double
1664
  // check that the actual starting point of this segment (r) is still in the
1665
  // same geometry source region that we started in. If an artifact is detected,
1666
  // we discard the segment (and attenuation through it) as it is not really a
1667
  // valid source region and will have only an infinitessimally small cell
1668
  // combined with the mesh bin. Thankfully, this is a fairly rare condition,
1669
  // and only triggers for very short ray lengths. It can be fixed by decreasing
1670
  // the value of FP_REL_PRECISION in constants.h, but this may have unknown
1671
  // consequences for the general ray tracer, so for now we do the below sanity
1672
  // checks before generating phantom source regions. A significant extra cost
1673
  // is incurred in instantiating the GeometryState object and doing a cell
1674
  // lookup, but again, this is going to be an extremely rare thing to check
1675
  // after the first power iteration has completed.
1676

1677
  // Sanity check on source region id
1678
  GeometryState gs;
2,376,417✔
1679
  gs.r() = r + TINY_BIT * u;
2,376,417✔
1680
  gs.u() = {1.0, 0.0, 0.0};
2,376,417✔
1681
  exhaustive_find_cell(gs);
2,376,417✔
1682
  int64_t sr_found = lookup_base_source_region_idx(gs);
2,376,417✔
1683
  if (sr_found != sr_key.base_source_region_id) {
2,376,417✔
1684
    discovered_source_regions_.unlock(sr_key);
473✔
1685
    SourceRegionHandle handle;
473✔
1686
    handle.is_numerical_fp_artifact_ = true;
473✔
1687
    return handle;
473✔
1688
  }
1689

1690
  // Sanity check on mesh bin
1691
  int mesh_idx = lookup_mesh_idx(sr_key.base_source_region_id);
2,375,944✔
1692
  if (mesh_idx == C_NONE) {
2,375,944✔
1693
    if (sr_key.mesh_bin != 0) {
369,908!
1694
      discovered_source_regions_.unlock(sr_key);
×
1695
      SourceRegionHandle handle;
×
1696
      handle.is_numerical_fp_artifact_ = true;
×
1697
      return handle;
×
1698
    }
1699
  } else {
1700
    Mesh* mesh = model::meshes[mesh_idx].get();
2,006,036✔
1701
    int bin_found = mesh->get_bin(r + TINY_BIT * u);
2,006,036✔
1702
    if (bin_found != sr_key.mesh_bin) {
2,006,036!
1703
      discovered_source_regions_.unlock(sr_key);
×
1704
      SourceRegionHandle handle;
×
1705
      handle.is_numerical_fp_artifact_ = true;
×
1706
      return handle;
×
1707
    }
1708
  }
1709

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

1717
  // Call the basic constructor for the source region and store in the parallel
1718
  // map.
1719
  bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT;
2,375,944✔
1720
  SourceRegion* sr_ptr = discovered_source_regions_.emplace(
2,375,944✔
1721
    sr_key, {negroups_, ndgroups_, is_linear});
1722
  SourceRegionHandle handle {*sr_ptr};
2,375,944✔
1723

1724
  // Determine the material
1725
  int gs_i_cell = gs.lowest_coord().cell();
2,375,944✔
1726
  Cell& cell = *model::cells[gs_i_cell];
2,375,944✔
1727
  int material = cell.material(gs.cell_instance());
2,375,944✔
1728

1729
  // If material total XS is extremely low, just set it to void to avoid
1730
  // problems with 1/Sigma_t
1731
  for (int g = 0; g < negroups_; g++) {
5,308,843✔
1732
    double sigma_t = sigma_t_[material * negroups_ + g];
2,955,051✔
1733
    if (sigma_t < MINIMUM_MACRO_XS) {
2,955,051✔
1734
      material = MATERIAL_VOID;
22,152✔
1735
      break;
22,152✔
1736
    }
1737
  }
1738

1739
  handle.material() = material;
2,375,944✔
1740

1741
  // Store the mesh index (if any) assigned to this source region
1742
  handle.mesh() = mesh_idx;
2,375,944✔
1743

1744
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
2,375,944✔
1745
    // Determine if there are any volumetric sources, and apply them.
1746
    // Volumetric sources are specifc only to the base SR idx.
1747
    auto it_vol =
1748
      external_volumetric_source_map_.find(sr_key.base_source_region_id);
2,291,750✔
1749
    if (it_vol != external_volumetric_source_map_.end()) {
2,291,750✔
1750
      const vector<int>& vol_sources = it_vol->second;
4,488✔
1751
      for (int src_idx : vol_sources) {
8,976✔
1752
        apply_external_source_to_source_region(src_idx, handle);
4,488✔
1753
      }
1754
    }
1755

1756
    // Determine if there are any point sources, and apply them.
1757
    // Point sources are specific to the source region key.
1758
    auto it_point = external_point_source_map_.find(sr_key);
2,291,750✔
1759
    if (it_point != external_point_source_map_.end()) {
2,291,750✔
1760
      const vector<int>& point_sources = it_point->second;
12✔
1761
      for (int src_idx : point_sources) {
24✔
1762
        apply_external_source_to_source_region(src_idx, handle);
12✔
1763
      }
1764
    }
1765

1766
    // Divide external source term by sigma_t
1767
    if (material != C_NONE) {
2,291,750✔
1768
      for (int g = 0; g < negroups_; g++) {
4,585,155✔
1769
        double sigma_t = sigma_t_[material * negroups_ + g];
2,315,557✔
1770
        handle.external_source(g) /= sigma_t;
2,315,557✔
1771
      }
1772
    }
1773
  }
1774

1775
  // Compute the combined source term
1776
  update_single_neutron_source(handle);
2,375,944✔
1777
  if (settings::kinetic_simulation && !simulation::is_initial_condition &&
2,375,944!
NEW
1778
      RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
×
NEW
1779
    compute_single_T1(handle);
×
1780
  }
1781

1782
  // Unlock the parallel map. Note: we may be tempted to release
1783
  // this lock earlier, and then just use the source region's lock to protect
1784
  // the flux/source initialization stages above. However, the rest of the code
1785
  // only protects updates to the new flux and volume fields, and assumes that
1786
  // the source is constant for the duration of transport. Thus, using just the
1787
  // source region's lock by itself would result in other threads potentially
1788
  // reading from the source before it is computed, as they won't use the lock
1789
  // when only reading from the SR's source. It would be expensive to protect
1790
  // those operations, whereas generating the SR is only done once, so we just
1791
  // hold the map's bucket lock until the source region is fully initialized.
1792
  discovered_source_regions_.unlock(sr_key);
2,375,944✔
1793

1794
  return handle;
2,375,944✔
1795
}
2,376,417✔
1796

1797
void FlatSourceDomain::finalize_discovered_source_regions()
108,362✔
1798
{
1799
  // Extract keys for entries with a valid volume.
1800
  vector<SourceRegionKey> keys;
108,362✔
1801
  for (const auto& pair : discovered_source_regions_) {
2,484,306✔
1802
    if (pair.second.volume_ > 0.0) {
2,375,944✔
1803
      keys.push_back(pair.first);
2,274,491✔
1804
    }
1805
  }
1806

1807
  if (!keys.empty()) {
108,362✔
1808
    // Sort the keys, so as to ensure reproducible ordering given that source
1809
    // regions may have been added to discovered_source_regions_ in an arbitrary
1810
    // order due to shared memory threading.
1811
    std::sort(keys.begin(), keys.end());
859✔
1812

1813
    // Remember the index of the first new source region
1814
    int64_t start_sr_id = source_regions_.n_source_regions();
859✔
1815

1816
    // Append the source regions in the sorted key order.
1817
    for (const auto& key : keys) {
2,275,350✔
1818
      const SourceRegion& sr = discovered_source_regions_[key];
2,274,491✔
1819
      source_region_map_[key] = source_regions_.n_source_regions();
2,274,491✔
1820
      source_regions_.push_back(sr);
2,274,491✔
1821
    }
1822

1823
    // Map all new source regions to tallies
1824
    convert_source_regions_to_tallies(start_sr_id);
859✔
1825
  }
1826

1827
  discovered_source_regions_.clear();
108,362✔
1828
}
108,362✔
1829

1830
// This is the "diagonal stabilization" technique developed by Gunow et al. in:
1831
//
1832
// Geoffrey Gunow, Benoit Forget, Kord Smith, Stabilization of multi-group
1833
// neutron transport with transport-corrected cross-sections, Annals of Nuclear
1834
// Energy, Volume 126, 2019, Pages 211-219, ISSN 0306-4549,
1835
// https://doi.org/10.1016/j.anucene.2018.10.036.
1836
void FlatSourceDomain::apply_transport_stabilization()
108,362✔
1837
{
1838
  // Don't do anything if all in-group scattering
1839
  // cross sections are positive
1840
  if (!is_transport_stabilization_needed_) {
108,362✔
1841
    return;
106,602✔
1842
  }
1843

1844
  // Apply the stabilization factor to all source elements
1845
#pragma omp parallel for
960✔
1846
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
74,800✔
1847
    int material = source_regions_.material(sr);
74,000✔
1848
    if (material == MATERIAL_VOID) {
74,000!
1849
      continue;
1850
    }
1851
    for (int g = 0; g < negroups_; g++) {
5,254,000✔
1852
      // Only apply stabilization if the diagonal (in-group) scattering XS is
1853
      // negative
1854
      double sigma_s =
1855
        sigma_s_[material * negroups_ * negroups_ + g * negroups_ + g];
5,180,000✔
1856
      if (sigma_s < 0.0) {
5,180,000✔
1857
        double sigma_t = sigma_t_[material * negroups_ + g];
1,786,000✔
1858
        double phi_new = source_regions_.scalar_flux_new(sr, g);
1,786,000✔
1859
        double phi_old = source_regions_.scalar_flux_old(sr, g);
1,786,000✔
1860

1861
        // Equation 18 in the above Gunow et al. 2019 paper. For a default
1862
        // rho of 1.0, this ensures there are no negative diagonal elements
1863
        // in the iteration matrix. A lesser rho could be used (or exposed
1864
        // as a user input parameter) to reduce the negative impact on
1865
        // convergence rate though would need to be experimentally tested to see
1866
        // if it doesn't become unstable. rho = 1.0 is good as it gives the
1867
        // highest assurance of stability, and the impacts on convergence rate
1868
        // are pretty mild.
1869
        double D = diagonal_stabilization_rho_ * sigma_s / sigma_t;
1,786,000✔
1870

1871
        // Equation 16 in the above Gunow et al. 2019 paper
1872
        source_regions_.scalar_flux_new(sr, g) =
1,786,000✔
1873
          (phi_new - D * phi_old) / (1.0 - D);
1,786,000✔
1874
      }
1875
    }
1876
  }
1877
}
1878

1879
// Determines the base source region index (i.e., a material filled cell
1880
// instance) that corresponds to a particular location in the geometry. Requires
1881
// that the "gs" object passed in has already been initialized and has called
1882
// find_cell etc.
1883
int64_t FlatSourceDomain::lookup_base_source_region_idx(
2,147,483,647✔
1884
  const GeometryState& gs) const
1885
{
1886
  int i_cell = gs.lowest_coord().cell();
2,147,483,647✔
1887
  int64_t sr = source_region_offsets_[i_cell] + gs.cell_instance();
2,147,483,647✔
1888
  return sr;
2,147,483,647✔
1889
}
1890

1891
// Determines the index of the mesh (if any) that has been applied
1892
// to a particular base source region index.
1893
int FlatSourceDomain::lookup_mesh_idx(int64_t sr) const
2,147,483,647✔
1894
{
1895
  int mesh_idx = C_NONE;
2,147,483,647✔
1896
  auto mesh_it = mesh_map_.find(sr);
2,147,483,647✔
1897
  if (mesh_it != mesh_map_.end()) {
2,147,483,647✔
1898
    mesh_idx = mesh_it->second;
2,147,483,647✔
1899
  }
1900
  return mesh_idx;
2,147,483,647✔
1901
}
1902

1903
// Determines the source region key that corresponds to a particular location in
1904
// the geometry. This takes into account both the base source region index as
1905
// well as the mesh bin if a mesh is applied to this source region for
1906
// subdivision.
1907
SourceRegionKey FlatSourceDomain::lookup_source_region_key(
11,536,437✔
1908
  const GeometryState& gs) const
1909
{
1910
  int64_t sr = lookup_base_source_region_idx(gs);
11,536,437✔
1911
  int64_t mesh_bin = lookup_mesh_bin(sr, gs.r());
11,536,437✔
1912
  return SourceRegionKey {sr, mesh_bin};
11,536,437✔
1913
}
1914

1915
// Determines the mesh bin that corresponds to a particular base source region
1916
// index and position.
1917
int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const
11,536,437✔
1918
{
1919
  int mesh_idx = lookup_mesh_idx(sr);
11,536,437✔
1920
  int mesh_bin = 0;
11,536,437✔
1921
  if (mesh_idx != C_NONE) {
11,536,437✔
1922
    mesh_bin = model::meshes[mesh_idx]->get_bin(r);
4,654,837✔
1923
  }
1924
  return mesh_bin;
11,536,437✔
1925
}
1926

1927
//------------------------------------------------------------------------------
1928
// Methods for kinetic simulations
1929

1930
// Generates new estimate of k_dynamic based on the fraction between this
1931
// timestep's estimate of neutron production and loss. (previous timestep
1932
// fission vs current timestep fission?)
1933
// TODO: implement compute_k_dynamic
1934

1935
// Compute new estimate of scattering + fission (+ precursor decay for
1936
// kinetic simulations) sources in each source region based on the flux
1937
// estimate from the previous iteration.
1938

1939
// T1 calculation
NEW
1940
void FlatSourceDomain::compute_single_T1(SourceRegionHandle& srh)
×
1941
{
1942
  double A0 =
NEW
1943
    (bd_coefficients_first_order_.at(RandomRay::bd_order_))[0] / settings::dt;
×
NEW
1944
  double B0 = (bd_coefficients_second_order_.at(RandomRay::bd_order_))[0] /
×
NEW
1945
              (settings::dt * settings::dt);
×
NEW
1946
  int material = srh.material();
×
NEW
1947
  for (int g = 0; g < negroups_; g++) {
×
NEW
1948
    double inverse_vbar = inverse_vbar_[material * negroups_ + g];
×
NEW
1949
    double sigma_t = 1.0;
×
NEW
1950
    if (material != MATERIAL_VOID)
×
NEW
1951
      sigma_t = sigma_t_[material * negroups_ + g];
×
1952

1953
    // Multiply out sigma_t to correctly compute the derivative term
1954
    float source_time_derivative =
NEW
1955
      A0 * srh.source(g) * sigma_t + srh.source_rhs_bd(g);
×
1956

1957
    double scalar_flux_time_derivative_2 =
NEW
1958
      B0 * srh.scalar_flux_old(g) + srh.scalar_flux_rhs_bd_2(g);
×
NEW
1959
    scalar_flux_time_derivative_2 *= inverse_vbar;
×
1960

1961
    // Divide by sigma_t to save time during transport
NEW
1962
    srh.T1(g) =
×
NEW
1963
      (source_time_derivative - scalar_flux_time_derivative_2) / sigma_t;
×
1964
  }
NEW
1965
}
×
1966

1967
void FlatSourceDomain::compute_single_delayed_fission_source(
85,161,978✔
1968
  SourceRegionHandle& srh)
1969
{
1970

1971
  // Reset all delayed fission sources to zero (important for void regions)
1972
  for (int dg = 0; dg < ndgroups_; dg++) {
765,657,002✔
1973
    srh.delayed_fission_source(dg) = 0.0;
680,495,024✔
1974
  }
1975

1976
  int material = srh.material();
85,161,978✔
1977
  if (material != MATERIAL_VOID) {
85,161,978!
1978
    double inverse_k_eff = 1.0 / k_eff_;
85,161,978✔
1979
    for (int dg = 0; dg < ndgroups_; dg++) {
765,657,002✔
1980
      // We cannot have delayed neutrons if there is no delayed data
1981
      double lambda = lambda_[material * ndgroups_ + dg];
680,495,024✔
1982
      if (lambda != 0.0) {
680,495,024✔
1983
        for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
1984
          double scalar_flux = scalar_flux = srh.scalar_flux_new(g);
2,147,483,647✔
1985
          double nu_d_sigma_f = nu_d_sigma_f_[material * negroups_ * ndgroups_ +
2,147,483,647✔
1986
                                              dg * negroups_ + g];
2,147,483,647✔
1987
          srh.delayed_fission_source(dg) += nu_d_sigma_f * scalar_flux;
2,147,483,647✔
1988
        }
1989
        srh.delayed_fission_source(dg) *= inverse_k_eff;
314,159,912✔
1990
      }
1991
    }
1992
  }
1993
}
85,161,978✔
1994

1995
void FlatSourceDomain::compute_single_precursors(SourceRegionHandle& srh)
85,161,978✔
1996
{
1997
  // Reset all precursors to zero (important for void regions)
1998
  for (int dg = 0; dg < ndgroups_; dg++) {
765,657,002✔
1999
    srh.precursors_new(dg) = 0.0;
680,495,024✔
2000
  }
2001

2002
  int material = srh.material();
85,161,978✔
2003
  if (material != MATERIAL_VOID) {
85,161,978!
2004
    for (int dg = 0; dg < ndgroups_; dg++) {
765,657,002✔
2005
      double lambda = lambda_[material * ndgroups_ + dg];
680,495,024✔
2006
      if (lambda != 0.0) {
680,495,024✔
2007
        double delayed_fission_source = srh.delayed_fission_source(dg);
314,159,912✔
2008
        if (simulation::is_initial_condition) {
314,159,912✔
2009
          srh.precursors_new(dg) = delayed_fission_source / lambda;
89,759,912✔
2010
        } else {
2011
          double precursor_rhs_bd = srh.precursors_rhs_bd(dg);
224,400,000✔
2012
          srh.precursors_new(dg) = delayed_fission_source - precursor_rhs_bd;
224,400,000✔
2013
          double A0 =
2014
            (bd_coefficients_first_order_.at(RandomRay::bd_order_))[0] /
224,400,000✔
2015
            settings::dt;
224,400,000✔
2016
          srh.precursors_new(dg) /= A0 + lambda;
224,400,000✔
2017
        }
2018
      }
2019
    }
2020
  }
2021
}
85,161,978✔
2022

2023
void FlatSourceDomain::compute_all_precursors()
96,250✔
2024
{
2025
  simulation::time_compute_precursors.start();
96,250✔
2026

2027
#pragma omp parallel for
52,500✔
2028
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
38,753,740✔
2029
    SourceRegionHandle srh = source_regions_.get_source_region_handle(sr);
38,709,990✔
2030
    compute_single_delayed_fission_source(srh);
38,709,990✔
2031
    compute_single_precursors(srh);
38,709,990✔
2032
  }
2033

2034
  simulation::time_compute_precursors.start();
96,250✔
2035
}
96,250✔
2036

NEW
2037
void FlatSourceDomain::serialize_final_precursors(vector<double>& precursors)
×
2038
{
2039
  // Ensure array is correct size
NEW
2040
  precursors.resize(n_source_regions() * ndgroups_);
×
2041
// Serialize the precursors for output
2042
#pragma omp parallel for
2043
  for (int64_t de = 0; de < n_delay_elements(); de++) {
×
2044
    precursors[de] = source_regions_.precursors_final(de);
2045
  }
NEW
2046
}
×
2047

2048
void FlatSourceDomain::precursors_swap()
96,250✔
2049
{
2050
  source_regions_.precursors_swap();
96,250✔
2051
}
96,250✔
2052

2053
void FlatSourceDomain::accumulate_iteration_quantities()
52,696✔
2054
{
2055
  accumulate_iteration_flux();
52,696✔
2056
  if (settings::kinetic_simulation) {
52,696✔
2057
#pragma omp parallel for
26,040✔
2058
    for (int64_t sr = 0; sr < n_source_regions(); sr++) {
19,358,500✔
2059
      for (int g = 0; g < negroups_; g++) {
155,568,000✔
2060
        if (RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
136,231,200!
2061
          source_regions_.source_final(sr, g) += source_regions_.source(sr, g);
2062
        }
2063
      }
2064
      if (settings::create_delayed_neutrons) {
19,336,800!
2065
        for (int dg = 0; dg < ndgroups_; dg++) {
173,885,600✔
2066
          source_regions_.precursors_final(sr, dg) +=
154,548,800✔
2067
            source_regions_.precursors_new(sr, dg);
154,548,800✔
2068
        }
2069
      }
2070
    }
2071
  }
2072
}
52,696✔
2073

2074
void FlatSourceDomain::normalize_final_quantities()
1,506✔
2075
{
2076
  double normalization_factor =
1,506✔
2077
    1.0 / (settings::n_batches - settings::n_inactive);
1,506✔
2078
  double source_normalization_factor;
2079
  if (!settings::kinetic_simulation ||
1,506!
2080
      settings::kinetic_simulation &&
784✔
2081
        simulation::current_timestep == settings::n_timesteps)
784✔
2082
    source_normalization_factor =
834✔
2083
      compute_fixed_source_normalization_factor() * normalization_factor;
834✔
2084
  else
2085
    // The source normalization should only be applied to internal quantities at
2086
    // the end of time stepping in preparation for an adjoint solve.
2087
    source_normalization_factor = 1.0 * normalization_factor;
672✔
2088

2089
#pragma omp parallel for
848✔
2090
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
1,286,258✔
2091
    for (int g = 0; g < negroups_; g++) {
3,561,680✔
2092
      source_regions_.scalar_flux_final(sr, g) *= source_normalization_factor;
2,276,080✔
2093
      if (RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
2,276,080!
2094
        source_regions_.source_final(sr, g) *= source_normalization_factor;
2095
      }
2096
    }
2097
    if (settings::kinetic_simulation) {
1,285,600✔
2098
      for (int dg = 0; dg < ndgroups_; dg++) {
968,800✔
2099
        source_regions_.precursors_final(sr, dg) *= source_normalization_factor;
857,920✔
2100
      }
2101
    }
2102
  }
2103
}
1,506✔
2104

2105
void FlatSourceDomain::propagate_final_quantities()
672✔
2106
{
2107
#pragma omp parallel for
378✔
2108
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
95,334✔
2109
    for (int g = 0; g < negroups_; g++) {
910,080✔
2110
      source_regions_.scalar_flux_old(sr, g) =
815,040✔
2111
        source_regions_.scalar_flux_final(sr, g);
815,040✔
2112
    }
2113
    if (settings::create_delayed_neutrons) {
95,040!
2114
      for (int dg = 0; dg < ndgroups_; dg++) {
830,400✔
2115
        source_regions_.precursors_old(sr, dg) =
735,360✔
2116
          source_regions_.precursors_final(sr, dg);
735,360✔
2117
      }
2118
    }
2119
  }
2120
}
672✔
2121

2122
void FlatSourceDomain::store_time_step_quantities(bool increment_not_initialize)
672✔
2123
{
2124
#pragma omp parallel for
378✔
2125
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
95,334✔
2126
    for (int g = 0; g < negroups_; g++) {
910,080✔
2127
      int j = 0;
815,040✔
2128
      if (RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION)
815,040!
2129
        j = 1;
2130
      add_value_to_bd_vector(source_regions_.scalar_flux_bd(sr, g),
815,040✔
2131
        source_regions_.scalar_flux_final(sr, g), increment_not_initialize,
2132
        RandomRay::bd_order_ + j);
2133
      if (RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
815,040!
2134
        // TODO: add support for void regions
2135
        // Multiply out sigma_t to store the base source
2136
        double sigma_t = sigma_t =
2137
          sigma_t_[source_regions_.material(sr) * negroups_ + g];
2138
        float source = source_regions_.source_final(sr, g) * sigma_t;
×
2139
        add_value_to_bd_vector(source_regions_.source_bd(sr, g), source,
×
2140
          increment_not_initialize, RandomRay::bd_order_);
2141
      }
2142
    }
2143
    if (settings::create_delayed_neutrons) {
95,040!
2144
      for (int dg = 0; dg < ndgroups_; dg++) {
830,400✔
2145
        add_value_to_bd_vector(source_regions_.precursors_bd(sr, dg),
735,360✔
2146
          source_regions_.precursors_final(sr, dg), increment_not_initialize,
2147
          RandomRay::bd_order_);
2148
      }
2149
    }
2150
  }
2151
}
672✔
2152

2153
void FlatSourceDomain::compute_rhs_bd_quantities()
560✔
2154
{
2155
#pragma omp parallel for
315✔
2156
  for (int64_t sr = 0; sr < n_source_regions(); sr++) {
79,445✔
2157
    for (int g = 0; g < negroups_; g++) {
758,400✔
2158
      source_regions_.scalar_flux_rhs_bd(sr, g) =
1,358,400✔
2159
        rhs_backwards_difference(source_regions_.scalar_flux_bd(sr, g),
679,200✔
2160
          RandomRay::bd_order_, settings::dt);
2161

2162
      if (RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
679,200!
2163
        source_regions_.source_rhs_bd(sr, g) = rhs_backwards_difference(
2164
          source_regions_.source_bd(sr, g), RandomRay::bd_order_, settings::dt);
2165

2166
        source_regions_.scalar_flux_rhs_bd_2(sr, g) =
2167
          rhs_backwards_difference(source_regions_.scalar_flux_bd(sr, g),
2168
            RandomRay::bd_order_, settings::dt, 2);
2169
      }
2170
    }
2171
    if (settings::create_delayed_neutrons) {
79,200!
2172
      for (int dg = 0; dg < ndgroups_; dg++) {
692,000✔
2173
        source_regions_.precursors_rhs_bd(sr, dg) =
612,800✔
2174
          rhs_backwards_difference(source_regions_.precursors_bd(sr, dg),
612,800✔
2175
            RandomRay::bd_order_, settings::dt);
2176
      }
2177
    }
2178
  }
2179
}
560✔
2180

2181
// Update material density and cross sections
2182
void FlatSourceDomain::update_material_density(int i)
560✔
2183
{
2184
#pragma omp parallel for
315✔
2185
  for (int j = 0; j < model::materials.size(); j++) {
910✔
2186
    auto& mat {model::materials[j]};
665✔
2187
    if (mat->density_timeseries_.size() != 0) {
665✔
2188
      double density_factor = mat->density_timeseries_[i] / mat->density_;
245✔
2189
      mat->density_ = mat->density_timeseries_[i];
245✔
2190
      for (int g_out = 0; g_out < negroups_; g_out++) {
3,640✔
2191
        for (int dg = 0; dg < ndgroups_; dg++) {
25,235✔
2192
          nu_d_sigma_f_[j * negroups_ * ndgroups_ + dg * negroups_ + g_out] *=
21,840✔
2193
            density_factor;
2194
        }
2195
        nu_p_sigma_f_[j * negroups_ + g_out] *= density_factor;
3,395✔
2196
        sigma_t_[j * negroups_ + g_out] *= density_factor;
3,395✔
2197
        nu_sigma_f_[j * negroups_ + g_out] *= density_factor;
3,395✔
2198
        sigma_f_[j * negroups_ + g_out] *= density_factor;
3,395✔
2199
        for (int g_in = 0; g_in < negroups_; g_in++) {
180,460✔
2200
          sigma_s_[j * negroups_ * negroups_ + g_out * negroups_ + g_in] *=
177,065✔
2201
            density_factor;
2202
        }
2203
      }
2204
    }
2205
  }
2206
}
560✔
2207

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