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

openmc-dev / openmc / 21139931957

19 Jan 2026 01:50PM UTC coverage: 81.835% (-0.2%) from 82.058%
21139931957

Pull #2693

github

web-flow
Merge 1258e263b into 5847b0de2
Pull Request #2693: Add reactivity control to coupled transport-depletion analyses

17180 of 23968 branches covered (71.68%)

Branch coverage included in aggregate %.

78 of 84 new or added lines in 4 files covered. (92.86%)

345 existing lines in 27 files now uncovered.

55616 of 64987 relevant lines covered (85.58%)

50201535.92 hits per line

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

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

3
#include "openmc/constants.h"
4
#include "openmc/geometry.h"
5
#include "openmc/message_passing.h"
6
#include "openmc/mgxs_interface.h"
7
#include "openmc/random_ray/flat_source_domain.h"
8
#include "openmc/random_ray/linear_source_domain.h"
9
#include "openmc/search.h"
10
#include "openmc/settings.h"
11
#include "openmc/simulation.h"
12

13
#include "openmc/distribution_spatial.h"
14
#include "openmc/random_dist.h"
15
#include "openmc/source.h"
16

17
namespace openmc {
18

19
//==============================================================================
20
// Non-method functions
21
//==============================================================================
22

23
// returns 1 - exp(-tau)
24
// Equivalent to -(_expm1f(-tau)), but faster
25
// Written by Colin Josey.
26
float cjosey_exponential(float tau)
1,103,888,018✔
27
{
28
  constexpr float c1n = -1.0000013559236386308f;
1,103,888,018✔
29
  constexpr float c2n = 0.23151368626911062025f;
1,103,888,018✔
30
  constexpr float c3n = -0.061481916409314966140f;
1,103,888,018✔
31
  constexpr float c4n = 0.0098619906458127653020f;
1,103,888,018✔
32
  constexpr float c5n = -0.0012629460503540849940f;
1,103,888,018✔
33
  constexpr float c6n = 0.00010360973791574984608f;
1,103,888,018✔
34
  constexpr float c7n = -0.000013276571933735820960f;
1,103,888,018✔
35

36
  constexpr float c0d = 1.0f;
1,103,888,018✔
37
  constexpr float c1d = -0.73151337729389001396f;
1,103,888,018✔
38
  constexpr float c2d = 0.26058381273536471371f;
1,103,888,018✔
39
  constexpr float c3d = -0.059892419041316836940f;
1,103,888,018✔
40
  constexpr float c4d = 0.0099070188241094279067f;
1,103,888,018✔
41
  constexpr float c5d = -0.0012623388962473160860f;
1,103,888,018✔
42
  constexpr float c6d = 0.00010361277635498731388f;
1,103,888,018✔
43
  constexpr float c7d = -0.000013276569500666698498f;
1,103,888,018✔
44

45
  float x = -tau;
1,103,888,018✔
46

47
  float den = c7d;
1,103,888,018✔
48
  den = den * x + c6d;
1,103,888,018✔
49
  den = den * x + c5d;
1,103,888,018✔
50
  den = den * x + c4d;
1,103,888,018✔
51
  den = den * x + c3d;
1,103,888,018✔
52
  den = den * x + c2d;
1,103,888,018✔
53
  den = den * x + c1d;
1,103,888,018✔
54
  den = den * x + c0d;
1,103,888,018✔
55

56
  float num = c7n;
1,103,888,018✔
57
  num = num * x + c6n;
1,103,888,018✔
58
  num = num * x + c5n;
1,103,888,018✔
59
  num = num * x + c4n;
1,103,888,018✔
60
  num = num * x + c3n;
1,103,888,018✔
61
  num = num * x + c2n;
1,103,888,018✔
62
  num = num * x + c1n;
1,103,888,018✔
63
  num = num * x;
1,103,888,018✔
64

65
  return num / den;
1,103,888,018✔
66
}
67

68
// The below two functions (exponentialG and exponentialG2) were developed
69
// by Colin Josey. The implementation of these functions is closely based
70
// on the OpenMOC versions of these functions. The OpenMOC license is given
71
// below:
72

73
// Copyright (C) 2012-2023 Massachusetts Institute of Technology and OpenMOC
74
// contributors
75
//
76
// Permission is hereby granted, free of charge, to any person obtaining a copy
77
// of this software and associated documentation files (the "Software"), to deal
78
// in the Software without restriction, including without limitation the rights
79
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
80
// copies of the Software, and to permit persons to whom the Software is
81
// furnished to do so, subject to the following conditions:
82
//
83
// The above copyright notice and this permission notice shall be included in
84
// all copies or substantial portions of the Software.
85
//
86
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
87
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
88
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
89
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
90
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
91
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
92
// SOFTWARE.
93

94
// Computes y = 1/x-(1-exp(-x))/x**2 using a 5/6th order rational
95
// approximation. It is accurate to 2e-7 over [0, 1e5]. Developed by Colin
96
// Josey using Remez's algorithm, with original implementation in OpenMOC at:
97
// https://github.com/mit-crpg/OpenMOC/blob/develop/src/exponentials.h
98
float exponentialG(float tau)
2,124,742,860✔
99
{
100
  // Numerator coefficients in rational approximation for 1/x - (1 - exp(-x)) /
101
  // x^2
102
  constexpr float d0n = 0.5f;
2,124,742,860✔
103
  constexpr float d1n = 0.176558112351595f;
2,124,742,860✔
104
  constexpr float d2n = 0.04041584305811143f;
2,124,742,860✔
105
  constexpr float d3n = 0.006178333902037397f;
2,124,742,860✔
106
  constexpr float d4n = 0.0006429894635552992f;
2,124,742,860✔
107
  constexpr float d5n = 0.00006064409107557148f;
2,124,742,860✔
108

109
  // Denominator coefficients in rational approximation for 1/x - (1 - exp(-x))
110
  // / x^2
111
  constexpr float d0d = 1.0f;
2,124,742,860✔
112
  constexpr float d1d = 0.6864462055546078f;
2,124,742,860✔
113
  constexpr float d2d = 0.2263358514260129f;
2,124,742,860✔
114
  constexpr float d3d = 0.04721469893686252f;
2,124,742,860✔
115
  constexpr float d4d = 0.006883236664917246f;
2,124,742,860✔
116
  constexpr float d5d = 0.0007036272419147752f;
2,124,742,860✔
117
  constexpr float d6d = 0.00006064409107557148f;
2,124,742,860✔
118

119
  float x = tau;
2,124,742,860✔
120

121
  float num = d5n;
2,124,742,860✔
122
  num = num * x + d4n;
2,124,742,860✔
123
  num = num * x + d3n;
2,124,742,860✔
124
  num = num * x + d2n;
2,124,742,860✔
125
  num = num * x + d1n;
2,124,742,860✔
126
  num = num * x + d0n;
2,124,742,860✔
127

128
  float den = d6d;
2,124,742,860✔
129
  den = den * x + d5d;
2,124,742,860✔
130
  den = den * x + d4d;
2,124,742,860✔
131
  den = den * x + d3d;
2,124,742,860✔
132
  den = den * x + d2d;
2,124,742,860✔
133
  den = den * x + d1d;
2,124,742,860✔
134
  den = den * x + d0d;
2,124,742,860✔
135

136
  return num / den;
2,124,742,860✔
137
}
138

139
// Computes G2 : y = 2/3 - (1 + 2/x) * (1/x + 0.5 - (1 + 1/x) * (1-exp(-x)) /
140
// x) using a 5/5th order rational approximation. It is accurate to 1e-6 over
141
// [0, 1e6]. Developed by Colin Josey using Remez's algorithm, with original
142
// implementation in OpenMOC at:
143
// https://github.com/mit-crpg/OpenMOC/blob/develop/src/exponentials.h
144
float exponentialG2(float tau)
2,124,742,860✔
145
{
146

147
  // Coefficients for numerator in rational approximation
148
  constexpr float g1n = -0.08335775885589858f;
2,124,742,860✔
149
  constexpr float g2n = -0.003603942303847604f;
2,124,742,860✔
150
  constexpr float g3n = 0.0037673183263550827f;
2,124,742,860✔
151
  constexpr float g4n = 0.00001124183494990467f;
2,124,742,860✔
152
  constexpr float g5n = 0.00016837426505799449f;
2,124,742,860✔
153

154
  // Coefficients for denominator in rational approximation
155
  constexpr float g1d = 0.7454048371823628f;
2,124,742,860✔
156
  constexpr float g2d = 0.23794300531408347f;
2,124,742,860✔
157
  constexpr float g3d = 0.05367250964303789f;
2,124,742,860✔
158
  constexpr float g4d = 0.006125197988351906f;
2,124,742,860✔
159
  constexpr float g5d = 0.0010102514456857377f;
2,124,742,860✔
160

161
  float x = tau;
2,124,742,860✔
162

163
  float num = g5n;
2,124,742,860✔
164
  num = num * x + g4n;
2,124,742,860✔
165
  num = num * x + g3n;
2,124,742,860✔
166
  num = num * x + g2n;
2,124,742,860✔
167
  num = num * x + g1n;
2,124,742,860✔
168
  num = num * x;
2,124,742,860✔
169

170
  float den = g5d;
2,124,742,860✔
171
  den = den * x + g4d;
2,124,742,860✔
172
  den = den * x + g3d;
2,124,742,860✔
173
  den = den * x + g2d;
2,124,742,860✔
174
  den = den * x + g1d;
2,124,742,860✔
175
  den = den * x + 1.0f;
2,124,742,860✔
176

177
  return num / den;
2,124,742,860✔
178
}
179

180
// Implementation of the Fisher-Yates shuffle algorithm.
181
// Algorithm adapted from:
182
//    https://en.cppreference.com/w/cpp/algorithm/random_shuffle#Version_3
183
void fisher_yates_shuffle(vector<int64_t>& arr, uint64_t* seed)
1,440,000✔
184
{
185
  // Loop over the array from the last element down to the second
186
  for (int i = arr.size() - 1; i > 0; --i) {
6,210,000✔
187
    // Generate a random index in the range [0, i]
188
    int j = uniform_int_distribution(0, i, seed);
4,770,000✔
189
    std::swap(arr[i], arr[j]);
4,770,000✔
190
  }
191
}
1,440,000✔
192

193
// Function to generate randomized Halton sequence samples
194
//
195
// Algorithm adapted from:
196
//      A. B. Owen. A randomized halton algorithm in r. Arxiv, 6 2017.
197
//      URL https://arxiv.org/abs/1706.02808
198
vector<double> rhalton(int dim, uint64_t* seed, int64_t skip = 0)
10,000✔
199
{
200
  if (dim > 10) {
10,000!
201
    fatal_error("Halton sampling dimension too large");
×
202
  }
203
  int64_t b, res, dig;
204
  double b2r, ans;
205
  const std::array<int64_t, 10> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
10,000✔
206
  vector<double> halton(dim, 0.0);
10,000✔
207

208
  vector<int64_t> perm;
10,000✔
209
  for (int D = 0; D < dim; ++D) {
60,000✔
210
    b = primes[D];
50,000✔
211
    perm.resize(b);
50,000✔
212
    b2r = 1.0 / b;
50,000✔
213
    res = skip;
50,000✔
214
    ans = 0.0;
50,000✔
215

216
    while ((1.0 - b2r) < 1.0) {
1,490,000✔
217
      std::iota(perm.begin(), perm.end(), 0);
1,440,000✔
218
      fisher_yates_shuffle(perm, seed);
1,440,000✔
219
      dig = res % b;
1,440,000✔
220
      ans += perm[dig] * b2r;
1,440,000✔
221
      res = (res - dig) / b;
1,440,000✔
222
      b2r /= b;
1,440,000✔
223
    }
224

225
    halton[D] = ans;
50,000✔
226
  }
227

228
  return halton;
20,000✔
229
}
10,000✔
230

231
//==============================================================================
232
// RandomRay implementation
233
//==============================================================================
234

235
// Static Variable Declarations
236
double RandomRay::distance_inactive_;
237
double RandomRay::distance_active_;
238
unique_ptr<Source> RandomRay::ray_source_;
239
RandomRaySourceShape RandomRay::source_shape_ {RandomRaySourceShape::FLAT};
240
RandomRaySampleMethod RandomRay::sample_method_ {RandomRaySampleMethod::PRNG};
241

242
RandomRay::RandomRay()
1,756,720✔
243
  : angular_flux_(data::mg.num_energy_groups_),
1,756,720✔
244
    delta_psi_(data::mg.num_energy_groups_),
1,756,720✔
245
    negroups_(data::mg.num_energy_groups_)
5,270,160✔
246
{
247
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
1,756,720✔
248
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
969,720✔
249
    delta_moments_.resize(negroups_);
900,500✔
250
  }
251
}
1,756,720✔
252

