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

openmc-dev / openmc / 20752759853

06 Jan 2026 03:18PM UTC coverage: 81.984% (-0.2%) from 82.154%
20752759853

Pull #3702

github

web-flow
Merge 93792a96d into c7d7fa461
Pull Request #3702: Random Ray Kinetic Simulation Mode

17538 of 24346 branches covered (72.04%)

Branch coverage included in aggregate %.

903 of 1115 new or added lines in 20 files covered. (80.99%)

224 existing lines in 14 files now uncovered.

55923 of 65258 relevant lines covered (85.7%)

50584462.14 hits per line

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

82.14
/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.
UNCOV
26
float cjosey_exponential(float tau)
×
27
{
UNCOV
28
  constexpr float c1n = -1.0000013559236386308f;
×
UNCOV
29
  constexpr float c2n = 0.23151368626911062025f;
×
UNCOV
30
  constexpr float c3n = -0.061481916409314966140f;
×
UNCOV
31
  constexpr float c4n = 0.0098619906458127653020f;
×
UNCOV
32
  constexpr float c5n = -0.0012629460503540849940f;
×
UNCOV
33
  constexpr float c6n = 0.00010360973791574984608f;
×
UNCOV
34
  constexpr float c7n = -0.000013276571933735820960f;
×
35

UNCOV
36
  constexpr float c0d = 1.0f;
×
UNCOV
37
  constexpr float c1d = -0.73151337729389001396f;
×
UNCOV
38
  constexpr float c2d = 0.26058381273536471371f;
×
UNCOV
39
  constexpr float c3d = -0.059892419041316836940f;
×
UNCOV
40
  constexpr float c4d = 0.0099070188241094279067f;
×
UNCOV
41
  constexpr float c5d = -0.0012623388962473160860f;
×
UNCOV
42
  constexpr float c6d = 0.00010361277635498731388f;
×
UNCOV
43
  constexpr float c7d = -0.000013276569500666698498f;
×
44

UNCOV
45
  float x = -tau;
×
46

UNCOV
47
  float den = c7d;
×
UNCOV
48
  den = den * x + c6d;
×
UNCOV
49
  den = den * x + c5d;
×
UNCOV
50
  den = den * x + c4d;
×
UNCOV
51
  den = den * x + c3d;
×
UNCOV
52
  den = den * x + c2d;
×
UNCOV
53
  den = den * x + c1d;
×
UNCOV
54
  den = den * x + c0d;
×
55

UNCOV
56
  float num = c7n;
×
UNCOV
57
  num = num * x + c6n;
×
UNCOV
58
  num = num * x + c5n;
×
UNCOV
59
  num = num * x + c4n;
×
UNCOV
60
  num = num * x + c3n;
×
UNCOV
61
  num = num * x + c2n;
×
UNCOV
62
  num = num * x + c1n;
×
UNCOV
63
  num = num * x;
×
64

UNCOV
65
  return num / den;
×
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,147,483,647✔
99
{
100
  // Numerator coefficients in rational approximation for 1/x - (1 - exp(-x)) /
101
  // x^2
102
  constexpr float d0n = 0.5f;
2,147,483,647✔
103
  constexpr float d1n = 0.176558112351595f;
2,147,483,647✔
104
  constexpr float d2n = 0.04041584305811143f;
2,147,483,647✔
105
  constexpr float d3n = 0.006178333902037397f;
2,147,483,647✔
106
  constexpr float d4n = 0.0006429894635552992f;
2,147,483,647✔
107
  constexpr float d5n = 0.00006064409107557148f;
2,147,483,647✔
108

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

119
  float x = tau;
2,147,483,647✔
120

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

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

136
  return num / den;
2,147,483,647✔
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,147,483,647✔
145
{
146

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

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

161
  float x = tau;
2,147,483,647✔
162

163
  float num = g5n;
2,147,483,647✔
164
  num = num * x + g4n;
2,147,483,647✔
165
  num = num * x + g3n;
2,147,483,647✔
166
  num = num * x + g2n;
2,147,483,647✔
167
  num = num * x + g1n;
2,147,483,647✔
168
  num = num * x;
2,147,483,647✔
169

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

177
  return num / den;
2,147,483,647✔
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,584,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,831,000✔
187
    // Generate a random index in the range [0, i]
188
    int j = uniform_int_distribution(0, i, seed);
5,247,000✔
189
    std::swap(arr[i], arr[j]);
5,247,000✔
190
  }
191
}
1,584,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)
11,000✔
199
{
200
  if (dim > 10) {
11,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};
11,000✔
206
  vector<double> halton(dim, 0.0);
11,000✔
207

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

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

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

228
  return halton;
22,000✔
229
}
11,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
double RandomRay::avg_miss_rate_;
243
int64_t RandomRay::n_source_regions_;
244
int64_t RandomRay::n_external_source_regions_;
245
uint64_t RandomRay::total_geometric_intersections_;
246

