diff --git a/include/openmc/particle_data.h b/include/openmc/particle_data.h index 24b7eb53c0a..7f47b4277de 100644 --- a/include/openmc/particle_data.h +++ b/include/openmc/particle_data.h @@ -534,8 +534,11 @@ class ParticleData : 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_; @@ -693,8 +696,11 @@ class ParticleData : 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& local_secondary_bank(int i) { return local_secondary_bank_[i]; } diff --git a/include/openmc/ray.h b/include/openmc/ray.h index 62e86b0d90f..fe6ccfbd63d 100644 --- a/include/openmc/ray.h +++ b/include/openmc/ray.h @@ -1,49 +1,240 @@ #ifndef OPENMC_RAY_H #define OPENMC_RAY_H -#include "openmc/particle_data.h" +#include // for copy + +#include "openmc/geometry.h" +#include "openmc/particle.h" +#include "openmc/particle_type.h" #include "openmc/position.h" +#include "openmc/random_lcg.h" namespace openmc { +//============================================================================== +//! 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: + //! 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; } + + //! 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 + //! requested distance, which is only accurate to floating-point roundoff. + bool completed() const { return completed_; } + + //! 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_; } + + //! 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}; + + // 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}; + + bool stop_ {false}; + + unsigned event_counter_ {0}; +}; + +//! 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 { +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 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. - */ - void trace(); + void trace(double max_distance = INFTY); - // Stops the ray and exits tracing when called from on_intersection - void stop() { stop_ = true; } + //! 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(); + } - // Sets the dist_ variable - void compute_distance(); + //! 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) + { + init_from_r_u(r, u); + 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. + 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 trace(double max_distance = INFTY); + + //! 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. + // + //! 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_; } + + void reset_trace_state() + { + reset_ray_state(); + boundary().reset(); + traversal_mfp_ = 0.0; + time() = time_start_; + } protected: - // Records how far the ray has traveled - double traversal_distance_ {0.0}; + // Records how much mean free paths the ray traveled + double traversal_mfp_ {0.0}; private: - // Max intersections before we assume ray tracing is caught in an infinite - // loop: - static const int MAX_INTERSECTIONS = 1000000; + //! 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; + } - bool stop_ {false}; + //! Set type, time and energy (and, in multigroup mode, the energy group). + void init_physics(ParticleType type_, double time_, double E_); - unsigned event_counter_ {0}; + // 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 3d848e3a3a7..aade1eca58f 100644 --- a/src/ray.cpp +++ b/src/ray.cpp @@ -2,17 +2,23 @@ #include "openmc/error.h" #include "openmc/geometry.h" +#include "openmc/material.h" +#include "openmc/mgxs_interface.h" #include "openmc/settings.h" 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() +template +void trace_ray(RayT& ray, double max_distance) { + // Clear anything left over from a previous trace on this object. + 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 // inside the model. If the ray is already in the model, phase one can be @@ -24,15 +30,18 @@ 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. + // Remaining distance budget + double max = 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. @@ -46,13 +55,38 @@ void Ray::trace() // Advance to the boundary of the model while (!inside_cell) { - advance_to_boundary_from_void(); - inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10); + 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 (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 = 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. + ray.move_distance(max - advance); + ray.update_distance(max); + ray.completed_ = true; + return; + } + ray.update_distance(advance); + max -= advance; + } + + 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; } @@ -62,30 +96,34 @@ void Ray::trace() 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) { - warning("Likely infinite loop in ray traced plot"); + ray.event_counter_++; + if (ray.event_counter_ > MAX_INTERSECTIONS) { + warning("Likely infinite loop while ray tracing"); return; } } + // From here on the ray is inside the model, so its flight counts toward + // traversal_distance_ as well as total_distance_. + 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. @@ -96,49 +134,62 @@ void Ray::trace() // 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 = ray.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}; // DAGMC surfaces expect us to go a little bit further than the advance // distance to properly check cell inclusion. - boundary().distance() += TINY_BIT; + double advance = surface_distance + TINY_BIT; - // Advance particle, prepare for next intersection - for (int lev = 0; lev < n_coord(); ++lev) { - coord(lev).r() += boundary().distance() * coord(lev).u(); + if (advance >= max) { + // The ray runs out of budget inside this cell, so no surface is + // crossed. Only the truncated distance was actually travelled. + ray.move_distance(max); + ray.update_distance(max); + ray.completed_ = true; + return; } - surface() = boundary().surface(); + + ray.move_distance(advance); + + 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 - 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); } - // Record how far the ray has traveled - traversal_distance_ += boundary().distance(); - 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 @@ -149,20 +200,107 @@ void Ray::trace() // 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) { - warning("Likely infinite loop in ray traced plot"); + ray.event_counter_++; + if (ray.event_counter_ > MAX_INTERSECTIONS) { + warning("Likely infinite loop while ray tracing"); return; } } } +void RayState::accumulate_distance(double distance) +{ + total_distance_ += distance; + if (in_model_) { + traversal_distance_ += 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_; + 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::update_distance(double distance) +{ + accumulate_distance(distance); + + time() += distance / speed(); + + // 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() = {}; + } + + 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