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

openmc-dev / openmc / 15371300071

01 Jun 2025 05:04AM UTC coverage: 85.143% (+0.3%) from 84.827%
15371300071

Pull #3176

github

web-flow
Merge 4f739184a into cb95c784b
Pull Request #3176: MeshFilter rotation - solution to issue #3166

86 of 99 new or added lines in 4 files covered. (86.87%)

3707 existing lines in 117 files now uncovered.

52212 of 61323 relevant lines covered (85.14%)

42831974.38 hits per line

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

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

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

45
  float x = -tau;
1,553,378,955✔
46

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

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

65
  return num / den;
1,553,378,955✔
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)
2,160,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) {
9,315,000✔
187
    // Generate a random index in the range [0, i]
188
    int j = uniform_int_distribution(0, i, seed);
7,155,000✔
189
    std::swap(arr[i], arr[j]);
7,155,000✔
190
  }
191
}
2,160,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)
15,000✔
199
{
200
  if (dim > 10) {
15,000✔
UNCOV
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};
15,000✔
206
  vector<double> halton(dim, 0.0);
15,000✔
207

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

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

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

228
  return halton;
30,000✔
229
}
15,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()
2,532,000✔
244
  : angular_flux_(data::mg.num_energy_groups_),
2,532,000✔
245
    delta_psi_(data::mg.num_energy_groups_),
2,532,000✔
246
    negroups_(data::mg.num_energy_groups_)
7,596,000✔
247
{
248
  if (source_shape_ == RandomRaySourceShape::LINEAR ||
2,532,000✔
249
      source_shape_ == RandomRaySourceShape::LINEAR_XY) {
1,411,500✔
250
    delta_moments_.resize(negroups_);
1,290,750✔
251
  }
252
}
2,532,000✔
253

254
RandomRay::RandomRay(uint64_t ray_id, FlatSourceDomain* domain) : RandomRay()
2,532,000✔
255
{
256
  initialize_ray(ray_id, domain);
2,532,000✔
257
}
2,532,000✔
258

259
// Transports ray until termination criteria are met
260
uint64_t RandomRay::transport_history_based_single_ray()
2,532,000✔
261
{
262
  using namespace openmc;
263
  while (alive()) {
1,045,611,975✔
264
    event_advance_ray();
1,045,611,975✔
265
    if (!alive())
1,045,611,975✔
266
      break;
2,532,000✔
267
    event_cross_surface();
1,043,079,975✔
268
  }
269

270
  return n_event();
2,532,000✔
271
}
272

273
// Transports ray across a single source region
274
void RandomRay::event_advance_ray()
1,045,611,975✔
275
{
276
  // Find the distance to the nearest boundary
277
  boundary() = distance_to_boundary(*this);
1,045,611,975✔
278
  double distance = boundary().distance;
1,045,611,975✔
279

280
  if (distance < 0.0) {
1,045,611,975✔
UNCOV
281
    mark_as_lost("Negative transport distance detected for particle " +
×
UNCOV
282
                 std::to_string(id()));
×
UNCOV
283
    return;
×
284
  }
285

286
  if (is_active_) {
1,045,611,975✔
287
    // If the ray is in the active length, need to check if it has
288
    // reached its maximum termination distance. If so, reduce
289
    // the ray traced length so that the ray does not overrun the
290
    // maximum numerical length (so as to avoid numerical bias).
291
    if (distance_travelled_ + distance >= distance_active_) {
846,301,950✔
292
      distance = distance_active_ - distance_travelled_;
2,532,000✔
293
      wgt() = 0.0;
2,532,000✔
294
    }
295

296
    distance_travelled_ += distance;
846,301,950✔
297
    attenuate_flux(distance, true);
846,301,950✔
298
  } else {
299
    // If the ray is still in the dead zone, need to check if it
300
    // has entered the active phase. If so, split into two segments (one
301
    // representing the final part of the dead zone, the other representing the
302
    // first part of the active length) and attenuate each. Otherwise, if the
303
    // full length of the segment is within the dead zone, attenuate as normal.
304
    if (distance_travelled_ + distance >= distance_inactive_) {
199,310,025✔
305
      is_active_ = true;
2,532,000✔
306
      double distance_dead = distance_inactive_ - distance_travelled_;
2,532,000✔
307
      attenuate_flux(distance_dead, false);
2,532,000✔
308

309
      double distance_alive = distance - distance_dead;
2,532,000✔
310

311
      // Ensure we haven't travelled past the active phase as well
312
      if (distance_alive > distance_active_) {
2,532,000✔
UNCOV
313
        distance_alive = distance_active_;
×
UNCOV
314
        wgt() = 0.0;
×
315
      }
316

317
      attenuate_flux(distance_alive, true, distance_dead);
2,532,000✔
318
      distance_travelled_ = distance_alive;
2,532,000✔
319
    } else {
320
      distance_travelled_ += distance;
196,778,025✔
321
      attenuate_flux(distance, false);
196,778,025✔
322
    }
323
  }
324

325
  // Advance particle
326
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
327
    coord(j).r += distance * coord(j).u;
2,147,483,647✔
328
  }