253
RandomRay::RandomRay(uint64_t ray_id, FlatSourceDomain* domain) : RandomRay()
1,756,720✔
254
{
255
  initialize_ray(ray_id, domain);
1,756,720✔
256
}
1,756,720✔
257

258
// Transports ray until termination criteria are met
259
uint64_t RandomRay::transport_history_based_single_ray()
1,756,720✔
260
{
261
  using namespace openmc;
262
  while (alive()) {
730,231,228!
263
    event_advance_ray();
730,231,228✔
264
    if (!alive())
730,231,228✔
265
      break;
1,756,720✔
266
    event_cross_surface();
728,474,508✔
267
    // If ray has too many events, display warning and kill it
268
    if (n_event() >= settings::max_particle_events) {
728,474,508!
269
      warning("Ray " + std::to_string(id()) +
×
270
              " underwent maximum number of events, terminating ray.");
271
      wgt() = 0.0;
×
272
    }
273
  }
274

275
  return n_event();
1,756,720✔
276
}
277

278
// Transports ray across a single source region
279
void RandomRay::event_advance_ray()
730,231,228✔
280
{
281
  // If geometry debug mode is on, check for cell overlaps
282
  if (settings::check_overlaps)
730,231,228!
283
    check_cell_overlap(*this);
×
284

285
  // Find the distance to the nearest boundary
286
  boundary() = distance_to_boundary(*this);
730,231,228✔
287
  double distance = boundary().distance();
730,231,228✔
288

289
  if (distance < 0.0) {
730,231,228!
290
    mark_as_lost("Negative transport distance detected for particle " +
×
291
                 std::to_string(id()));
×
292
    return;
×
293
  }
294

295
  if (is_active_) {
730,231,228✔
296
    // If the ray is in the active length, need to check if it has
297
    // reached its maximum termination distance. If so, reduce
298
    // the ray traced length so that the ray does not overrun the
299
    // maximum numerical length (so as to avoid numerical bias).
300
    if (distance_travelled_ + distance >= distance_active_) {
591,786,080✔
301
      distance = distance_active_ - distance_travelled_;
1,756,720✔
302
      wgt() = 0.0;
1,756,720✔
303
    }
304

305
    distance_travelled_ += distance;
591,786,080✔
306
    attenuate_flux(distance, true);
591,786,080✔
307
  } else {
308
    // If the ray is still in the dead zone, need to check if it
309
    // has entered the active phase. If so, split into two segments (one
310
    // representing the final part of the dead zone, the other representing the
311
    // first part of the active length) and attenuate each. Otherwise, if the
312
    // full length of the segment is within the dead zone, attenuate as normal.
313
    if (distance_travelled_ + distance >= distance_inactive_) {
138,445,148✔
314
      is_active_ = true;
1,756,720✔
315
      double distance_dead = distance_inactive_ - distance_travelled_;
1,756,720✔
316
      attenuate_flux(distance_dead, false);
1,756,720✔
317

318
      double distance_alive = distance - distance_dead;
1,756,720✔
319

320
      // Ensure we haven't travelled past the active phase as well
321
      if (distance_alive > distance_active_) {
1,756,720!
322
        distance_alive = distance_active_;
×
323
        wgt() = 0.0;
×
324
      }
325

326
      attenuate_flux(distance_alive, true, distance_dead);
1,756,720✔
327
      distance_travelled_ = distance_alive;
1,756,720✔
328
    } else {
329
      distance_travelled_ += distance;
136,688,428✔
330
      attenuate_flux(distance, false);
136,688,428✔
331
    }
332
  }
333

334
  // Advance particle
335
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
336
    coord(j).r() += distance * coord(j).u();
2,109,936,516✔
337
  }
