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

openmc-dev / openmc / 20698018026

04 Jan 2026 07:31PM UTC coverage: 81.948% (-0.2%) from 82.174%
20698018026

Pull #3702

github

web-flow
Merge 08bff5d91 into 9c91bddf0
Pull Request #3702: Random Ray Kinetic Simulation Mode

17559 of 24377 branches covered (72.03%)

Branch coverage included in aggregate %.

885 of 1122 new or added lines in 19 files covered. (78.88%)

403 existing lines in 14 files now uncovered.

55921 of 65290 relevant lines covered (85.65%)

50692989.71 hits per line

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

81.42
/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_),
11,536,420✔
256
    delta_psi_prime_(data::mg.num_energy_groups_)
34,609,260✔
257

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

468
      // Time Derivative Characteristic Equation
NEW
469
      float new_delta_psi_prime = (angular_flux_prime_[g] - T1) * exponential;
×
NEW
470
      delta_psi_prime_[g] = new_delta_psi_prime;
×
NEW
471
      angular_flux_prime_[g] -= new_delta_psi_prime;
×
472
    }
UNCOV
473
    delta_psi_[g] = new_delta_psi;
×
UNCOV
474
    angular_flux_[g] -= new_delta_psi;
×
475
  }
476

477
  // If ray is in the active phase (not in dead zone), make contributions to
478
  // source region bookkeeping
479

480
  // Aquire lock for source region
481
  srh.lock();
2,147,483,647✔
482

483
  if (is_active) {
2,147,483,647✔
484
    // Accumulate delta psi into new estimate of source region flux for
485
    // this iteration
UNCOV
486
    for (int g = 0; g < negroups_; g++) {
×
UNCOV
487
      srh.scalar_flux_new(g) += delta_psi_[g];
×
488
    }
489

490
    // Accomulate volume (ray distance) into this iteration's estimate
491
    // of the source region's volume
492
    srh.volume() += distance;
2,147,483,647✔
493

494
    srh.n_hits() += 1;
2,147,483,647✔
495
  }
496

497
  // Tally valid position inside the source region (e.g., midpoint of
498
  // the ray) if not done already
499
  if (!srh.position_recorded()) {
2,147,483,647✔
500
    Position midpoint = r + u() * (distance / 2.0);
1,543,730✔
501
    srh.position() = midpoint;
1,543,730✔
502
    srh.position_recorded() = 1;
1,543,730✔
503
  }
504

505
  // Release lock
506
  srh.unlock();
2,147,483,647✔
507
}
2,147,483,647✔
508

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

517
  int material = srh.material();
8,367,713✔
518

519
  // If ray is in the active phase (not in dead zone), make contributions to
520
  // source region bookkeeping
521
  if (is_active) {
8,367,713✔
522

523
    // Aquire lock for source region
524
    srh.lock();
6,959,311✔
525

526
    // Accumulate delta psi into new estimate of source region flux for
527
    // this iteration
528
    for (int g = 0; g < negroups_; g++) {
13,972,386✔
529
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
7,013,075✔
530
    }
531

532
    // Accomulate volume (ray distance) into this iteration's estimate
533
    // of the source region's volume
534
    srh.volume() += distance;
6,959,311✔
535
    srh.volume_sq() += distance * distance;
6,959,311✔
536
    srh.n_hits() += 1;
6,959,311✔
537

538
    // Tally valid position inside the source region (e.g., midpoint of
539
    // the ray) if not done already
540
    if (!srh.position_recorded()) {
6,959,311✔
541
      Position midpoint = r + u() * (distance / 2.0);
11,152✔
542
      srh.position() = midpoint;
11,152✔
543
      srh.position_recorded() = 1;
11,152✔
544
    }
545

546
    // Release lock
547
    srh.unlock();
6,959,311✔
548
  }
549

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