329
}
330

331
void RandomRay::attenuate_flux(double distance, bool is_active, double offset)
1,048,143,975✔
332
{
333
  // Determine source region index etc.
334
  int i_cell = lowest_coord().cell;
1,048,143,975✔
335

336
  // The base source region is the spatial region index
337
  int64_t sr = domain_->source_region_offsets_[i_cell] + cell_instance();
1,048,143,975✔
338

339
  // Perform ray tracing across mesh
340
  if (mesh_subdivision_enabled_) {
1,048,143,975✔
341
    // Determine the mesh index for the base source region, if any
342
    int mesh_idx = domain_->base_source_regions_.mesh(sr);
579,711,510✔
343

344
    if (mesh_idx == C_NONE) {
579,711,510✔
345
      // If there's no mesh being applied to this cell, then
346
      // we just attenuate the flux as normal, and set
347
      // the mesh bin to 0
UNCOV
348
      attenuate_flux_inner(distance, is_active, sr, 0, r());
×
349
    } else {
350
      // If there is a mesh being applied to this cell, then
351
      // we loop over all the bin crossings and attenuate
352
      // separately.
353
      Mesh* mesh = model::meshes[mesh_idx].get();
579,711,510✔
354

355
      // We adjust the start and end positions of the ray slightly
356
      // to accomodate for floating point precision issues that tend
357
      // to occur at mesh boundaries that overlap with geometry lattice
358
      // boundaries.
359
      Position start = r() + (offset + TINY_BIT) * u();
579,711,510✔
360
      Position end = start + (distance - 2.0 * TINY_BIT) * u();
579,711,510✔
361
      double reduced_distance = (end - start).norm();
579,711,510✔
362

363
      // Ray trace through the mesh and record bins and lengths
364
      mesh_bins_.resize(0);
579,711,510✔
365
      mesh_fractional_lengths_.resize(0);
579,711,510✔
366
      mesh->bins_crossed(start, end, u(), mesh_bins_, mesh_fractional_lengths_);
579,711,510✔
367

368
      // Loop over all mesh bins and attenuate flux
369
      for (int b = 0; b < mesh_bins_.size(); b++) {
1,766,580,720✔
370
        double physical_length = reduced_distance * mesh_fractional_lengths_[b];
1,186,869,210✔
371
        attenuate_flux_inner(
1,186,869,210✔
372
          physical_length, is_active, sr, mesh_bins_[b], start);
1,186,869,210✔
373
        start += physical_length * u();
1,186,869,210✔
374
      }
375
    }
376
  } else {
377
    attenuate_flux_inner(distance, is_active, sr, C_NONE, r());
468,432,465✔
378
  }
379
}
1,048,143,975✔
380

381
void RandomRay::attenuate_flux_inner(
1,655,301,675✔
382
  double distance, bool is_active, int64_t sr, int mesh_bin, Position r)