338
}
339

340
void RandomRay::attenuate_flux(double distance, bool is_active, double offset)
731,987,948✔
341
{
342
  // Lookup base source region index
343
  int64_t sr = domain_->lookup_base_source_region_idx(*this);
731,987,948✔
344

345
  // Perform ray tracing across mesh
346
  // Determine the mesh index for the base source region, if any
347
  int mesh_idx = domain_->lookup_mesh_idx(sr);
731,987,948✔
348

349
  if (mesh_idx == C_NONE) {
731,987,948✔
350
    // If there's no mesh being applied to this cell, then
351
    // we just attenuate the flux as normal, and set
352
    // the mesh bin to 0
353
    attenuate_flux_inner(distance, is_active, sr, 0, r());
327,618,030✔
354
  } else {
355
    // If there is a mesh being applied to this cell, then
356
    // we loop over all the bin crossings and attenuate
357
    // separately.
358
    Mesh* mesh = model::meshes[mesh_idx].get();
404,369,918✔
359

360
    // We adjust the start and end positions of the ray slightly
361
    // to accomodate for floating point precision issues that tend
362
    // to occur at mesh boundaries that overlap with geometry lattice
363
    // boundaries.
364
    Position start = r() + (offset + TINY_BIT) * u();
404,369,918✔
365
    Position end = start + (distance - 2.0 * TINY_BIT) * u();
404,369,918✔
366
    double reduced_distance = (end - start).norm();
404,369,918✔
367

368
    // Ray trace through the mesh and record bins and lengths
369
    mesh_bins_.resize(0);
404,369,918✔
370
    mesh_fractional_lengths_.resize(0);
404,369,918✔
371
    mesh->bins_crossed(start, end, u(), mesh_bins_, mesh_fractional_lengths_);
404,369,918✔
372

373
    // Loop over all mesh bins and attenuate flux
374
    for (int b = 0; b < mesh_bins_.size(); b++) {
1,219,256,728✔
375
      double physical_length = reduced_distance * mesh_fractional_lengths_[b];
814,886,810✔
376
      attenuate_flux_inner(
814,886,810✔
377
        physical_length, is_active, sr, mesh_bins_[b], start);
814,886,810✔
378
      start += physical_length * u();
814,886,810✔
379
    }
380
  }
381
}
731,987,948✔
382