247
// Kinetic simulation variables
248
int RandomRay::bd_order_ {3}; // order 3 BD balances accuracy with speed nicely
249
RandomRayTimeMethod RandomRay::time_method_ {RandomRayTimeMethod::ISOTROPIC};
250

251
RandomRay::RandomRay()
11,536,420✔
252
  : angular_flux_(data::mg.num_energy_groups_),
11,536,420✔
253
    delta_psi_(data::mg.num_energy_groups_),
11,536,420✔
254
    negroups_(data::mg.num_energy_groups_),
11,536,420✔
255
    angular_flux_prime_(data::mg.num_energy_groups_)
34,609,260✔
256

257
{
258
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
11,536,420✔
259
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
10,670,720✔
260
    delta_moments_.resize(negroups_);
990,550✔
261
  }
262
}
11,536,420✔
263

264
RandomRay::RandomRay(uint64_t ray_id, FlatSourceDomain* domain) : RandomRay()
11,536,420✔
265
{
266
  initialize_ray(ray_id, domain);
11,536,420✔
267
}
11,536,420✔
268

269
// Transports ray until termination criteria are met
270
uint64_t RandomRay::transport_history_based_single_ray()
11,536,420✔
271
{
272
  using namespace openmc;
273
  while (alive()) {
2,147,483,647!
274
    event_advance_ray();
2,147,483,647✔
275
    if (!alive())
2,147,483,647✔
276
      break;
11,536,420✔
277
    event_cross_surface();
2,147,483,647✔
278
    // If ray has too many events, display warning and kill it
279
    if (n_event() >= settings::max_particle_events) {
2,147,483,647!
280
      warning("Ray " + std::to_string(id()) +
×
281
              " underwent maximum number of events, terminating ray.");
282
      wgt() = 0.0;
×
283
    }
284
  }
285

286
  return n_event();
11,536,420✔
287
}
288

289
// Transports ray across a single source region
290
void RandomRay::event_advance_ray()
2,147,483,647✔
291
{
292
  // If geometry debug mode is on, check for cell overlaps
293
  if (settings::check_overlaps)
2,147,483,647!
294
    check_cell_overlap(*this);
×
295

296
  // Find the distance to the nearest boundary
297
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
298
  double distance = boundary().distance();
2,147,483,647✔
299

300
  if (distance < 0.0) {
2,147,483,647!
301
    mark_as_lost("Negative transport distance detected for particle " +
×
302
                 std::to_string(id()));
×
303
    return;
×
304
  }
305

306
  if (is_active_) {
2,147,483,647✔
307
    // If the ray is in the active length, need to check if it has
308
    // reached its maximum termination distance. If so, reduce
309
    // the ray traced length so that the ray does not overrun the
310
    // maximum numerical length (so as to avoid numerical bias).
311
    if (distance_travelled_ + distance >= distance_active_) {
2,147,483,647✔
312
      distance = distance_active_ - distance_travelled_;
11,536,420✔
313
      wgt() = 0.0;
11,536,420✔
314
    }
315

316
    distance_travelled_ += distance;
2,147,483,647✔
317
    attenuate_flux(distance, true);
2,147,483,647✔
318
  } else {
319
    // If the ray is still in the dead zone, need to check if it
320
    // has entered the active phase. If so, split into two segments (one
321
    // representing the final part of the dead zone, the other representing the
322
    // first part of the active length) and attenuate each. Otherwise, if the
323
    // full length of the segment is within the dead zone, attenuate as normal.
324
    if (distance_travelled_ + distance >= distance_inactive_) {
1,520,520,877✔
325
      is_active_ = true;
11,536,420✔
326
      double distance_dead = distance_inactive_ - distance_travelled_;
11,536,420✔
327
      attenuate_flux(distance_dead, false);
11,536,420✔
328

329
      double distance_alive = distance - distance_dead;
11,536,420✔
330

331
      // Ensure we haven't travelled past the active phase as well
332
      if (distance_alive > distance_active_) {
11,536,420!
333
        distance_alive = distance_active_;
×
334
        wgt() = 0.0;
×
335
      }
336

337
      attenuate_flux(distance_alive, true, distance_dead);
11,536,420✔
338
      distance_travelled_ = distance_alive;
11,536,420✔
339
    } else {
340
      distance_travelled_ += distance;
1,508,984,457✔
341
      attenuate_flux(distance, false);
1,508,984,457✔
342
    }
343
  }
344

345
  // Advance particle
346
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
347
    coord(j).r() += distance * coord(j).u();
2,147,483,647✔
348
  }
