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

openmc-dev / openmc / 21869950741

10 Feb 2026 02:55PM UTC coverage: 81.745% (-0.07%) from 81.817%
21869950741

Pull #3785

github

web-flow
Merge d0d599339 into 3f20a5e22
Pull Request #3785: Coincident source

17383 of 24442 branches covered (71.12%)

Branch coverage included in aggregate %.

137 of 214 new or added lines in 5 files covered. (64.02%)

505 existing lines in 13 files now uncovered.

56328 of 65730 relevant lines covered (85.7%)

46747049.69 hits per line

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

91.72
/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,941,017,593✔
27
{
28
  constexpr float c1n = -1.0000013559236386308f;
1,941,017,593✔
29
  constexpr float c2n = 0.23151368626911062025f;
1,941,017,593✔
30
  constexpr float c3n = -0.061481916409314966140f;
1,941,017,593✔
31
  constexpr float c4n = 0.0098619906458127653020f;
1,941,017,593✔
32
  constexpr float c5n = -0.0012629460503540849940f;
1,941,017,593✔
33
  constexpr float c6n = 0.00010360973791574984608f;
1,941,017,593✔
34
  constexpr float c7n = -0.000013276571933735820960f;
1,941,017,593✔
35

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

45
  float x = -tau;
1,941,017,593✔
46

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

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

65
  return num / den;
1,941,017,593✔
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
RandomRay::RandomRay()
2,119,320✔
243
  : angular_flux_(data::mg.num_energy_groups_),
2,119,320✔
244
    delta_psi_(data::mg.num_energy_groups_),
2,119,320✔
245
    negroups_(data::mg.num_energy_groups_)
6,357,960✔
246
{
247
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
2,119,320✔
248
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
1,187,620✔
249
    delta_moments_.resize(negroups_);
1,056,550✔
250
  }
251
}
2,119,320✔
252

253
RandomRay::RandomRay(uint64_t ray_id, FlatSourceDomain* domain) : RandomRay()
2,119,320✔
254
{
255
  initialize_ray(ray_id, domain);
2,119,320✔
256
}
2,119,320✔
257

258
// Transports ray until termination criteria are met
259
uint64_t RandomRay::transport_history_based_single_ray()
2,119,320✔
260
{
261
  using namespace openmc;
262
  while (alive()) {
936,369,831!
263
    event_advance_ray();
936,369,831✔
264
    if (!alive())
936,369,831✔
265
      break;
2,119,320✔
266
    event_cross_surface();
934,250,511✔
267
    // If ray has too many events, display warning and kill it
268
    if (n_event() >= settings::max_particle_events) {
934,250,511!
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();
2,119,320✔
276
}
277

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

285
  // Find the distance to the nearest boundary
286
  boundary() = distance_to_boundary(*this);
936,369,831✔
287
  double distance = boundary().distance();
936,369,831✔
288

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

295
  if (is_active_) {
936,369,831✔
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_) {
761,753,184✔
301
      distance = distance_active_ - distance_travelled_;
2,119,320✔
302
      wgt() = 0.0;
2,119,320✔
303
    }
304

305
    distance_travelled_ += distance;
761,753,184✔
306
    attenuate_flux(distance, true);
761,753,184✔
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_) {
174,616,647✔
314
      is_active_ = true;
2,119,320✔
315
      double distance_dead = distance_inactive_ - distance_travelled_;
2,119,320✔
316
      attenuate_flux(distance_dead, false);
2,119,320✔
317

318
      double distance_alive = distance - distance_dead;
2,119,320✔
319

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

326
      attenuate_flux(distance_alive, true, distance_dead);
2,119,320✔
327
      distance_travelled_ = distance_alive;
2,119,320✔
328
    } else {
329
      distance_travelled_ += distance;
172,497,327✔
330
      attenuate_flux(distance, false);
172,497,327✔
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,147,483,647✔
337
  }
338
}
339

340
void RandomRay::attenuate_flux(double distance, bool is_active, double offset)
938,489,151✔
341
{
342
  // Lookup base source region index
343
  int64_t sr = domain_->lookup_base_source_region_idx(*this);
938,489,151✔
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);
938,489,151✔
348

349
  if (mesh_idx == C_NONE) {
938,489,151✔
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());
464,200,209✔
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();
474,288,942✔
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();
474,288,942✔
365
    Position end = start + (distance - 2.0 * TINY_BIT) * u();
474,288,942✔
366
    double reduced_distance = (end - start).norm();
474,288,942✔
367

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

373
    // Loop over all mesh bins and attenuate flux