383
void RandomRay::attenuate_flux_inner(
1,142,504,840✔
384
  double distance, bool is_active, int64_t sr, int mesh_bin, Position r)
385
{
386
  SourceRegionKey sr_key {sr, mesh_bin};
1,142,504,840✔
387
  SourceRegionHandle srh;
1,142,504,840✔
388
  srh = domain_->get_subdivided_source_region_handle(sr_key, r, u());
1,142,504,840✔
389
  if (srh.is_numerical_fp_artifact_) {
1,142,504,840✔
390
    return;
80✔
391
  }
392

393
  switch (source_shape_) {
1,142,504,760!
394
  case RandomRaySourceShape::FLAT:
563,716,010✔
395
    if (srh.material() == MATERIAL_VOID) {
563,716,010✔
396
      attenuate_flux_flat_source_void(srh, distance, is_active, r);
7,612,926✔
397
    } else {
398
      attenuate_flux_flat_source(srh, distance, is_active, r);
556,103,084✔
399
    }
400
    break;
563,716,010✔
401
  case RandomRaySourceShape::LINEAR:
578,788,750✔
402
  case RandomRaySourceShape::LINEAR_XY:
403
    if (srh.material() == MATERIAL_VOID) {
578,788,750✔
404
      attenuate_flux_linear_source_void(srh, distance, is_active, r);
7,533,850✔
405
    } else {
406
      attenuate_flux_linear_source(srh, distance, is_active, r);
571,254,900✔
407
    }
408
    break;
578,788,750✔
409
  default:
×
410
    fatal_error("Unknown source shape for random ray transport.");
×
411
  }
412
}
413