349
}
350

351
void RandomRay::attenuate_flux(double distance, bool is_active, double offset)
2,147,483,647✔
352
{
353
  // Lookup base source region index
354
  int64_t sr = domain_->lookup_base_source_region_idx(*this);
2,147,483,647✔
355

356
  // Perform ray tracing across mesh
357
  // Determine the mesh index for the base source region, if any
358
  int mesh_idx = domain_->lookup_mesh_idx(sr);
2,147,483,647✔
359

360
  if (mesh_idx == C_NONE) {
2,147,483,647✔
361
    // If there's no mesh being applied to this cell, then
362
    // we just attenuate the flux as normal, and set
363
    // the mesh bin to 0
364
    attenuate_flux_inner(distance, is_active, sr, 0, r());
2,147,483,647✔
365
  } else {
366
    // If there is a mesh being applied to this cell, then
367
    // we loop over all the bin crossings and attenuate
368
    // separately.
369
    Mesh* mesh = model::meshes[mesh_idx].get();
2,147,483,647✔
370

371
    // We adjust the start and end positions of the ray slightly
372
    // to accomodate for floating point precision issues that tend
373
    // to occur at mesh boundaries that overlap with geometry lattice
374
    // boundaries.
375
    Position start = r() + (offset + TINY_BIT) * u();
2,147,483,647✔
376
    Position end = start + (distance - 2.0 * TINY_BIT) * u();
2,147,483,647✔
377
    double reduced_distance = (end - start).norm();
2,147,483,647✔
378

379
    // Ray trace through the mesh and record bins and lengths
380
    mesh_bins_.resize(0);
2,147,483,647✔
381
    mesh_fractional_lengths_.resize(0);
2,147,483,647✔
382
    mesh->bins_crossed(start, end, u(), mesh_bins_, mesh_fractional_lengths_);
2,147,483,647✔
383

384
    // Loop over all mesh bins and attenuate flux
385
    for (int b = 0; b < mesh_bins_.size(); b++) {
2,147,483,647✔
386
      double physical_length = reduced_distance * mesh_fractional_lengths_[b];
2,147,483,647✔
387
      attenuate_flux_inner(
2,147,483,647✔
388
        physical_length, is_active, sr, mesh_bins_[b], start);
2,147,483,647✔
389
      start += physical_length * u();
2,147,483,647✔
390
    }
391
  }
392
}
2,147,483,647✔
393

394
void RandomRay::attenuate_flux_inner(
2,147,483,647✔
395
  double distance, bool is_active, int64_t sr, int mesh_bin, Position r)