374
    for (int b = 0; b < mesh_bins_.size(); b++) {
1,409,541,426✔
375
      double physical_length = reduced_distance * mesh_fractional_lengths_[b];
935,252,484✔
376
      attenuate_flux_inner(
935,252,484✔
377
        physical_length, is_active, sr, mesh_bins_[b], start);
935,252,484✔
378
      start += physical_length * u();
935,252,484✔
379
    }
380
  }
381
}
938,489,151✔
382

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

393
  switch (source_shape_) {
1,399,452,605!
394
  case RandomRaySourceShape::FLAT:
723,900,552✔
395
    if (srh.material() == MATERIAL_VOID) {
723,900,552✔
396
      attenuate_flux_flat_source_void(srh, distance, is_active, r);
8,367,713✔
397
    } else {
398
      attenuate_flux_flat_source(srh, distance, is_active, r);
715,532,839✔
399
    }
400
    break;
723,900,552✔
401
  case RandomRaySourceShape::LINEAR:
675,552,053✔
402
  case RandomRaySourceShape::LINEAR_XY:
403
    if (srh.material() == MATERIAL_VOID) {
675,552,053✔
404
      attenuate_flux_linear_source_void(srh, distance, is_active, r);
8,287,235✔
405
    } else {
406
      attenuate_flux_linear_source(srh, distance, is_active, r);
667,264,818✔
407
    }
408
    break;
675,552,053✔
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(
715,532,839✔
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()++;
715,532,839✔
432

433
  // Get material
434
  int material = srh.material();
715,532,839✔
435
  int temp = srh.temperature_idx();
715,532,839✔
436

437
  // MOC incoming flux attenuation + source contribution/attenuation equation
438
  for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
439
    float sigma_t =
440
      domain_->sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
1,941,017,593✔
441
      srh.density_mult();
1,941,017,593✔
442
    float tau = sigma_t * distance;
1,941,017,593✔
443
    float exponential = cjosey_exponential(tau); // exponential = 1 - exp(-tau)
1,941,017,593✔
444
    float new_delta_psi = (angular_flux_[g] - srh.source(g)) * exponential;
1,941,017,593✔
445
    delta_psi_[g] = new_delta_psi;
1,941,017,593✔
446
    angular_flux_[g] -= new_delta_psi;
1,941,017,593✔
447
  }
448

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

452
  // Aquire lock for source region
453
  srh.lock();
715,532,839✔
454

455
  if (is_active) {
715,532,839✔
456
    // Accumulate delta psi into new estimate of source region flux for
457
    // this iteration
458
    for (int g = 0; g < negroups_; g++) {
2,144,162,302✔
459
      srh.scalar_flux_new(g) += delta_psi_[g];
1,556,960,516✔
460
    }
461

462
    // Accomulate volume (ray distance) into this iteration's estimate
463
    // of the source region's volume
464
    srh.volume() += distance;
587,201,786✔
465

466
    srh.n_hits() += 1;
587,201,786✔
467
  }
468

469
  // Tally valid position inside the source region (e.g., midpoint of
470
  // the ray) if not done already
471
  if (!srh.position_recorded()) {
715,532,839✔
472
    Position midpoint = r + u() * (distance / 2.0);
1,533,775✔
473
    srh.position() = midpoint;
1,533,775✔
474
    srh.position_recorded() = 1;
1,533,775✔
475
  }
476

477
  // Release lock
478
  srh.unlock();
715,532,839✔
479
}
715,532,839✔
480

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

488
  int material = srh.material();
8,367,713✔
489

490
  // If ray is in the active phase (not in dead zone), make contributions to
491
  // source region bookkeeping
492
  if (is_active) {
8,367,713✔
493

494
    // Aquire lock for source region
495
    srh.lock();
6,959,311✔
496

497
    // Accumulate delta psi into new estimate of source region flux for
498
    // this iteration
499
    for (int g = 0; g < negroups_; g++) {
13,972,386✔
500
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
7,013,075✔
501
    }
502

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

509
    // Tally valid position inside the source region (e.g., midpoint of
510
    // the ray) if not done already
511
    if (!srh.position_recorded()) {
6,959,311✔
512
      Position midpoint = r + u() * (distance / 2.0);
11,152✔
513
      srh.position() = midpoint;
11,152✔
514
      srh.position_recorded() = 1;
11,152✔
515
    }
516

517
    // Release lock
518
    srh.unlock();
6,959,311✔
519
  }
520

521
  // Add source to incoming angular flux, assuming void region
522
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,367,713!
523
    for (int g = 0; g < negroups_; g++) {
16,800,482✔
524
      angular_flux_[g] += srh.external_source(g) * distance;
8,432,769✔
525
    }