414
// This function forms the inner loop of the random ray transport process.
415
// It is responsible for several tasks. Based on the incoming angular flux
416
// of the ray and the source term in the region, the outgoing angular flux
417
// is computed. The delta psi between the incoming and outgoing fluxes is
418
// contributed to the estimate of the total scalar flux in the source region.
419
// Additionally, the contribution of the ray path to the stochastically
420
// estimated volume is also kept track of. All tasks involving writing
421
// to the data for the source region are done with a lock over the entire
422
// source region.  Locks are used instead of atomics as all energy groups
423
// must be written, such that locking once is typically much more efficient
424
// than use of many atomic operations corresponding to each energy group
425
// individually (at least on CPU). Several other bookkeeping tasks are also
426
// performed when inside the lock.
427
void RandomRay::attenuate_flux_flat_source(
556,103,084✔
428
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
429
{
430
  // The number of geometric intersections is counted for reporting purposes
431
  n_event()++;
556,103,084✔
432

433
  // Get material
434
  int material = srh.material();
556,103,084✔
435

436
  // MOC incoming flux attenuation + source contribution/attenuation equation
437
  for (int g = 0; g < negroups_; g++) {
1,659,991,102✔
438
    float sigma_t =
439
      domain_->sigma_t_[material * negroups_ + g] * srh.density_mult();
1,103,888,018✔
440
    float tau = sigma_t * distance;
1,103,888,018✔
441
    float exponential = cjosey_exponential(tau); // exponential = 1 - exp(-tau)
1,103,888,018✔
442
    float new_delta_psi = (angular_flux_[g] - srh.source(g)) * exponential;
1,103,888,018✔
443
    delta_psi_[g] = new_delta_psi;
1,103,888,018✔
444
    angular_flux_[g] -= new_delta_psi;
1,103,888,018✔
445
  }
446

447
  // If ray is in the active phase (not in dead zone), make contributions to
448
  // source region bookkeeping
449

450
  // Aquire lock for source region
451
  srh.lock();
556,103,084✔
452

453
  if (is_active) {
556,103,084✔
454
    // Accumulate delta psi into new estimate of source region flux for
455
    // this iteration
456
    for (int g = 0; g < negroups_; g++) {
1,320,605,666✔
457
      srh.scalar_flux_new(g) += delta_psi_[g];
865,364,524✔
458
    }
459

460
    // Accomulate volume (ray distance) into this iteration's estimate
461
    // of the source region's volume
462
    srh.volume() += distance;
455,241,142✔
463

464
    srh.n_hits() += 1;
455,241,142✔
465
  }
466

467
  // Tally valid position inside the source region (e.g., midpoint of
468
  // the ray) if not done already
469
  if (!srh.position_recorded()) {
556,103,084✔
470
    Position midpoint = r + u() * (distance / 2.0);
1,391,423✔
471
    srh.position() = midpoint;
1,391,423✔
472
    srh.position_recorded() = 1;
1,391,423✔
473
  }
474

475
  // Release lock
476
  srh.unlock();
556,103,084✔
477
}
556,103,084✔
478

479
// Alternative flux attenuation function for true void regions.
480
void RandomRay::attenuate_flux_flat_source_void(
7,612,926✔
481
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
482
{
483
  // The number of geometric intersections is counted for reporting purposes
484
  n_event()++;
7,612,926✔
485

486
  int material = srh.material();
7,612,926✔
487

488
  // If ray is in the active phase (not in dead zone), make contributions to
489
  // source region bookkeeping
490
  if (is_active) {
7,612,926✔
491

492
    // Aquire lock for source region
493
    srh.lock();
6,331,534✔
494

495
    // Accumulate delta psi into new estimate of source region flux for
496
    // this iteration
497
    for (int g = 0; g < negroups_; g++) {
12,716,832✔
498
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,385,298✔
499
    }
500

501
    // Accomulate volume (ray distance) into this iteration's estimate
502
    // of the source region's volume
503
    srh.volume() += distance;
6,331,534✔
504
    srh.volume_sq() += distance * distance;
6,331,534✔
505
    srh.n_hits() += 1;
6,331,534✔
506

507
    // Tally valid position inside the source region (e.g., midpoint of
508
    // the ray) if not done already
509
    if (!srh.position_recorded()) {
6,331,534✔
510
      Position midpoint = r + u() * (distance / 2.0);
10,144✔
511
      srh.position() = midpoint;
10,144✔
512
      srh.position_recorded() = 1;
10,144✔
513
    }
514

515
    // Release lock
516
    srh.unlock();
6,331,534✔
517
  }
518

519
  // Add source to incoming angular flux, assuming void region
520
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,612,926!
521
    for (int g = 0; g < negroups_; g++) {
15,290,908✔
522
      angular_flux_[g] += srh.external_source(g) * distance;
7,677,982✔
523
    }
524
  }
525
}
7,612,926✔
526

527
void RandomRay::attenuate_flux_linear_source(
571,254,900✔
528
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
529
{
530
  // The number of geometric intersections is counted for reporting purposes
531
  n_event()++;
571,254,900✔
532

533
  int material = srh.material();
571,254,900✔
534

535
  Position& centroid = srh.centroid();
571,254,900✔
536
  Position midpoint = r + u() * (distance / 2.0);
571,254,900✔
537

538
  // Determine the local position of the midpoint and the ray origin
539
  // relative to the source region's centroid
540
  Position rm_local;
571,254,900✔
541
  Position r0_local;
571,254,900✔
542

543
  // In the first few iterations of the simulation, the source region
544
  // may not yet have had any ray crossings, in which case there will
545
  // be no estimate of its centroid. We detect this by checking if it has
546
  // any accumulated volume. If its volume is zero, just use the midpoint
547
  // of the ray as the region's centroid.
548
  if (srh.volume_t()) {
571,254,900✔
549
    rm_local = midpoint - centroid;
550,861,250✔
550
    r0_local = r - centroid;
550,861,250✔
551
  } else {
552
    rm_local = {0.0, 0.0, 0.0};
20,393,650✔
553
    r0_local = -u() * 0.5 * distance;
20,393,650✔
554
  }
555
  double distance_2 = distance * distance;
571,254,900✔
556

557
  // Linear Source MOC incoming flux attenuation + source
558
  // contribution/attenuation equation
559
  for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
560

561
    // Compute tau, the optical thickness of the ray segment
562
    float sigma_t =
563
      domain_->sigma_t_[material * negroups_ + g] * srh.density_mult();
2,124,742,860✔
564
    float tau = sigma_t * distance;
2,124,742,860✔
565

566
    // If tau is very small, set it to zero to avoid numerical issues.
567
    // The following computations will still work with tau = 0.
568
    if (tau < 1.0e-8f) {
2,124,742,860✔
569
      tau = 0.0f;
5,340✔
570
    }
571

572
    // Compute linear source terms, spatial and directional (dir),
573
    // calculated from the source gradients dot product with local centroid
574
    // and direction, respectively.
575
    float spatial_source =
576
      srh.source(g) + rm_local.dot(srh.source_gradients(g));
2,124,742,860✔
577
    float dir_source = u().dot(srh.source_gradients(g));
2,124,742,860✔
578

579
    float gn = exponentialG(tau);
2,124,742,860✔
580
    float f1 = 1.0f - tau * gn;
2,124,742,860✔
581
    float f2 = (2.0f * gn - f1) * distance_2;
2,124,742,860✔
582
    float new_delta_psi = (angular_flux_[g] - spatial_source) * f1 * distance -
2,124,742,860✔
583
                          0.5 * dir_source * f2;
2,124,742,860✔
584

585
    float h1 = f1 - gn;
2,124,742,860✔
586
    float g1 = 0.5f - h1;
2,124,742,860✔
587
    float g2 = exponentialG2(tau);
2,124,742,860✔
588
    g1 = g1 * spatial_source;
2,124,742,860✔
589
    g2 = g2 * dir_source * distance * 0.5f;
2,124,742,860✔
590
    h1 = h1 * angular_flux_[g];
2,124,742,860✔
591
    h1 = (g1 + g2 + h1) * distance_2;
2,124,742,860✔
592
    spatial_source = spatial_source * distance + new_delta_psi;
2,124,742,860✔
593

594
    // Store contributions for this group into arrays, so that they can
595
    // be accumulated into the source region's estimates inside of the locked
596
    // region.
597
    delta_psi_[g] = new_delta_psi;
2,124,742,860✔
598
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
2,124,742,860✔
599

600
    // Update the angular flux for this group
601
    angular_flux_[g] -= new_delta_psi * sigma_t;
2,124,742,860✔
602

603
    // If 2D mode is enabled, the z-component of the flux moments is forced
604
    // to zero
605
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
2,124,742,860✔
606
      delta_moments_[g].z = 0.0;
420,189,130✔
607
    }
608
  }
609

610
  // Compute an estimate of the spatial moments matrix for the source
611
  // region based on parameters from this ray's crossing
612
  MomentMatrix moment_matrix_estimate;
613
  moment_matrix_estimate.compute_spatial_moments_matrix(
571,254,900✔
614
    rm_local, u(), distance);
571,254,900✔
615

616
  // Aquire lock for source region
617
  srh.lock();
571,254,900✔
618

619
  // If ray is in the active phase (not in dead zone), make contributions to
620
  // source region bookkeeping
621

622
  if (is_active) {
571,254,900✔
623
    // Accumulate deltas into the new estimate of source region flux for this
624
    // iteration
625
    for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
626
      srh.scalar_flux_new(g) += delta_psi_[g];
1,714,981,280✔
627
      srh.flux_moments_new(g) += delta_moments_[g];
1,714,981,280✔
628
    }
629

630
    // Accumulate the volume (ray segment distance), centroid, and spatial
631
    // momement estimates into the running totals for the iteration for this
632
    // source region. The centroid and spatial momements estimates are scaled
633
    // by the ray segment length as part of length averaging of the estimates.
634
    srh.volume() += distance;
467,799,060✔
635
    srh.centroid_iteration() += midpoint * distance;
467,799,060✔
636
    moment_matrix_estimate *= distance;
467,799,060✔
637
    srh.mom_matrix() += moment_matrix_estimate;
467,799,060✔
638

639
    srh.n_hits() += 1;
467,799,060✔
640
  }
