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

openmc-dev / openmc / 15618759193

12 Jun 2025 06:59PM UTC coverage: 85.165% (+0.007%) from 85.158%
15618759193

Pull #3436

github

web-flow
Merge f2964f7dc into 6c9c69628
Pull Request #3436: Allowing chain_file to be chain object to save reloading time

18 of 22 new or added lines in 4 files covered. (81.82%)

374 existing lines in 7 files now uncovered.

52385 of 61510 relevant lines covered (85.17%)

36774825.05 hits per line

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

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

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

45
  float x = -tau;
1,139,144,567✔
46

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

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

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

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

119
  float x = tau;
2,129,833,530✔
120

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

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

136
  return num / den;
2,129,833,530✔
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,129,833,530✔
145
{
146

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

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

161
  float x = tau;
2,129,833,530✔
162

163
  float num = g5n;
2,129,833,530✔
164
  num = num * x + g4n;
2,129,833,530✔
165
  num = num * x + g3n;
2,129,833,530✔
166
  num = num * x + g2n;
2,129,833,530✔
167
  num = num * x + g1n;
2,129,833,530✔
168
  num = num * x;
2,129,833,530✔
169

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

177
  return num / den;
2,129,833,530✔
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
bool RandomRay::mesh_subdivision_enabled_ {false};
241
RandomRaySampleMethod RandomRay::sample_method_ {RandomRaySampleMethod::PRNG};
242

243
RandomRay::RandomRay()
1,856,800✔
244
  : angular_flux_(data::mg.num_energy_groups_),
1,856,800✔
245
    delta_psi_(data::mg.num_energy_groups_),
1,856,800✔
246
    negroups_(data::mg.num_energy_groups_)
5,570,400✔
247
{
248
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
1,856,800✔
249
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
1,035,100✔
250
    delta_moments_.resize(negroups_);
946,550✔
251
  }
252
}
1,856,800✔
253

254
RandomRay::RandomRay(uint64_t ray_id, FlatSourceDomain* domain) : RandomRay()
1,856,800✔
255
{
256
  initialize_ray(ray_id, domain);
1,856,800✔
257
}
1,856,800✔
258

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

276
  return n_event();
1,856,800✔
277
}
278

279
// Transports ray across a single source region
280
void RandomRay::event_advance_ray()
766,782,115✔
281
{
282
  // Find the distance to the nearest boundary
283
  boundary() = distance_to_boundary(*this);
766,782,115✔
284
  double distance = boundary().distance;
766,782,115✔
285

286
  if (distance < 0.0) {
766,782,115✔
UNCOV
287
    mark_as_lost("Negative transport distance detected for particle " +
×
UNCOV
288
                 std::to_string(id()));
×
UNCOV
289
    return;
×
290
  }
291

292
  if (is_active_) {
766,782,115✔
293
    // If the ray is in the active length, need to check if it has
294
    // reached its maximum termination distance. If so, reduce
295
    // the ray traced length so that the ray does not overrun the
296
    // maximum numerical length (so as to avoid numerical bias).
297
    if (distance_travelled_ + distance >= distance_active_) {
620,621,430✔
298
      distance = distance_active_ - distance_travelled_;
1,856,800✔
299
      wgt() = 0.0;
1,856,800✔
300
    }
301

302
    distance_travelled_ += distance;
620,621,430✔
303
    attenuate_flux(distance, true);
620,621,430✔
304
  } else {
305
    // If the ray is still in the dead zone, need to check if it
306
    // has entered the active phase. If so, split into two segments (one
307
    // representing the final part of the dead zone, the other representing the
308
    // first part of the active length) and attenuate each. Otherwise, if the
309
    // full length of the segment is within the dead zone, attenuate as normal.
310
    if (distance_travelled_ + distance >= distance_inactive_) {
146,160,685✔
311
      is_active_ = true;
1,856,800✔
312
      double distance_dead = distance_inactive_ - distance_travelled_;
1,856,800✔
313
      attenuate_flux(distance_dead, false);
1,856,800✔
314

315
      double distance_alive = distance - distance_dead;
1,856,800✔
316

317
      // Ensure we haven't travelled past the active phase as well
318
      if (distance_alive > distance_active_) {
1,856,800✔
UNCOV
319
        distance_alive = distance_active_;
×
UNCOV
320
        wgt() = 0.0;
×
321
      }
322

323
      attenuate_flux(distance_alive, true, distance_dead);
1,856,800✔
324
      distance_travelled_ = distance_alive;
1,856,800✔
325
    } else {
326
      distance_travelled_ += distance;
144,303,885✔
327
      attenuate_flux(distance, false);
144,303,885✔
328
    }
329
  }
330

331
  // Advance particle
332
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
333
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
334
  }