396
{
397
  SourceRegionKey sr_key {sr, mesh_bin};
2,147,483,647✔
398
  SourceRegionHandle srh;
2,147,483,647✔
399
  srh = domain_->get_subdivided_source_region_handle(sr_key, r, u());
2,147,483,647✔
400
  if (srh.is_numerical_fp_artifact_) {
2,147,483,647✔
401
    return;
473✔
402
  }
403

404
  switch (source_shape_) {
2,147,483,647!
405
  case RandomRaySourceShape::FLAT:
2,147,483,647✔
406
    if (srh.material() == MATERIAL_VOID) {
2,147,483,647✔
407
      attenuate_flux_flat_source_void(srh, distance, is_active, r);
8,367,713✔
408
    } else {
409
      attenuate_flux_flat_source(srh, distance, is_active, r);
2,147,483,647✔
410
    }
411
    break;
2,147,483,647✔
412
  case RandomRaySourceShape::LINEAR:
636,667,625✔
413
  case RandomRaySourceShape::LINEAR_XY:
414
    // TODO: time-dependent linear source regions
415
    if (srh.material() == MATERIAL_VOID) {
636,667,625✔
416
      attenuate_flux_linear_source_void(srh, distance, is_active, r);
8,287,235✔
417
    } else {
418
      attenuate_flux_linear_source(srh, distance, is_active, r);
628,380,390✔
419
    }
420
    break;
636,667,625✔
421
  default:
×
422
    fatal_error("Unknown source shape for random ray transport.");
×
423
  }
424
}
425

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

445
  // Get material
446
  int material = srh.material();
2,147,483,647✔
447

448
  // MOC incoming flux attenuation + source contribution/attenuation equation
UNCOV
449
  for (int g = 0; g < negroups_; g++) {
×
UNCOV
450
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
×
UNCOV
451
    float tau = sigma_t * distance;
×
UNCOV
452
    float exponential = cjosey_exponential(tau); // exponential = 1 - exp(-tau)
×
UNCOV
453
    float new_delta_psi = (angular_flux_[g] - srh.source(g)) * exponential;
×
NEW
454
    if (settings::kinetic_simulation && !simulation::is_initial_condition &&
×
NEW
455
        RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
×
NEW
456
      float T1 = srh.T1(g);
×
457

458
      // Source Derivative Propogation terms for Characteristic Equation
NEW
459
      float inverse_vbar = domain_->inverse_vbar_[material * negroups_ + g];
×
NEW
460
      new_delta_psi += T1 * inverse_vbar * exponential / sigma_t;
×
NEW
461
      new_delta_psi += distance * inverse_vbar * (angular_flux_prime_[g] - T1) *
×
NEW
462
                       (1 - exponential);
×
463

464
      // Time Derivative Characteristic Equation
NEW
465
      angular_flux_prime_[g] -= (angular_flux_prime_[g] - T1) * exponential;
×
466
    }
UNCOV
467
    delta_psi_[g] = new_delta_psi;
×
UNCOV
468
    angular_flux_[g] -= new_delta_psi;
×
469
  }
470

471
  // If ray is in the active phase (not in dead zone), make contributions to
472
  // source region bookkeeping
473

474
  // Aquire lock for source region
475
  srh.lock();
2,147,483,647✔
476

477
  if (is_active) {
2,147,483,647✔
478
    // Accumulate delta psi into new estimate of source region flux for
479
    // this iteration
UNCOV
480
    for (int g = 0; g < negroups_; g++) {
×
UNCOV
481
      srh.scalar_flux_new(g) += delta_psi_[g];
×
482
    }
483

484
    // Accomulate volume (ray distance) into this iteration's estimate
485
    // of the source region's volume
486
    srh.volume() += distance;
2,147,483,647✔
487

488
    srh.n_hits() += 1;
2,147,483,647✔
489
  }
490

491
  // Tally valid position inside the source region (e.g., midpoint of
492
  // the ray) if not done already
493
  if (!srh.position_recorded()) {
2,147,483,647✔
494
    Position midpoint = r + u() * (distance / 2.0);
1,543,730✔
495
    srh.position() = midpoint;
1,543,730✔
496
    srh.position_recorded() = 1;
1,543,730✔
497
  }
498

499
  // Release lock
500
  srh.unlock();
2,147,483,647✔
501
}
2,147,483,647✔
502