641

642
  // Tally valid position inside the source region (e.g., midpoint of
643
  // the ray) if not done already
644
  if (!srh.position_recorded()) {
571,254,900✔
645
    srh.position() = midpoint;
736,420✔
646
    srh.position_recorded() = 1;
736,420✔
647
  }
648

649
  // Release lock
650
  srh.unlock();
571,254,900✔
651
}
571,254,900✔
652

653
// If traveling through a void region, the source term is either zero
654
// or an external source. As all external sources are currently assumed
655
// to be flat, we don't really need this function and could instead just call
656
// the "attenuate_flux_flat_source_void" function and get the same numerical and
657
// tally results. However, computation of the flux moments in void regions is
658
// nonetheless useful as this information is still used by the plotter when
659
// estimating the flux at specific pixel coordinates. Thus, plots will look
660
// nicer/more accurate if we record flux moments, so this function is useful.
661
void RandomRay::attenuate_flux_linear_source_void(
7,533,850✔
662
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
663
{
664
  // The number of geometric intersections is counted for reporting purposes
665
  n_event()++;
7,533,850✔
666

667
  Position& centroid = srh.centroid();
7,533,850✔
668
  Position midpoint = r + u() * (distance / 2.0);
7,533,850✔
669

670
  // Determine the local position of the midpoint and the ray origin
671
  // relative to the source region's centroid
672
  Position rm_local;
7,533,850✔
673
  Position r0_local;
7,533,850✔
674

675
  // In the first few iterations of the simulation, the source region
676
  // may not yet have had any ray crossings, in which case there will
677
  // be no estimate of its centroid. We detect this by checking if it has
678
  // any accumulated volume. If its volume is zero, just use the midpoint
679
  // of the ray as the region's centroid.
680
  if (srh.volume_t()) {
7,533,850✔
681
    rm_local = midpoint - centroid;
7,349,260✔
682
    r0_local = r - centroid;
7,349,260✔
683
  } else {
684
    rm_local = {0.0, 0.0, 0.0};
184,590✔
685
    r0_local = -u() * 0.5 * distance;
184,590✔
686
  }
687
  double distance_2 = distance * distance;
7,533,850✔
688

689
  // Compared to linear flux attenuation through solid regions,
690
  // transport through a void region is greatly simplified. Here we
691
  // compute the updated flux moments.
692
  for (int g = 0; g < negroups_; g++) {
15,067,700✔
693
    float spatial_source = 0.f;
7,533,850✔
694
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,533,850!
695
      spatial_source = srh.external_source(g);
7,533,850✔
696
    }
697
    float new_delta_psi = (angular_flux_[g] - spatial_source) * distance;
7,533,850✔
698
    float h1 = 0.5f;
7,533,850✔
699
    h1 = h1 * angular_flux_[g];
7,533,850✔
700
    h1 = h1 * distance_2;
7,533,850✔
701
    spatial_source = spatial_source * distance + new_delta_psi;
7,533,850✔
702

703
    // Store contributions for this group into arrays, so that they can
704
    // be accumulated into the source region's estimates inside of the locked
705
    // region.
706
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
7,533,850✔
707

708
    // If 2D mode is enabled, the z-component of the flux moments is forced
709
    // to zero
710
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
7,533,850!
UNCOV
711
      delta_moments_[g].z = 0.0;
×
712
    }
713
  }