335
}
336

337
void RandomRay::attenuate_flux(double distance, bool is_active, double offset)
768,638,915✔
338
{
339
  // Determine source region index etc.
340
  int i_cell = lowest_coord().cell;
768,638,915✔
341

342
  // The base source region is the spatial region index
343
  int64_t sr = domain_->source_region_offsets_[i_cell] + cell_instance();
768,638,915✔
344

345
  // Perform ray tracing across mesh
346
  if (mesh_subdivision_enabled_) {
768,638,915✔
347
    // Determine the mesh index for the base source region, if any
348
    int mesh_idx = domain_->base_source_regions_.mesh(sr);
425,121,774✔
349

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

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

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

374
      // Loop over all mesh bins and attenuate flux
375
      for (int b = 0; b < mesh_bins_.size(); b++) {
1,295,492,528✔
376
        double physical_length = reduced_distance * mesh_fractional_lengths_[b];
870,370,754✔
377
        attenuate_flux_inner(
870,370,754✔
378
          physical_length, is_active, sr, mesh_bins_[b], start);
870,370,754✔
379
        start += physical_length * u();
870,370,754✔
380
      }
381
    }
382
  } else {
383
    attenuate_flux_inner(distance, is_active, sr, C_NONE, r());
343,517,141✔
384
  }
385
}
768,638,915✔
386

387
void RandomRay::attenuate_flux_inner(
1,213,887,895✔
388
  double distance, bool is_active, int64_t sr, int mesh_bin, Position r)
389
{
390
  SourceRegionHandle srh;
1,213,887,895✔
391
  if (mesh_subdivision_enabled_) {
1,213,887,895✔
392
    srh = domain_->get_subdivided_source_region_handle(
870,370,754✔
393
      sr, mesh_bin, r, distance, u());
870,370,754✔
394
    if (srh.is_numerical_fp_artifact_) {
870,370,754✔
395
      return;
88✔
396
    }
397
  } else {
398
    srh = domain_->source_regions_.get_source_region_handle(sr);
343,517,141✔
399
  }
400

401
  switch (source_shape_) {
1,213,887,807✔
402
  case RandomRaySourceShape::FLAT:
603,143,134✔
403
    if (this->material() == MATERIAL_VOID) {
603,143,134✔
404
      attenuate_flux_flat_source_void(srh, distance, is_active, r);
8,287,235✔
405
    } else {
406
      attenuate_flux_flat_source(srh, distance, is_active, r);
594,855,899✔
407
    }
408
    break;
603,143,134✔
409
  case RandomRaySourceShape::LINEAR:
610,744,673✔
410
  case RandomRaySourceShape::LINEAR_XY:
411
    if (this->material() == MATERIAL_VOID) {
610,744,673✔
412
      attenuate_flux_linear_source_void(srh, distance, is_active, r);
8,287,235✔
413
    } else {
414
      attenuate_flux_linear_source(srh, distance, is_active, r);
602,457,438✔
415
    }
416
    break;
610,744,673✔
UNCOV
417
  default:
×
UNCOV
418
    fatal_error("Unknown source shape for random ray transport.");
×
419
  }
420
}
421

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

441
  // Get material
442
  int material = this->material();
594,855,899✔
443

444
  // MOC incoming flux attenuation + source contribution/attenuation equation