383
{
384
  SourceRegionHandle srh;
1,655,301,675✔
385
  if (mesh_subdivision_enabled_) {
1,655,301,675✔
386
    srh = domain_->get_subdivided_source_region_handle(
1,186,869,210✔
387
      sr, mesh_bin, r, distance, u());
1,186,869,210✔
388
    if (srh.is_numerical_fp_artifact_) {
1,186,869,210✔
389
      return;
120✔
390
    }
391
  } else {
392
    srh = domain_->source_regions_.get_source_region_handle(sr);
468,432,465✔
393
  }
394

395
  switch (source_shape_) {
1,655,301,555✔
396
  case RandomRaySourceShape::FLAT:
822,467,910✔
397
    if (this->material() == MATERIAL_VOID) {
822,467,910✔
398
      attenuate_flux_flat_source_void(srh, distance, is_active, r);
11,300,775✔
399
    } else {
400
      attenuate_flux_flat_source(srh, distance, is_active, r);
811,167,135✔
401
    }
402
    break;
822,467,910✔
403
  case RandomRaySourceShape::LINEAR:
832,833,645✔
404
  case RandomRaySourceShape::LINEAR_XY:
405
    if (this->material() == MATERIAL_VOID) {
832,833,645✔
406
      attenuate_flux_linear_source_void(srh, distance, is_active, r);
11,300,775✔
407
    } else {
408
      attenuate_flux_linear_source(srh, distance, is_active, r);
821,532,870✔
409
    }
410
    break;
832,833,645✔
UNCOV
411
  default:
×
UNCOV
412
    fatal_error("Unknown source shape for random ray transport.");
×
413
  }
414
}
415

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

435
  // Get material
436
  int material = this->material();
811,167,135✔
437

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

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

451
  // Aquire lock for source region
452
  srh.lock();
811,167,135✔
453

454
  if (is_active) {
811,167,135✔
455
    // Accumulate delta psi into new estimate of source region flux for
456
    // this iteration
457
    for (int g = 0; g < negroups_; g++) {
1,876,456,170✔
458
      srh.scalar_flux_new(g) += delta_psi_[g];
1,212,727,095✔
459
    }
460

461
    // Accomulate volume (ray distance) into this iteration's estimate
462
    // of the source region's volume
463
    srh.volume() += distance;
663,729,075✔
464

465
    srh.n_hits() += 1;
663,729,075✔
466
  }
467

468
  // Tally valid position inside the source region (e.g., midpoint of
469
  // the ray) if not done already
470
  if (!srh.position_recorded()) {
811,167,135✔
471
    Position midpoint = r + u() * (distance / 2.0);
2,087,220✔
472
    srh.position() = midpoint;
2,087,220✔
473
    srh.position_recorded() = 1;
2,087,220✔
474
  }
475

476
  // Release lock
477
  srh.unlock();
811,167,135✔
478
}
811,167,135✔
479

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

487
  int material = this->material();
11,300,775✔
488

489
  // If ray is in the active phase (not in dead zone), make contributions to
490
  // source region bookkeeping
491
  if (is_active) {
11,300,775✔
492

493
    // Aquire lock for source region
494
    srh.lock();
9,398,730✔
495

496
    // Accumulate delta psi into new estimate of source region flux for
497
    // this iteration
498
    for (int g = 0; g < negroups_; g++) {
18,797,460✔
499
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
9,398,730✔
500
    }
501

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

508
    // Tally valid position inside the source region (e.g., midpoint of
509
    // the ray) if not done already
510
    if (!srh.position_recorded()) {
9,398,730✔
511
      Position midpoint = r + u() * (distance / 2.0);
15,000✔
512
      srh.position() = midpoint;
15,000✔
513
      srh.position_recorded() = 1;
15,000✔
514
    }
515

516
    // Release lock
517
    srh.unlock();
9,398,730✔
518
  }
519

520
  // Add source to incoming angular flux, assuming void region
521
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
11,300,775✔
522
    for (int g = 0; g < negroups_; g++) {
22,601,550✔
523
      angular_flux_[g] += srh.external_source(g) * distance;
11,300,775✔
524
    }
525
  }
526
}
11,300,775✔
527

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

534
  int material = this->material();
821,532,870✔
535

536
  Position& centroid = srh.centroid();
821,532,870✔
537
  Position midpoint = r + u() * (distance / 2.0);
821,532,870✔
538

539
  // Determine the local position of the midpoint and the ray origin
540
  // relative to the source region's centroid
541
  Position rm_local;
821,532,870✔
542
  Position r0_local;
821,532,870✔
543

544
  // In the first few iterations of the simulation, the source region
545
  // may not yet have had any ray crossings, in which case there will
546
  // be no estimate of its centroid. We detect this by checking if it has
547
  // any accumulated volume. If its volume is zero, just use the midpoint
548
  // of the ray as the region's centroid.
549
  if (srh.volume_t()) {
821,532,870✔
550
    rm_local = midpoint - centroid;
794,472,135✔
551
    r0_local = r - centroid;
794,472,135✔
552
  } else {
553
    rm_local = {0.0, 0.0, 0.0};
27,060,735✔
554
    r0_local = -u() * 0.5 * distance;
27,060,735✔
555
  }