558
void RandomRay::attenuate_flux_linear_source(
628,380,390✔
559
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
560
{
561
  // The number of geometric intersections is counted for reporting purposes
562
  n_event()++;
628,380,390✔
563

564
  int material = srh.material();
628,380,390✔
565

566
  Position& centroid = srh.centroid();
628,380,390✔
567
  Position midpoint = r + u() * (distance / 2.0);
628,380,390✔
568

569
  // Determine the local position of the midpoint and the ray origin
570
  // relative to the source region's centroid
571
  Position rm_local;
628,380,390✔
572
  Position r0_local;
628,380,390✔
573

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

588
  // Linear Source MOC incoming flux attenuation + source
589
  // contribution/attenuation equation
590
  for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
591

592
    // Compute tau, the optical thickness of the ray segment
593
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
2,147,483,647✔
594
    float tau = sigma_t * distance;
2,147,483,647✔
595

596
    // If tau is very small, set it to zero to avoid numerical issues.
597
    // The following computations will still work with tau = 0.
598
    if (tau < 1.0e-8f) {
2,147,483,647✔
599
      tau = 0.0f;
5,874✔
600
    }
601

602
    // Compute linear source terms, spatial and directional (dir),
603
    // calculated from the source gradients dot product with local centroid
604
    // and direction, respectively.
605
    float spatial_source =
606
      srh.source(g) + rm_local.dot(srh.source_gradients(g));
2,147,483,647✔
607
    float dir_source = u().dot(srh.source_gradients(g));
2,147,483,647✔
608

609
    float gn = exponentialG(tau);
2,147,483,647✔
610
    float f1 = 1.0f - tau * gn;
2,147,483,647✔
611
    float f2 = (2.0f * gn - f1) * distance_2;
2,147,483,647✔
612
    float new_delta_psi = (angular_flux_[g] - spatial_source) * f1 * distance -
2,147,483,647✔
613
                          0.5 * dir_source * f2;
2,147,483,647✔
614

615
    float h1 = f1 - gn;
2,147,483,647✔
616
    float g1 = 0.5f - h1;
2,147,483,647✔
617
    float g2 = exponentialG2(tau);
2,147,483,647✔
618
    g1 = g1 * spatial_source;
2,147,483,647✔
619
    g2 = g2 * dir_source * distance * 0.5f;
2,147,483,647✔
620
    h1 = h1 * angular_flux_[g];
2,147,483,647✔
621
    h1 = (g1 + g2 + h1) * distance_2;
2,147,483,647✔
622
    spatial_source = spatial_source * distance + new_delta_psi;
2,147,483,647✔
623

624
    // Store contributions for this group into arrays, so that they can
625
    // be accumulated into the source region's estimates inside of the locked
626
    // region.
627
    delta_psi_[g] = new_delta_psi;
2,147,483,647✔
628
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
2,147,483,647✔
629

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

633
    // If 2D mode is enabled, the z-component of the flux moments is forced
634
    // to zero
635
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
2,147,483,647✔
636
      delta_moments_[g].z = 0.0;
462,208,043✔
637
    }
638
  }
639

640
  // Compute an estimate of the spatial moments matrix for the source
641
  // region based on parameters from this ray's crossing
642
  MomentMatrix moment_matrix_estimate;
643
  moment_matrix_estimate.compute_spatial_moments_matrix(
628,380,390✔
644
    rm_local, u(), distance);
628,380,390✔
645

646
  // Aquire lock for source region
647
  srh.lock();
628,380,390✔
648

649
  // If ray is in the active phase (not in dead zone), make contributions to
650
  // source region bookkeeping
651

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

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

669
    srh.n_hits() += 1;
514,578,966✔
670
  }
671

672
  // Tally valid position inside the source region (e.g., midpoint of
673
  // the ray) if not done already
674
  if (!srh.position_recorded()) {
628,380,390✔
675
    srh.position() = midpoint;
810,062✔
676
    srh.position_recorded() = 1;
810,062✔
677
  }
678

679
  // Release lock
680
  srh.unlock();
628,380,390✔
681
}
628,380,390✔
682

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

697
  Position& centroid = srh.centroid();
8,287,235✔
698
  Position midpoint = r + u() * (distance / 2.0);
8,287,235✔
699

700
  // Determine the local position of the midpoint and the ray origin
701
  // relative to the source region's centroid
702
  Position rm_local;
8,287,235✔
703
  Position r0_local;
8,287,235✔
704

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

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

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

738
    // If 2D mode is enabled, the z-component of the flux moments is forced
739
    // to zero
740
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
8,287,235!
741
      delta_moments_[g].z = 0.0;
×
742
    }
743
  }
744

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

754
    // Aquire lock for source region
755
    srh.lock();
6,892,402✔
756

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

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

774
    // Tally valid position inside the source region (e.g., midpoint of
775
    // the ray) if not done already
776
    if (!srh.position_recorded()) {
6,892,402✔
777
      srh.position() = midpoint;
11,000✔
778
      srh.position_recorded() = 1;
11,000✔
779
    }