445
  for (int g = 0; g < negroups_; g++) {
1,734,000,466✔
446
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
1,139,144,567✔
447
    float tau = sigma_t * distance;
1,139,144,567✔
448
    float exponential = cjosey_exponential(tau); // exponential = 1 - exp(-tau)
1,139,144,567✔
449
    float new_delta_psi = (angular_flux_[g] - srh.source(g)) * exponential;
1,139,144,567✔
450
    delta_psi_[g] = new_delta_psi;
1,139,144,567✔
451
    angular_flux_[g] -= new_delta_psi;
1,139,144,567✔
452
  }
453

454
  // If ray is in the active phase (not in dead zone), make contributions to
455
  // source region bookkeeping
456

457
  // Aquire lock for source region
458
  srh.lock();
594,855,899✔
459

460
  if (is_active) {
594,855,899✔
461
    // Accumulate delta psi into new estimate of source region flux for
462
    // this iteration
463
    for (int g = 0; g < negroups_; g++) {
1,376,067,858✔
464
      srh.scalar_flux_new(g) += delta_psi_[g];
889,333,203✔
465
    }
466

467
    // Accomulate volume (ray distance) into this iteration's estimate
468
    // of the source region's volume
469
    srh.volume() += distance;
486,734,655✔
470

471
    srh.n_hits() += 1;
486,734,655✔
472
  }
473

474
  // Tally valid position inside the source region (e.g., midpoint of
475
  // the ray) if not done already
476
  if (!srh.position_recorded()) {
594,855,899✔
477
    Position midpoint = r + u() * (distance / 2.0);
1,530,628✔
478
    srh.position() = midpoint;
1,530,628✔
479
    srh.position_recorded() = 1;
1,530,628✔
480
  }
481

482
  // Release lock
483
  srh.unlock();
594,855,899✔
484
}
594,855,899✔
485

486
// Alternative flux attenuation function for true void regions.
487
void RandomRay::attenuate_flux_flat_source_void(
8,287,235✔
488
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
489
{
490
  // The number of geometric intersections is counted for reporting purposes
491
  n_event()++;
8,287,235✔
492

493
  int material = this->material();
8,287,235✔
494

495
  // If ray is in the active phase (not in dead zone), make contributions to
496
  // source region bookkeeping
497
  if (is_active) {
8,287,235✔
498

499
    // Aquire lock for source region
500
    srh.lock();
6,892,402✔
501

502
    // Accumulate delta psi into new estimate of source region flux for
503
    // this iteration
504
    for (int g = 0; g < negroups_; g++) {
13,784,804✔
505
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
6,892,402✔
506
    }
507

508
    // Accomulate volume (ray distance) into this iteration's estimate
509
    // of the source region's volume
510
    srh.volume() += distance;
6,892,402✔
511
    srh.volume_sq() += distance * distance;
6,892,402✔
512
    srh.n_hits() += 1;
6,892,402✔
513

514
    // Tally valid position inside the source region (e.g., midpoint of
515
    // the ray) if not done already
516
    if (!srh.position_recorded()) {
6,892,402✔
517
      Position midpoint = r + u() * (distance / 2.0);
11,000✔
518
      srh.position() = midpoint;
11,000✔
519
      srh.position_recorded() = 1;
11,000✔
520
    }
521

522
    // Release lock
523
    srh.unlock();
6,892,402✔
524
  }
525

526
  // Add source to incoming angular flux, assuming void region
527
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
8,287,235✔
528
    for (int g = 0; g < negroups_; g++) {
16,574,470✔
529
      angular_flux_[g] += srh.external_source(g) * distance;
8,287,235✔
530
    }
531
  }
532
}
8,287,235✔
533

534
void RandomRay::attenuate_flux_linear_source(
602,457,438✔
535
  SourceRegionHandle& srh, double distance, bool is_active, Position r)