556
  double distance_2 = distance * distance;
821,532,870✔
557

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

562
    // Compute tau, the optical thickness of the ray segment
563
    float sigma_t = domain_->sigma_t_[material * negroups_ + g];
2,147,483,647✔
564
    float tau = sigma_t * distance;
2,147,483,647✔
565

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

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

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

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

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

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

603
    // If 2D mode is enabled, the z-component of the flux moments is forced
604
    // to zero
605
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
2,147,483,647✔
606
      delta_moments_[g].z = 0.0;
630,283,695✔
607
    }
608
  }
609

610
  // Compute an estimate of the spatial moments matrix for the source
611
  // region based on parameters from this ray's crossing
612
  MomentMatrix moment_matrix_estimate;
613
  moment_matrix_estimate.compute_spatial_moments_matrix(
821,532,870✔
614
    rm_local, u(), distance);
821,532,870✔
615

616
  // Aquire lock for source region
617
  srh.lock();
821,532,870✔
618

619
  // If ray is in the active phase (not in dead zone), make contributions to
620
  // source region bookkeeping
621

622
  if (is_active) {
821,532,870✔
623
    // Accumulate deltas into the new estimate of source region flux for this
624
    // iteration
625
    for (int g = 0; g < negroups_; g++) {
2,147,483,647✔
626
      srh.scalar_flux_new(g) += delta_psi_[g];
2,147,483,647✔
627
      srh.flux_moments_new(g) += delta_moments_[g];
2,147,483,647✔
628
    }
629

630
    // Accumulate the volume (ray segment distance), centroid, and spatial
631
    // momement estimates into the running totals for the iteration for this
632
    // source region. The centroid and spatial momements estimates are scaled
633
    // by the ray segment length as part of length averaging of the estimates.
634
    srh.volume() += distance;
672,267,750✔
635
    srh.centroid_iteration() += midpoint * distance;
672,267,750✔
636
    moment_matrix_estimate *= distance;
672,267,750✔
637
    srh.mom_matrix() += moment_matrix_estimate;
672,267,750✔
638

639
    srh.n_hits() += 1;
672,267,750✔
640
  }
641

642
  // Tally valid position inside the source region (e.g., midpoint of
643
  // the ray) if not done already
644
  if (!srh.position_recorded()) {
821,532,870✔
645
    srh.position() = midpoint;
1,103,910✔
646
    srh.position_recorded() = 1;
1,103,910✔
647
  }
648

649
  // Release lock
650
  srh.unlock();
821,532,870✔
651
}
821,532,870✔
652

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

667
  Position& centroid = srh.centroid();
11,300,775✔
668
  Position midpoint = r + u() * (distance / 2.0);
11,300,775✔
669

670
  // Determine the local position of the midpoint and the ray origin
671
  // relative to the source region's centroid
672
  Position rm_local;
11,300,775✔
673
  Position r0_local;
11,300,775✔
674

675
  // In the first few iterations of the simulation, the source region
676
  // may not yet have had any ray crossings, in which case there will
677
  // be no estimate of its centroid. We detect this by checking if it has
678
  // any accumulated volume. If its volume is zero, just use the midpoint
679
  // of the ray as the region's centroid.
680
  if (srh.volume_t()) {
11,300,775✔
681
    rm_local = midpoint - centroid;
11,023,890✔
682
    r0_local = r - centroid;
11,023,890✔
683
  } else {
684
    rm_local = {0.0, 0.0, 0.0};
276,885✔
685
    r0_local = -u() * 0.5 * distance;
276,885✔
686
  }
687
  double distance_2 = distance * distance;
11,300,775✔
688

689
  // Compared to linear flux attenuation through solid regions,
690
  // transport through a void region is greatly simplified. Here we
691
  // compute the updated flux moments.
