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

openmc-dev / openmc / 21887062786

10 Feb 2026 11:55PM UTC coverage: 81.899% (-0.1%) from 82.009%
21887062786

Pull #3493

github

web-flow
Merge 320b68711 into 3f20a5e22
Pull Request #3493: Implement vector fitting to replace external `vectfit` package

17361 of 24292 branches covered (71.47%)

Branch coverage included in aggregate %.

185 of 218 new or added lines in 3 files covered. (84.86%)

2770 existing lines in 69 files now uncovered.

56369 of 65733 relevant lines covered (85.75%)

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

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

45
  float x = -tau;
1,764,563,138✔
46

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

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

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

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

119
  float x = tau;
2,195,441,820✔
120

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

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

136
  return num / den;
2,195,441,820✔
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,195,441,820✔
145
{
146

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

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

161
  float x = tau;
2,195,441,820✔
162

163
  float num = g5n;
2,195,441,820✔
164
  num = num * x + g4n;
2,195,441,820✔
165
  num = num * x + g3n;
2,195,441,820✔
166
  num = num * x + g2n;
2,195,441,820✔
167
  num = num * x + g1n;
2,195,441,820✔
168
  num = num * x;
2,195,441,820✔
169

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

177
  return num / den;
2,195,441,820✔
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,926,720✔
243
  : angular_flux_(data::mg.num_energy_groups_),
1,926,720✔
244
    delta_psi_(data::mg.num_energy_groups_),
1,926,720✔
245
    negroups_(data::mg.num_energy_groups_)
5,780,160✔
246
{
247
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
1,926,720✔
248
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
1,079,720✔
249
    delta_moments_.resize(negroups_);
960,500✔
250
  }
251
}
1,926,720✔
252

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

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

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

285
  // Find the distance to the nearest boundary
286
  boundary() = distance_to_boundary(*this);
851,247,608✔
287
  double distance = boundary().distance();
851,247,608✔
288

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

295
  if (is_active_) {
851,247,608✔
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_) {
692,504,760✔
301
      distance = distance_active_ - distance_travelled_;
1,926,720✔
302
      wgt() = 0.0;
1,926,720✔
303
    }
304

305
    distance_travelled_ += distance;
692,504,760✔
306
    attenuate_flux(distance, true);
692,504,760✔
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_) {
158,742,848✔
314
      is_active_ = true;
1,926,720✔
315
      double distance_dead = distance_inactive_ - distance_travelled_;
1,926,720✔
316
      attenuate_flux(distance_dead, false);
1,926,720✔
317

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

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

326
      attenuate_flux(distance_alive, true, distance_dead);
1,926,720✔
327
      distance_travelled_ = distance_alive;
1,926,720✔
328
    } else {
329
      distance_travelled_ += distance;
156,816,128✔
330
      attenuate_flux(distance, false);
156,816,128✔
331
    }
332
  }
333

334
  // Advance particle
335
  for (int j = 0; j < n_coord(); ++j) {
2,474,626,650✔
336
    coord(j).r() += distance * coord(j).u();
2,389,479,049✔
337
  }
338
}
339

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

349
  if (mesh_idx == C_NONE) {
853,174,328✔
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());
422,000,190✔
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();
431,174,138✔
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();
431,174,138✔
365
    Position end = start + (distance - 2.0 * TINY_BIT) * u();
431,174,138✔
366
    double reduced_distance = (end - start).norm();
431,174,138✔
367

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

373
    // Loop over all mesh bins and attenuate flux
374
    for (int b = 0; b < mesh_bins_.size(); b++) {
1,281,410,428✔
375
      double physical_length = reduced_distance * mesh_fractional_lengths_[b];
850,236,290✔
376
      attenuate_flux_inner(
850,236,290✔
377
        physical_length, is_active, sr, mesh_bins_[b], start);
850,236,290✔
378
      start += physical_length * u();
850,236,290✔
379
    }
380
  }
381
}
853,174,328✔
382

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

393
  switch (source_shape_) {
1,272,236,400!
394
  case RandomRaySourceShape::FLAT:
658,098,170✔
395
    if (srh.material() == MATERIAL_VOID) {
658,098,170✔
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);
650,485,244✔
399
    }
400
    break;
658,098,170✔
401
  case RandomRaySourceShape::LINEAR:
614,138,230✔
402
  case RandomRaySourceShape::LINEAR_XY:
403
    if (srh.material() == MATERIAL_VOID) {
614,138,230✔
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);
606,604,380✔
407
    }
408
    break;