536
{
537
  // The number of geometric intersections is counted for reporting purposes
538
  n_event()++;
602,457,438✔
539

540
  int material = this->material();
602,457,438✔
541

542
  Position& centroid = srh.centroid();
602,457,438✔
543
  Position midpoint = r + u() * (distance / 2.0);
602,457,438✔
544

545
  // Determine the local position of the midpoint and the ray origin
546
  // relative to the source region's centroid
547
  Position rm_local;
602,457,438✔
548
  Position r0_local;
602,457,438✔
549

550
  // In the first few iterations of the simulation, the source region
551
  // may not yet have had any ray crossings, in which case there will
552
  // be no estimate of its centroid. We detect this by checking if it has
553
  // any accumulated volume. If its volume is zero, just use the midpoint
554
  // of the ray as the region's centroid.
555
  if (srh.volume_t()) {
602,457,438✔
556
    rm_local = midpoint - centroid;
582,612,899✔
557
    r0_local = r - centroid;
582,612,899✔
558
  } else {
559
    rm_local = {0.0, 0.0, 0.0};
19,844,539✔
560
    r0_local = -u() * 0.5 * distance;
19,844,539✔
561
  }
562
  double distance_2 = distance * distance;
602,457,438✔
563

564
  // Linear Source MOC incoming flux attenuation + source
565
  // contribution/attenuation equation
566
  for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
567

568
    // Compute tau, the optical thickness of the ray segment
569
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
2,129,833,530✔
570
    float tau = sigma_t * distance;
2,129,833,530✔
571

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

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

585
    float gn = exponentialG(tau);
2,129,833,530✔
586
    float f1 = 1.0f - tau * gn;
2,129,833,530✔
587
    float f2 = (2.0f * gn - f1) * distance_2;
2,129,833,530✔
588
    float new_delta_psi = (angular_flux_[g] - spatial_source) * f1 * distance -
2,129,833,530✔
589
                          0.5 * dir_source * f2;
2,129,833,530✔
590

591
    float h1 = f1 - gn;
2,129,833,530✔
592
    float g1 = 0.5f - h1;
2,129,833,530✔
593
    float g2 = exponentialG2(tau);
2,129,833,530✔
594
    g1 = g1 * spatial_source;
2,129,833,530✔
595
    g2 = g2 * dir_source * distance * 0.5f;
2,129,833,530✔
596
    h1 = h1 * angular_flux_[g];
2,129,833,530✔
597
    h1 = (g1 + g2 + h1) * distance_2;
2,129,833,530✔
598
    spatial_source = spatial_source * distance + new_delta_psi;
2,129,833,530✔
599

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

606
    // Update the angular flux for this group
607
    angular_flux_[g] -= new_delta_psi * sigma_t;
2,129,833,530✔
608

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

616
  // Compute an estimate of the spatial moments matrix for the source
617
  // region based on parameters from this ray's crossing
618
  MomentMatrix moment_matrix_estimate;
619
  moment_matrix_estimate.compute_spatial_moments_matrix(
602,457,438✔
620
    rm_local, u(), distance);
602,457,438✔
621

622
  // Aquire lock for source region
623
  srh.lock();
602,457,438✔
624

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

628
  if (is_active) {
602,457,438✔
629
    // Accumulate deltas into the new estimate of source region flux for this
630
    // iteration
631
    for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
632
      srh.scalar_flux_new(g) += delta_psi_[g];
1,713,818,480✔
633
      srh.flux_moments_new(g) += delta_moments_[g];
1,713,818,480✔
634
    }
635

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

645
    srh.n_hits() += 1;
492,996,350✔
646
  }
647

648
  // Tally valid position inside the source region (e.g., midpoint of
649
  // the ray) if not done already
650
  if (!srh.position_recorded()) {
602,457,438✔
651
    srh.position() = midpoint;
809,534✔
652
    srh.position_recorded() = 1;
809,534✔
653
  }
654

655
  // Release lock
656
  srh.unlock();
602,457,438✔
657
}
602,457,438✔
658

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

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

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

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

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

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

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

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

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

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

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

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

757
    srh.n_hits() += 1;
6,892,402✔
758

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

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