714

715
  // If ray is in the active phase (not in dead zone), make contributions to
716
  // source region bookkeeping
717
  if (is_active) {
7,533,850✔
718
    // Compute an estimate of the spatial moments matrix for the source
719
    // region based on parameters from this ray's crossing
720
    MomentMatrix moment_matrix_estimate;
721
    moment_matrix_estimate.compute_spatial_moments_matrix(
6,265,820✔
722
      rm_local, u(), distance);
6,265,820✔
723

724
    // Aquire lock for source region
725
    srh.lock();
6,265,820✔
726

727
    // Accumulate delta psi into new estimate of source region flux for
728
    // this iteration, and update flux momements
729
    for (int g = 0; g < negroups_; g++) {
12,531,640✔
730
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,265,820✔
731
      srh.flux_moments_new(g) += delta_moments_[g];
6,265,820✔
732
    }
733

734
    // Accumulate the volume (ray segment distance), centroid, and spatial
735
    // momement estimates into the running totals for the iteration for this
736
    // source region. The centroid and spatial momements estimates are scaled by
737
    // the ray segment length as part of length averaging of the estimates.
738
    srh.volume() += distance;
6,265,820✔
739
    srh.volume_sq() += distance_2;
6,265,820✔
740
    srh.centroid_iteration() += midpoint * distance;
6,265,820✔
741
    moment_matrix_estimate *= distance;
6,265,820✔
742
    srh.mom_matrix() += moment_matrix_estimate;
6,265,820✔
743

744
    // Tally valid position inside the source region (e.g., midpoint of
745
    // the ray) if not done already
746
    if (!srh.position_recorded()) {
6,265,820✔
747
      srh.position() = midpoint;
10,000✔
748
      srh.position_recorded() = 1;
10,000✔
749
    }
750

751
    srh.n_hits() += 1;
6,265,820✔
752

753
    // Release lock
754
    srh.unlock();
6,265,820✔
755
  }