614,138,230✔
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(
650,485,244✔
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()++;
650,485,244✔
432

433
  // Get material
434
  int material = srh.material();
650,485,244✔
435
  int temp = srh.temperature_idx();
650,485,244✔
436

437
  // MOC incoming flux attenuation + source contribution/attenuation equation
438
  for (int g = 0; g < negroups_; g++) {
2,389,013,579✔
439
    float sigma_t =
440
      domain_->sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] *
1,764,563,138✔
441
      srh.density_mult();
1,764,563,138✔
442
    float tau = sigma_t * distance;
1,764,563,138✔
443
    float exponential = cjosey_exponential(tau); // exponential = 1 - exp(-tau)
1,764,563,138✔
444
    float new_delta_psi = (angular_flux_[g] - srh.source(g)) * exponential;
1,764,563,138✔
445
    delta_psi_[g] = new_delta_psi;
1,764,563,138✔
446
    angular_flux_[g] -= new_delta_psi;
1,764,563,138✔
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();
650,485,244✔
454

455
  if (is_active) {
650,485,244✔
456
    // Accumulate delta psi into new estimate of source region flux for
457
    // this iteration
458
    for (int g = 0; g < negroups_; g++) {
1,949,240,546✔
459
      srh.scalar_flux_new(g) += delta_psi_[g];
1,415,420,044✔
460
    }
461

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

466
    srh.n_hits() += 1;
533,820,502✔
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()) {
650,485,244✔
472
    Position midpoint = r + u() * (distance / 2.0);
1,394,343✔
473
    srh.position() = midpoint;
1,394,343✔
474
    srh.position_recorded() = 1;
1,394,343✔
475
  }
476

477
  // Release lock
478
  srh.unlock();
650,485,244✔
479
}
650,485,244✔
480

481
// Alternative flux attenuation function for true void regions.
482
void RandomRay::attenuate_flux_flat_source_void(
7,612,926✔
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()++;
7,612,926✔
487

488
  int material = srh.material();
7,612,926✔
489

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

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

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

503
    // Accomulate volume (ray distance) into this iteration's estimate
504
    // of the source region's volume
505
    srh.volume() += distance;
6,331,534✔
506
    srh.volume_sq() += distance * distance;
6,331,534✔
507
    srh.n_hits() += 1;
6,331,534✔
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,331,534✔
512
      Position midpoint = r + u() * (distance / 2.0);
10,144✔
513
      srh.position() = midpoint;
10,144✔
514
      srh.position_recorded() = 1;
10,144✔
515
    }
516

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

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

529
void RandomRay::attenuate_flux_linear_source(
606,604,380✔
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()++;
606,604,380✔
534

535
  int material = srh.material();
606,604,380✔
536
  int temp = srh.temperature_idx();
606,604,380✔
537

538
  Position& centroid = srh.centroid();
606,604,380✔
539
  Position midpoint = r + u() * (distance / 2.0);
606,604,380✔
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;
606,604,380✔
544
  Position r0_local;
606,604,380✔
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()) {
606,604,380✔
552
    rm_local = midpoint - centroid;
582,680,990✔
553
    r0_local = r - centroid;
582,680,990✔
554
  } else {
555
    rm_local = {0.0, 0.0, 0.0};
23,923,390✔
556
    r0_local = -u() * 0.5 * distance;
23,923,390✔
557
  }
558
  double distance_2 = distance * distance;
606,604,380✔
559

560
  // Linear Source MOC incoming flux attenuation + source
561
  // contribution/attenuation equation