503
// Alternative flux attenuation function for true void regions.
504
// TODO: Implement support for time dependent voids
505
void RandomRay::attenuate_flux_flat_source_void(
8,367,713✔
506
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
507
{
508
  // The number of geometric intersections is counted for reporting purposes
509
  n_event()++;
8,367,713✔
510

511
  int material = srh.material();
8,367,713✔
512

513
  // If ray is in the active phase (not in dead zone), make contributions to
514
  // source region bookkeeping
515
  if (is_active) {
8,367,713✔
516

517
    // Aquire lock for source region
518
    srh.lock();
6,959,311✔
519

520
    // Accumulate delta psi into new estimate of source region flux for
521
    // this iteration
522
    for (int g = 0; g < negroups_; g++) {
13,972,386✔
523
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
7,013,075✔
524
    }
525

526
    // Accomulate volume (ray distance) into this iteration's estimate
527
    // of the source region's volume
528
    srh.volume() += distance;
6,959,311✔
529
    srh.volume_sq() += distance * distance;
6,959,311✔
530
    srh.n_hits() += 1;
6,959,311✔
531

532
    // Tally valid position inside the source region (e.g., midpoint of
533
    // the ray) if not done already
534
    if (!srh.position_recorded()) {
6,959,311✔
535
      Position midpoint = r + u() * (distance / 2.0);
11,152✔
536
      srh.position() = midpoint;
11,152✔
537
      srh.position_recorded() = 1;
11,152✔
538
    }
539

540
    // Release lock
541
    srh.unlock();
6,959,311✔
542
  }
543

544
  // Add source to incoming angular flux, assuming void region
545
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,367,713!
546
    for (int g = 0; g < negroups_; g++) {
16,800,482✔
547
      angular_flux_[g] += srh.external_source(g) * distance;
8,432,769✔
548
    }
549
  }
550
}
8,367,713✔
551

552
void RandomRay::attenuate_flux_linear_source(
628,380,390✔
553
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
554
{
555
  // The number of geometric intersections is counted for reporting purposes
556
  n_event()++;
628,380,390✔
557

558
  int material = srh.material();
628,380,390✔
559

560
  Position& centroid = srh.centroid();
628,380,390✔
561
  Position midpoint = r + u() * (distance / 2.0);
628,380,390✔
562

563
  // Determine the local position of the midpoint and the ray origin
564
  // relative to the source region's centroid
565
  Position rm_local;
628,380,390✔
566
  Position r0_local;
628,380,390✔
567

568
  // In the first few iterations of the simulation, the source region
569
  // may not yet have had any ray crossings, in which case there will
570
  // be no estimate of its centroid. We detect this by checking if it has
571
  // any accumulated volume. If its volume is zero, just use the midpoint
572
  // of the ray as the region's centroid.
573
  if (srh.volume_t()) {
628,380,390✔
574
    rm_local = midpoint - centroid;
605,947,375✔
575
    r0_local = r - centroid;
605,947,375✔
576
  } else {
577
    rm_local = {0.0, 0.0, 0.0};
22,433,015✔
578
    r0_local = -u() * 0.5 * distance;
22,433,015✔
579
  }
580
  double distance_2 = distance * distance;
628,380,390✔
581

582
  // Linear Source MOC incoming flux attenuation + source
583
  // contribution/attenuation equation
584
  for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
585

586
    // Compute tau, the optical thickness of the ray segment
587
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
2,147,483,647✔
588
    float tau = sigma_t * distance;
2,147,483,647✔
589

590
    // If tau is very small, set it to zero to avoid numerical issues.
591
    // The following computations will still work with tau = 0.
592
    if (tau < 1.0e-8f) {
2,147,483,647✔
593
      tau = 0.0f;
5,874✔
594
    }
595

596
    // Compute linear source terms, spatial and directional (dir),
597
    // calculated from the source gradients dot product with local centroid
598
    // and direction, respectively.
599
    float spatial_source =
600
      srh.source(g) + rm_local.dot(srh.source_gradients(g));
2,147,483,647✔
601
    float dir_source = u().dot(srh.source_gradients(g));
2,147,483,647✔
602

603
    float gn = exponentialG(tau);
2,147,483,647✔
604
    float f1 = 1.0f - tau * gn;
2,147,483,647✔
605
    float f2 = (2.0f * gn - f1) * distance_2;
2,147,483,647✔
606
    float new_delta_psi = (angular_flux_[g] - spatial_source) * f1 * distance -
2,147,483,647✔
607
                          0.5 * dir_source * f2;
2,147,483,647✔
608

609
    float h1 = f1 - gn;
2,147,483,647✔
610
    float g1 = 0.5f - h1;
2,147,483,647✔
611
    float g2 = exponentialG2(tau);
2,147,483,647✔
612
    g1 = g1 * spatial_source;
2,147,483,647✔
613
    g2 = g2 * dir_source * distance * 0.5f;
2,147,483,647✔
614
    h1 = h1 * angular_flux_[g];
2,147,483,647✔
615
    h1 = (g1 + g2 + h1) * distance_2;
2,147,483,647✔
616
    spatial_source = spatial_source * distance + new_delta_psi;
2,147,483,647✔
617

618
    // Store contributions for this group into arrays, so that they can
619
    // be accumulated into the source region's estimates inside of the locked
620
    // region.
621
    delta_psi_[g] = new_delta_psi;
2,147,483,647✔
622
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
2,147,483,647✔
623

624
    // Update the angular flux for this group
625
    angular_flux_[g] -= new_delta_psi * sigma_t;
2,147,483,647✔
626

627
    // If 2D mode is enabled, the z-component of the flux moments is forced
628
    // to zero
629
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
2,147,483,647✔
630
      delta_moments_[g].z = 0.0;
462,208,043✔
631
    }
632
  }