780

781
    srh.n_hits() += 1;
6,892,402✔
782

783
    // Release lock
784
    srh.unlock();
6,892,402✔
785
  }
786

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

795
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
11,536,420✔
796
{
797
  domain_ = domain;
11,536,420✔
798

799
  // Reset particle event counter
800
  n_event() = 0;
11,536,420✔
801

802
  is_active_ = (distance_inactive_ <= 0.0);
11,536,420✔
803

804
  wgt() = 1.0;
11,536,420✔
805

806
  // set identifier for particle
807
  id() = ray_id;
11,536,420✔
808

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

822
  site.E = 0.0;
11,536,420✔
823
  this->from_source(&site);
11,536,420✔
824

825
  // Locate ray
826
  if (lowest_coord().cell() == C_NONE) {
11,536,420!
827
    if (!exhaustive_find_cell(*this)) {
11,536,420!
828
      this->mark_as_lost(
×
829
        "Could not find the cell containing particle " + std::to_string(id()));
×
830
    }
831

832
    // Set birth cell attribute
833
    if (cell_born() == C_NONE)
11,536,420!
834
      cell_born() = lowest_coord().cell();
11,536,420✔
835
  }
836

837
  SourceRegionKey sr_key = domain_->lookup_source_region_key(*this);
11,536,420✔
838
  SourceRegionHandle srh =
839
    domain_->get_subdivided_source_region_handle(sr_key, r(), u());
11,536,420✔
840

841
  // Initialize ray's starting angular flux to starting location's isotropic
842
  // source
843
  if (!srh.is_numerical_fp_artifact_) {
11,536,420!
844
    for (int g = 0; g < negroups_; g++) {
92,582,560✔
845
      angular_flux_[g] = srh.source(g);
81,046,140✔
846
    }
847
    if (settings::kinetic_simulation && !simulation::is_initial_condition &&
11,536,420✔
848
        RandomRay::time_method_ == RandomRayTimeMethod::PROPAGATION) {
6,875,000!
NEW
849
      for (int g = 0; g < negroups_; g++) {
×
NEW
850
        double source_derivative = srh.source_time_derivative(g);
×
NEW
851
        double flux_derivative_2 = srh.scalar_flux_time_derivative_2(g);
×
852
        // T1
NEW
853
        angular_flux_prime_[g] = source_derivative - flux_derivative_2;
×
854
      }
855
    }
856
  }
857
}
11,536,420✔
858

859
SourceSite RandomRay::sample_prng()
11,525,420✔
860
{
861
  // set random number seed
862
  int64_t particle_seed =
863
    (simulation::current_batch - 1) * settings::n_particles + id();
11,525,420✔
864
  init_particle_seeds(particle_seed, seeds());
11,525,420✔
865
  stream() = STREAM_TRACKING;
11,525,420✔
866

867
  // Sample from ray source distribution
868
  SourceSite site {ray_source_->sample(current_seed())};
11,525,420✔
869

870
  return site;
11,525,420✔
871
}
872

873
SourceSite RandomRay::sample_halton()
11,000✔
874
{
875
  SourceSite site;
11,000✔
876

877
  // Set random number seed
878
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
11,000✔
879
  int64_t skip = id();
11,000✔
880
  init_particle_seeds(batch_seed, seeds());
11,000✔
881
  stream() = STREAM_TRACKING;
11,000✔
882

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

886
  // Get spatial box of ray_source_
887
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
11,000!
888
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
11,000!
889

890
  // Sample spatial distribution
891
  Position xi {samples[0], samples[1], samples[2]};
11,000✔
892
  // make a small shift in position to avoid geometry floating point issues
893
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
11,000✔
894
  site.r = (sb->lower_left() + shift) +
895
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
11,000✔
896

897
  // Sample Polar cosine and azimuthal angles
898
  double mu = 2.0 * samples[3] - 1.0;
11,000✔
899
  double azi = 2.0 * PI * samples[4];
11,000✔
900
  // Convert to Cartesian coordinates
901
  double c = std::sqrt(1.0 - mu * mu);
11,000✔
902
  site.u.x = mu;
11,000✔
903
  site.u.y = std::cos(azi) * c;
11,000✔
904
  site.u.z = std::sin(azi) * c;
11,000✔
905

906
  return site;
22,000✔
907
}
11,000✔
908

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