692
  for (int g = 0; g < negroups_; g++) {
22,601,550✔
693
    float spatial_source = 0.f;
11,300,775✔
694
    if (settings::run_mode == RunMode::FIXED_SOURCE) {
11,300,775✔
695
      spatial_source = srh.external_source(g);
11,300,775✔
696
    }
697
    float new_delta_psi = (angular_flux_[g] - spatial_source) * distance;
11,300,775✔
698
    float h1 = 0.5f;
11,300,775✔
699
    h1 = h1 * angular_flux_[g];
11,300,775✔
700
    h1 = h1 * distance_2;
11,300,775✔
701
    spatial_source = spatial_source * distance + new_delta_psi;
11,300,775✔
702

703
    // Store contributions for this group into arrays, so that they can
704
    // be accumulated into the source region's estimates inside of the locked
705
    // region.
706
    delta_moments_[g] = r0_local * spatial_source + u() * h1;
11,300,775✔
707

708
    // If 2D mode is enabled, the z-component of the flux moments is forced
709
    // to zero
710
    if (source_shape_ == RandomRaySourceShape::LINEAR_XY) {
11,300,775✔
UNCOV
711
      delta_moments_[g].z = 0.0;
×
712
    }
713
  }
714

715
  // If ray is in the active phase (not in dead zone), make contributions to
716
  // source region bookkeeping
717
  if (is_active) {
11,300,775✔
718
    // Compute an estimate of the spatial moments matrix for the source
719
    // region based on parameters from this ray's crossing
720
    MomentMatrix moment_matrix_estimate;
721
    moment_matrix_estimate.compute_spatial_moments_matrix(
9,398,730✔
722
      rm_local, u(), distance);
9,398,730✔
723

724
    // Aquire lock for source region
725
    srh.lock();
9,398,730✔
726

727
    // Accumulate delta psi into new estimate of source region flux for
728
    // this iteration, and update flux momements
729
    for (int g = 0; g < negroups_; g++) {
18,797,460✔
730
      srh.scalar_flux_new(g) += angular_flux_[g] * distance;
9,398,730✔
731
      srh.flux_moments_new(g) += delta_moments_[g];
9,398,730✔
732
    }
733

734
    // Accumulate the volume (ray segment distance), centroid, and spatial
735
    // momement estimates into the running totals for the iteration for this
736
    // source region. The centroid and spatial momements estimates are scaled by
737
    // the ray segment length as part of length averaging of the estimates.
738
    srh.volume() += distance;
9,398,730✔
739
    srh.volume_sq() += distance_2;
9,398,730✔
740
    srh.centroid_iteration() += midpoint * distance;
9,398,730✔
741
    moment_matrix_estimate *= distance;
9,398,730✔
742
    srh.mom_matrix() += moment_matrix_estimate;
9,398,730✔
743

744
    // Tally valid position inside the source region (e.g., midpoint of
745
    // the ray) if not done already
746
    if (!srh.position_recorded()) {
9,398,730✔
747
      srh.position() = midpoint;
15,000✔
748
      srh.position_recorded() = 1;
15,000✔
749
    }
750

751
    srh.n_hits() += 1;
9,398,730✔
752

753
    // Release lock
754
    srh.unlock();
9,398,730✔
755
  }
756

757
  // Add source to incoming angular flux, assuming void region
758
  if (settings::run_mode == RunMode::FIXED_SOURCE) {
11,300,775✔
759
    for (int g = 0; g < negroups_; g++) {
22,601,550✔
760
      angular_flux_[g] += srh.external_source(g) * distance;
11,300,775✔
761
    }
762
  }
763
}
11,300,775✔
764