633

634
  // Compute an estimate of the spatial moments matrix for the source
635
  // region based on parameters from this ray's crossing
636
  MomentMatrix moment_matrix_estimate;
637
  moment_matrix_estimate.compute_spatial_moments_matrix(
628,380,390✔
638
    rm_local, u(), distance);
628,380,390✔
639

640
  // Aquire lock for source region
641
  srh.lock();
628,380,390✔
642

643
  // If ray is in the active phase (not in dead zone), make contributions to
644
  // source region bookkeeping
645

646
  if (is_active) {
628,380,390✔
647
    // Accumulate deltas into the new estimate of source region flux for this
648
    // iteration
649
    for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
650
      srh.scalar_flux_new(g) += delta_psi_[g];
1,886,479,408✔
651
      srh.flux_moments_new(g) += delta_moments_[g];
1,886,479,408✔
652
    }
653

654
    // Accumulate the volume (ray segment distance), centroid, and spatial
655
    // momement estimates into the running totals for the iteration for this
656
    // source region. The centroid and spatial momements estimates are scaled
657
    // by the ray segment length as part of length averaging of the estimates.
658
    srh.volume() += distance;
514,578,966✔
659
    srh.centroid_iteration() += midpoint * distance;
514,578,966✔
660
    moment_matrix_estimate *= distance;
514,578,966✔
661
    srh.mom_matrix() += moment_matrix_estimate;
514,578,966✔
662

663
    srh.n_hits() += 1;
514,578,966✔
664
  }
665

666
  // Tally valid position inside the source region (e.g., midpoint of
667
  // the ray) if not done already
668
  if (!srh.position_recorded()) {
628,380,390✔
669
    srh.position() = midpoint;
810,062✔
670
    srh.position_recorded() = 1;
810,062✔
671
  }
672

673
  // Release lock
674
  srh.unlock();
628,380,390✔
675
}
628,380,390✔
676