526
  }
527
}
8,367,713✔
528

529
void RandomRay::attenuate_flux_linear_source(
667,264,818✔
530
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
531
{
532
  // The number of geometric intersections is counted for reporting purposes
533
  n_event()++;
667,264,818✔
534

535
  int material = srh.material();
667,264,818✔
536
  int temp = srh.temperature_idx();
667,264,818✔
537

538
  Position& centroid = srh.centroid();
667,264,818✔
539
  Position midpoint = r + u() * (distance / 2.0);
667,264,818✔
540

541
  // Determine the local position of the midpoint and the ray origin
542
  // relative to the source region's centroid
543
  Position rm_local;
667,264,818✔
544
  Position r0_local;
667,264,818✔
545

546
  // In the first few iterations of the simulation, the source region
547
  // may not yet have had any ray crossings, in which case there will
548
  // be no estimate of its centroid. We detect this by checking if it has
549
  // any accumulated volume. If its volume is zero, just use the midpoint
550
  // of the ray as the region's centroid.
551
  if (srh.volume_t()) {
667,264,818✔
552
    rm_local = midpoint - centroid;
640,949,089✔
553
    r0_local = r - centroid;
640,949,089✔
554
  } else {
555
    rm_local = {0.0, 0.0, 0.0};
26,315,729✔
556
    r0_local = -u() * 0.5 * distance;
26,315,729✔
557
  }
558
  double distance_2 = distance * distance;
667,264,818✔
559

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

564
    // Compute tau, the optical thickness of the ray segment
565
    float sigma_t =
566
      domain_->sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
2,147,483,647✔
567
      srh.density_mult();
2,147,483,647✔
568
    float tau = sigma_t * distance;
2,147,483,647✔
569

570
    // If tau is very small, set it to zero to avoid numerical issues.
571
    // The following computations will still work with tau = 0.
572
    if (tau < 1.0e-8f) {
2,147,483,647✔
573
      tau = 0.0f;
5,874✔
574
    }
575

576
    // Compute linear source terms, spatial and directional (dir),
577
    // calculated from the source gradients dot product with local centroid
578
    // and direction, respectively.
579
    float spatial_source =
580
      srh.source(g) + rm_local.dot(srh.source_gradients(g));
2,147,483,647✔
581
    float dir_source = u().dot(srh.source_gradients(g));
2,147,483,647✔
582

583
    float gn = exponentialG(tau);
2,147,483,647✔
584
    float f1 = 1.0f - tau * gn;
2,147,483,647✔
585
    float f2 = (2.0f * gn - f1) * distance_2;
2,147,483,647✔
586
    float new_delta_psi = (angular_flux_[g] - spatial_source) * f1 * distance -
2,147,483,647✔
587
                          0.5 * dir_source * f2;
2,147,483,647✔
588

589
    float h1 = f1 - gn;
2,147,483,647✔
590
    float g1 = 0.5f - h1;
2,147,483,647✔
591
    float g2 = exponentialG2(tau);
2,147,483,647✔
592
    g1 = g1 * spatial_source;
2,147,483,647✔
593
    g2 = g2 * dir_source * distance * 0.5f;
2,147,483,647✔
594
    h1 = h1 * angular_flux_[g];
2,147,483,647✔
595
    h1 = (g1 + g2 + h1) * distance_2;
2,147,483,647✔
596
    spatial_source = spatial_source * distance + new_delta_psi;
2,147,483,647✔
597

598
    // Store contributions for this group into arrays, so that they can
599
    // be accumulated into the source region's estimates inside of the locked
600
    // region.
601
    delta_psi_[g] = new_delta_psi;
2,147,483,647✔
602
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
2,147,483,647✔
603

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

607
    // If 2D mode is enabled, the z-component of the flux moments is forced
608
    // to zero
609
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
2,147,483,647✔
610
      delta_moments_[g].z = 0.0;
462,208,043✔
611
    }
612
  }
613

614
  // Compute an estimate of the spatial moments matrix for the source
615
  // region based on parameters from this ray's crossing
616
  MomentMatrix moment_matrix_estimate;
617
  moment_matrix_estimate.compute_spatial_moments_matrix(
667,264,818✔
618
    rm_local, u(), distance);
667,264,818✔
619

620
  // Aquire lock for source region
621
  srh.lock();
667,264,818✔
622

623
  // If ray is in the active phase (not in dead zone), make contributions to
624
  // source region bookkeeping
625