765
void RandomRay::initialize_ray(uint64_t ray_id, FlatSourceDomain* domain)
2,532,000✔
766
{
767
  domain_ = domain;
2,532,000✔
768

769
  // Reset particle event counter
770
  n_event() = 0;
2,532,000✔
771

772
  is_active_ = (distance_inactive_ <= 0.0);
2,532,000✔
773

774
  wgt() = 1.0;
2,532,000✔
775

776
  // set identifier for particle
777
  id() = ray_id;
2,532,000✔
778

779
  // generate source site using sample method
780
  SourceSite site;
2,532,000✔
781
  switch (sample_method_) {
2,532,000✔
782
  case RandomRaySampleMethod::PRNG:
2,517,000✔
783
    site = sample_prng();
2,517,000✔
784
    break;
2,517,000✔
785
  case RandomRaySampleMethod::HALTON:
15,000✔
786
    site = sample_halton();
15,000✔
787
    break;
15,000✔
UNCOV
788
  default:
×
UNCOV
789
    fatal_error("Unknown sample method for random ray transport.");
×
790
  }
791

792
  site.E = 0.0;
2,532,000✔
793
  this->from_source(&site);
2,532,000✔
794

795
  // Locate ray
796
  if (lowest_coord().cell == C_NONE) {
2,532,000✔
797
    if (!exhaustive_find_cell(*this)) {
2,532,000✔
UNCOV
798
      this->mark_as_lost(
×
UNCOV
799
        "Could not find the cell containing particle " + std::to_string(id()));
×
800
    }
801

802
    // Set birth cell attribute
803
    if (cell_born() == C_NONE)
2,532,000✔
804
      cell_born() = lowest_coord().cell;
2,532,000✔
805
  }
806

807
  // Initialize ray's starting angular flux to starting location's isotropic
808
  // source
809
  int i_cell = lowest_coord().cell;
2,532,000✔
810
  int64_t sr = domain_->source_region_offsets_[i_cell] + cell_instance();
2,532,000✔
811

812
  SourceRegionHandle srh;
2,532,000✔
813
  if (mesh_subdivision_enabled_) {
2,532,000✔
814
    int mesh_idx = domain_->base_source_regions_.mesh(sr);
1,561,500✔
815
    int mesh_bin;
816
    if (mesh_idx == C_NONE) {
1,561,500✔
UNCOV
817
      mesh_bin = 0;
×
818
    } else {
819
      Mesh* mesh = model::meshes[mesh_idx].get();
1,561,500✔
820
      mesh_bin = mesh->get_bin(r());
1,561,500✔
821
    }
822
    srh =
823
      domain_->get_subdivided_source_region_handle(sr, mesh_bin, r(), 0.0, u());
1,561,500✔
824
  } else {
825
    srh = domain_->source_regions_.get_source_region_handle(sr);
970,500✔
826
  }
827

828
  if (!srh.is_numerical_fp_artifact_) {
2,532,000✔
829
    for (int g = 0; g < negroups_; g++) {
9,024,000✔
830
      angular_flux_[g] = srh.source(g);
6,492,000✔
831
    }
832
  }
833
}
2,532,000✔
834

835
SourceSite RandomRay::sample_prng()
2,517,000✔
836
{
837
  // set random number seed
838
  int64_t particle_seed =
839
    (simulation::current_batch - 1) * settings::n_particles + id();
2,517,000✔
840
  init_particle_seeds(particle_seed, seeds());
2,517,000✔
841
  stream() = STREAM_TRACKING;
2,517,000✔
842

843
  // Sample from ray source distribution
844
  SourceSite site {ray_source_->sample(current_seed())};
2,517,000✔
845

846
  return site;
2,517,000✔
847
}
848

849
SourceSite RandomRay::sample_halton()
15,000✔
850
{
851
  SourceSite site;
15,000✔
852

853
  // Set random number seed
854
  int64_t batch_seed = (simulation::current_batch - 1) * settings::n_particles;
15,000✔
855
  int64_t skip = id();
15,000✔
856
  init_particle_seeds(batch_seed, seeds());
15,000✔
857
  stream() = STREAM_TRACKING;
15,000✔
858

859
  // Calculate next samples in LDS across 5 dimensions
860
  vector<double> samples = rhalton(5, current_seed(), skip = skip);
15,000✔
861

862
  // Get spatial box of ray_source_
863
  SpatialBox* sb = dynamic_cast<SpatialBox*>(
15,000✔
864
    dynamic_cast<IndependentSource*>(RandomRay::ray_source_.get())->space());
15,000✔
865

866
  // Sample spatial distribution
867
  Position xi {samples[0], samples[1], samples[2]};
15,000✔
868
  // make a small shift in position to avoid geometry floating point issues
869
  Position shift {FP_COINCIDENT, FP_COINCIDENT, FP_COINCIDENT};
15,000✔
870
  site.r = (sb->lower_left() + shift) +
871
           xi * ((sb->upper_right() - shift) - (sb->lower_left() + shift));
15,000✔
872

873
  // Sample Polar cosine and azimuthal angles
874
  double mu = 2.0 * samples[3] - 1.0;
15,000✔
875
  double azi = 2.0 * PI * samples[4];
15,000✔
876
  // Convert to Cartesian coordinates
877
  double c = std::sqrt(1.0 - mu * mu);
15,000✔
878
  site.u.x = mu;
15,000✔
879
  site.u.y = std::cos(azi) * c;
15,000✔
880
  site.u.z = std::sin(azi) * c;
15,000✔
881

882
  return site;
30,000✔
883
}
15,000✔
884

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