771
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
1,856,800✔
772
{
773
  domain_ = domain;
1,856,800✔
774

775
  // Reset particle event counter
776
  n_event() = 0;
1,856,800✔
777

778
  is_active_ = (distance_inactive_ <= 0.0);
1,856,800✔
779

780
  wgt() = 1.0;
1,856,800✔
781

782
  // set identifier for particle
783
  id() = ray_id;
1,856,800✔
784

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

798
  site.E = 0.0;
1,856,800✔
799
  this->from_source(&site);
1,856,800✔
800

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

808
    // Set birth cell attribute
809
    if (cell_born() == C_NONE)
1,856,800✔
810
      cell_born() = lowest_coord().cell;
1,856,800✔
811
  }
812

813
  // Initialize ray's starting angular flux to starting location's isotropic
814
  // source
815
  int i_cell = lowest_coord().cell;
1,856,800✔
816
  int64_t sr = domain_->source_region_offsets_[i_cell] + cell_instance();
1,856,800✔
817

818
  SourceRegionHandle srh;
1,856,800✔
819
  if (mesh_subdivision_enabled_) {
1,856,800✔
820
    int mesh_idx = domain_->base_source_regions_.mesh(sr);
1,145,100✔
821
    int mesh_bin;
822
    if (mesh_idx == C_NONE) {
1,145,100✔
UNCOV
823
      mesh_bin = 0;
×
824
    } else {
825
      Mesh* mesh = model::meshes[mesh_idx].get();
1,145,100✔
826
      mesh_bin = mesh->get_bin(r());
1,145,100✔
827
    }
828
    srh =
829
      domain_->get_subdivided_source_region_handle(sr, mesh_bin, r(), 0.0, u());
1,145,100✔
830
  } else {
831
    srh = domain_->source_regions_.get_source_region_handle(sr);
711,700✔
832
  }
833

834
  if (!srh.is_numerical_fp_artifact_) {
1,856,800✔
835
    for (int g = 0; g < negroups_; g++) {
6,617,600✔
836
      angular_flux_[g] = srh.source(g);
4,760,800✔
837
    }
838
  }
839
}
1,856,800✔
840

841
SourceSite RandomRay::sample_prng()
1,845,800✔
842
{
843
  // set random number seed
844
  int64_t particle_seed =
845
    (simulation::current_batch - 1) * settings::n_particles + id();
1,845,800✔
846
  init_particle_seeds(particle_seed, seeds());
1,845,800✔
847
  stream() = STREAM_TRACKING;
1,845,800✔
848

849
  // Sample from ray source distribution
850
  SourceSite site {ray_source_->sample(current_seed())};
1,845,800✔
851

852
  return site;
1,845,800✔
853
}
854

855
SourceSite RandomRay::sample_halton()
11,000✔
856
{
857
  SourceSite site;
11,000✔
858

859
  // Set random number seed
860
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
11,000✔
861
  int64_t skip = id();
11,000✔
862
  init_particle_seeds(batch_seed, seeds());
11,000✔
863
  stream() = STREAM_TRACKING;
11,000✔
864

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

868
  // Get spatial box of ray_source_
869
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
11,000✔
870
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
11,000✔
871

872
  // Sample spatial distribution
873
  Position xi {samples[0], samples[1], samples[2]};
11,000✔
874
  // make a small shift in position to avoid geometry floating point issues
875
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
11,000✔
876
  site.r = (sb->lower_left() + shift) +
877
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
11,000✔
878

879
  // Sample Polar cosine and azimuthal angles
880
  double mu = 2.0 * samples[3] - 1.0;
11,000✔
881
  double azi = 2.0 * PI * samples[4];
11,000✔
882
  // Convert to Cartesian coordinates
883
  double c = std::sqrt(1.0 - mu * mu);
11,000✔
884
  site.u.x = mu;
11,000✔
885
  site.u.y = std::cos(azi) * c;
11,000✔
886
  site.u.z = std::sin(azi) * c;
11,000✔
887

888
  return site;
22,000✔
889
}
11,000✔
890

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

© 2025 Coveralls, Inc