626
  if (is_active) {
667,264,818✔
627
    // Accumulate deltas into the new estimate of source region flux for this
628
    // iteration
629
    for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
630
      srh.scalar_flux_new(g) += delta_psi_[g];
1,951,227,256✔
631
      srh.flux_moments_new(g) += delta_moments_[g];
1,951,227,256✔
632
    }
633

634
    // Accumulate the volume (ray segment distance), centroid, and spatial
635
    // momement estimates into the running totals for the iteration for this
636
    // source region. The centroid and spatial momements estimates are scaled
637
    // by the ray segment length as part of length averaging of the estimates.
638
    srh.volume() += distance;
546,952,890✔
639
    srh.centroid_iteration() += midpoint * distance;
546,952,890✔
640
    moment_matrix_estimate *= distance;
546,952,890✔
641
    srh.mom_matrix() += moment_matrix_estimate;
546,952,890✔
642

643
    srh.n_hits() += 1;
546,952,890✔
644
  }
645

646
  // Tally valid position inside the source region (e.g., midpoint of
647
  // the ray) if not done already
648
  if (!srh.position_recorded()) {
667,264,818✔
649
    srh.position() = midpoint;
810,854✔
650
    srh.position_recorded() = 1;
810,854✔
651
  }
652

653
  // Release lock
654
  srh.unlock();
667,264,818✔
655
}
667,264,818✔
656

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

671
  Position& centroid = srh.centroid();
8,287,235✔
672
  Position midpoint = r + u() * (distance / 2.0);
8,287,235✔
673

674
  // Determine the local position of the midpoint and the ray origin
675
  // relative to the source region's centroid
676
  Position rm_local;
8,287,235✔
677
  Position r0_local;
8,287,235✔
678

679
  // In the first few iterations of the simulation, the source region
680
  // may not yet have had any ray crossings, in which case there will
681
  // be no estimate of its centroid. We detect this by checking if it has
682
  // any accumulated volume. If its volume is zero, just use the midpoint
683
  // of the ray as the region's centroid.
684
  if (srh.volume_t()) {
8,287,235✔
685
    rm_local = midpoint - centroid;
8,084,186✔
686
    r0_local = r - centroid;
8,084,186✔
687
  } else {
688
    rm_local = {0.0, 0.0, 0.0};
203,049✔
689
    r0_local = -u() * 0.5 * distance;
203,049✔
690
  }
691
  double distance_2 = distance * distance;
8,287,235✔
692

693
  // Compared to linear flux attenuation through solid regions,
694
  // transport through a void region is greatly simplified. Here we
695
  // compute the updated flux moments.
696
  for (int g = 0; g < negroups_; g++) {
16,574,470✔
697
    float spatial_source = 0.f;
8,287,235✔
698
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,287,235!
699
      spatial_source = srh.external_source(g);
8,287,235✔
700
    }
701
    float new_delta_psi = (angular_flux_[g] - spatial_source) * distance;
8,287,235✔
702
    float h1 = 0.5f;
8,287,235✔
703
    h1 = h1 * angular_flux_[g];
8,287,235✔
704
    h1 = h1 * distance_2;
8,287,235✔
705
    spatial_source = spatial_source * distance + new_delta_psi;
8,287,235✔
706

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

712
    // If 2D mode is enabled, the z-component of the flux moments is forced
713
    // to zero
714
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
8,287,235!
UNCOV
715
      delta_moments_[g].z = 0.0;
×
716
    }
717
  }
718

719
  // If ray is in the active phase (not in dead zone), make contributions to
720
  // source region bookkeeping
721
  if (is_active) {
8,287,235✔
722
    // Compute an estimate of the spatial moments matrix for the source
723
    // region based on parameters from this ray's crossing
724
    MomentMatrix moment_matrix_estimate;
725
    moment_matrix_estimate.compute_spatial_moments_matrix(
6,892,402✔
726
      rm_local, u(), distance);
6,892,402✔
727

728
    // Aquire lock for source region
729
    srh.lock();
6,892,402✔
730

731
    // Accumulate delta psi into new estimate of source region flux for
732
    // this iteration, and update flux momements
733
    for (int g = 0; g < negroups_; g++) {
13,784,804✔
734
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,892,402✔
735
      srh.flux_moments_new(g) += delta_moments_[g];
6,892,402✔
736
    }
737

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

748
    // Tally valid position inside the source region (e.g., midpoint of
749
    // the ray) if not done already
750
    if (!srh.position_recorded()) {
6,892,402✔
751
      srh.position() = midpoint;
11,000✔
752
      srh.position_recorded() = 1;
11,000✔
753
    }
754

755
    srh.n_hits() += 1;
6,892,402✔
756

757
    // Release lock
758
    srh.unlock();
6,892,402✔
759
  }