677
// If traveling through a void region, the source term is either zero
678
// or an external source. As all external sources are currently assumed
679
// to be flat, we don't really need this function and could instead just call
680
// the "attenuate_flux_flat_source_void" function and get the same numerical and
681
// tally results. However, computation of the flux moments in void regions is
682
// nonetheless useful as this information is still used by the plotter when
683
// estimating the flux at specific pixel coordinates. Thus, plots will look
684
// nicer/more accurate if we record flux moments, so this function is useful.
685
void RandomRay::attenuate_flux_linear_source_void(
8,287,235✔
686
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
687
{
688
  // The number of geometric intersections is counted for reporting purposes
689
  n_event()++;
8,287,235✔
690

691
  Position& centroid = srh.centroid();
8,287,235✔
692
  Position midpoint = r + u() * (distance / 2.0);
8,287,235✔
693

694
  // Determine the local position of the midpoint and the ray origin
695
  // relative to the source region's centroid
696
  Position rm_local;
8,287,235✔
697
  Position r0_local;
8,287,235✔
698

699
  // In the first few iterations of the simulation, the source region
700
  // may not yet have had any ray crossings, in which case there will
701
  // be no estimate of its centroid. We detect this by checking if it has
702
  // any accumulated volume. If its volume is zero, just use the midpoint
703
  // of the ray as the region's centroid.
704
  if (srh.volume_t()) {
8,287,235✔
705
    rm_local = midpoint - centroid;
8,084,186✔
706
    r0_local = r - centroid;
8,084,186✔
707
  } else {
708
    rm_local = {0.0, 0.0, 0.0};
203,049✔
709
    r0_local = -u() * 0.5 * distance;
203,049✔
710
  }
711
  double distance_2 = distance * distance;
8,287,235✔
712

713
  // Compared to linear flux attenuation through solid regions,
714
  // transport through a void region is greatly simplified. Here we
715
  // compute the updated flux moments.
716
  for (int g = 0; g < negroups_; g++) {
16,574,470✔
717
    float spatial_source = 0.f;
8,287,235✔
718
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,287,235!
719
      spatial_source = srh.external_source(g);
8,287,235✔
720
    }
721
    float new_delta_psi = (angular_flux_[g] - spatial_source) * distance;
8,287,235✔
722
    float h1 = 0.5f;
8,287,235✔
723
    h1 = h1 * angular_flux_[g];
8,287,235✔
724
    h1 = h1 * distance_2;
8,287,235✔
725
    spatial_source = spatial_source * distance + new_delta_psi;
8,287,235✔
726

727
    // Store contributions for this group into arrays, so that they can
728
    // be accumulated into the source region's estimates inside of the locked
729
    // region.
730
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
8,287,235✔
731

732
    // If 2D mode is enabled, the z-component of the flux moments is forced
733
    // to zero
734
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
8,287,235!
735
      delta_moments_[g].z = 0.0;
×
736
    }
737
  }
738

739
  // If ray is in the active phase (not in dead zone), make contributions to
740
  // source region bookkeeping
741
  if (is_active) {
8,287,235✔
742
    // Compute an estimate of the spatial moments matrix for the source
743
    // region based on parameters from this ray's crossing
744
    MomentMatrix moment_matrix_estimate;
745
    moment_matrix_estimate.compute_spatial_moments_matrix(
6,892,402✔
746
      rm_local, u(), distance);
6,892,402✔
747

748
    // Aquire lock for source region
749
    srh.lock();
6,892,402✔
750

751
    // Accumulate delta psi into new estimate of source region flux for
752
    // this iteration, and update flux momements
753
    for (int g = 0; g < negroups_; g++) {
13,784,804✔
754
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,892,402✔
755
      srh.flux_moments_new(g) += delta_moments_[g];
6,892,402✔
756
    }
757

758
    // Accumulate the volume (ray segment distance), centroid, and spatial
759
    // momement estimates into the running totals for the iteration for this
760
    // source region. The centroid and spatial momements estimates are scaled by
761
    // the ray segment length as part of length averaging of the estimates.
762
    srh.volume() += distance;
6,892,402✔
763
    srh.volume_sq() += distance_2;
6,892,402✔
764
    srh.centroid_iteration() += midpoint * distance;
6,892,402✔
765
    moment_matrix_estimate *= distance;
6,892,402✔
766
    srh.mom_matrix() += moment_matrix_estimate;
6,892,402✔
767

768
    // Tally valid position inside the source region (e.g., midpoint of
769
    // the ray) if not done already
770
    if (!srh.position_recorded()) {
6,892,402✔
771
      srh.position() = midpoint;
11,000✔
772
      srh.position_recorded() = 1;
11,000✔
773
    }
774

775
    srh.n_hits() += 1;
6,892,402✔
776

777
    // Release lock
778
    srh.unlock();
6,892,402✔
779
  }
780

781
  // Add source to incoming angular flux, assuming void region
782
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,287,235!
783
    for (int g = 0; g < negroups_; g++) {
16,574,470✔
784
      angular_flux_[g] += srh.external_source(g) * distance;
8,287,235✔
785
    }
786
  }
787
}
8,287,235✔
788

