From 2343d27bd235f39aa7dcf3ddd20a503b1be1eb34 Mon Sep 17 00:00:00 2001 From: GuySten Date: Sun, 15 Mar 2026 20:02:41 +0200 Subject: [PATCH 1/8] implement ParticleRay class --- include/openmc/particle_data.h | 2 +- include/openmc/ray.h | 19 ++++++++++++-- src/ray.cpp | 47 ++++++++++++++++++++++++++++++++-- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/include/openmc/particle_data.h b/include/openmc/particle_data.h index 5b632bbce53..52aba848a10 100644 --- a/include/openmc/particle_data.h +++ b/include/openmc/particle_data.h @@ -484,7 +484,7 @@ class GeometryState { * Algorithms.” Annals of Nuclear Energy 113 (March 2018): 506–18. * https://doi.org/10.1016/j.anucene.2017.11.032. */ -class ParticleData : public GeometryState { +class ParticleData : virtual public GeometryState { private: //========================================================================== // Data members -- see public: below for descriptions diff --git a/include/openmc/ray.h b/include/openmc/ray.h index 62e86b0d90f..1b4ebdb96b4 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -1,14 +1,14 @@ #ifndef OPENMC_RAY_H #define OPENMC_RAY_H -#include "openmc/particle_data.h" +#include "openmc/particle.h" #include "openmc/position.h" namespace openmc { // Base class that implements ray tracing logic, not necessarily through // defined regions of the geometry but also outside of it. -class Ray : public GeometryState { +class Ray : virtual public GeometryState { public: // Initialize from location and direction @@ -32,6 +32,8 @@ class Ray : public GeometryState { // Sets the dist_ variable void compute_distance(); + virtual void update_distance(); + protected: // Records how far the ray has traveled double traversal_distance_ {0.0}; @@ -46,5 +48,18 @@ class Ray : public GeometryState { unsigned event_counter_ {0}; }; +class ParticleRay : public Ray, public Particle { + +public: + // Sets the dist_ variable + void update_distance() override; + +protected: + // Records how much time passed during travel + double time_distance_ {0.0}; + // Records how much mean free paths the ray traveled + double mfp_distance_ {0.0}; +}; + } // namespace openmc #endif // OPENMC_RAY_H diff --git a/src/ray.cpp b/src/ray.cpp index 3d848e3a3a7..3287d001986 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -2,6 +2,8 @@ #include "openmc/error.h" #include "openmc/geometry.h" +#include "openmc/material.h" +#include "openmc/mgxs_interface.h" #include "openmc/settings.h" namespace openmc { @@ -136,8 +138,8 @@ void Ray::trace() cross_lattice(*this, boundary(), settings::verbosity >= 10); } - // Record how far the ray has traveled - traversal_distance_ += boundary().distance(); + update_distance(); + inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10); // Call the specialized logic for this type of ray. Note that we do not @@ -165,4 +167,45 @@ void Ray::trace() } } +void Ray::update_distance() +{ + // Record how far the ray has traveled + traversal_distance_ += boundary().distance(); +} + +void ParticleRay::update_distance() +{ + Ray::update_distance(); + + time_distance_ += speed() * boundary().distance(); + + // Calculate microscopic and macroscopic cross sections + if (material() != MATERIAL_VOID) { + if (settings::run_CE) { + if (material() != material_last() || sqrtkT() != sqrtkT_last() || + density_mult() != density_mult_last()) { + // If the material is the same as the last material and the + // temperature hasn't changed, we don't need to lookup cross + // sections again. + model::materials[material()]->calculate_xs(*this); + } + } else { + // Get the MG data; unlike the CE case above, we have to re-calculate + // cross sections for every collision since the cross sections may + // be angle-dependent + data::mg.macro_xs_[material()].calculate_xs(*this); + + // Update the particle's group while we know we are multi-group + g_last() = g(); + } + } else { + macro_xs().total = 0.0; + macro_xs().absorption = 0.0; + macro_xs().fission = 0.0; + macro_xs().nu_fission = 0.0; + } + + mfp_distance_ += macro_xs().total * boundary().distance(); +} + } // namespace openmc From c19ba54698cf0bce039705b0c7d2f768f2e68019 Mon Sep 17 00:00:00 2001 From: GuySten Date: Mon, 16 Mar 2026 15:12:57 +0200 Subject: [PATCH 2/8] update --- include/openmc/ray.h | 18 +++++++++++++++--- src/ray.cpp | 6 ++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/include/openmc/ray.h b/include/openmc/ray.h index 1b4ebdb96b4..d4eed886850 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -51,14 +51,26 @@ class Ray : virtual public GeometryState { class ParticleRay : public Ray, public Particle { public: + ParticleRay( + Position r, Direction u, ParticleType type_, double time_, double E_) + : Ray(r, u) + { + type() = type_; + time() = time_; + E() = E_; + } + + void on_intersection() override; + // Sets the dist_ variable void update_distance() override; + const double& traversal_distance() const { return traversal_distance_; } + const double& traversal_mfp() const { return traversal_mfp_; } + protected: - // Records how much time passed during travel - double time_distance_ {0.0}; // Records how much mean free paths the ray traveled - double mfp_distance_ {0.0}; + double traversal_mfp_ {0.0}; }; } // namespace openmc diff --git a/src/ray.cpp b/src/ray.cpp index 3287d001986..f0667ff5e16 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -173,11 +173,13 @@ void Ray::update_distance() traversal_distance_ += boundary().distance(); } +void ParticleRay::on_intersection() {} + void ParticleRay::update_distance() { Ray::update_distance(); - time_distance_ += speed() * boundary().distance(); + time() += boundary().distance() / speed(); // Calculate microscopic and macroscopic cross sections if (material() != MATERIAL_VOID) { @@ -205,7 +207,7 @@ void ParticleRay::update_distance() macro_xs().nu_fission = 0.0; } - mfp_distance_ += macro_xs().total * boundary().distance(); + traversal_mfp_ += macro_xs().total * boundary().distance(); } } // namespace openmc From e6d096390f0a8f79229cb49eb496b6bc2a3df929 Mon Sep 17 00:00:00 2001 From: GuySten Date: Mon, 11 May 2026 10:55:49 +0300 Subject: [PATCH 3/8] add option to stop after some distance --- include/openmc/ray.h | 4 +++- src/ray.cpp | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/include/openmc/ray.h b/include/openmc/ray.h index d4eed886850..b357ae8bbc4 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -24,7 +24,7 @@ class Ray : virtual public GeometryState { * Traces the ray through the geometry, calling on_intersection * at every surface boundary. */ - void trace(); + void trace(double max_distance = INFTY); // Stops the ray and exits tracing when called from on_intersection void stop() { stop_ = true; } @@ -58,6 +58,8 @@ class ParticleRay : public Ray, public Particle { type() = type_; time() = time_; E() = E_; + E_last() = E_; + r_last() = r; } void on_intersection() override; diff --git a/src/ray.cpp b/src/ray.cpp index f0667ff5e16..5e9a8419ff7 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -13,7 +13,7 @@ void Ray::compute_distance() boundary() = distance_to_boundary(*this); } -void Ray::trace() +void Ray::trace(double max_distance) { // To trace the ray from its origin all the way through the model, we have // to proceed in two phases. In the first, the ray may or may not be found @@ -26,6 +26,8 @@ void Ray::trace() // After phase one is done, we can starting tracing from cell to cell within // the model. This step can use neighbor lists to accelerate the ray tracing. + double max = max_distance; + bool inside_cell; // Check for location if the particle is already known if (lowest_coord().cell() == C_NONE) { @@ -120,10 +122,20 @@ void Ray::trace() // distance to properly check cell inclusion. boundary().distance() += TINY_BIT; + double distance = std::min(boundary().distance(), max); + // Advance particle, prepare for next intersection for (int lev = 0; lev < n_coord(); ++lev) { - coord(lev).r() += boundary().distance() * coord(lev).u(); + coord(lev).r() += distance * coord(lev).u(); } + + max -= distance; + + if (max == 0.0) { + update_distance(); + break; + } + surface() = boundary().surface(); // Initialize last cells from the current cell, because the cell() variable // does not contain the data for the case of a single-segment ray From 33358e4a235b3931c208b334deeca7eeab259efe Mon Sep 17 00:00:00 2001 From: GuySten Date: Fri, 4 Sep 2026 16:02:03 +0300 Subject: [PATCH 4/8] see if ray completed full flight --- include/openmc/ray.h | 9 +++++++++ src/ray.cpp | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/include/openmc/ray.h b/include/openmc/ray.h index b357ae8bbc4..29a7a9382e3 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -34,10 +34,19 @@ class Ray : virtual public GeometryState { virtual void update_distance(); + //! Whether the ray travelled the full max_distance passed to trace(). + //! False if it left the model (or hit a dead end) beforehand. This is an + //! exact flag rather than a comparison of traversal_distance() against the + //! requested distance, which is only accurate to floating-point roundoff. + bool completed() const { return completed_; } + protected: // Records how far the ray has traveled double traversal_distance_ {0.0}; + // Set when trace() consumed the whole max_distance it was given + bool completed_ {false}; + private: // Max intersections before we assume ray tracing is caught in an infinite // loop: diff --git a/src/ray.cpp b/src/ray.cpp index 5e9a8419ff7..d28db19735a 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -132,7 +132,15 @@ void Ray::trace(double max_distance) max -= distance; if (max == 0.0) { + // The ray stopped part-way through this segment, so only the truncated + // distance was actually travelled. update_distance() accumulates + // boundary().distance() into traversal_distance_ and traversal_mfp_, + // so it has to see the truncated value -- otherwise the remainder of + // the segment (out to the next surface) is counted, which over-states + // the optical depth for anything that stops inside a cell. + boundary().distance() = distance; update_distance(); + completed_ = true; break; } From 127318a33ea4cf89473968dfd10854e265a50864 Mon Sep 17 00:00:00 2001 From: GuySten Date: Mon, 7 Sep 2026 23:42:21 +0300 Subject: [PATCH 5/8] some fixes --- include/openmc/particle_data.h | 3 + include/openmc/ray.h | 115 ++++++++++++++++++++---- src/ray.cpp | 131 +++++++++++++++++++--------- tests/cpp_unit_tests/CMakeLists.txt | 1 + tests/cpp_unit_tests/test_ray.cpp | 115 ++++++++++++++++++++++++ 5 files changed, 310 insertions(+), 55 deletions(-) create mode 100644 tests/cpp_unit_tests/test_ray.cpp diff --git a/include/openmc/particle_data.h b/include/openmc/particle_data.h index 52aba848a10..64d14f0a872 100644 --- a/include/openmc/particle_data.h +++ b/include/openmc/particle_data.h @@ -689,8 +689,11 @@ class ParticleData : virtual public GeometryState { // RNG state uint64_t& seeds(int i) { return seeds_[i]; } + const uint64_t& seeds(int i) const { return seeds_[i]; } uint64_t* seeds() { return seeds_; } + const uint64_t* seeds() const { return seeds_; } int& stream() { return stream_; } + int stream() const { return stream_; } // secondary particle bank SourceSite& secondary_bank(int i) { return secondary_bank_[i]; } diff --git a/include/openmc/ray.h b/include/openmc/ray.h index 29a7a9382e3..cafcedc9529 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -1,8 +1,12 @@ #ifndef OPENMC_RAY_H #define OPENMC_RAY_H +#include // for copy + #include "openmc/particle.h" +#include "openmc/particle_type.h" #include "openmc/position.h" +#include "openmc/random_lcg.h" namespace openmc { @@ -14,15 +18,21 @@ class Ray : virtual public GeometryState { // Initialize from location and direction Ray(Position r, Direction u) { init_from_r_u(r, u); } - // Initialize from known geometry state - Ray(const GeometryState& p) : GeometryState(p) {} + //! Initialize from a known geometry state. + explicit Ray(const GeometryState& p) + { + static_cast(*this) = p; + } + + virtual ~Ray() = default; // Called at every surface intersection within the model virtual void on_intersection() = 0; /* * Traces the ray through the geometry, calling on_intersection - * at every surface boundary. + * at every surface boundary. All per-trace accumulators are reset on + * entry, so a Ray may be traced more than once. */ void trace(double max_distance = INFTY); @@ -32,7 +42,9 @@ class Ray : virtual public GeometryState { // Sets the dist_ variable void compute_distance(); - virtual void update_distance(); + //! Accumulate a segment of flight path. + //! \param distance true geometric length of the segment + virtual void update_distance(double distance); //! Whether the ray travelled the full max_distance passed to trace(). //! False if it left the model (or hit a dead end) beforehand. This is an @@ -40,7 +52,22 @@ class Ray : virtual public GeometryState { //! requested distance, which is only accurate to floating-point roundoff. bool completed() const { return completed_; } + // Records how far the ray has traveled, including any flight through void + // before it reached the model + double traversal_distance() const { return traversal_distance_; } + protected: + //! Reset everything trace() accumulates. Derived classes that add their own + //! accumulators must override this and call the base version first. + virtual void reset_trace_state() + { + traversal_distance_ = 0.0; + completed_ = false; + stop_ = false; + event_counter_ = 0; + boundary().reset(); + } + // Records how far the ray has traveled double traversal_distance_ {0.0}; @@ -50,7 +77,7 @@ class Ray : virtual public GeometryState { private: // Max intersections before we assume ray tracing is caught in an infinite // loop: - static const int MAX_INTERSECTIONS = 1000000; + static constexpr int MAX_INTERSECTIONS = 1000000; bool stop_ {false}; @@ -60,28 +87,84 @@ class Ray : virtual public GeometryState { class ParticleRay : public Ray, public Particle { public: - ParticleRay( - Position r, Direction u, ParticleType type_, double time_, double E_) + //! Construct a free-standing ray with an explicitly chosen RNG seed. + // + //! \param seed_id value used to stride the ray's RNG seeds. Rays that are + //! spawned by a particle should use the parent-particle constructor + //! below instead; this one is for rays with no parent. + ParticleRay(Position r, Direction u, ParticleType type_, double time_, + double E_, int64_t seed_id = 0) : Ray(r, u) { - type() = type_; - time() = time_; - E() = E_; - E_last() = E_; - r_last() = r; + init_seeds(seed_id); + init_physics(type_, time_, E_); + } + + //! Construct a ray emitted by an existing particle. + // + //! The parent's RNG seeds are *copied*, not shared. Cross section lookups + //! along the ray (URR probability tables, temperature interpolation, + //! S(a,b) interpolation) consume random numbers, and drawing them from the + //! parent's live state would perturb the parent's random walk and change + //! the results of the underlying simulation. Copying also means the ray + //! samples the same URR probability-table realization the parent would + //! have, which preserves the correlation of the resonance structure along + //! the flight path. + ParticleRay(const Particle& parent, Direction u, double E_) + // The direction differs from the parent's, so the cached coordinate + // levels are no longer valid and the cell has to be found again. Starting + // from r/u rather than copying the parent's GeometryState keeps this + // correct at the cost of one exhaustive cell search. + : Ray(parent.r(), u) + { + std::copy(parent.seeds(), parent.seeds() + N_STREAMS, seeds()); + stream() = STREAM_TRACKING; + init_physics(parent.type(), parent.time(), E_); } void on_intersection() override; - // Sets the dist_ variable - void update_distance() override; + void update_distance(double distance) override; - const double& traversal_distance() const { return traversal_distance_; } - const double& traversal_mfp() const { return traversal_mfp_; } + //! A ray that cannot be located is not a lost particle. + // + //! Particle::mark_as_lost() writes a restart file, increments the shared + //! simulation::n_lost_particles counter and can abort the run outright. + //! None of that is appropriate for a ray, which is not transported and + //! whose failure to find a cell simply ends the trace. + void mark_as_lost(const char* message) override; + + // Keep the std::string / std::stringstream overloads visible; declaring + // mark_as_lost above would otherwise hide them. + using GeometryState::mark_as_lost; + + // Records how many mean free paths the ray traveled + double traversal_mfp() const { return traversal_mfp_; } protected: + void reset_trace_state() override + { + Ray::reset_trace_state(); + traversal_mfp_ = 0.0; + time() = time_start_; + } + // Records how much mean free paths the ray traveled double traversal_mfp_ {0.0}; + +private: + //! Give the ray a deterministic, self-contained RNG state. + void init_seeds(int64_t seed_id) + { + init_particle_seeds(seed_id, seeds()); + stream() = STREAM_TRACKING; + } + + //! Set type, time and energy (and, in multigroup mode, the energy group). + void init_physics(ParticleType type_, double time_, double E_); + + // Time the ray was launched, restored by reset_trace_state() + double time_start_ {0.0}; }; } // namespace openmc diff --git a/src/ray.cpp b/src/ray.cpp index d28db19735a..d9949a15840 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -15,6 +15,9 @@ void Ray::compute_distance() void Ray::trace(double max_distance) { + // Clear anything left over from a previous trace on this object. + reset_trace_state(); + // To trace the ray from its origin all the way through the model, we have // to proceed in two phases. In the first, the ray may or may not be found // inside the model. If the ray is already in the model, phase one can be @@ -26,6 +29,7 @@ void Ray::trace(double max_distance) // After phase one is done, we can starting tracing from cell to cell within // the model. This step can use neighbor lists to accelerate the ray tracing. + // Remaining distance budget double max = max_distance; bool inside_cell; @@ -51,6 +55,28 @@ void Ray::trace(double max_distance) // Advance to the boundary of the model while (!inside_cell) { advance_to_boundary_from_void(); + + // Flight through void is real flight: it has to be charged against the + // distance budget and accumulated, otherwise a ray that starts outside + // the model reports a traversal distance that excludes the leg up to the + // model, and max_distance ends up being measured from the entry point + // rather than from the ray's origin. advance_to_boundary_from_void() + // leaves boundary().distance() holding the true distance and has already + // moved the ray that far plus TINY_BIT of padding. + if (boundary().surface() != SURFACE_NONE && + boundary().distance() < INFTY) { + if (boundary().distance() >= max) { + // The budget runs out before the ray even reaches the model. Back it + // up to exactly max, undoing the padding as well. + move_distance(max - boundary().distance() - TINY_BIT); + update_distance(max); + completed_ = true; + return; + } + update_distance(boundary().distance()); + max -= boundary().distance(); + } + inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10); // If true this means no surface was intersected. See cell.cpp and search @@ -71,7 +97,7 @@ void Ray::trace(double max_distance) event_counter_++; if (event_counter_ > MAX_INTERSECTIONS) { - warning("Likely infinite loop in ray traced plot"); + warning("Likely infinite loop while ray tracing"); return; } } @@ -111,38 +137,32 @@ void Ray::trace(double max_distance) return; } + // True geometric distance to the next surface, before any numerical + // padding is applied. Everything that is physics -- accumulated path + // length, optical depth, time of flight -- has to be based on this and + // not on the padded value, or every surface crossing biases the result + // by TINY_BIT. + const double surface_distance = boundary().distance(); + // See below comment where call_on_intersection is checked in an // if statement for an explanation of this. - bool call_on_intersection {true}; - if (boundary().distance() < 10 * TINY_BIT) { - call_on_intersection = false; + bool call_on_intersection {surface_distance >= 10 * TINY_BIT}; + + if (surface_distance >= max) { + // The ray runs out of budget inside this cell, so no surface is + // crossed. Only the truncated distance was actually travelled. + move_distance(max); + update_distance(max); + completed_ = true; + return; } // DAGMC surfaces expect us to go a little bit further than the advance - // distance to properly check cell inclusion. - boundary().distance() += TINY_BIT; + // distance to properly check cell inclusion. The padding is applied to + // the motion only. + move_distance(surface_distance + TINY_BIT); - double distance = std::min(boundary().distance(), max); - - // Advance particle, prepare for next intersection - for (int lev = 0; lev < n_coord(); ++lev) { - coord(lev).r() += distance * coord(lev).u(); - } - - max -= distance; - - if (max == 0.0) { - // The ray stopped part-way through this segment, so only the truncated - // distance was actually travelled. update_distance() accumulates - // boundary().distance() into traversal_distance_ and traversal_mfp_, - // so it has to see the truncated value -- otherwise the remainder of - // the segment (out to the next surface) is counted, which over-states - // the optical depth for anything that stops inside a cell. - boundary().distance() = distance; - update_distance(); - completed_ = true; - break; - } + max -= surface_distance; surface() = boundary().surface(); // Initialize last cells from the current cell, because the cell() variable @@ -158,7 +178,9 @@ void Ray::trace(double max_distance) cross_lattice(*this, boundary(), settings::verbosity >= 10); } - update_distance(); + // Accumulate before the cell search, while material() still refers to the + // cell the ray just crossed. + update_distance(surface_distance); inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10); @@ -181,25 +203,59 @@ void Ray::trace(double max_distance) event_counter_++; if (event_counter_ > MAX_INTERSECTIONS) { - warning("Likely infinite loop in ray traced plot"); + warning("Likely infinite loop while ray tracing"); return; } } } -void Ray::update_distance() +void Ray::update_distance(double distance) { // Record how far the ray has traveled - traversal_distance_ += boundary().distance(); + traversal_distance_ += distance; +} + +void ParticleRay::init_physics( + ParticleType type_, double time_, double E_) +{ + type() = type_; + time() = time_; + time_start_ = time_; + + E() = E_; + E_last() = E_; + + // In multigroup mode the physics is driven by the group index rather than + // the energy. Particle::from_source() takes the group straight from the + // source site; here it has to be derived from the energy, otherwise every + // ray silently uses group 0. + if (!settings::run_CE) { + g() = data::mg.get_group_index(E_); + g_last() = g(); + E() = data::mg.energy_bin_avg_[g()]; + E_last() = E(); + } + + // MacroXS has no default member initializers, and the void branch of + // update_distance() only writes four of its fields. + macro_xs() = {}; +} + +void ParticleRay::mark_as_lost(const char* message) +{ + if (settings::verbosity >= 10) { + warning(message); + } + stop(); } void ParticleRay::on_intersection() {} -void ParticleRay::update_distance() +void ParticleRay::update_distance(double distance) { - Ray::update_distance(); + Ray::update_distance(distance); - time() += boundary().distance() / speed(); + time() += distance / speed(); // Calculate microscopic and macroscopic cross sections if (material() != MATERIAL_VOID) { @@ -221,13 +277,10 @@ void ParticleRay::update_distance() g_last() = g(); } } else { - macro_xs().total = 0.0; - macro_xs().absorption = 0.0; - macro_xs().fission = 0.0; - macro_xs().nu_fission = 0.0; + macro_xs() = {}; } - traversal_mfp_ += macro_xs().total * boundary().distance(); + traversal_mfp_ += macro_xs().total * distance; } } // namespace openmc diff --git a/tests/cpp_unit_tests/CMakeLists.txt b/tests/cpp_unit_tests/CMakeLists.txt index ce7e539ea57..3eb88f02378 100644 --- a/tests/cpp_unit_tests/CMakeLists.txt +++ b/tests/cpp_unit_tests/CMakeLists.txt @@ -6,6 +6,7 @@ set(TEST_NAMES test_math test_mcpl_stat_sum test_mesh + test_ray test_region test_tensor # Add additional unit test files here diff --git a/tests/cpp_unit_tests/test_ray.cpp b/tests/cpp_unit_tests/test_ray.cpp new file mode 100644 index 00000000000..e13c8bf1df1 --- /dev/null +++ b/tests/cpp_unit_tests/test_ray.cpp @@ -0,0 +1,115 @@ +#include + +#include + +#include "openmc/geometry.h" +#include "openmc/particle.h" +#include "openmc/particle_type.h" +#include "openmc/random_lcg.h" +#include "openmc/ray.h" + +using namespace openmc; + +namespace { + +// GeometryState sizes its coordinate levels from model::n_coord_levels, which +// is zero until a model is read. These tests do not trace through geometry, +// but they do construct rays, so one level has to exist. +struct CoordLevelFixture { + CoordLevelFixture() : saved_(model::n_coord_levels) + { + model::n_coord_levels = 1; + } + ~CoordLevelFixture() { model::n_coord_levels = saved_; } + int saved_; +}; + +ParticleRay make_ray(int64_t seed_id) +{ + return ParticleRay({0.0, 0.0, 0.0}, {0.0, 0.0, 1.0}, + ParticleType::neutron(), 0.0, 1.0e6, seed_id); +} + +} // namespace + +TEST_CASE("ParticleRay initializes its RNG state") +{ + CoordLevelFixture fixture; + + ParticleRay ray = make_ray(0); + + // stream() indexes seeds_, so an uninitialized value is an out-of-bounds + // pointer in current_seed(), which prn() writes through. + REQUIRE(ray.stream() == STREAM_TRACKING); + REQUIRE(ray.current_seed() == ray.seeds() + STREAM_TRACKING); + + // Every stream must be seeded, not just the tracking one: URR probability + // tables draw from STREAM_URR_PTABLE during cross section lookup. + uint64_t expected[N_STREAMS]; + init_particle_seeds(0, expected); + for (int i = 0; i < N_STREAMS; ++i) { + REQUIRE(ray.seeds(i) == expected[i]); + } +} + +TEST_CASE("ParticleRay seeding is deterministic and seed_id dependent") +{ + CoordLevelFixture fixture; + + ParticleRay a = make_ray(7); + ParticleRay b = make_ray(7); + ParticleRay c = make_ray(8); + + for (int i = 0; i < N_STREAMS; ++i) { + REQUIRE(a.seeds(i) == b.seeds(i)); + } + REQUIRE(a.seeds(STREAM_TRACKING) != c.seeds(STREAM_TRACKING)); +} + +TEST_CASE("ParticleRay copies its parent's RNG state without sharing it") +{ + CoordLevelFixture fixture; + + Particle parent; + init_particle_seeds(1234, parent.seeds()); + parent.stream() = STREAM_TRACKING; + parent.type() = ParticleType::neutron(); + parent.E() = 2.0e6; + parent.time() = 3.0e-8; + + uint64_t parent_seeds_before[N_STREAMS]; + std::copy(parent.seeds(), parent.seeds() + N_STREAMS, parent_seeds_before); + + ParticleRay ray(parent, {1.0, 0.0, 0.0}, 2.0e6); + + // The ray starts from the parent's state, so the URR probability table + // realization it samples matches the parent's. + for (int i = 0; i < N_STREAMS; ++i) { + REQUIRE(ray.seeds(i) == parent_seeds_before[i]); + } + REQUIRE(ray.stream() == STREAM_TRACKING); + REQUIRE(ray.time() == parent.time()); + + // Drawing from the ray must not disturb the parent's random walk. + prn(ray.current_seed()); + for (int i = 0; i < N_STREAMS; ++i) { + REQUIRE(parent.seeds(i) == parent_seeds_before[i]); + } + REQUIRE(ray.seeds(STREAM_TRACKING) != parent.seeds(STREAM_TRACKING)); +} + +TEST_CASE("ParticleRay accumulators start clean") +{ + CoordLevelFixture fixture; + + ParticleRay ray = make_ray(0); + + REQUIRE(ray.traversal_distance() == 0.0); + REQUIRE(ray.traversal_mfp() == 0.0); + REQUIRE_FALSE(ray.completed()); + + // update_distance() in a void region must not touch the mfp. + ray.update_distance(10.0); + REQUIRE(ray.traversal_distance() == 10.0); + REQUIRE(ray.traversal_mfp() == 0.0); +} From 32712e32fe11d2d30578db9e4e0d9d113da5ea44 Mon Sep 17 00:00:00 2001 From: GuySten Date: Tue, 8 Sep 2026 00:14:55 +0300 Subject: [PATCH 6/8] some fixes --- include/openmc/ray.h | 24 ++++++++++++++--- src/ray.cpp | 62 +++++++++++++++++++++++--------------------- 2 files changed, 53 insertions(+), 33 deletions(-) diff --git a/include/openmc/ray.h b/include/openmc/ray.h index cafcedc9529..4b45de9f9c4 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -48,29 +48,45 @@ class Ray : virtual public GeometryState { //! Whether the ray travelled the full max_distance passed to trace(). //! False if it left the model (or hit a dead end) beforehand. This is an - //! exact flag rather than a comparison of traversal_distance() against the + //! exact flag rather than a comparison of total_distance() against the //! requested distance, which is only accurate to floating-point roundoff. bool completed() const { return completed_; } - // Records how far the ray has traveled, including any flight through void - // before it reached the model + //! Distance travelled inside the model, i.e. measured from the point where + //! the ray entered the model rather than from its origin. This is the + //! quantity reported to on_intersection(). double traversal_distance() const { return traversal_distance_; } + //! Distance travelled since the ray's origin, including any flight through + //! void before the model was reached. This is what max_distance is measured + //! against. + double total_distance() const { return total_distance_; } + protected: //! Reset everything trace() accumulates. Derived classes that add their own //! accumulators must override this and call the base version first. virtual void reset_trace_state() { traversal_distance_ = 0.0; + total_distance_ = 0.0; + in_model_ = false; completed_ = false; stop_ = false; event_counter_ = 0; boundary().reset(); } - // Records how far the ray has traveled + // Records how far the ray has traveled inside the model double traversal_distance_ {0.0}; + // Records how far the ray has traveled in total, including the leg through + // void before it reached the model + double total_distance_ {0.0}; + + // Whether the ray has entered the model yet. Segments flown before that + // count toward total_distance_ but not toward traversal_distance_. + bool in_model_ {false}; + // Set when trace() consumed the whole max_distance it was given bool completed_ {false}; diff --git a/src/ray.cpp b/src/ray.cpp index d9949a15840..f01cae873bb 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -57,24 +57,26 @@ void Ray::trace(double max_distance) advance_to_boundary_from_void(); // Flight through void is real flight: it has to be charged against the - // distance budget and accumulated, otherwise a ray that starts outside - // the model reports a traversal distance that excludes the leg up to the - // model, and max_distance ends up being measured from the entry point - // rather than from the ray's origin. advance_to_boundary_from_void() - // leaves boundary().distance() holding the true distance and has already - // moved the ray that far plus TINY_BIT of padding. - if (boundary().surface() != SURFACE_NONE && - boundary().distance() < INFTY) { - if (boundary().distance() >= max) { + // distance budget, otherwise max_distance ends up being measured from the + // point where the ray entered the model rather than from its origin. It + // is accumulated into total_distance_ only -- traversal_distance_ stays + // zero until the model is reached. + if (boundary().surface() != SURFACE_NONE && boundary().distance() < INFTY) { + // advance_to_boundary_from_void() has already moved the ray to the + // boundary plus the TINY_BIT of padding, so that is the distance to + // account for. + double advance = boundary().distance() + TINY_BIT; + + if (advance >= max) { // The budget runs out before the ray even reaches the model. Back it - // up to exactly max, undoing the padding as well. - move_distance(max - boundary().distance() - TINY_BIT); + // up so the net movement is exactly max. + move_distance(max - advance); update_distance(max); completed_ = true; return; } - update_distance(boundary().distance()); - max -= boundary().distance(); + update_distance(advance); + max -= advance; } inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10); @@ -102,6 +104,10 @@ void Ray::trace(double max_distance) } } + // From here on the ray is inside the model, so its flight counts toward + // traversal_distance_ as well as total_distance_. + in_model_ = true; + // Call the specialized logic for this type of ray. This is for the // intersection for the first intersection if we had one. if (boundary().surface() != SURFACE_NONE) { @@ -137,18 +143,18 @@ void Ray::trace(double max_distance) return; } - // True geometric distance to the next surface, before any numerical - // padding is applied. Everything that is physics -- accumulated path - // length, optical depth, time of flight -- has to be based on this and - // not on the padded value, or every surface crossing biases the result - // by TINY_BIT. + // Distance from the ray's current position to the next surface. const double surface_distance = boundary().distance(); // See below comment where call_on_intersection is checked in an // if statement for an explanation of this. bool call_on_intersection {surface_distance >= 10 * TINY_BIT}; - if (surface_distance >= max) { + // DAGMC surfaces expect us to go a little bit further than the advance + // distance to properly check cell inclusion. + double advance = surface_distance + TINY_BIT; + + if (advance >= max) { // The ray runs out of budget inside this cell, so no surface is // crossed. Only the truncated distance was actually travelled. move_distance(max); @@ -157,12 +163,9 @@ void Ray::trace(double max_distance) return; } - // DAGMC surfaces expect us to go a little bit further than the advance - // distance to properly check cell inclusion. The padding is applied to - // the motion only. - move_distance(surface_distance + TINY_BIT); + move_distance(advance); - max -= surface_distance; + max -= advance; surface() = boundary().surface(); // Initialize last cells from the current cell, because the cell() variable @@ -180,7 +183,7 @@ void Ray::trace(double max_distance) // Accumulate before the cell search, while material() still refers to the // cell the ray just crossed. - update_distance(surface_distance); + update_distance(advance); inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10); @@ -211,12 +214,13 @@ void Ray::trace(double max_distance) void Ray::update_distance(double distance) { - // Record how far the ray has traveled - traversal_distance_ += distance; + total_distance_ += distance; + if (in_model_) { + traversal_distance_ += distance; + } } -void ParticleRay::init_physics( - ParticleType type_, double time_, double E_) +void ParticleRay::init_physics(ParticleType type_, double time_, double E_) { type() = type_; time() = time_; From d67168158f7ec63c58755781cbf31ca8ff16a33b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 12 Sep 2026 16:07:01 +0000 Subject: [PATCH 7/8] Give ParticleRay a Particle without a virtual GeometryState base ParticleRay was spelled `public Ray, public Particle`, which required both Ray and ParticleData to inherit GeometryState virtually so that the two halves would share one copy. That is paid for by the whole code: a virtual base means every geometry access through a Particle -- r(), u(), coord(), material() -- reaches its data through the vtable. Reading coord_[0] compiled to movq (%rdi), %rax load vptr movq -24(%rax), %rax load vbase offset from the vtable movq 24(%rdi,%rax), %rax only now index coord_ where a plain base needs just `movq 24(%rdi), %rax`. Particle is the hottest class in the code and this reached every user of it, for the sake of one kind of ray. Split the per-flight bookkeeping into RayState, which carries no geometry, and move the tracing loop into a trace_ray() template explicitly instantiated for Ray and ParticleRay. Ray becomes a plain `GeometryState, RayState` and ParticleRay a plain `Particle, RayState`, each reaching GeometryState once, non-virtually. Sharing the loop through a template rather than a base class is what removes the need for the two to meet at a common base at all, and it devirtualizes the on_intersection() and update_distance() hooks for ParticleRay as a side effect. This also clears the -Wvirtual-move-assign warning the virtual base produced. Also here, both consequences of building a ParticleData outside the transport machinery: - Default-initialize seeds_ and stream_. init_particle_seeds() is what normally sets them, and a ParticleRay is built without it, leaving current_seed() indexing seeds_ with an indeterminate stream_. - Add ParticleRay::reset(), which re-initializes a ray in place. The buffers ParticleData's constructor sizes from the loaded model -- the microscopic cross section caches, the filter matches, the flux derivatives -- come to tens of kilobytes, so a caller launching many rays wants to reuse one rather than construct each. Note that init_from_r_u() clears material(), which is what stops a reused ray from carrying stale cross sections into its next flight. Verified by rendering both ray-traced plot types, which drive the same loop through ProjectionRay and PhongRay: output is byte-identical to before. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WtCexLeoCYmBVQocfBaEG5 --- include/openmc/particle_data.h | 9 +- include/openmc/ray.h | 170 ++++++++++++++++++++++----------- src/ray.cpp | 125 +++++++++++++----------- 3 files changed, 188 insertions(+), 116 deletions(-) diff --git a/include/openmc/particle_data.h b/include/openmc/particle_data.h index 950c7c81d82..7f47b4277de 100644 --- a/include/openmc/particle_data.h +++ b/include/openmc/particle_data.h @@ -488,7 +488,7 @@ class GeometryState { * Algorithms.” Annals of Nuclear Energy 113 (March 2018): 506–18. * https://doi.org/10.1016/j.anucene.2017.11.032. */ -class ParticleData : virtual public GeometryState { +class ParticleData : public GeometryState { private: //========================================================================== // Data members -- see public: below for descriptions @@ -534,8 +534,11 @@ class ParticleData : virtual public GeometryState { bool write_track_ {false}; - uint64_t seeds_[N_STREAMS]; - int stream_; + // Default-initialized: ParticleRay and any other ParticleData built outside + // init_particle_seeds() would otherwise carry indeterminate values, and + // current_seed() indexes seeds_ with stream_ + uint64_t seeds_[N_STREAMS] {}; + int stream_ {STREAM_TRACKING}; vector local_secondary_bank_; diff --git a/include/openmc/ray.h b/include/openmc/ray.h index 4b45de9f9c4..fe6ccfbd63d 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -3,6 +3,7 @@ #include // for copy +#include "openmc/geometry.h" #include "openmc/particle.h" #include "openmc/particle_type.h" #include "openmc/position.h" @@ -10,42 +11,28 @@ namespace openmc { -// Base class that implements ray tracing logic, not necessarily through -// defined regions of the geometry but also outside of it. -class Ray : virtual public GeometryState { - +//============================================================================== +//! Per-flight bookkeeping, kept separate from any geometry or physics state. +//! +//! This lives in its own class so that ParticleRay can be both a Particle and +//! a ray without the two meeting at a *virtual* GeometryState base. A virtual +//! base would put a vtable indirection in front of every geometry access -- +//! r(), u(), coord(), material() -- throughout the transport loop, which is +//! far too high a price to pay across all of OpenMC for one kind of ray. +//! +//! Members are public because trace_ray() drives them directly. +//============================================================================== + +class RayState { public: - // Initialize from location and direction - Ray(Position r, Direction u) { init_from_r_u(r, u); } - - //! Initialize from a known geometry state. - explicit Ray(const GeometryState& p) - { - static_cast(*this) = p; - } - - virtual ~Ray() = default; - - // Called at every surface intersection within the model - virtual void on_intersection() = 0; - - /* - * Traces the ray through the geometry, calling on_intersection - * at every surface boundary. All per-trace accumulators are reset on - * entry, so a Ray may be traced more than once. - */ - void trace(double max_distance = INFTY); + //! Accumulate a segment of flight path, splitting it between the distance + //! travelled overall and the distance travelled inside the model. + //! \param distance true geometric length of the segment + void accumulate_distance(double distance); // Stops the ray and exits tracing when called from on_intersection void stop() { stop_ = true; } - // Sets the dist_ variable - void compute_distance(); - - //! Accumulate a segment of flight path. - //! \param distance true geometric length of the segment - virtual void update_distance(double distance); - //! Whether the ray travelled the full max_distance passed to trace(). //! False if it left the model (or hit a dead end) beforehand. This is an //! exact flag rather than a comparison of total_distance() against the @@ -62,19 +49,8 @@ class Ray : virtual public GeometryState { //! against. double total_distance() const { return total_distance_; } -protected: - //! Reset everything trace() accumulates. Derived classes that add their own - //! accumulators must override this and call the base version first. - virtual void reset_trace_state() - { - traversal_distance_ = 0.0; - total_distance_ = 0.0; - in_model_ = false; - completed_ = false; - stop_ = false; - event_counter_ = 0; - boundary().reset(); - } + //! Reset everything a flight accumulates. + void reset_ray_state() { *this = RayState {}; } // Records how far the ray has traveled inside the model double traversal_distance_ {0.0}; @@ -90,19 +66,92 @@ class Ray : virtual public GeometryState { // Set when trace() consumed the whole max_distance it was given bool completed_ {false}; -private: - // Max intersections before we assume ray tracing is caught in an infinite - // loop: - static constexpr int MAX_INTERSECTIONS = 1000000; - bool stop_ {false}; unsigned event_counter_ {0}; }; -class ParticleRay : public Ray, public Particle { +//! Trace a ray through the geometry, calling ray.on_intersection() at every +//! surface boundary. All per-flight accumulators are reset on entry, so a ray +//! may be traced more than once. +//! +//! RayT must be a GeometryState that also carries a RayState and supplies +//! on_intersection(), update_distance(double) and reset_trace_state(). +//! Explicitly instantiated in ray.cpp for Ray and ParticleRay; being a +//! template rather than a virtual method is what lets the two share this +//! logic without sharing a base class. +template +void trace_ray(RayT& ray, double max_distance); + +// Base class that implements ray tracing logic, not necessarily through +// defined regions of the geometry but also outside of it. +class Ray : public GeometryState, public RayState { public: + Ray() = default; + + // Initialize from location and direction + Ray(Position r, Direction u) { init_from_r_u(r, u); } + + //! Initialize from a known geometry state. + explicit Ray(const GeometryState& p) + { + static_cast(*this) = p; + } + + virtual ~Ray() = default; + + // Called at every surface intersection within the model + virtual void on_intersection() = 0; + + void trace(double max_distance = INFTY); + + //! Recompute the distance to the next surface, e.g. after a direction change + void compute_distance() { boundary() = distance_to_boundary(*this); } + + //! Accumulate a segment of flight path. + //! \param distance true geometric length of the segment + virtual void update_distance(double distance) + { + accumulate_distance(distance); + } + + //! Reset everything trace() accumulates. Derived classes that add their own + //! accumulators must override this and call the base version first. + virtual void reset_trace_state() + { + reset_ray_state(); + boundary().reset(); + } +}; + +class ParticleRay : public Particle, public RayState { + +public: + ParticleRay() = default; + + //! Re-initialize an existing ray for a new flight. + //! + //! Everything trace() accumulates is reset, but the heap buffers that + //! ParticleData's constructor sizes from the loaded model -- the + //! microscopic cross section caches, the filter matches, the flux + //! derivatives -- are left allocated so they can be reused. That is the + //! point of resetting rather than constructing: a caller that launches many + //! rays would otherwise allocate and zero tens of kilobytes apiece, which is + //! not affordable anywhere near the transport loop. + //! + //! Note that init_from_r_u() clears material(), so the first segment of the + //! new flight always recomputes cross sections rather than reusing whatever + //! the previous flight happened to leave cached. + void reset( + Position r, Direction u, ParticleType type_, double time_, double E_) + { + init_from_r_u(r, u); + reset_trace_state(); + init_physics(type_, time_, E_); + zero_flux_derivs(); + } + //! Construct a free-standing ray with an explicitly chosen RNG seed. // //! \param seed_id value used to stride the ray's RNG seeds. Rays that are @@ -110,8 +159,8 @@ class ParticleRay : public Ray, public Particle { //! below instead; this one is for rays with no parent. ParticleRay(Position r, Direction u, ParticleType type_, double time_, double E_, int64_t seed_id = 0) - : Ray(r, u) { + init_from_r_u(r, u); init_seeds(seed_id); init_physics(type_, time_, E_); } @@ -127,20 +176,24 @@ class ParticleRay : public Ray, public Particle { //! have, which preserves the correlation of the resonance structure along //! the flight path. ParticleRay(const Particle& parent, Direction u, double E_) + { // The direction differs from the parent's, so the cached coordinate // levels are no longer valid and the cell has to be found again. Starting // from r/u rather than copying the parent's GeometryState keeps this // correct at the cost of one exhaustive cell search. - : Ray(parent.r(), u) - { + init_from_r_u(parent.r(), u); std::copy(parent.seeds(), parent.seeds() + N_STREAMS, seeds()); stream() = STREAM_TRACKING; init_physics(parent.type(), parent.time(), E_); } - void on_intersection() override; + void trace(double max_distance = INFTY); - void update_distance(double distance) override; + //! No-op: a ParticleRay has nothing to do at a surface crossing, since the + //! optical depth is accumulated in update_distance() instead. + void on_intersection() {} + + void update_distance(double distance); //! A ray that cannot be located is not a lost particle. // @@ -157,14 +210,15 @@ class ParticleRay : public Ray, public Particle { // Records how many mean free paths the ray traveled double traversal_mfp() const { return traversal_mfp_; } -protected: - void reset_trace_state() override + void reset_trace_state() { - Ray::reset_trace_state(); + reset_ray_state(); + boundary().reset(); traversal_mfp_ = 0.0; time() = time_start_; } +protected: // Records how much mean free paths the ray traveled double traversal_mfp_ {0.0}; diff --git a/src/ray.cpp b/src/ray.cpp index f01cae873bb..8c80cb4416d 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -8,15 +8,16 @@ namespace openmc { -void Ray::compute_distance() -{ - boundary() = distance_to_boundary(*this); -} +namespace { +// Max intersections before we assume ray tracing is caught in an infinite loop +constexpr int MAX_INTERSECTIONS = 1000000; +} // namespace -void Ray::trace(double max_distance) +template +void trace_ray(RayT& ray, double max_distance) { // Clear anything left over from a previous trace on this object. - reset_trace_state(); + ray.reset_trace_state(); // To trace the ray from its origin all the way through the model, we have // to proceed in two phases. In the first, the ray may or may not be found @@ -34,13 +35,13 @@ void Ray::trace(double max_distance) bool inside_cell; // Check for location if the particle is already known - if (lowest_coord().cell() == C_NONE) { + if (ray.lowest_coord().cell() == C_NONE) { // The geometry position of the particle is either unknown or outside of the // edge of the model. - if (lowest_coord().universe() == C_NONE) { + if (ray.lowest_coord().universe() == C_NONE) { // Attempt to initialize the particle. We may have to // enter a loop to move it up to the edge of the model. - inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10); + inside_cell = exhaustive_find_cell(ray, settings::verbosity >= 10); } else { // It has been already calculated that the current position is outside of // the edge of the model. @@ -54,37 +55,38 @@ void Ray::trace(double max_distance) // Advance to the boundary of the model while (!inside_cell) { - advance_to_boundary_from_void(); + ray.advance_to_boundary_from_void(); // Flight through void is real flight: it has to be charged against the // distance budget, otherwise max_distance ends up being measured from the // point where the ray entered the model rather than from its origin. It // is accumulated into total_distance_ only -- traversal_distance_ stays // zero until the model is reached. - if (boundary().surface() != SURFACE_NONE && boundary().distance() < INFTY) { + if (ray.boundary().surface() != SURFACE_NONE && + ray.boundary().distance() < INFTY) { // advance_to_boundary_from_void() has already moved the ray to the // boundary plus the TINY_BIT of padding, so that is the distance to // account for. - double advance = boundary().distance() + TINY_BIT; + double advance = ray.boundary().distance() + TINY_BIT; if (advance >= max) { // The budget runs out before the ray even reaches the model. Back it // up so the net movement is exactly max. - move_distance(max - advance); - update_distance(max); - completed_ = true; + ray.move_distance(max - advance); + ray.update_distance(max); + ray.completed_ = true; return; } - update_distance(advance); + ray.update_distance(advance); max -= advance; } - inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10); + inside_cell = exhaustive_find_cell(ray, settings::verbosity >= 10); // If true this means no surface was intersected. See cell.cpp and search // for numeric_limits to see where we return it. - if (surface() == std::numeric_limits::max()) { - warning(fmt::format("Lost a ray, r = {}, u = {}", r(), u())); + if (ray.surface() == std::numeric_limits::max()) { + warning(fmt::format("Lost a ray, r = {}, u = {}", ray.r(), ray.u())); return; } @@ -94,11 +96,11 @@ void Ray::trace(double max_distance) break; // if there is no intersection with the model, we're done - if (boundary().surface() == SURFACE_NONE) + if (ray.boundary().surface() == SURFACE_NONE) return; - event_counter_++; - if (event_counter_ > MAX_INTERSECTIONS) { + ray.event_counter_++; + if (ray.event_counter_ > MAX_INTERSECTIONS) { warning("Likely infinite loop while ray tracing"); return; } @@ -106,22 +108,22 @@ void Ray::trace(double max_distance) // From here on the ray is inside the model, so its flight counts toward // traversal_distance_ as well as total_distance_. - in_model_ = true; + ray.in_model_ = true; // Call the specialized logic for this type of ray. This is for the // intersection for the first intersection if we had one. - if (boundary().surface() != SURFACE_NONE) { + if (ray.boundary().surface() != SURFACE_NONE) { // set the geometry state's surface attribute to be used for // surface normal computation - surface() = boundary().surface(); - on_intersection(); - if (stop_) + ray.surface() = ray.boundary().surface(); + ray.on_intersection(); + if (ray.stop_) return; } // reset surface attribute to zero after the first intersection so that it // doesn't perturb surface crossing logic from here on out - surface() = 0; + ray.surface() = 0; // This is the ray tracing loop within the model. It exits after exiting // the model, which is equivalent to assuming that the model is convex. @@ -132,19 +134,20 @@ void Ray::trace(double max_distance) // fine. while (true) { - compute_distance(); + ray.boundary() = distance_to_boundary(ray); // There are no more intersections to process // if we hit the edge of the model, so stop // the particle in that case. Also, just exit // if a negative distance was somehow computed. - if (boundary().distance() == INFTY || boundary().distance() == INFINITY || - boundary().distance() < 0) { + if (ray.boundary().distance() == INFTY || + ray.boundary().distance() == INFINITY || + ray.boundary().distance() < 0) { return; } // Distance from the ray's current position to the next surface. - const double surface_distance = boundary().distance(); + const double surface_distance = ray.boundary().distance(); // See below comment where call_on_intersection is checked in an // if statement for an explanation of this. @@ -157,35 +160,35 @@ void Ray::trace(double max_distance) if (advance >= max) { // The ray runs out of budget inside this cell, so no surface is // crossed. Only the truncated distance was actually travelled. - move_distance(max); - update_distance(max); - completed_ = true; + ray.move_distance(max); + ray.update_distance(max); + ray.completed_ = true; return; } - move_distance(advance); + ray.move_distance(advance); max -= advance; - surface() = boundary().surface(); + ray.surface() = ray.boundary().surface(); // Initialize last cells from the current cell, because the cell() variable // does not contain the data for the case of a single-segment ray - for (int j = 0; j < n_coord(); ++j) { - cell_last(j) = coord(j).cell(); + for (int j = 0; j < ray.n_coord(); ++j) { + ray.cell_last(j) = ray.coord(j).cell(); } - n_coord_last() = n_coord(); - n_coord() = boundary().coord_level(); - if (boundary().lattice_translation()[0] != 0 || - boundary().lattice_translation()[1] != 0 || - boundary().lattice_translation()[2] != 0) { - cross_lattice(*this, boundary(), settings::verbosity >= 10); + ray.n_coord_last() = ray.n_coord(); + ray.n_coord() = ray.boundary().coord_level(); + if (ray.boundary().lattice_translation()[0] != 0 || + ray.boundary().lattice_translation()[1] != 0 || + ray.boundary().lattice_translation()[2] != 0) { + cross_lattice(ray, ray.boundary(), settings::verbosity >= 10); } // Accumulate before the cell search, while material() still refers to the // cell the ray just crossed. - update_distance(advance); + ray.update_distance(advance); - inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10); + inside_cell = neighbor_list_find_cell(ray, settings::verbosity >= 10); // Call the specialized logic for this type of ray. Note that we do not // call this if the advance distance is very small. Unfortunately, it seems @@ -196,23 +199,23 @@ void Ray::trace(double max_distance) // threshold 10x larger than the scoot distance used to advance up to the // model boundary, we can avoid that situation. if (call_on_intersection) { - on_intersection(); - if (stop_) + ray.on_intersection(); + if (ray.stop_) return; } if (!inside_cell) return; - event_counter_++; - if (event_counter_ > MAX_INTERSECTIONS) { + ray.event_counter_++; + if (ray.event_counter_ > MAX_INTERSECTIONS) { warning("Likely infinite loop while ray tracing"); return; } } } -void Ray::update_distance(double distance) +void RayState::accumulate_distance(double distance) { total_distance_ += distance; if (in_model_) { @@ -220,6 +223,16 @@ void Ray::update_distance(double distance) } } +void Ray::trace(double max_distance) +{ + trace_ray(*this, max_distance); +} + +void ParticleRay::trace(double max_distance) +{ + trace_ray(*this, max_distance); +} + void ParticleRay::init_physics(ParticleType type_, double time_, double E_) { type() = type_; @@ -253,11 +266,9 @@ void ParticleRay::mark_as_lost(const char* message) stop(); } -void ParticleRay::on_intersection() {} - void ParticleRay::update_distance(double distance) { - Ray::update_distance(distance); + accumulate_distance(distance); time() += distance / speed(); @@ -287,4 +298,8 @@ void ParticleRay::update_distance(double distance) traversal_mfp_ += macro_xs().total * distance; } +// Explicit instantiations: the two kinds of ray that share the tracing loop +template void trace_ray(Ray&, double); +template void trace_ray(ParticleRay&, double); + } // namespace openmc From 3574ce504aedc2fb34d49aaf6afc128a3828a50b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 14:09:19 +0000 Subject: [PATCH 8/8] Accumulate ray segments before crossing into the next cell cross_lattice() locates the particle in the next cell, which overwrites material(), so the segment was scored with the next cell's cross sections when a lattice was crossed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BK6aD4aznm1HR84bTxGn5v --- src/ray.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/ray.cpp b/src/ray.cpp index 8c80cb4416d..aade1eca58f 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -170,6 +170,11 @@ void trace_ray(RayT& ray, double max_distance) max -= advance; + // Accumulate before crossing into the next cell, while material() still + // refers to the cell the ray just traversed. Both cross_lattice() and the + // cell search below overwrite it. + ray.update_distance(advance); + ray.surface() = ray.boundary().surface(); // Initialize last cells from the current cell, because the cell() variable // does not contain the data for the case of a single-segment ray @@ -184,10 +189,6 @@ void trace_ray(RayT& ray, double max_distance) cross_lattice(ray, ray.boundary(), settings::verbosity >= 10); } - // Accumulate before the cell search, while material() still refers to the - // cell the ray just crossed. - ray.update_distance(advance); - inside_cell = neighbor_list_find_cell(ray, settings::verbosity >= 10); // Call the specialized logic for this type of ray. Note that we do not