562
  for (int g = 0; g < negroups_; g++) {
2,427,688,267✔
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,195,441,820✔
567
      srh.density_mult();
2,195,441,820✔
568
    float tau = sigma_t * distance;
2,195,441,820✔
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,195,441,820✔
573
      tau = 0.0f;
5,340✔
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,195,441,820✔
581
    float dir_source = u().dot(srh.source_gradients(g));
2,195,441,820✔
582

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

589
    float h1 = f1 - gn;
2,195,441,820✔
590
    float g1 = 0.5f - h1;
2,195,441,820✔
591
    float g2 = exponentialG2(tau);
2,195,441,820✔
592
    g1 = g1 * spatial_source;
2,195,441,820✔
593
    g2 = g2 * dir_source * distance * 0.5f;
2,195,441,820✔
594
    h1 = h1 * angular_flux_[g];
2,195,441,820✔
595
    h1 = (g1 + g2 + h1) * distance_2;
2,195,441,820✔
596
    spatial_source = spatial_source * distance + new_delta_psi;
2,195,441,820✔
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,195,441,820✔
602
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
2,195,441,820✔
603

604
    // Update the angular flux for this group
605
    angular_flux_[g] -= new_delta_psi * sigma_t;
2,195,441,820✔
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,195,441,820✔
610
      delta_moments_[g].z = 0.0;
420,189,130✔
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(
606,604,380✔
618
    rm_local, u(), distance);
606,604,380✔
619

620
  // Aquire lock for source region
621
  srh.lock();
606,604,380✔
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) {
606,604,380✔
627
    // Accumulate deltas into the new estimate of source region flux for this
628
    // iteration
629
    for (int g = 0; g < negroups_; g++) {
2,271,072,860✔
630
      srh.scalar_flux_new(g) += delta_psi_[g];
1,773,842,960✔
631
      srh.flux_moments_new(g) += delta_moments_[g];
1,773,842,960✔
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;
497,229,900✔
639
    srh.centroid_iteration() += midpoint * distance;
497,229,900✔
640
    moment_matrix_estimate *= distance;
497,229,900✔
641
    srh.mom_matrix() += moment_matrix_estimate;
497,229,900✔
642

643
    srh.n_hits() += 1;
497,229,900✔
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()) {
606,604,380✔
649
    srh.position() = midpoint;
737,140✔
650
    srh.position_recorded() = 1;
737,140✔
651
  }
652

653
  // Release lock
654
  srh.unlock();
606,604,380✔
655
}
606,604,380✔
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(
7,533,850✔
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()++;
7,533,850✔
670

671
  Position& centroid = srh.centroid();
7,533,850✔
672
  Position midpoint = r + u() * (distance / 2.0);
7,533,850✔
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;
7,533,850✔
677
  Position r0_local;
7,533,850✔
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()) {
7,533,850✔
685
    rm_local = midpoint - centroid;
7,349,260✔
686
    r0_local = r - centroid;
7,349,260✔
687
  } else {
688
    rm_local = {0.0, 0.0, 0.0};
184,590✔
689
    r0_local = -u() * 0.5 * distance;
184,590✔
690
  }
691
  double distance_2 = distance * distance;
7,533,850✔
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++) {
15,067,700✔
697
    float spatial_source = 0.f;
7,533,850✔
698
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
7,533,850!
699
      spatial_source = srh.external_source(g);
7,533,850✔
700
    }
701
    float new_delta_psi = (angular_flux_[g] - spatial_source) * distance;
7,533,850✔
702
    float h1 = 0.5f;
7,533,850✔
703
    h1 = h1 * angular_flux_[g];
7,533,850✔
704
    h1 = h1 * distance_2;
7,533,850✔
705
    spatial_source = spatial_source * distance + new_delta_psi;
7,533,850✔
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;
7,533,850✔
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) {
7,533,850!
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) {
7,533,850✔
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,265,820✔
726
      rm_local, u(), distance);
6,265,820✔
727

728
    // Aquire lock for source region
729
    srh.lock();
6,265,820✔
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++) {
12,531,640✔
734
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,265,820✔
735
      srh.flux_moments_new(g) += delta_moments_[g];
6,265,820✔
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,265,820✔
743
    srh.volume_sq() += distance_2;
6,265,820✔
744
    srh.centroid_iteration() += midpoint * distance;
6,265,820✔
745
    moment_matrix_estimate *= distance;
6,265,820✔
746
    srh.mom_matrix() += moment_matrix_estimate;
6,265,820✔
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,265,820✔
751
      srh.position() = midpoint;
10,000✔
752
      srh.position_recorded() = 1;
10,000✔
753
    }
754

755
    srh.n_hits() += 1;
6,265,820✔
756

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

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

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

774
  // Reset particle event counter
775
  n_event() = 0;
1,926,720✔
776

777
  is_active_ = (distance_inactive_ <= 0.0);
1,926,720✔
778

779
  wgt() = 1.0;
1,926,720✔
780

781
  // set identifier for particle
782
  id() = ray_id;
1,926,720✔
783

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

797
  site.E = 0.0;
1,926,720✔
798
  this->from_source(&site);
1,926,720✔
799

800
  // Locate ray
801
  if (lowest_coord().cell() == C_NONE) {
1,926,720!
802
    if (!exhaustive_find_cell(*this)) {
1,926,720!
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)
1,926,720!
809
      cell_born() = lowest_coord().cell();
1,926,720✔
810
  }
811

812
  SourceRegionKey sr_key = domain_->lookup_source_region_key(*this);
1,926,720✔
813
  SourceRegionHandle srh =
814
    domain_->get_subdivided_source_region_handle(sr_key, r(), u());
1,926,720✔
815

816
  // Initialize ray's starting angular flux to starting location's isotropic
817
  // source
818
  if (!srh.is_numerical_fp_artifact_) {
1,926,720!
819
    for (int g = 0; g < negroups_; g++) {
7,554,160✔
820
      angular_flux_[g] = srh.source(g);
5,627,440✔
821
    }
822
  }
823
}
1,926,720✔
824

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

833
  // Sample from ray source distribution
834
  SourceSite site {ray_source_->sample(current_seed())};
1,916,720✔
835

836
  return site;
1,916,720✔
837
}
838

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

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

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

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

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

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

872
  return site;
20,000✔
873
}
10,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