789
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
11,536,420✔
790
{
791
  domain_ = domain;
11,536,420✔
792

793
  // Reset particle event counter
794
  n_event() = 0;
11,536,420✔
795

796
  is_active_ = (distance_inactive_ <= 0.0);
11,536,420✔
797

798
  wgt() = 1.0;
11,536,420✔
799

800
  // set identifier for particle
801
  id() = ray_id;
11,536,420✔
802

803
  // generate source site using sample method
804
  SourceSite site;
11,536,420✔
805
  switch (sample_method_) {
11,536,420!
806
  case RandomRaySampleMethod::PRNG:
11,525,420✔
807
    site = sample_prng();
11,525,420✔
808
    break;
11,525,420✔
809
  case RandomRaySampleMethod::HALTON:
11,000✔
810
    site = sample_halton();
11,000✔
811
    break;
11,000✔
812
  default:
×
813
    fatal_error("Unknown sample method for random ray transport.");
×
814
  }
815

816
  site.E = 0.0;
11,536,420✔
817
  this->from_source(&site);
11,536,420✔
818

819
  // Locate ray
820
  if (lowest_coord().cell() == C_NONE) {
11,536,420!
821
    if (!exhaustive_find_cell(*this)) {
11,536,420!
822
      this->mark_as_lost(
×
823
        "Could not find the cell containing particle " + std::to_string(id()));
×
824
    }
825

826
    // Set birth cell attribute
827
    if (cell_born() == C_NONE)
11,536,420!
828
      cell_born() = lowest_coord().cell();
11,536,420✔
829
  }
830

831
  SourceRegionKey sr_key = domain_->lookup_source_region_key(*this);
11,536,420✔
832
  SourceRegionHandle srh =
833
    domain_->get_subdivided_source_region_handle(sr_key, r(), u());
11,536,420✔
834

835
  // Initialize ray's starting angular flux to starting location's isotropic
836
  // source
837
  if (!srh.is_numerical_fp_artifact_) {
11,536,420!
838
    for (int g = 0; g < negroups_; g++) {
92,582,560✔
839
      angular_flux_[g] = srh.source(g);
81,046,140✔
840
    }
841
    if (settings::kinetic_simulation && !simulation::is_initial_condition &&
11,536,420✔
842
        RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
6,875,000!
NEW
843
      for (int g = 0; g < negroups_; g++) {
×
844
        // T1
NEW
845
        angular_flux_prime_[g] = srh.T1(g);
×
846
      }
847
    }
848
  }
849
}
11,536,420✔
850

851
SourceSite RandomRay::sample_prng()
11,525,420✔
852
{
853
  // set random number seed
854
  int64_t particle_seed =
855
    (simulation::current_batch - 1) * settings::n_particles + id();
11,525,420✔
856
  init_particle_seeds(particle_seed, seeds());
11,525,420✔
857
  stream() = STREAM_TRACKING;
11,525,420✔
858

859
  // Sample from ray source distribution
860
  SourceSite site {ray_source_->sample(current_seed())};
11,525,420✔
861

862
  return site;
11,525,420✔
863
}
864

865
SourceSite RandomRay::sample_halton()
11,000✔
866
{
867
  SourceSite site;
11,000✔
868

869
  // Set random number seed
870
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
11,000✔
871
  int64_t skip = id();
11,000✔
872
  init_particle_seeds(batch_seed, seeds());
11,000✔
873
  stream() = STREAM_TRACKING;
11,000✔
874

875
  // Calculate next samples in LDS across 5 dimensions
876
  vector<double> samples = rhalton(5, current_seed(), skip = skip);
11,000✔
877

878
  // Get spatial box of ray_source_
879
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
11,000!
880
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
11,000!
881

882
  // Sample spatial distribution
883
  Position xi {samples[0], samples[1], samples[2]};
11,000✔
884
  // make a small shift in position to avoid geometry floating point issues
885
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
11,000✔
886
  site.r = (sb->lower_left() + shift) +
887
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
11,000✔
888

889
  // Sample Polar cosine and azimuthal angles
890
  double mu = 2.0 * samples[3] - 1.0;
11,000✔
891
  double azi = 2.0 * PI * samples[4];
11,000✔
892
  // Convert to Cartesian coordinates
893
  double c = std::sqrt(1.0 - mu * mu);
11,000✔
894
  site.u.x = mu;
11,000✔
895
  site.u.y = std::cos(azi) * c;
11,000✔
896
  site.u.z = std::sin(azi) * c;
11,000✔
897

898
  return site;
22,000✔
899
}
11,000✔
900

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