756

757
  // Add source to incoming angular flux, assuming void region
758
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,533,850!
759
    for (int g = 0; g < negroups_; g++) {
15,067,700✔
760
      angular_flux_[g] += srh.external_source(g) * distance;
7,533,850✔
761
    }
762
  }
763
}
7,533,850✔
764

765
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
1,756,720✔
766
{
767
  domain_ = domain;
1,756,720✔
768

769
  // Reset particle event counter
770
  n_event() = 0;
1,756,720✔
771

772
  is_active_ = (distance_inactive_ <= 0.0);
1,756,720✔
773

774
  wgt() = 1.0;
1,756,720✔
775

776
  // set identifier for particle
777
  id() = ray_id;
1,756,720✔
778

779
  // generate source site using sample method
780
  SourceSite site;
1,756,720✔
781
  switch (sample_method_) {
1,756,720!
782
  case RandomRaySampleMethod::PRNG:
1,746,720✔
783
    site = sample_prng();
1,746,720✔
784
    break;
1,746,720✔
785
  case RandomRaySampleMethod::HALTON:
10,000✔
786
    site = sample_halton();
10,000✔
787
    break;
10,000✔
UNCOV
788
  default:
×
UNCOV
789
    fatal_error("Unknown sample method for random ray transport.");
×
790
  }
791

792
  site.E = 0.0;
1,756,720✔
793
  this->from_source(&site);
1,756,720✔
794

795
  // Locate ray
796
  if (lowest_coord().cell() == C_NONE) {
1,756,720!
797
    if (!exhaustive_find_cell(*this)) {
1,756,720!
UNCOV
798
      this->mark_as_lost(
×
UNCOV
799
        "Could not find the cell containing particle " + std::to_string(id()));
×
800
    }
801

802
    // Set birth cell attribute
803
    if (cell_born() == C_NONE)
1,756,720!
804
      cell_born() = lowest_coord().cell();
1,756,720✔
805
  }
806

807
  SourceRegionKey sr_key = domain_->lookup_source_region_key(*this);
1,756,720✔
808
  SourceRegionHandle srh =
809
    domain_->get_subdivided_source_region_handle(sr_key, r(), u());
1,756,720✔
810

811
  // Initialize ray's starting angular flux to starting location's isotropic
812
  // source
813
  if (!srh.is_numerical_fp_artifact_) {
1,756,720!
814
    for (int g = 0; g < negroups_; g++) {
6,494,160✔
815
      angular_flux_[g] = srh.source(g);
4,737,440✔
816
    }
817
  }
818
}
1,756,720✔
819

820
SourceSite RandomRay::sample_prng()
1,746,720✔
821
{
822
  // set random number seed
823
  int64_t particle_seed =
824
    (simulation::current_batch - 1) * settings::n_particles + id();
1,746,720✔
825
  init_particle_seeds(particle_seed, seeds());
1,746,720✔
826
  stream() = STREAM_TRACKING;
1,746,720✔
827

828
  // Sample from ray source distribution
829
  SourceSite site {ray_source_->sample(current_seed())};
1,746,720✔
830

831
  return site;
1,746,720✔
832
}
833

834
SourceSite RandomRay::sample_halton()
10,000✔
835
{
836
  SourceSite site;
10,000✔
837

838
  // Set random number seed
839
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
10,000✔
840
  int64_t skip = id();
10,000✔
841
  init_particle_seeds(batch_seed, seeds());
10,000✔
842
  stream() = STREAM_TRACKING;
10,000✔
843

844
  // Calculate next samples in LDS across 5 dimensions
845
  vector<double> samples = rhalton(5, current_seed(), skip = skip);
10,000✔
846

847
  // Get spatial box of ray_source_
848
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
10,000!
849
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
10,000!
850

851
  // Sample spatial distribution
852
  Position xi {samples[0], samples[1], samples[2]};
10,000✔
853
  // make a small shift in position to avoid geometry floating point issues
854
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
10,000✔
855
  site.r = (sb->lower_left() + shift) +
856
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
10,000✔
857

858
  // Sample Polar cosine and azimuthal angles
859
  double mu = 2.0 * samples[3] - 1.0;
10,000✔
860
  double azi = 2.0 * PI * samples[4];
10,000✔
861
  // Convert to Cartesian coordinates
862
  double c = std::sqrt(1.0 - mu * mu);
10,000✔
863
  site.u.x = mu;
10,000✔
864
  site.u.y = std::cos(azi) * c;
10,000✔
865
  site.u.z = std::sin(azi) * c;
10,000✔
866

867
  return site;
20,000✔
868
}
10,000✔
869

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