760

761
  // Add source to incoming angular flux, assuming void region
762
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,287,235!
763
    for (int g = 0; g < negroups_; g++) {
16,574,470✔
764
      angular_flux_[g] += srh.external_source(g) * distance;
8,287,235✔
765
    }
766
  }
767
}
8,287,235✔
768

769
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
2,119,320✔
770
{
771
  domain_ = domain;
2,119,320✔
772
  ntemperature_ = domain->ntemperature_;
2,119,320✔
773

774
  // Reset particle event counter
775
  n_event() = 0;
2,119,320✔
776

777
  is_active_ = (distance_inactive_ <= 0.0);
2,119,320✔
778

779
  wgt() = 1.0;
2,119,320✔
780

781
  // set identifier for particle
782
  id() = ray_id;
2,119,320✔
783

784
  // generate source site using sample method
785
  SourceSite site;
2,119,320✔
786
  switch (sample_method_) {
2,119,320!
787
  case RandomRaySampleMethod::PRNG:
2,108,320✔
788
    site = sample_prng();
2,108,320✔
789
    break;
2,108,320✔
790
  case RandomRaySampleMethod::HALTON:
11,000✔
791
    site = sample_halton();
11,000✔
792
    break;
11,000✔
UNCOV
793
  default:
×
UNCOV
794
    fatal_error("Unknown sample method for random ray transport.");
×
795
  }
796

797
  site.E = 0.0;
2,119,320✔
798
  this->from_source(&site);
2,119,320✔
799

800
  // Locate ray
801
  if (lowest_coord().cell() == C_NONE) {
2,119,320!
802
    if (!exhaustive_find_cell(*this)) {
2,119,320!
UNCOV
803
      this->mark_as_lost(
×
UNCOV
804
        "Could not find the cell containing particle " + std::to_string(id()));
×
805
    }
806

807
    // Set birth cell attribute
808
    if (cell_born() == C_NONE)
2,119,320!
809
      cell_born() = lowest_coord().cell();
2,119,320✔
810
  }
811

812
  SourceRegionKey sr_key = domain_->lookup_source_region_key(*this);
2,119,320✔
813
  SourceRegionHandle srh =
814
    domain_->get_subdivided_source_region_handle(sr_key, r(), u());
2,119,320✔
815

816
  // Initialize ray's starting angular flux to starting location's isotropic
817
  // source
818
  if (!srh.is_numerical_fp_artifact_) {
2,119,320!
819
    for (int g = 0; g < negroups_; g++) {
8,309,360✔
820
      angular_flux_[g] = srh.source(g);
6,190,040✔
821
    }
822
  }
823
}
2,119,320✔
824

825
SourceSite RandomRay::sample_prng()
2,108,320✔
826
{
827
  // set random number seed
828
  int64_t particle_seed =
829
    (simulation::current_batch - 1) * settings::n_particles + id();
2,108,320✔
830
  init_particle_seeds(particle_seed, seeds());
2,108,320✔
831
  stream() = STREAM_TRACKING;
2,108,320✔
832

833
  // Sample from ray source distribution
834
  SourceSite site {ray_source_->sample(current_seed())};
2,108,320✔
835

836
  return site;
2,108,320✔
837
}
838

839
SourceSite RandomRay::sample_halton()
11,000✔
840
{
841
  SourceSite site;
11,000✔
842

843
  // Set random number seed
844
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
11,000✔
845
  int64_t skip = id();
11,000✔
846
  init_particle_seeds(batch_seed, seeds());
11,000✔
847
  stream() = STREAM_TRACKING;
11,000✔
848

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

852
  // Get spatial box of ray_source_
853
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
11,000!
854
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
11,000!
855

856
  // Sample spatial distribution
857
  Position xi {samples[0], samples[1], samples[2]};
11,000✔
858
  // make a small shift in position to avoid geometry floating point issues
859
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
11,000✔
860
  site.r = (sb->lower_left() + shift) +
861
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
11,000✔
862

863
  // Sample Polar cosine and azimuthal angles
864
  double mu = 2.0 * samples[3] - 1.0;
11,000✔
865
  double azi = 2.0 * PI * samples[4];
11,000✔
866
  // Convert to Cartesian coordinates
867
  double c = std::sqrt(1.0 - mu * mu);
11,000✔
868
  site.u.x = mu;
11,000✔
869
  site.u.y = std::cos(azi) * c;
11,000✔
870
  site.u.z = std::sin(azi) * c;
11,000✔
871

872
  return site;
22,000✔
873
}
11,000✔
874

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