From fa3fc916816fb79c19f95749aec12fdf32e41f53 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Tue, 16 Jun 2026 16:05:43 -0400 Subject: [PATCH 01/37] angular flux init --- include/openmc/random_ray/source_region.h | 22 ++++++++++++++++++++++ src/random_ray/source_region.cpp | 1 + 2 files changed, 23 insertions(+) diff --git a/include/openmc/random_ray/source_region.h b/include/openmc/random_ray/source_region.h index 65f2e6bc41c..f231b30fee2 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -180,6 +180,7 @@ class SourceRegionHandle { float* source_; float* external_source_; double* scalar_flux_final_; + vector* angular_flux_new_; MomentArray* source_gradients_; MomentArray* flux_moments_old_; @@ -279,6 +280,9 @@ class SourceRegionHandle { double& scalar_flux_final(int g) { return scalar_flux_final_[g]; } const double scalar_flux_final(int g) const { return scalar_flux_final_[g]; } + double& angular_flux_new(int g, int angle) { return angular_flux_new_[g]; } + const double angular_flux_new(int g) const { return angular_flux_new_[g]; } + float& source(int g) { return source_[g]; } const float source(int g) const { return source_[g]; } @@ -375,6 +379,9 @@ class SourceRegion { //!< active iterations (used for plotting, //!< or computing adjoint sources) + vector + angular_flux_new_; //!< The angular flux from the current iteration + vector source_gradients_; //!< The linear source gradients vector flux_moments_old_; //!< The linear flux moments from the previous iteration @@ -572,6 +579,20 @@ class SourceRegionContainer { return scalar_flux_final_[se]; } + double& angular_flux_new(int64_t sr, int g) + { + return angular_flux_new_[index(sr, g)]; + } + const double angular_flux_new(int64_t sr, int g) const + { + return angular_flux_new_[index(sr, g)]; + } + double& angular_flux_new(int64_t se) { return angular_flux_new_[se]; } + const double angular_flux_new(int64_t se) const + { + return angular_flux_new_[se]; + } + float& source(int64_t sr, int g) { return source_[index(sr, g)]; } const float source(int64_t sr, int g) const { return source_[index(sr, g)]; } float& source(int64_t se) { return source_[se]; } @@ -671,6 +692,7 @@ class SourceRegionContainer { vector scalar_flux_old_; vector scalar_flux_new_; vector scalar_flux_final_; + vector angular_flux_new_; vector source_; vector external_source_; diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 78543c5ab53..01d8d6b6962 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -26,6 +26,7 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) scalar_flux_new_(sr.scalar_flux_new_.data()), source_(sr.source_.data()), external_source_(sr.external_source_.data()), scalar_flux_final_(sr.scalar_flux_final_.data()), + angular_flux_new_(sr.angular_flux_new_.data()), source_gradients_(sr.source_gradients_.data()), flux_moments_old_(sr.flux_moments_old_.data()), flux_moments_new_(sr.flux_moments_new_.data()), From 8ff54d8175c572b3d201c5935cfa70e0e8384d76 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 13 Aug 2026 12:06:17 -0400 Subject: [PATCH 02/37] Particle, RandomRay, SourceRegion and TallyTask changes to support angular flux accumulation --- include/openmc/particle.h | 4 ++ include/openmc/random_ray/random_ray.h | 3 + include/openmc/random_ray/source_region.h | 60 +++++++++++----- src/boundary_condition.cpp | 3 + src/random_ray/random_ray.cpp | 86 ++++++++++++++++++++--- src/random_ray/source_region.cpp | 28 ++++++-- 6 files changed, 151 insertions(+), 33 deletions(-) diff --git a/include/openmc/particle.h b/include/openmc/particle.h index 8db9721baa8..d4191213f2d 100644 --- a/include/openmc/particle.h +++ b/include/openmc/particle.h @@ -106,6 +106,10 @@ class Particle : public ParticleData { void cross_periodic_bc( const Surface& surf, Position new_r, Direction new_u, int new_surface); + //! Reset angular flux tally bin if in RandomRay mode + //! (does nothing for MC particles) + virtual void direction_changed() {} + //! mark a particle as lost and create a particle restart file //! \param message A warning message to display virtual void mark_as_lost(const char* message) override; diff --git a/include/openmc/random_ray/random_ray.h b/include/openmc/random_ray/random_ray.h index b61d2d67aa8..32a5657ed27 100644 --- a/include/openmc/random_ray/random_ray.h +++ b/include/openmc/random_ray/random_ray.h @@ -36,12 +36,14 @@ class RandomRay : public Particle { SourceRegionHandle& srh, double distance, bool is_active, Position r); void attenuate_flux_linear_source_void( SourceRegionHandle& srh, double distance, bool is_active, Position r); + void direction_changed() override { angular_bin_ = C_NONE; }; void initialize_ray(uint64_t ray_id, FlatSourceDomain* domain); uint64_t transport_history_based_single_ray(); SourceSite sample_prng(); SourceSite sample_halton(); SourceSite sample_s2(); + int angular_bin(); // accessor for current angular quadrature bin index //---------------------------------------------------------------------------- // Static data members @@ -67,6 +69,7 @@ class RandomRay : public Particle { int negroups_; int ntemperature_; + int angular_bin_ {C_NONE}; FlatSourceDomain* domain_ {nullptr}; // pointer to domain that has flat source // data needed for ray transport double distance_travelled_ {0}; diff --git a/include/openmc/random_ray/source_region.h b/include/openmc/random_ray/source_region.h index f231b30fee2..db28adda0d6 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -54,9 +54,17 @@ struct TallyTask { int filter_idx; int score_idx; int score_type; - TallyTask(int tally_idx, int filter_idx, int score_idx, int score_type) + // Angular quadrature bin index this task applies to. C_NONE (the default) + // means the task is angle-independent and scores against the source + // region's scalar flux, as normal. A non-negative value means the task + // is scoring the angular flux tally for that specific angular bin + // (source_regions_.angular_flux_new(sr, g, angle_bin)), and is only ever + // created for source regions with an external source present. + int angle_bin {C_NONE}; + TallyTask(int tally_idx, int64_t filter_idx, int score_idx, int score_type, + int angle_bin = C_NONE) : tally_idx(tally_idx), filter_idx(filter_idx), score_idx(score_idx), - score_type(score_type) + score_type(score_type), angle_bin(angle_bin) {} TallyTask() = default; @@ -65,7 +73,8 @@ struct TallyTask { bool operator==(const TallyTask& other) const { return tally_idx == other.tally_idx && filter_idx == other.filter_idx && - score_idx == other.score_idx && score_type == other.score_type; + score_idx == other.score_idx && score_type == other.score_type && + angle_bin == other.angle_bin; } struct HashFunctor { @@ -76,6 +85,7 @@ struct TallyTask { hash_combine(seed, task.filter_idx); hash_combine(seed, task.score_idx); hash_combine(seed, task.score_type); + hash_combine(seed, task.angle_bin); return seed; } }; @@ -141,6 +151,7 @@ class SourceRegionHandle { //---------------------------------------------------------------------------- // Public Data members int negroups_; + int nangles_ {1}; //!< Number of angular bins for angular flux binning bool is_numerical_fp_artifact_ {false}; bool is_linear_ {false}; @@ -180,7 +191,7 @@ class SourceRegionHandle { float* source_; float* external_source_; double* scalar_flux_final_; - vector* angular_flux_new_; + double* angular_flux_new_; //!< only accumulated for ext. source biasing MomentArray* source_gradients_; MomentArray* flux_moments_old_; @@ -280,8 +291,14 @@ class SourceRegionHandle { double& scalar_flux_final(int g) { return scalar_flux_final_[g]; } const double scalar_flux_final(int g) const { return scalar_flux_final_[g]; } - double& angular_flux_new(int g, int angle) { return angular_flux_new_[g]; } - const double angular_flux_new(int g) const { return angular_flux_new_[g]; } + double& angular_flux_new(int g, int a) + { + return angular_flux_new_[g * nangles_ + a]; + } + const double angular_flux_new(int g, int a) const + { + return angular_flux_new_[g * nangles_ + a]; + } float& source(int g) { return source_[g]; } const float source(int g) const { return source_[g]; } @@ -319,7 +336,7 @@ class SourceRegion { public: //---------------------------------------------------------------------------- // Constructors - SourceRegion(int negroups, bool is_linear); + SourceRegion(int negroups, bool is_linear, int nangles = 1); SourceRegion() = default; //---------------------------------------------------------------------------- @@ -402,8 +419,8 @@ class SourceRegionContainer { public: //---------------------------------------------------------------------------- // Constructors - SourceRegionContainer(int negroups, bool is_linear) - : negroups_(negroups), is_linear_(is_linear) + SourceRegionContainer(int negroups, bool is_linear, int nangles = 1) + : negroups_(negroups), is_linear_(is_linear), nangles_(nangles) {} SourceRegionContainer() = default; @@ -579,18 +596,18 @@ class SourceRegionContainer { return scalar_flux_final_[se]; } - double& angular_flux_new(int64_t sr, int g) + double& angular_flux_new(int64_t sr, int g, int a) { - return angular_flux_new_[index(sr, g)]; + return angular_flux_new_[index_angle(sr, g, a)]; } - const double angular_flux_new(int64_t sr, int g) const + const double angular_flux_new(int64_t sr, int g, int a) const { - return angular_flux_new_[index(sr, g)]; + return angular_flux_new_[index_angle(sr, g, a)]; } - double& angular_flux_new(int64_t se) { return angular_flux_new_[se]; } - const double angular_flux_new(int64_t se) const + double& angular_flux_new(int64_t sea) { return angular_flux_new_[sea]; } + const double angular_flux_new(int64_t sea) const { - return angular_flux_new_[se]; + return angular_flux_new_[sea]; } float& source(int64_t sr, int g) { return source_[index(sr, g)]; } @@ -647,8 +664,14 @@ class SourceRegionContainer { void flux_swap(); int64_t n_source_regions() const { return n_source_regions_; } int64_t n_source_elements() const { return n_source_regions_ * negroups_; } + int64_t n_source_angular_elements() const + { + return n_source_regions_ * negroups_ * nangles_; + } int& negroups() { return negroups_; } const int negroups() const { return negroups_; } + int& nangles() { return nangles_; } + const int nangles() const { return nangles_; } bool& is_linear() { return is_linear_; } const bool is_linear() const { return is_linear_; } SourceRegionHandle get_source_region_handle(int64_t sr); @@ -659,6 +682,7 @@ class SourceRegionContainer { // Private Data Members int64_t n_source_regions_ {0}; int negroups_ {0}; + int nangles_ {1}; bool is_linear_ {false}; // SoA storage for scalar fields (one item per source region) @@ -713,6 +737,10 @@ class SourceRegionContainer { // Helper function for indexing inline int index(int64_t sr, int g) const { return sr * negroups_ + g; } + inline int64_t index_angle(int64_t sr, int g, int a) const + { + return (sr * negroups_ + g) * nangles_ + a; + } }; } // namespace openmc diff --git a/src/boundary_condition.cpp b/src/boundary_condition.cpp index 5bbda483059..85adb200ee8 100644 --- a/src/boundary_condition.cpp +++ b/src/boundary_condition.cpp @@ -39,6 +39,7 @@ void ReflectiveBC::handle_particle(Particle& p, const Surface& surf) const { Direction u = surf.reflect(p.r(), p.u(), &p); u /= u.norm(); + p.direction_changed(); // Handle the effects of the surface albedo on the particle's weight. BoundaryCondition::handle_albedo(p, surf); @@ -54,6 +55,7 @@ void WhiteBC::handle_particle(Particle& p, const Surface& surf) const { Direction u = surf.diffuse_reflect(p.r(), p.u(), p.current_seed()); u /= u.norm(); + p.direction_changed(); // Handle the effects of the surface albedo on the particle's weight. BoundaryCondition::handle_albedo(p, surf); @@ -240,6 +242,7 @@ void RotationalPeriodicBC::handle_particle( new_u[zero_axis_idx_] = u[zero_axis_idx_]; new_u[axis_1_idx_] = cos_theta * u[axis_1_idx_] - sin_theta * u[axis_2_idx_]; new_u[axis_2_idx_] = sin_theta * u[axis_1_idx_] + cos_theta * u[axis_2_idx_]; + p.direction_changed(); // Handle the effects of the surface albedo on the particle's weight. BoundaryCondition::handle_albedo(p, surf); diff --git a/src/random_ray/random_ray.cpp b/src/random_ray/random_ray.cpp index dde5023e44f..f88768984f2 100644 --- a/src/random_ray/random_ray.cpp +++ b/src/random_ray/random_ray.cpp @@ -457,8 +457,22 @@ void RandomRay::attenuate_flux_flat_source( if (is_active) { // Accumulate delta psi into new estimate of source region flux for // this iteration - for (int g = 0; g < negroups_; g++) { - srh.scalar_flux_new(g) += delta_psi_[g]; + if (srh.external_source_present()) { + // Accumulate angular flux data in regions with external source + // for later source biasing. + // + // TODO: replace the above condition with a different + // SourceRegionHandle flag to enable angular flux tallying more + // generally. + int a = angular_bin(); + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += delta_psi_[g]; + srh.angular_flux_new(g, a) += delta_psi_[g]; + } + } else { + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += delta_psi_[g]; + } } // Accomulate volume (ray distance) into this iteration's estimate @@ -498,8 +512,22 @@ void RandomRay::attenuate_flux_flat_source_void( // Accumulate delta psi into new estimate of source region flux for // this iteration - for (int g = 0; g < negroups_; g++) { - srh.scalar_flux_new(g) += angular_flux_[g] * distance; + if (srh.external_source_present()) { + // Accumulate angular flux data in regions with external source + // for later source biasing. + // + // TODO: replace the above condition with a different + // SourceRegionHandle flag to enable angular flux tallying more + // generally. + int a = angular_bin(); + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += angular_flux_[g] * distance; + srh.angular_flux_new(g, a) += angular_flux_[g] * distance; + } + } else { + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += angular_flux_[g] * distance; + } } // Accomulate volume (ray distance) into this iteration's estimate @@ -628,9 +656,24 @@ void RandomRay::attenuate_flux_linear_source( if (is_active) { // Accumulate deltas into the new estimate of source region flux for this // iteration - for (int g = 0; g < negroups_; g++) { - srh.scalar_flux_new(g) += delta_psi_[g]; - srh.flux_moments_new(g) += delta_moments_[g]; + if (srh.external_source_present()) { + // Accumulate angular flux data in regions with external source + // for later source biasing. + // + // TODO: replace the above condition with a different + // SourceRegionHandle flag to enable angular flux tallying more + // generally. + int a = angular_bin(); + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += delta_psi_[g]; + srh.flux_moments_new(g) += delta_moments_[g]; + srh.angular_flux_new(g, a) += delta_psi_[g]; + } + } else { + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += delta_psi_[g]; + srh.flux_moments_new(g) += delta_moments_[g]; + } } // Accumulate the volume (ray segment distance), centroid, and spatial @@ -732,9 +775,24 @@ void RandomRay::attenuate_flux_linear_source_void( // Accumulate delta psi into new estimate of source region flux for // this iteration, and update flux momements - for (int g = 0; g < negroups_; g++) { - srh.scalar_flux_new(g) += angular_flux_[g] * distance; - srh.flux_moments_new(g) += delta_moments_[g]; + if (srh.external_source_present()) { + // Accumulate angular flux data in regions with external source + // for later source biasing. + // + // TODO: replace the above condition with a different + // SourceRegionHandle flag to enable angular flux tallying more + // generally. + int a = angular_bin(); + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += angular_flux_[g] * distance; + srh.flux_moments_new(g) += delta_moments_[g]; + srh.angular_flux_new(g, a) += angular_flux_[g] * distance; + } + } else { + for (int g = 0; g < negroups_; g++) { + srh.scalar_flux_new(g) += angular_flux_[g] * distance; + srh.flux_moments_new(g) += delta_moments_[g]; + } } // Accumulate the volume (ray segment distance), centroid, and spatial @@ -900,4 +958,12 @@ SourceSite RandomRay::sample_s2() return site; } +int RandomRay::angular_bin() +{ + if (angular_bin_ == C_NONE) { + angular_bin_ = domain_->get_angular_bin(u()); + } + return angular_bin_; +} + } // namespace openmc diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 01d8d6b6962..5a305cfe27e 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -10,12 +10,16 @@ namespace openmc { // SourceRegionHandle implementation //============================================================================== SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) - : negroups_(sr.scalar_flux_old_.size()), material_(&sr.material_), - temperature_idx_(&sr.temperature_idx_), density_mult_(&sr.density_mult_), - is_small_(&sr.is_small_), n_hits_(&sr.n_hits_), - is_linear_(sr.source_gradients_.size() > 0), lock_(&sr.lock_), - volume_(&sr.volume_), volume_t_(&sr.volume_t_), volume_sq_(&sr.volume_sq_), - volume_sq_t_(&sr.volume_sq_t_), volume_naive_(&sr.volume_naive_), + : negroups_(sr.scalar_flux_old_.size()), + nangles_(sr.angular_flux_new_.empty() + ? 1 + : sr.angular_flux_new_.size() / sr.scalar_flux_old_.size()), + material_(&sr.material_), temperature_idx_(&sr.temperature_idx_), + density_mult_(&sr.density_mult_), is_small_(&sr.is_small_), + n_hits_(&sr.n_hits_), is_linear_(sr.source_gradients_.size() > 0), + lock_(&sr.lock_), volume_(&sr.volume_), volume_t_(&sr.volume_t_), + volume_sq_(&sr.volume_sq_), volume_sq_t_(&sr.volume_sq_t_), + volume_naive_(&sr.volume_naive_), position_recorded_(&sr.position_recorded_), external_source_present_(&sr.external_source_present_), position_(&sr.position_), centroid_(&sr.centroid_), @@ -37,7 +41,7 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) //============================================================================== // SourceRegion implementation //============================================================================== -SourceRegion::SourceRegion(int negroups, bool is_linear) +SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles) { if (settings::run_mode == RunMode::EIGENVALUE) { // If in eigenvalue mode, set starting flux to guess of 1 @@ -52,6 +56,7 @@ SourceRegion::SourceRegion(int negroups, bool is_linear) scalar_flux_new_.assign(negroups, 0.0); source_.assign(negroups, 0.0); scalar_flux_final_.assign(negroups, 0.0); + angular_flux_new_.assign(negroups * nangles, 0.0f); tally_task_.resize(negroups); if (is_linear) { @@ -119,6 +124,11 @@ void SourceRegionContainer::push_back(const SourceRegion& sr) // Tally tasks tally_task_.emplace_back(sr.tally_task_[g]); } + + // Angle- and energy-dependent flux + for (int ga = 0; ga < negroups_ * nangles_; ++ga) { + angular_flux_new_.push_back(sr.angular_flux_new_[ga]); + } } void SourceRegionContainer::assign( @@ -154,6 +164,7 @@ void SourceRegionContainer::assign( scalar_flux_old_.clear(); scalar_flux_new_.clear(); scalar_flux_final_.clear(); + angular_flux_new_.clear(); source_.clear(); external_source_.clear(); @@ -185,6 +196,7 @@ SourceRegionHandle SourceRegionContainer::get_source_region_handle(int64_t sr) { SourceRegionHandle handle; handle.negroups_ = negroups(); + handle.nangles_ = nangles(); handle.material_ = &material(sr); handle.temperature_idx_ = &temperature_idx(sr); handle.density_mult_ = &density_mult(sr); @@ -212,6 +224,7 @@ SourceRegionHandle SourceRegionContainer::get_source_region_handle(int64_t sr) handle.external_source_ = nullptr; } handle.scalar_flux_final_ = &scalar_flux_final(sr, 0); + handle.angular_flux_new_ = &angular_flux_new(sr, 0, 0); handle.tally_task_ = &tally_task(sr, 0); if (handle.is_linear_) { @@ -254,6 +267,7 @@ void SourceRegionContainer::adjoint_reset() std::fill(scalar_flux_old_.begin(), scalar_flux_old_.end(), 1.0); } std::fill(scalar_flux_new_.begin(), scalar_flux_new_.end(), 0.0); + std::fill(angular_flux_new_.begin(), angular_flux_new_.end(), 0.0f); std::fill(source_.begin(), source_.end(), 0.0f); std::fill(external_source_.begin(), external_source_.end(), 0.0f); std::fill(source_gradients_.begin(), source_gradients_.end(), From eae7736d5263f4c9bc6e642cf3e27ca0d9cf18dc Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 21 Aug 2026 14:03:16 -0400 Subject: [PATCH 03/37] angular flux tallying workflow init --- include/openmc/mesh.h | 77 +++++++ .../openmc/random_ray/flat_source_domain.h | 14 +- .../openmc/random_ray/linear_source_domain.h | 2 +- include/openmc/random_ray/random_ray.h | 2 +- include/openmc/tallies/filter.h | 1 + include/openmc/tallies/filter_meshangular.h | 41 ++++ openmc/filter.py | 10 +- openmc/lib/filter.py | 42 +++- openmc/lib/mesh.py | 5 +- openmc/mesh.py | 196 ++++++++++++++++++ src/mesh.cpp | 80 +++++++ src/random_ray/flat_source_domain.cpp | 44 +++- src/random_ray/linear_source_domain.cpp | 2 +- src/random_ray/random_ray.cpp | 2 +- src/random_ray/random_ray_simulation.cpp | 2 +- src/tallies/filter.cpp | 3 + src/tallies/filter_mesh.cpp | 6 +- src/tallies/filter_meshangular.cpp | 49 +++++ 18 files changed, 560 insertions(+), 18 deletions(-) create mode 100644 include/openmc/tallies/filter_meshangular.h create mode 100644 src/tallies/filter_meshangular.cpp diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 3d11d39017a..9c10356b1d6 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -826,6 +826,83 @@ class UnstructuredMesh : public Mesh { virtual void initialize() = 0; }; +// Abstract class for meshes over directions (points on the unit sphere), +// as opposed to meshes over volumes. +class AngularMesh : public Mesh { +public: + AngularMesh() { n_dimension_ = 2; } + AngularMesh(pugi::xml_node node) : Mesh(node) { n_dimension_ = 2; } + AngularMesh(hid_t group) : Mesh(group) { n_dimension_ = 2; } + + // Angular meshes partition direction space, not a volume. + // Therefore, "bin crossing" methods are not used; only the "get_bin" method. + void bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const override + { + fatal_error("Angular meshes do not support spatial tracklength tallies."); + } + + void surface_bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins) const override + { + fatal_error("Angular meshes do not support surface-crossing tallies."); + } + + int n_surface_bins() const override { return 0; } + + std::pair, vector> plot( + Position plot_ll, Position plot_ur) const override + { + return {{}, {}}; + } + + std::string bin_label(int bin) const override + { + return fmt::format("Element Index ({})", bin); + } + + Position lower_left() const override { return {-1., -1., -1.}; } + Position upper_right() const override { return {1., 1., 1.}; } +}; + +class UnitSpherePointset : public AngularMesh { +public: + UnitSpherePointset() = default; + explicit UnitSpherePointset(vector points); + UnitSpherePointset(pugi::xml_node node); + UnitSpherePointset(hid_t group); + + //! TODO: add sampling from within a spherical Voronoi cell + Position sample_element(int32_t bin, uint64_t* seed) const override + { + fatal_error( + "Sampling over a UnitSpherePointset angular mesh is not supported"); + } + + int get_bin(Direction u) const override; + + int n_bins() const override { return static_cast(points_.size()); } + + double volume(int bin) const override + { + fatal_error("Volume calculation over UnitSpherePointset is not supported"); + } + + void material_volumes(int nx, int ny, int nz, int max_materials, + int32_t* materials, double* volumes, double* bboxes) const override + { + fatal_error("material_volumes() is not supported for UnitSpherePointset") + } + + std::string get_mesh_type() const override { return mesh_type; } + static const std::string mesh_type; + + void to_hdf5_inner(hid_t group) const override; + + vector points_; + vector data_; +}; + #ifdef OPENMC_DAGMC_ENABLED class MOABMesh : public UnstructuredMesh { diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index 09414fd4465..216fe0ec436 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -30,7 +30,7 @@ class FlatSourceDomain { virtual void update_single_neutron_source(SourceRegionHandle& srh); virtual void update_all_neutron_sources(); void compute_k_eff(); - virtual void normalize_scalar_flux_and_volumes( + virtual void normalize_flux_and_volumes( double total_active_distance_per_iteration); int64_t add_source_to_scalar_flux(); @@ -68,10 +68,16 @@ class FlatSourceDomain { { return source_regions_.n_source_regions() * negroups_; } + int64_t n_source_angular_elements() const + { + return source_regions_.n_source_angular_elements(); + } int64_t lookup_base_source_region_idx(const GeometryState& p) const; SourceRegionKey lookup_source_region_key(const GeometryState& p) const; int64_t lookup_mesh_bin(int64_t sr, Position r) const; int lookup_mesh_idx(int64_t sr) const; + int lookup_angular_bin(Direction u) const; + Direction angular_mesh_direction(int a) { return angular_bin_angles_[a]; } //---------------------------------------------------------------------------- // Static Data members @@ -174,6 +180,12 @@ class FlatSourceDomain { //---------------------------------------------------------------------------- // Private data members int negroups_; // Number of energy groups in simulation + int nangles_; // Number of bins for any angular flux tallies + + vector angular_bin_angles_; // Directions corresponding to each + // bin midpoint in the angular flux + // tallying scheme, flattened to 1D: + // [x0, y0, z0, x1, y1, z1,...] double simulation_volume_; // Total physical volume of the simulation domain, as diff --git a/include/openmc/random_ray/linear_source_domain.h b/include/openmc/random_ray/linear_source_domain.h index 0098c782001..2c083dcec0d 100644 --- a/include/openmc/random_ray/linear_source_domain.h +++ b/include/openmc/random_ray/linear_source_domain.h @@ -21,7 +21,7 @@ class LinearSourceDomain : public FlatSourceDomain { //---------------------------------------------------------------------------- // Methods void update_single_neutron_source(SourceRegionHandle& srh) override; - void normalize_scalar_flux_and_volumes( + void normalize_flux_and_volumes( double total_active_distance_per_iteration) override; void batch_reset() override; diff --git a/include/openmc/random_ray/random_ray.h b/include/openmc/random_ray/random_ray.h index 32a5657ed27..e4d0bb0d443 100644 --- a/include/openmc/random_ray/random_ray.h +++ b/include/openmc/random_ray/random_ray.h @@ -36,7 +36,7 @@ class RandomRay : public Particle { SourceRegionHandle& srh, double distance, bool is_active, Position r); void attenuate_flux_linear_source_void( SourceRegionHandle& srh, double distance, bool is_active, Position r); - void direction_changed() override { angular_bin_ = C_NONE; }; + void direction_changed() override { angular_bin_ = C_NONE; } void initialize_ray(uint64_t ray_id, FlatSourceDomain* domain); uint64_t transport_history_based_single_ray(); diff --git a/include/openmc/tallies/filter.h b/include/openmc/tallies/filter.h index 77b0d9f420d..d78ddadcf72 100644 --- a/include/openmc/tallies/filter.h +++ b/include/openmc/tallies/filter.h @@ -32,6 +32,7 @@ enum class FilterType { MATERIAL, MATERIALFROM, MESH, + MESH_ANGULAR, MESHBORN, MESH_MATERIAL, MESH_SURFACE, diff --git a/include/openmc/tallies/filter_meshangular.h b/include/openmc/tallies/filter_meshangular.h new file mode 100644 index 00000000000..8535f5bf699 --- /dev/null +++ b/include/openmc/tallies/filter_meshangular.h @@ -0,0 +1,41 @@ +#ifndef OPENMC_TALLIES_FILTER_MESHSURFACE_H +#define OPENMC_TALLIES_FILTER_MESHSURFACE_H + +#include "openmc/tallies/filter_mesh.h" + +namespace openmc { + +//============================================================================== +//! Indexes the direction of particle events to a mesh. +//============================================================================== + +class MeshAngularFilter : public MeshFilter { +public: + //---------------------------------------------------------------------------- + // Methods + + std::string type_str() const override { return "meshangular"; } + FilterType type() const override { return FilterType::MESH_ANGULAR; } + + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; + + void to_statepoint(hid_t filter_group) const override; + + + //---------------------------------------------------------------------------- + // Accessors + + void set_translation(const Position& translation) const override + { + fatal_error("Angular mesh filters do not permit translation."); + } + + void set_translation(const double translation[3]) const override + { + fatal_error("Angular mesh filters do not permit translation."); + } +}; + +} // namespace openmc +#endif // OPENMC_TALLIES_FILTER_MESHSURFACE_H diff --git a/openmc/filter.py b/openmc/filter.py index 31d72b0dd4c..00a2f31014c 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -27,7 +27,7 @@ 'delayedgroup', 'energyfunction', 'cellfrom', 'materialfrom', 'legendre', 'spatiallegendre', 'sphericalharmonics', 'zernike', 'zernikeradial', 'particle', 'particleproduction', 'cellinstance', 'collision', 'time', 'parentnuclide', - 'weight', 'meshborn', 'meshsurface', 'meshmaterial', 'reaction', + 'weight', 'meshangular', 'meshborn', 'meshsurface', 'meshmaterial', 'reaction', ) def _mesh_current_names(mesh): @@ -1349,6 +1349,14 @@ def get_pandas_dataframe(self, data_size, stride, **kwargs): # Initialize a Pandas DataFrame from the mesh dictionary return pd.concat([df, pd.DataFrame(filter_dict)]) +class MeshAngularFilter(Filter): + """Bins tally events based on incident particle's direction, using + an angular mesh. + + """ + def __init__(self): + pass + class CollisionFilter(Filter): """Bins tally events based on the number of collisions. diff --git a/openmc/lib/filter.py b/openmc/lib/filter.py index cd011dc5d42..edda4ed77c6 100644 --- a/openmc/lib/filter.py +++ b/openmc/lib/filter.py @@ -20,12 +20,12 @@ 'Filter', 'AzimuthalFilter', 'CellFilter', 'CellbornFilter', 'CellfromFilter', 'CellInstanceFilter', 'CollisionFilter', 'DistribcellFilter', 'DelayedGroupFilter', 'EnergyFilter', 'EnergyoutFilter', 'EnergyFunctionFilter', 'LegendreFilter', - 'MaterialFilter', 'MaterialFromFilter', 'MeshFilter', 'MeshBornFilter', - 'MeshMaterialFilter', 'MeshSurfaceFilter', 'MuFilter', 'MuSurfaceFilter', - 'ParentNuclideFilter', 'ParticleFilter', 'ParticleProductionFilter', 'PolarFilter', - 'ReactionFilter', 'SphericalHarmonicsFilter', 'SpatialLegendreFilter', - 'SurfaceFilter', 'TimeFilter', 'UniverseFilter', 'WeightFilter', 'ZernikeFilter', - 'ZernikeRadialFilter', 'filters' + 'MaterialFilter', 'MaterialFromFilter', 'MeshFilter', 'MeshAngularFilter', + 'MeshBornFilter', 'MeshMaterialFilter', 'MeshSurfaceFilter', 'MuFilter', + 'MuSurfaceFilter', 'ParentNuclideFilter', 'ParticleFilter', + 'ParticleProductionFilter', 'PolarFilter', 'ReactionFilter', + 'SphericalHarmonicsFilter', 'SpatialLegendreFilter', 'SurfaceFilter', 'TimeFilter', + 'UniverseFilter', 'WeightFilter', 'ZernikeFilter', 'ZernikeRadialFilter', 'filters' ] # Tally functions @@ -106,6 +106,12 @@ c_int32, POINTER(c_double), c_size_t] _dll.openmc_mesh_filter_set_rotation.restype = c_int _dll.openmc_mesh_filter_set_rotation.errcheck = _error_handler +_dll.openmc_meshangular_filter_get_mesh.argtypes = [c_int32, POINTER(c_int32)] +_dll.openmc_meshangular_filter_get_mesh.restype = c_int +_dll.openmc_meshangular_filter_get_mesh.errcheck = _error_handler +_dll.openmc_meshangular_filter_set_mesh.argtypes = [c_int32, c_int32] +_dll.openmc_meshangular_filter_set_mesh.restype = c_int +_dll.openmc_meshangular_filter_set_mesh.errcheck = _error_handler _dll.openmc_meshborn_filter_get_mesh.argtypes = [c_int32, POINTER(c_int32)] _dll.openmc_meshborn_filter_get_mesh.restype = c_int _dll.openmc_meshborn_filter_get_mesh.errcheck = _error_handler @@ -466,6 +472,29 @@ def rotation(self, rotation_data): _dll.openmc_mesh_filter_set_rotation( self._index, flat_rotation.ctypes.data_as(POINTER(c_double)), c_size_t(len(flat_rotation))) + +class MeshAngularFilter(MeshFilter): + """Angular mesh filter stored internally. + + """ + filter_type = 'meshangular' + + def __init__(self, mesh=None, uid=None, new=True, index=None): + super().__init__(uid, new, index) + if mesh is not None: + self.mesh = mesh + + @mesh.setter + def mesh(self, mesh): + _dll.openmc_meshangular_filter_set_mesh(self._index, mesh._index) + + @property + def translation(self): + raise AttributeError("Angular mesh filters do not permit translation.") + + @translation.setter + def translation(self, translation): + raise AttributeError("Angular mesh filters do not permit translation.") class MeshBornFilter(Filter): """MeshBorn filter stored internally. @@ -725,6 +754,7 @@ class ZernikeRadialFilter(ZernikeFilter): 'material': MaterialFilter, 'materialfrom': MaterialFromFilter, 'mesh': MeshFilter, + 'meshangular': MeshAngularFilter, 'meshborn': MeshBornFilter, 'meshmaterial': MeshMaterialFilter, 'meshsurface': MeshSurfaceFilter, diff --git a/openmc/lib/mesh.py b/openmc/lib/mesh.py index 19e6f74d7ad..f176422fbca 100644 --- a/openmc/lib/mesh.py +++ b/openmc/lib/mesh.py @@ -730,13 +730,16 @@ def set_grid(self, r_grid, theta_grid, phi_grid): class UnstructuredMesh(Mesh): pass +class UnitSpherePointset(Mesh): + pass _MESH_TYPE_MAP = { 'regular': RegularMesh, 'rectilinear': RectilinearMesh, 'cylindrical': CylindricalMesh, 'spherical': SphericalMesh, - 'unstructured': UnstructuredMesh + 'unstructured': UnstructuredMesh, + 'unitsphere_pointset': UnitSpherePointset } diff --git a/openmc/mesh.py b/openmc/mesh.py index 670fcceab67..9d73a6a4a87 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -307,6 +307,8 @@ def from_hdf5(cls, group: h5py.Group): return SphericalMesh.from_hdf5(group, mesh_id, mesh_name) elif mesh_type == 'unstructured': return UnstructuredMesh.from_hdf5(group, mesh_id, mesh_name) + elif mesh_type == 'angular_pointset': + return UnitSpherePointset.from_hdf5(group, mesh_id, mesh_name) else: raise ValueError('Unrecognized mesh type: "' + mesh_type + '"') @@ -354,6 +356,8 @@ def from_xml_element(cls, elem: ET.Element): mesh = SphericalMesh.from_xml_element(elem) elif mesh_type == 'unstructured': mesh = UnstructuredMesh.from_xml_element(elem) + elif mesh_type == 'angular_pointset': + mesh = UnitSpherePointset.from_xml_element(elem) else: raise ValueError(f'Unrecognized mesh type "{mesh_type}" found.') @@ -3352,6 +3356,198 @@ def from_xml_element(cls, elem: ET.Element): return cls(filename, library, mesh_id, '', length_multiplier, options) +class AngularMesh(MeshBase): + """Base class for angular meshes of the unit sphere.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @property + @abstractmethod + def dimension(self): + pass + + @property + @abstractmethod + def n_dimension(self): + pass + + @property + @abstractmethod + def axis_labels(self): + """tuple of str : Names of the mesh axes, one per dimension.""" + pass + + @property + def n_elements(self): + pass + + # override non-applicable methods of MeshBase + def get_homogenized_materials(self, *args, **kwargs): + raise NotImplementedError( + "Material attributes are not available for angular meshes.") + + def material_volumes(self, *args, **kwargs): + raise NotImplementedError( + "Material attributes are not available for angular meshes.") + +class UnitSpherePointset(AngularMesh): + """Set of points on the unit sphere. Used for mesh-based angular flux + tallying based on a Voronoi diagram generated from the pointset. + + Parameters + ---------- + points : iterable of float + Unit-vector endpoints constituting the mesh. Must be either a numpy + array or a nested list and have shape (N,3), where each row provides + the [x, y, z] components of one such vector. + data : iterable of float + Scalar data (e.g. flux) assigned to each point in the mesh + mesh_id : int + Unique identifier for the mesh + name : str + Name of the mesh + + Attributes + ---------- + id : int + Unique identifier for the mesh + name : str + Name of the mesh + points : numpy array of float + Array storing the + data : numpy array of float + Scalar data assigned to each point in the mesh + """ + def __init__( + self, + points, + data: float | None = None, + mesh_id: int | None = None, + name: str = '', + ): + super().__init__(mesh_id, name) + self.points = points + self.data = data + + @property + def points(self): + return self._points + + @points.setter + def points(self, pts): + cv.check_type("unit vector pointset", pts, Iterable, Real) + pts = np.asarray(pts) + if pts.shape != (len(pts),3): + raise ValueError( + "Unit vector array for UnitSpherePointset must have shape (N,3).") + self._points = pts + + @property + def data(self): + return self._data + + @data.setter + def data(self, d): + if d is not None: + cv.check_type("AngularMesh data", d, Iterable, Real) + d = np.asarray(d).flatten() + if len(d) != len(self.points): + raise ValueError( + "Data for UnitSpherePointset does not match number of mesh elements.") + self._data = d + + @property + def n_elements(self): + return len(self.points) + + @property + def dimension(self): + return (self.n_elements,) + + @property + def n_dimension(self): + return 2 + + @property + def lower_left(self): + return np.array((-1., -1., -1.)) + + @property + def upper_right(self): + return np.array((1., 1., 1.)) + + @property + def axis_labels(self): + return ('element_index',) + + @property + def indices(self): + return [(i,) for i in range(self.n_elements)] + + @classmethod + def from_hdf5(cls, group: h5py.Group, mesh_id: int, name: str): + points = np.asarray(group['points'][()]) + n = points.size // 3 + points = points.reshape(n, 3) + + data = group['data'][()] if 'data' in group else None + + return cls(points, data=data, mesh_id=mesh_id, name=name) + + def to_xml_element(self): + """Return XML representation of the mesh + + Returns + ------- + element : lxml.etree._Element + XML element containing mesh data + + """ + element = super().to_xml_element() + element.set("type", "angular_pointset") + + # flatten to a (3*N,) array + pts = self.points.flatten() + + subelement = ET.SubElement(element, "points") + subelement.text = ' '.join(map(str, pts)) + + if self.data is not None: + subelement = ET.SubElement(element, "data") + subelement.text = ' '.join(map(str, self.data)) + + return element + + @classmethod + def from_xml_element(cls, elem: ET.Element): + """Generate a unit sphere pointset from an XML element + + Parameters + ---------- + elem : lxml.etree._Element + XML element + + Returns + ------- + openmc.UnitSpherePointset + Unit-sphere pointset object + + """ + mesh_id = int(get_text(elem, 'id')) + + points = np.array(get_elem_list(elem, "points", float)) + n = points.size // 3 + points = points.reshape(n, 3) + + data_elem = elem.find("data") + if data_elem is not None: + data = get_elem_list(elem, "data", float) + else: + data = None + + return cls(points, data, mesh_id=mesh_id) + def _read_meshes(elem): """Generate dictionary of meshes from a given XML node diff --git a/src/mesh.cpp b/src/mesh.cpp index a0e497613c0..e288b455967 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2429,6 +2429,86 @@ double SphericalMesh::volume(const MeshIndex& ijk) const (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i); } +//============================================================================== +// Angular mesh implementations +//============================================================================== + +const std::string UnitSpherePointset::mesh_type = "angular_pointset"; + +UnitSpherePointset::UnitSpherePointset(vector points) + : points_(std::move(points)) +{} + +UnitSpherePointset::UnitSpherePointset(pugi::xml_node node) : AngularMesh(node) +{ + if (check_for_node(node, "type")) { + auto temp = get_node_value(node, "type", true, true); + if (temp != mesh_type) + fatal_error(fmt::format("Invalid mesh type: {}", temp)); + } + + vector flat = get_node_array(node, "points"); + if (flat.size() % 3 != 0) { + fatal_error(fmt::format("Point array for unit sphere pointset mesh {} " + "does not contain a whole number of points.", + id_)); + } + int n = static_cast(flat.size() / 3); + points_.reserve(n); + for (int i = 0; i < n; ++i) + points_.push_back({flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]}); +} + +UnitSpherePointset::UnitSpherePointset(hid_t group) : AngularMesh(group) +{ + if (object_exists(group, "type")) { + std::string temp; + read_dataset(group, "type", temp); + if (temp != mesh_type) + fatal_error(fmt::format("Invalid mesh type: {}", temp)); + } + + vector flat; + read_dataset(group, "points", flat); + int n = static_cast(flat.size() / 3); + points_.reserve(n); + for (int i = 0; i < n; ++i) + points_.push_back({flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]}); + + if (object_exists(group, "data")) + read_dataset(group, "data", data_); +} + +void UnitSpherePointset::to_hdf5_inner(hid_t mesh_group) const +{ + int n = this->n_bins(); + vector flat(3 * n); + for (int i = 0; i < n; ++i) { + flat[3 * i + 0] = points_[i].x; + flat[3 * i + 1] = points_[i].y; + flat[3 * i + 2] = points_[i].z; + } + write_dataset(mesh_group, "points", flat); + + if (!data_.empty()) + write_dataset(mesh_group, "data", data_); +} + +int UnitSpherePointset::get_bin(Direction u) const +{ + int best = -1; + double best_dot = -2.0; + for (int i = 0; i < this->n_bins(); ++i) { + double d = points_[i].dot(u); + if (d > best_dot) { + best_dot = d; + best = i; + } + } + return best; +} + + //============================================================================== // Helper functions for the C API //============================================================================== diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 1346a2b23af..94376c9fefb 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -54,9 +54,13 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) } } + // Count the number of angular bins if performing angular flux tallying + // and store the angle set. + nangles = + // Initialize source regions. bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT; - source_regions_ = SourceRegionContainer(negroups_, is_linear); + source_regions_ = SourceRegionContainer(negroups_, is_linear, nangles_); // Initialize tally volumes if (volume_normalized_flux_tallies_) { @@ -92,6 +96,11 @@ void FlatSourceDomain::batch_reset() for (int64_t se = 0; se < n_source_elements(); se++) { source_regions_.scalar_flux_new(se) = 0.0; } + +#pragma omp parallel for + for (int64_t sea = 0; sea < n_source_angular_elements(); sea++) { + source_regions_.angular_flux_new(sea) = 0.0; + } } void FlatSourceDomain::accumulate_iteration_flux() @@ -165,7 +174,7 @@ void FlatSourceDomain::update_all_neutron_sources() } // Normalizes flux and updates simulation-averaged volume estimate -void FlatSourceDomain::normalize_scalar_flux_and_volumes( +void FlatSourceDomain::normalize_flux_and_volumes( double total_active_distance_per_iteration) { double normalization_factor = 1.0 / total_active_distance_per_iteration; @@ -179,6 +188,12 @@ void FlatSourceDomain::normalize_scalar_flux_and_volumes( source_regions_.scalar_flux_new(se) *= normalization_factor; } +// Normalize angular flux in the same way +#pragma omp parallel for + for (int64_t sea = 0; sea < n_source_angular_elements(); sea++) { + source_regions_.angular_flux_new(sea) *= normalization_factor; + } + // Accumulate cell-wise ray length tallies collected this iteration, then // update the simulation-averaged cell-wise volume estimates #pragma omp parallel for @@ -1852,4 +1867,29 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const return mesh_bin; } +// If tallying angular flux, this function is used to determine which angular +// bin the current ray contributes to. Rays are assigned to bins based on the +// unit-sphere Voronoi diagram generated from the "quadrature" angle set. +int FlatSourceDomain::lookup_angular_bin(Direction u) const +{ + const double x = u.x; + const double y = u.y; + const double z = u.z; + + double max_dot = -INFTY; + std::size_t best_bin = 0; + for (std::size_t j = 0; j < nangles_; ++j) { + const std::size_t k = 3 * j; + const double dot = x * angular_bin_angles_[k] + + y * angular_bin_angles_[k + 1] + + z * angular_bin_angles_[k + 2]; + if (dot > max_dot) { + max_dot = dot; + best_bin = j; + } + } + + return static_cast(best_bin); +} + } // namespace openmc diff --git a/src/random_ray/linear_source_domain.cpp b/src/random_ray/linear_source_domain.cpp index b4701ed1fa9..b74f6e9adf8 100644 --- a/src/random_ray/linear_source_domain.cpp +++ b/src/random_ray/linear_source_domain.cpp @@ -113,7 +113,7 @@ void LinearSourceDomain::update_single_neutron_source(SourceRegionHandle& srh) } } -void LinearSourceDomain::normalize_scalar_flux_and_volumes( +void LinearSourceDomain::normalize_flux_and_volumes( double total_active_distance_per_iteration) { double normalization_factor = 1.0 / total_active_distance_per_iteration; diff --git a/src/random_ray/random_ray.cpp b/src/random_ray/random_ray.cpp index f88768984f2..a6f8592daab 100644 --- a/src/random_ray/random_ray.cpp +++ b/src/random_ray/random_ray.cpp @@ -961,7 +961,7 @@ SourceSite RandomRay::sample_s2() int RandomRay::angular_bin() { if (angular_bin_ == C_NONE) { - angular_bin_ = domain_->get_angular_bin(u()); + angular_bin_ = domain_->lookup_angular_bin(u()); } return angular_bin_; } diff --git a/src/random_ray/random_ray_simulation.cpp b/src/random_ray/random_ray_simulation.cpp index 0a1ed0381d9..11bd8eec8c0 100644 --- a/src/random_ray/random_ray_simulation.cpp +++ b/src/random_ray/random_ray_simulation.cpp @@ -445,7 +445,7 @@ void RandomRaySimulation::simulate() domain_->finalize_discovered_source_regions(); // Normalize scalar flux and update volumes - domain_->normalize_scalar_flux_and_volumes( + domain_->normalize_flux_and_volumes( settings::n_particles * RandomRay::distance_active_); // Add source to scalar flux, compute number of FSR hits diff --git a/src/tallies/filter.cpp b/src/tallies/filter.cpp index badb9107733..0db8d7f1568 100644 --- a/src/tallies/filter.cpp +++ b/src/tallies/filter.cpp @@ -24,6 +24,7 @@ #include "openmc/tallies/filter_material.h" #include "openmc/tallies/filter_materialfrom.h" #include "openmc/tallies/filter_mesh.h" +#include "openmc/tallies/filter_meshangular.h" #include "openmc/tallies/filter_meshborn.h" #include "openmc/tallies/filter_meshmaterial.h" #include "openmc/tallies/filter_meshsurface.h" @@ -134,6 +135,8 @@ Filter* Filter::create(const std::string& type, int32_t id) return Filter::create(id); } else if (type == "mesh") { return Filter::create(id); + } else if (type == "meshangular") { + return Filter::create(id); } else if (type == "meshborn") { return Filter::create(id); } else if (type == "meshmaterial") { diff --git a/src/tallies/filter_mesh.cpp b/src/tallies/filter_mesh.cpp index a0698992d01..f713367bcd0 100644 --- a/src/tallies/filter_mesh.cpp +++ b/src/tallies/filter_mesh.cpp @@ -259,7 +259,8 @@ extern "C" int openmc_mesh_filter_get_rotation( // Check the filter type const auto& filter = model::tally_filters[index]; - if (filter->type() != FilterType::MESH) { + if (filter->type() != FilterType::MESH && + filter->type() != FilterType::MESH_ANGULAR) { set_errmsg("Tried to get a rotation from a non-mesh filter."); return OPENMC_E_INVALID_TYPE; } @@ -281,7 +282,8 @@ extern "C" int openmc_mesh_filter_set_rotation( const auto& filter = model::tally_filters[index]; // Check the filter type - if (filter->type() != FilterType::MESH) { + if (filter->type() != FilterType::MESH && + filter->type() != FilterType::MESH_ANGULAR) { set_errmsg("Tried to set a rotation from a non-mesh filter."); return OPENMC_E_INVALID_TYPE; } diff --git a/src/tallies/filter_meshangular.cpp b/src/tallies/filter_meshangular.cpp new file mode 100644 index 00000000000..c0409a9eaf6 --- /dev/null +++ b/src/tallies/filter_meshangular.cpp @@ -0,0 +1,49 @@ +#include "openmc/tallies/filter_meshsurface.h" + +#include "openmc/capi.h" +#include "openmc/constants.h" +#include "openmc/error.h" +#include "openmc/mesh.h" + +namespace openmc { + +void MeshAngularFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const +{ + Direction u = p.u(); + if (!rotation_.empty()) { + u = u.rotate(rotation_); + } + auto bin = model::meshes[mesh_]->get_bin(r); + if (bin >= 0) { + match.bins_.push_back(bin); + match.weights_.push_back(1.0); + } +} + +void MeshAngularFilter::to_statepoint(hid_t filter_group) const +{ + Filter::to_statepoint(filter_group); + write_dataset(filter_group, "bins", model::meshes[mesh_]->id_); + if (rotated_) { + write_dataset(filter_group, "rotation", rotation_); + } +} + +//============================================================================== +// C-API functions +//============================================================================== + +extern "C" int openmc_meshangular_filter_get_mesh( + int32_t index, int32_t* index_mesh) +{ + return openmc_mesh_filter_get_mesh(index, index_mesh); +} + +extern "C" int openmc_meshangular_filter_set_mesh( + int32_t index, int32_t index_mesh) +{ + return openmc_mesh_filter_set_mesh(index, index_mesh); +} + +} // namespace openmc From 566415faf463bd872136e8470cb05de0cd45e8a3 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 21 Aug 2026 18:05:38 -0400 Subject: [PATCH 04/37] Add pointset generators --- openmc/model/funcs.py | 335 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 335 insertions(+) diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index e076b080a9d..320bfbfd432 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -1,5 +1,7 @@ from collections.abc import Iterable from math import sqrt +from itertools import product +import numpy as np from operator import attrgetter from warnings import warn @@ -290,3 +292,336 @@ def pin(surfaces, items, subdivisions=None, divide_vols=True, regions = subdivide(surfaces) cells = [Cell(fill=f, region=r) for r, f in zip(regions, items)] return Universe(cells=cells, **kwargs) + +# Pointset generators for discrete-ordinate angular meshes + +def generate_levelsymmetric_sn(N: int, mu1_sq: float = None): + """ + Generates the direction vectors of an order-N level-symmetric + quadrature set. Does not provide the corresponding weights. + + Parameters + ---------- + N : int + Even quadrature order (e.g. 2, 4, 6, ..., 20). + mu1_sq : float + Square of the first direction cosine mu_1, used to generate other + levels. Must lie in the open interval (0, 1/3). For the special case + N == 2, mu1_sq must be equal to 1/3. + + Returns + ------- + np.ndarray + Array of shape (N*(N+2), 3) giving the [x, y, z] unit-vector + directions of every point in the quadrature set. + """ + if N < 2 or N % 2 != 0: + raise ValueError(f"N must be a positive even integer, got {N}") + M = N // 2 + + # lookup mu1_sq if not provided + if mu1_sq is not None: + if N == 2: + if not np.isclose(mu1_sq, 1 / 3): + raise ValueError("For N=2, mu1_sq must equal 1/3 (got {mu1_sq}).") + mu = np.array([np.sqrt(1 / 3)]) + elif N > 20: + raise ValueError( + f"Level-symmetric quadrature generation only supported for 2<=N<=20; got {N}") + else: + if not (0 < mu1_sq < 1 / 3): + raise ValueError( + f"mu1_sq={mu1_sq} is out of the valid range (0, 1/3) for N={N}." + ) + + Delta = (1 - 3 * mu1_sq) / (M - 1) + mu_sq = np.array([mu1_sq + i * Delta for i in range(M)]) + mu = np.sqrt(mu_sq) + + else: + match N: + case 2: + pass + case 4: + mu1_sq = 0.1225148226554413 + case 6: + mu1_sq = 0.0710944373419735 + case 8: + mu1_sq = 0.0476190476190470 + case 10: + mu1_sq = 0.0358425646593916 + case 12: + mu1_sq = 0.0279600712640057 + case 14: + mu1_sq = 0.0230997020840970 + case 16: + mu1_sq = 0.0193090131285642 + case 18: + mu1_sq = 0.0167300008552435 + case 20: + mu1_sq = 0.0145451663522475 + case _: + raise ValueError( + f"Level-symmetric quadrature generation only supported for 2<=N<=20; got {N}") + + if M == 1: + mu = np.array([np.sqrt(1 / 3)]) + else: + Delta = (1 - 3 * mu1_sq) / (M - 1) + mu_sq = np.array([mu1_sq + i * Delta for i in range(M)]) + mu = np.sqrt(mu_sq) + + # generate the angles for 1 octant of unit sphere + octant_points = [] + for l in range(0, M): + for m in range(0, M): + for n in range(0, M): + if l + m + n == (M + 1): + octant_points.append((mu[l], mu[m], mu[n])) + octant_points = np.array(octant_points) + + # reflect into other octants + signs = list(product([1, -1], repeat=3)) + all_points = np.array( + [pt * np.array(s) for pt in octant_points for s in signs] + ) + + return all_points + +def generate_tcl_sn(N: int): + """ + Generate the direction vectors of an order-N triangular + Chebyshev-Legendre (TCL) quadrature set. Supports even N >= 4. + + Parameters + ---------- + N : int + Even quadrature order (e.g. 4, 6, 8, ...). + + Returns + ------- + np.ndarray + Array of shape (N*(N+2), 3) giving the [x, y, z] unit-vector + directions of every point in the quadrature set. + """ + if N < 4 or N % 2 != 0: + raise ValueError(f"N must be an even integer >= 4, got {N}") + + M = N // 2 + + # get polar levels + nodes, _ = np.polynomial.legendre.leggauss(N) + mu = np.sort(nodes[nodes > 0]) + + # generate the angles for 1 octant using Chebyshev quadrature for + # azimuthal angles + octant_points = [] + for i in range(M): + count = M - i # rings get smaller towards pole + m = mu[i] + sin_theta = np.sqrt(1 - m**2) + for k in range(1, count + 1): + phi = (2 * k - 1) * (np.pi / 2) / (2 * count) + x = sin_theta * np.cos(phi) + y = sin_theta * np.sin(phi) + z = m + octant_points.append((x, y, z)) + octant_points = np.array(octant_points) + + # reflect into other octants + signs = list(product([1, -1], repeat=3)) + all_points = np.array( + [pt * np.array(s) for pt in octant_points for s in signs] + ) + + assert np.allclose(np.linalg.norm(all_points, axis=1), 1.0), ( + "Not all generated points lie on the unit sphere" + ) + + return all_points + +def _subdivide_icosahedron_faces(vertices, faces, nu): + """ + Given a list of the coordinates of the vertices of a unit icosahedron, + and a list linking sets of these vertices to individual faces of the unit + icosahedron, this function will subdivides each edge of the icosahedron + into nu equal segments, adding vertices on the edges and faces to produce + triangular subfaces of equal size. + + Parameters + ---------- + vertices : numpy array of shape (n_verts, 3) + Coordinates of each vertex of the unit icosahedron + faces : numpy array of shape (n_faces, 3) + List of vertex indices corresponding to each face of the base + icosahedron + nu : int + Subdivision frequency, integer > 1 + + Returns + ------- + subvertices : numpy array of shape (n_verts + n_faces*(nu+1)*(nu-1)/2, 3) + List of vertices on subdivided icosahedron + subfaces : numpy array of shape (n_faces*nu**2, 3) + List of vertex indices corresponding to each face of the subdivided + icosahedron + """ + edges = np.vstack([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [0, 2]]]) + edges = np.unique(np.sort(edges, axis=1), axis=0) + + n_faces = faces.shape[0] + n_vertices = vertices.shape[0] + n_edges = edges.shape[0] + n_int_verts = (nu - 1) * (nu - 2) // 2 + + n_subverts = n_vertices + n_edges * (nu - 1) + n_faces * n_int_verts + subvertices = np.empty((n_subverts, 3)) + subvertices[:n_vertices] = vertices + + # populate edge vertices: + # position of the k-th vertex along edge AB is given by + # (1 − w_k)·a + w_k·b, w_k = (k+1)/nu + w = np.arange(1, nu) / nu + vA = vertices[edges[:, 0]] + vB = vertices[edges[:, 1]] + edge_verts = (1 - w)[:, None, None] * vA[None] + w[:, None, None] * vB[None] + subvertices[n_vertices : n_vertices + n_edges * (nu - 1)] = ( + edge_verts.transpose(1, 0, 2).reshape(-1, 3) + ) + + f_A, f_B, f_C = faces[:, 0], faces[:, 1], faces[:, 2] + + edge_dict = {(int(a), int(b)): i for i, (a, b) in enumerate(edges)} + edge_dict.update({(int(b), int(a)): ~i for i, (a, b) in enumerate(edges)}) + + def directed_edge_indices(u_arr, v_arr): + # Return (n_faces, nu-1) global vertex indices along the u->v edge + ei = np.array([edge_dict[(int(u), int(v))] for u, v in zip(u_arr, v_arr)]) + base = n_vertices + np.where(ei >= 0, ei, ~ei) * (nu - 1) + idx = base[:, None] + np.arange(nu - 1) + idx[ei < 0] = idx[ei < 0, ::-1] + return idx + + AB = directed_edge_indices(f_A, f_B) + AC = directed_edge_indices(f_A, f_C) + BC = directed_edge_indices(f_B, f_C) + + # global indices of subvertices: + # (0,0) = corner "A," (nu, 0) = corner B, (nu, nu) = corner C + # and along the edges above + local_idx = np.empty((n_faces, nu + 1, nu + 1), dtype=int) + local_idx[:, 0, 0 ] = f_A + local_idx[:, nu, 0 ] = f_B + local_idx[:, nu, nu ] = f_C + local_idx[:, 1:nu, 0 ] = AB + r_e = np.arange(1, nu) + local_idx[:, r_e, r_e ] = AC + local_idx[:, nu, 1:nu] = BC + + # row, column indices of interior points + r_int = np.array([r for r in range(2, nu) for _ in range(r - 1)]) # (n_int,) + c_int = np.array([c for r in range(2, nu) for c in range(1, r)]) + T_base = n_vertices + n_edges * (nu - 1) + + if n_int_verts > 0: + T_start = T_base + np.arange(n_faces) * n_int_verts + local_idx[:, r_int, c_int] = ( + T_start[:, None] + np.arange(n_int_verts)[None, :] + ) + + # populate subfaces with vertex coordination info: + # local vertex (r, c) with 0 ≤ c ≤ r ≤ nu has barycentric weights + # A'=(nu-r)/nu, B'=(r-c)/nu, C'=c/nu + # interior vertices have 0 < col < row < nu + tri_list = [] + for i in range(nu): + for j in range(i): + tri_list.append([(i,j), (i+1,j), (i+1,j+1)]) + tri_list.append([(i,j), (i+1,j+1), (i,j+1)]) + tri_list.append([(i,i), (i+1,i), (i+1,i+1)]) + tri_arr = np.array(tri_list) + tr, tc = tri_arr[:, :, 0], tri_arr[:, :, 1] + subfaces = local_idx[:, tr, tc].reshape(n_faces * nu ** 2, 3) + + if n_int_verts > 0: + alpha = (nu - r_int) / nu + beta = (r_int - c_int) / nu + gamma = c_int / nu + int_verts = ( alpha[None, :, None] * vertices[f_A][:, None, :] + + beta [None, :, None] * vertices[f_B][:, None, :] + + gamma[None, :, None] * vertices[f_C][:, None, :]) + subvertices[T_base:] = int_verts.reshape(-1, 3) + + return subvertices, subfaces + +def generate_icosphere_sn(nu: int = 1, point_type: str = "centroids"): + """ + Generates direction vectors from the vertices or centroids of a + unit spherical icosahedron with principal faces subdivided at the nu-th + frequency. + + That is, beginning from a "parent" icosahedron inscribed in the unit + sphere, the edges are first divided into nu equal segments, and then the + endpoints of these segments are connected to subdivide each "parent" face + into nu^2 triangular subfaces. Lastly, the vectors describing the + locations of either the vertices or centroids of these faces are + projected back onto the surface of the unit sphere. + + Parameters + ---------- + nu : int + Subdivision frequency + point_type: str + Keyword specifying whether to return the vertices ("vertices", + "vertex", or "vert") or centroids ("centroids", "centroid", or + "cent") of the subtriangles on the icosphere + + Returns + ------- + pointset : numpy array of shape (12 + 10 * (nu+1) * (nu-1), 3) if + specifying "vertices" or of shape (20 * nu**2, 3) if specifying + "centroids" + + """ + # check pointset type + match point_type: + case "vertices" | "vertex" | "vert" : + return_type = "vert" + case "centroids" | "centroid" | "cent": + return_type = "cent" + case _: + return ValueError(f"Unknown pointset type specified (got {point_type})") + + # vertices of base icosahedron + phi = (1 + np.sqrt(5)) / 2 + vertices = np.array([ + [0, 1, phi], [0, -1, phi], [1, phi, 0], + [-1, phi, 0], [phi, 0, 1], [-phi, 0, 1], + [0, -1, -phi], [0, 1, -phi], [-1, -phi, 0], + [1, -phi, 0], [-phi, 0, -1], [phi, 0, -1]]) + vertices /= np.sqrt(1 + phi ** 2) + + # coordination of vertices to faces: + # each entry in the array is a row vector, corresponding to one + # individual face of the icosahedron, giving the indices into the + # "vertices" array of its own particular vertices + faces = np.array([ + [0, 5, 1], [0, 3, 5], [0, 2, 3], [0, 4, 2], [0, 1, 4], + [1, 5, 8], [5, 3, 10], [3, 2, 7], [2, 4, 11], [4, 1, 9], + [7, 11, 6], [11, 9, 6], [9, 8, 6], [8, 10, 6], [10, 7, 6], + [2, 11, 7], [4, 9, 11], [1, 8, 9], [5, 10, 8], [3, 7, 10]]) + + # subdividing + if nu > 1: + vertices, faces = _subdivide_icosahedron_faces(vertices, faces, nu) + # project back to unit length + vertices = vertices / np.sqrt(np.sum(vertices ** 2, axis=1, keepdims=True)) + + if return_type == "vert": + pointset = vertices + else: + # return centroids + pointset = vertices[faces].mean(axis=1) + pointset = pointset / np.sqrt(np.sum(pointset ** 2, axis=1, keepdims=True)) + + return pointset \ No newline at end of file From f82335804388132fb823bf0365d909796a89fdb7 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Tue, 25 Aug 2026 10:52:04 -0400 Subject: [PATCH 05/37] remove mesh data field --- include/openmc/mesh.h | 3 +-- openmc/mesh.py | 38 +++----------------------------------- openmc/model/funcs.py | 6 +++--- src/mesh.cpp | 6 ------ 4 files changed, 7 insertions(+), 46 deletions(-) diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 9c10356b1d6..79aca5eb822 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -891,7 +891,7 @@ class UnitSpherePointset : public AngularMesh { void material_volumes(int nx, int ny, int nz, int max_materials, int32_t* materials, double* volumes, double* bboxes) const override { - fatal_error("material_volumes() is not supported for UnitSpherePointset") + fatal_error("material_volumes() is not supported for UnitSpherePointset"); } std::string get_mesh_type() const override { return mesh_type; } @@ -900,7 +900,6 @@ class UnitSpherePointset : public AngularMesh { void to_hdf5_inner(hid_t group) const override; vector points_; - vector data_; }; #ifdef OPENMC_DAGMC_ENABLED diff --git a/openmc/mesh.py b/openmc/mesh.py index 9d73a6a4a87..46b17630727 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3401,8 +3401,6 @@ class UnitSpherePointset(AngularMesh): Unit-vector endpoints constituting the mesh. Must be either a numpy array or a nested list and have shape (N,3), where each row provides the [x, y, z] components of one such vector. - data : iterable of float - Scalar data (e.g. flux) assigned to each point in the mesh mesh_id : int Unique identifier for the mesh name : str @@ -3415,20 +3413,16 @@ class UnitSpherePointset(AngularMesh): name : str Name of the mesh points : numpy array of float - Array storing the - data : numpy array of float - Scalar data assigned to each point in the mesh + Array storing the direction vectors constituting the mesh. """ def __init__( self, points, - data: float | None = None, mesh_id: int | None = None, name: str = '', ): super().__init__(mesh_id, name) self.points = points - self.data = data @property def points(self): @@ -3442,20 +3436,6 @@ def points(self, pts): raise ValueError( "Unit vector array for UnitSpherePointset must have shape (N,3).") self._points = pts - - @property - def data(self): - return self._data - - @data.setter - def data(self, d): - if d is not None: - cv.check_type("AngularMesh data", d, Iterable, Real) - d = np.asarray(d).flatten() - if len(d) != len(self.points): - raise ValueError( - "Data for UnitSpherePointset does not match number of mesh elements.") - self._data = d @property def n_elements(self): @@ -3491,9 +3471,7 @@ def from_hdf5(cls, group: h5py.Group, mesh_id: int, name: str): n = points.size // 3 points = points.reshape(n, 3) - data = group['data'][()] if 'data' in group else None - - return cls(points, data=data, mesh_id=mesh_id, name=name) + return cls(points, mesh_id=mesh_id, name=name) def to_xml_element(self): """Return XML representation of the mesh @@ -3513,10 +3491,6 @@ def to_xml_element(self): subelement = ET.SubElement(element, "points") subelement.text = ' '.join(map(str, pts)) - if self.data is not None: - subelement = ET.SubElement(element, "data") - subelement.text = ' '.join(map(str, self.data)) - return element @classmethod @@ -3540,13 +3514,7 @@ def from_xml_element(cls, elem: ET.Element): n = points.size // 3 points = points.reshape(n, 3) - data_elem = elem.find("data") - if data_elem is not None: - data = get_elem_list(elem, "data", float) - else: - data = None - - return cls(points, data, mesh_id=mesh_id) + return cls(points, mesh_id=mesh_id) def _read_meshes(elem): diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index 320bfbfd432..784ce5e4f77 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -295,7 +295,7 @@ def pin(surfaces, items, subdivisions=None, divide_vols=True, # Pointset generators for discrete-ordinate angular meshes -def generate_levelsymmetric_sn(N: int, mu1_sq: float = None): +def levelsymmetric_sn(N: int, mu1_sq: float = None): """ Generates the direction vectors of an order-N level-symmetric quadrature set. Does not provide the corresponding weights. @@ -388,7 +388,7 @@ def generate_levelsymmetric_sn(N: int, mu1_sq: float = None): return all_points -def generate_tcl_sn(N: int): +def tcl_sn(N: int): """ Generate the direction vectors of an order-N triangular Chebyshev-Legendre (TCL) quadrature set. Supports even N >= 4. @@ -554,7 +554,7 @@ def directed_edge_indices(u_arr, v_arr): return subvertices, subfaces -def generate_icosphere_sn(nu: int = 1, point_type: str = "centroids"): +def icosphere_sn(nu: int = 1, point_type: str = "centroids"): """ Generates direction vectors from the vertices or centroids of a unit spherical icosahedron with principal faces subdivided at the nu-th diff --git a/src/mesh.cpp b/src/mesh.cpp index e288b455967..b9d0d76d8d2 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2474,9 +2474,6 @@ UnitSpherePointset::UnitSpherePointset(hid_t group) : AngularMesh(group) points_.reserve(n); for (int i = 0; i < n; ++i) points_.push_back({flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]}); - - if (object_exists(group, "data")) - read_dataset(group, "data", data_); } void UnitSpherePointset::to_hdf5_inner(hid_t mesh_group) const @@ -2489,9 +2486,6 @@ void UnitSpherePointset::to_hdf5_inner(hid_t mesh_group) const flat[3 * i + 2] = points_[i].z; } write_dataset(mesh_group, "points", flat); - - if (!data_.empty()) - write_dataset(mesh_group, "data", data_); } int UnitSpherePointset::get_bin(Direction u) const From 2cdebea935c12a81b6c289fb810ec4adeecf422e Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Wed, 26 Aug 2026 11:21:11 -0400 Subject: [PATCH 06/37] Compact data format for angular_flux_new, angular quadrature storage --- .../openmc/random_ray/flat_source_domain.h | 26 +- include/openmc/random_ray/source_region.h | 36 ++- src/random_ray/flat_source_domain.cpp | 232 +++++++++++++++--- src/random_ray/source_region.cpp | 31 ++- 4 files changed, 260 insertions(+), 65 deletions(-) diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index 216fe0ec436..9906bf98675 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -7,6 +7,7 @@ #include "openmc/random_ray/parallel_map.h" #include "openmc/random_ray/source_region.h" #include "openmc/source.h" +#include "openmc/mesh.h" #include #include @@ -36,6 +37,7 @@ class FlatSourceDomain { int64_t add_source_to_scalar_flux(); virtual void batch_reset(); void convert_source_regions_to_tallies(int64_t start_sr_id); + void initialize_angular_quadrature(); void reset_tally_volumes(); void random_ray_tally(); virtual void accumulate_iteration_flux(); @@ -68,16 +70,14 @@ class FlatSourceDomain { { return source_regions_.n_source_regions() * negroups_; } - int64_t n_source_angular_elements() const - { - return source_regions_.n_source_angular_elements(); - } int64_t lookup_base_source_region_idx(const GeometryState& p) const; SourceRegionKey lookup_source_region_key(const GeometryState& p) const; int64_t lookup_mesh_bin(int64_t sr, Position r) const; int lookup_mesh_idx(int64_t sr) const; - int lookup_angular_bin(Direction u) const; - Direction angular_mesh_direction(int a) { return angular_bin_angles_[a]; } + int get_angular_bin(Direction u) const; + Direction angular_quadrature_direction(int a) const; + bool tally_angular_flux_applies( + int cell_idx, int material, int mesh_idx) const; //---------------------------------------------------------------------------- // Static Data members @@ -180,12 +180,14 @@ class FlatSourceDomain { //---------------------------------------------------------------------------- // Private data members int negroups_; // Number of energy groups in simulation - int nangles_; // Number of bins for any angular flux tallies - - vector angular_bin_angles_; // Directions corresponding to each - // bin midpoint in the angular flux - // tallying scheme, flattened to 1D: - // [x0, y0, z0, x1, y1, z1,...] + int nangles_ {1}; // Number of bins for any angular flux tallies + const UnitSpherePointset* angular_mesh_ {nullptr}; + + vector tally_is_angular_; + std::unordered_set angular_target_cells_; + std::unordered_set angular_target_materials_; + std::unordered_set angular_target_meshes_; + bool tally_angular_flux_everywhere_ {false}; double simulation_volume_; // Total physical volume of the simulation domain, as diff --git a/include/openmc/random_ray/source_region.h b/include/openmc/random_ray/source_region.h index 8698f0a1427..d6726f3fa86 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -166,6 +166,7 @@ class SourceRegionHandle { double* volume_naive_; int* position_recorded_; int* external_source_present_; + int* needs_angular_flux_; Position* position_; Position* centroid_; Position* centroid_iteration_; @@ -244,6 +245,12 @@ class SourceRegionHandle { return *external_source_present_; } + int& needs_angular_flux() { return *needs_angular_flux_; } + const int needs_angular_flux() const + { + return *needs_angular_flux_; + } + Position& position() { return *position_; } const Position position() const { return *position_; } @@ -332,7 +339,8 @@ class SourceRegion { public: //---------------------------------------------------------------------------- // Constructors - SourceRegion(int negroups, bool is_linear, int nangles = 1); + SourceRegion(int negroups, bool is_linear, int nangles = 1, + bool needs_angular_flux = false); SourceRegion() = default; //---------------------------------------------------------------------------- @@ -355,6 +363,8 @@ class SourceRegion { int position_recorded_ {0}; //!< Has the position been recorded yet? int external_source_present_ { 0}; //!< Is an external source present in this region? + int needs_angular_flux_ { + 0}; //!< Is angular flux tallying active in this region? int is_small_ {0}; //!< Is it "small", receiving < 1.5 hits per iteration? int n_hits_ {0}; //!< Number of total hits (ray crossings) // Mesh that subdivides this source region @@ -470,6 +480,15 @@ class SourceRegionContainer { return external_source_present_[sr]; } + int& needs_angular_flux(int64_t sr) + { + return needs_angular_flux_[sr]; + } + const int needs_angular_flux(int64_t sr) const + { + return needs_angular_flux_[sr]; + } + Position& position(int64_t sr) { return position_[sr]; } const Position position(int64_t sr) const { return position_[sr]; } @@ -594,11 +613,11 @@ class SourceRegionContainer { double& angular_flux_new(int64_t sr, int g, int a) { - return angular_flux_new_[index_angle(sr, g, a)]; + return angular_flux_new_[angular_flux_offset_[sr] + g * nangles_ + a]; } const double angular_flux_new(int64_t sr, int g, int a) const { - return angular_flux_new_[index_angle(sr, g, a)]; + return angular_flux_new_[angular_flux_offset_[sr] + g * nangles_ + a]; } double& angular_flux_new(int64_t sea) { return angular_flux_new_[sea]; } const double angular_flux_new(int64_t sea) const @@ -660,10 +679,7 @@ class SourceRegionContainer { void flux_swap(); int64_t n_source_regions() const { return n_source_regions_; } int64_t n_source_elements() const { return n_source_regions_ * negroups_; } - int64_t n_source_angular_elements() const - { - return n_source_regions_ * negroups_ * nangles_; - } + int64_t n_source_angular_elements() const { return angular_flux_new_.size(); } int& negroups() { return negroups_; } const int negroups() const { return negroups_; } int& nangles() { return nangles_; } @@ -697,6 +713,7 @@ class SourceRegionContainer { vector volume_naive_; vector position_recorded_; vector external_source_present_; + vector needs_angular_flux_; vector position_; vector centroid_; vector centroid_iteration_; @@ -713,6 +730,7 @@ class SourceRegionContainer { vector scalar_flux_new_; vector scalar_flux_final_; vector angular_flux_new_; + vector angular_flux_offset_; vector source_; vector external_source_; @@ -733,10 +751,6 @@ class SourceRegionContainer { // Helper function for indexing inline int64_t index(int64_t sr, int g) const { return sr * negroups_ + g; } - inline int64_t index_angle(int64_t sr, int g, int a) const - { - return (sr * negroups_ + g) * nangles_ + a; - } }; } // namespace openmc diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 94376c9fefb..8ced8417220 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -5,6 +5,7 @@ #include "openmc/eigenvalue.h" #include "openmc/geometry.h" #include "openmc/material.h" +#include "openmc/mesh.h" #include "openmc/message_passing.h" #include "openmc/mgxs_interface.h" #include "openmc/output.h" @@ -12,6 +13,10 @@ #include "openmc/random_ray/random_ray.h" #include "openmc/simulation.h" #include "openmc/tallies/filter.h" +#include "openmc/tallies/filter_cell.h" +#include "openmc/tallies/filter_material.h" +#include "openmc/tallies/filter_mesh.h" +#include "openmc/tallies/filter_mesh_angular.h" #include "openmc/tallies/tally.h" #include "openmc/tallies/tally_scoring.h" #include "openmc/timer.h" @@ -54,9 +59,9 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) } } - // Count the number of angular bins if performing angular flux tallying - // and store the angle set. - nangles = + // Count the number of angular bins for each SourceRegion if performing + // angular flux tallying and store the angle set. + initialize_angular_quadrature(); // Initialize source regions. bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT; @@ -98,7 +103,8 @@ void FlatSourceDomain::batch_reset() } #pragma omp parallel for - for (int64_t sea = 0; sea < n_source_angular_elements(); sea++) { + for (int64_t sea = 0; sea < source_regions_.n_source_angular_elements(); + sea++) { source_regions_.angular_flux_new(sea) = 0.0; } } @@ -190,7 +196,8 @@ void FlatSourceDomain::normalize_flux_and_volumes( // Normalize angular flux in the same way #pragma omp parallel for - for (int64_t sea = 0; sea < n_source_angular_elements(); sea++) { + for (int64_t sea = 0; sea < source_regions_.n_source_angular_elements(); + sea++) { source_regions_.angular_flux_new(sea) *= normalization_factor; } @@ -243,6 +250,7 @@ void FlatSourceDomain::set_flux_to_source(int64_t sr, int g) // Combine transport flux contributions and flat source contributions from the // previous iteration to generate this iteration's estimate of scalar flux. +// Not performed for angular flux as sources are isotropic int64_t FlatSourceDomain::add_source_to_scalar_flux() { int64_t n_hits = 0; @@ -404,6 +412,115 @@ void FlatSourceDomain::compute_k_eff() k_eff_ = k_eff_new; } +// Scan all tallies for a MeshAngularFilter and determine where angular flux +// tallying will occur and on how many angles +void FlatSourceDomain::initialize_angular_quadrature() +{ + angular_mesh_ = nullptr; + tally_is_angular_.assign(model::tallies.size(), false); + angular_target_cells_.clear(); + angular_target_materials_.clear(); + angular_target_meshes_.clear(); + tally_angular_flux_everywhere_ = false; + + for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) { + Tally& tally {*model::tallies[i_tally]}; + + bool has_angular_filter = false; + bool has_spatial_filter = false; + + vector tally_cells; + vector tally_materials; + vector tally_meshes; + + for (auto i_filt : tally.filters()) { + Filter* filt = model::tally_filters[i_filt].get(); + + if (auto* angular_filter = dynamic_cast(filt)) { + has_angular_filter = true; + + const auto* this_mesh = dynamic_cast( + model::meshes[angular_filter->mesh()].get()); + if (!this_mesh) { + fatal_error("MeshAngularFilter must reference a UnitSpherePointset " + "mesh for tallying in Random Ray."); + } + // if we've already found an angular tally that uses a different mesh, + // throw error + if (angular_mesh_ && angular_mesh_ != this_mesh) { + fatal_error( + "Multiple distinct angular quadratures found across " + "MeshAngularFilter tallies. All angularly-resolved tallies in " + "a Random Ray simulation must reference the same " + "UnitSpherePointset mesh."); + } + angular_mesh_ = this_mesh; + continue; + } + + if (auto* cell_filter = dynamic_cast(filt)) { + has_spatial_filter = true; + for (int32_t c : cell_filter->cells()) { + tally_cells.push_back(c); + } + } else if (auto* mat_filter = dynamic_cast(filt)) { + has_spatial_filter = true; + for (int32_t m : mat_filter->materials()) { + tally_materials.push_back(m); + } + } else if (auto* mesh_filter = dynamic_cast(filt)) { + has_spatial_filter = true; + tally_meshes.push_back(mesh_filter->mesh()); + } + } + + if (!has_angular_filter) + continue; + + tally_is_angular_[i_tally] = true; + + if (!has_spatial_filter) { + tally_angular_flux_everywhere_ = true; + continue; + } + + for (int32_t c : tally_cells) { + angular_target_cells_.insert(c); + } + for (int32_t m : tally_materials) { + angular_target_materials_.insert(m); + } + for (int32_t m : tally_meshes) { + angular_target_meshes_.insert(m); + } + } + + nangles_ = angular_mesh_ ? angular_mesh_->points_.size() : 1; +} + +// Determines whether a source region with the given cell/material/mesh +// should have angular flux tallied. +bool FlatSourceDomain::tally_angular_flux_applies( + int cell_idx, int material, int mesh_idx) const +{ + if (tally_angular_flux_everywhere_) { + return true; + } + if (angular_target_cells_.count(cell_idx)) { + return true; + } + if (material != MATERIAL_VOID && + angular_target_materials_.count(material)) { + return true; + } + if (mesh_idx != C_NONE && angular_target_meshes_.count(mesh_idx)) { + // will flag every source region this mesh applies to, whether or + // not the region actually falls in a bin + return true; + } + return false; +} + // This function is responsible for generating a mapping between random // ray flat source regions (cell instances) and tally bins. The mapping // takes the form of a "TallyTask" object, which accounts for one single @@ -449,6 +566,9 @@ void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id) // Tracks if we've generated a mapping yet for all source regions. bool all_source_regions_mapped = true; + // Get flags for tallies that need a loop layer to cover angular bins + const vector& tally_is_angular = tally_is_angular_; + // Attempt to generate mapping for all source regions #pragma omp parallel for for (int64_t sr = start_sr_id; sr < n_source_regions(); sr++) { @@ -490,6 +610,11 @@ void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id) // to what happens when scanning for applicable tallies during // MC transport. for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) { + // skip angle-dependent tallies for now + if (tally_is_angular[i_tally]) { + continue; + } + Tally& tally {*model::tallies[i_tally]}; // Initialize an iterator over valid filter bin combinations. @@ -522,6 +647,37 @@ void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id) // Reset all the filter matches for the next tally event. for (auto& match : p.filter_matches()) match.bins_present_ = false; + + // Now loop over angle-dependent tallies + if (source_regions_.needs_angular_flux(sr)) { + for (int a = 0; a < source_regions_.nangles(); a++) { + p.u() = angular_quadrature_direction(a); + + for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) { + if (!tally_is_angular[i_tally]) + continue; + Tally& tally {*model::tallies[i_tally]}; + + auto filter_iter = FilterBinIter(tally, p); + auto end = FilterBinIter(tally, true, &p.filter_matches()); + if (filter_iter == end) + continue; + + for (; filter_iter != end; ++filter_iter) { + auto filter_index = filter_iter.index_; + + for (int score = 0; score < tally.scores_.size(); score++) { + auto score_bin = tally.scores_[score]; + TallyTask task(i_tally, filter_index, score, score_bin, a); + source_regions_.tally_task(sr, g).push_back(task); + source_regions_.volume_task(sr).insert(task); + } + } + } + for (auto& match : p.filter_matches()) + match.bins_present_ = false; + } + } } } openmc::simulation::time_tallies.stop(); @@ -658,17 +814,24 @@ void FlatSourceDomain::random_ray_tally() // Determine numerical score value for (auto& task : source_regions_.tally_task(sr, g)) { + // If the current task belongs to an angle-dependent tally, replace + // scalar flux with angular flux at the task's angle. + double task_flux = (task.angle_bin == C_NONE) + ? flux + : source_regions_.angular_flux_new(sr, g, task.angle_bin) * + source_normalization_factor; + double score = 0.0; switch (task.score_type) { case SCORE_FLUX: - score = flux * volume; + score = task_flux * volume; break; case SCORE_TOTAL: if (material != MATERIAL_VOID) { score = - flux * volume * + task_flux * volume * sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] * density_mult; } @@ -677,7 +840,7 @@ void FlatSourceDomain::random_ray_tally() case SCORE_FISSION: if (material != MATERIAL_VOID) { score = - flux * volume * + task_flux * volume * sigma_f_[(material * ntemperature_ + temp) * negroups_ + g] * density_mult; } @@ -686,7 +849,7 @@ void FlatSourceDomain::random_ray_tally() case SCORE_NU_FISSION: if (material != MATERIAL_VOID) { score = - flux * volume * + task_flux * volume * nu_sigma_f_[(material * ntemperature_ + temp) * negroups_ + g] * density_mult; } @@ -698,7 +861,7 @@ void FlatSourceDomain::random_ray_tally() case SCORE_KAPPA_FISSION: score = - flux * volume * + task_flux * volume * kappa_fission_[(material * ntemperature_ + temp) * negroups_ + g] * density_mult; break; @@ -1642,13 +1805,6 @@ SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle( // Additionally, we need to determine the source region's material, initialize // the starting scalar flux guess, and apply any known external sources. - // Call the basic constructor for the source region and store in the parallel - // map. - bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT; - SourceRegion* sr_ptr = - discovered_source_regions_.emplace(sr_key, {negroups_, is_linear}); - SourceRegionHandle handle {*sr_ptr}; - // Determine the material int gs_i_cell = gs.lowest_coord().cell(); Cell& cell = *model::cells[gs_i_cell]; @@ -1671,6 +1827,18 @@ SourceRegionHandle FlatSourceDomain::get_subdivided_source_region_handle( } } + // Determine whether to size the source region's angular flux array for + // tallying + bool needs_angular_flux = + tally_angular_flux_applies(gs_i_cell, material, mesh_idx); + + // Call the basic constructor for the source region and store in the parallel + // map. + bool is_linear = RandomRay::source_shape_ != RandomRaySourceShape::FLAT; + SourceRegion* sr_ptr = discovered_source_regions_.emplace( + sr_key, {negroups_, is_linear, nangles_, needs_angular_flux}); + SourceRegionHandle handle {*sr_ptr}; + handle.material() = material; handle.temperature_idx() = temp; @@ -1869,27 +2037,19 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const // If tallying angular flux, this function is used to determine which angular // bin the current ray contributes to. Rays are assigned to bins based on the -// unit-sphere Voronoi diagram generated from the "quadrature" angle set. -int FlatSourceDomain::lookup_angular_bin(Direction u) const +// unit-sphere Voronoi diagram generated from the "quadrature" angle set, +// stored in the referenced angular mesh. +int FlatSourceDomain::get_angular_bin(Direction u) const { - const double x = u.x; - const double y = u.y; - const double z = u.z; - - double max_dot = -INFTY; - std::size_t best_bin = 0; - for (std::size_t j = 0; j < nangles_; ++j) { - const std::size_t k = 3 * j; - const double dot = x * angular_bin_angles_[k] + - y * angular_bin_angles_[k + 1] + - z * angular_bin_angles_[k + 2]; - if (dot > max_dot) { - max_dot = dot; - best_bin = j; - } - } + return angular_mesh_->get_bin(u); +} - return static_cast(best_bin); +// Returns the representative direction of angular quadrature bin a. Used in +// convert_source_regions_to_tallies() to link angular filter bins to specific +// quadrature angles. +Direction FlatSourceDomain::angular_quadrature_direction(int a) const +{ + return angular_mesh_->points_[a]; } } // namespace openmc diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 5a305cfe27e..103a9b99a32 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -22,6 +22,7 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) volume_naive_(&sr.volume_naive_), position_recorded_(&sr.position_recorded_), external_source_present_(&sr.external_source_present_), + needs_angular_flux_(&sr.needs_angular_flux_), position_(&sr.position_), centroid_(&sr.centroid_), centroid_iteration_(&sr.centroid_iteration_), centroid_t_(&sr.centroid_t_), mom_matrix_(&sr.mom_matrix_), mom_matrix_t_(&sr.mom_matrix_t_), @@ -41,7 +42,8 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) //============================================================================== // SourceRegion implementation //============================================================================== -SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles) +SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles, + bool needs_angular_flux) { if (settings::run_mode == RunMode::EIGENVALUE) { // If in eigenvalue mode, set starting flux to guess of 1 @@ -56,7 +58,11 @@ SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles) scalar_flux_new_.assign(negroups, 0.0); source_.assign(negroups, 0.0); scalar_flux_final_.assign(negroups, 0.0); - angular_flux_new_.assign(negroups * nangles, 0.0f); + // Only allocate angular flux storage for regions that need it + needs_angular_flux_= needs_angular_flux; + if (needs_angular_flux_) { + angular_flux_new_.assign(negroups * nangles, 0.0f); + } tally_task_.resize(negroups); if (is_linear) { @@ -89,6 +95,7 @@ void SourceRegionContainer::push_back(const SourceRegion& sr) volume_naive_.push_back(sr.volume_naive_); position_recorded_.push_back(sr.position_recorded_); external_source_present_.push_back(sr.external_source_present_); + needs_angular_flux_.push_back(sr.needs_angular_flux_); position_.push_back(sr.position_); volume_task_.push_back(sr.volume_task_); mesh_.push_back(sr.mesh_); @@ -126,8 +133,13 @@ void SourceRegionContainer::push_back(const SourceRegion& sr) } // Angle- and energy-dependent flux - for (int ga = 0; ga < negroups_ * nangles_; ++ga) { - angular_flux_new_.push_back(sr.angular_flux_new_[ga]); + if (!sr.angular_flux_new_.empty()) { + angular_flux_offset_.push_back(angular_flux_new_.size()); + for (int ga = 0; ga < negroups_ * nangles_; ++ga) { + angular_flux_new_.push_back(sr.angular_flux_new_[ga]); + } + } else { + angular_flux_offset_.push_back(C_NONE); } } @@ -149,6 +161,7 @@ void SourceRegionContainer::assign( volume_naive_.clear(); position_recorded_.clear(); external_source_present_.clear(); + needs_angular_flux_.clear(); position_.clear(); mesh_.clear(); parent_sr_.clear(); @@ -165,6 +178,7 @@ void SourceRegionContainer::assign( scalar_flux_new_.clear(); scalar_flux_final_.clear(); angular_flux_new_.clear(); + angular_flux_offset_.clear(); source_.clear(); external_source_.clear(); @@ -211,6 +225,7 @@ SourceRegionHandle SourceRegionContainer::get_source_region_handle(int64_t sr) handle.volume_naive_ = &volume_naive(sr); handle.position_recorded_ = &position_recorded(sr); handle.external_source_present_ = &external_source_present(sr); + handle.needs_angular_flux_ = &needs_angular_flux(sr); handle.position_ = &position(sr); handle.volume_task_ = &volume_task(sr); handle.mesh_ = &mesh(sr); @@ -224,7 +239,11 @@ SourceRegionHandle SourceRegionContainer::get_source_region_handle(int64_t sr) handle.external_source_ = nullptr; } handle.scalar_flux_final_ = &scalar_flux_final(sr, 0); - handle.angular_flux_new_ = &angular_flux_new(sr, 0, 0); + if (angular_flux_offset_[sr] != C_NONE) { + handle.angular_flux_new_ = &angular_flux_new(sr, 0, 0); + } else { + handle.angular_flux_new_ = nullptr; + } handle.tally_task_ = &tally_task(sr, 0); if (handle.is_linear_) { @@ -267,7 +286,7 @@ void SourceRegionContainer::adjoint_reset() std::fill(scalar_flux_old_.begin(), scalar_flux_old_.end(), 1.0); } std::fill(scalar_flux_new_.begin(), scalar_flux_new_.end(), 0.0); - std::fill(angular_flux_new_.begin(), angular_flux_new_.end(), 0.0f); + std::fill(angular_flux_new_.begin(), angular_flux_new_.end(), 0.0); std::fill(source_.begin(), source_.end(), 0.0f); std::fill(external_source_.begin(), external_source_.end(), 0.0f); std::fill(source_gradients_.begin(), source_gradients_.end(), From afce8f4a501962a2a9783a708a5852eb5344649c Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Wed, 26 Aug 2026 14:00:57 -0400 Subject: [PATCH 07/37] formatting and MeshAngularFilter in Python API --- include/openmc/mesh.h | 4 +- .../openmc/random_ray/flat_source_domain.h | 6 +- include/openmc/random_ray/source_region.h | 18 +-- include/openmc/tallies/filter_meshangular.h | 3 +- openmc/filter.py | 152 +++++++++++++++++- src/random_ray/flat_source_domain.cpp | 32 ++-- src/random_ray/source_region.cpp | 18 +-- 7 files changed, 185 insertions(+), 48 deletions(-) diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 79aca5eb822..3a4a0cd8ac2 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -826,7 +826,7 @@ class UnstructuredMesh : public Mesh { virtual void initialize() = 0; }; -// Abstract class for meshes over directions (points on the unit sphere), +// Abstract class for meshes over directions (points on the unit sphere), // as opposed to meshes over volumes. class AngularMesh : public Mesh { public: @@ -873,7 +873,7 @@ class UnitSpherePointset : public AngularMesh { UnitSpherePointset(hid_t group); //! TODO: add sampling from within a spherical Voronoi cell - Position sample_element(int32_t bin, uint64_t* seed) const override + Position sample_element(int32_t bin, uint64_t* seed) const override { fatal_error( "Sampling over a UnitSpherePointset angular mesh is not supported"); diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index 9906bf98675..b3b0ab6277c 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -2,12 +2,12 @@ #define OPENMC_RANDOM_RAY_FLAT_SOURCE_DOMAIN_H #include "openmc/constants.h" +#include "openmc/mesh.h" #include "openmc/openmp_interface.h" #include "openmc/position.h" #include "openmc/random_ray/parallel_map.h" #include "openmc/random_ray/source_region.h" #include "openmc/source.h" -#include "openmc/mesh.h" #include #include @@ -179,8 +179,8 @@ class FlatSourceDomain { //---------------------------------------------------------------------------- // Private data members - int negroups_; // Number of energy groups in simulation - int nangles_ {1}; // Number of bins for any angular flux tallies + int negroups_; // Number of energy groups in simulation + int nangles_ {1}; // Number of bins for any angular flux tallies const UnitSpherePointset* angular_mesh_ {nullptr}; vector tally_is_angular_; diff --git a/include/openmc/random_ray/source_region.h b/include/openmc/random_ray/source_region.h index d6726f3fa86..e273a0e26db 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -54,7 +54,7 @@ struct TallyTask { int64_t filter_idx; int score_idx; int score_type; - // Angular quadrature bin index. Defaults to C_NONE for angle-independent, + // Angular quadrature bin index. Defaults to C_NONE for angle-independent, // scoring via the source region's scalar flux. int angle_bin {C_NONE}; TallyTask(int tally_idx, int64_t filter_idx, int score_idx, int score_type, @@ -246,10 +246,7 @@ class SourceRegionHandle { } int& needs_angular_flux() { return *needs_angular_flux_; } - const int needs_angular_flux() const - { - return *needs_angular_flux_; - } + const int needs_angular_flux() const { return *needs_angular_flux_; } Position& position() { return *position_; } const Position position() const { return *position_; } @@ -339,7 +336,7 @@ class SourceRegion { public: //---------------------------------------------------------------------------- // Constructors - SourceRegion(int negroups, bool is_linear, int nangles = 1, + SourceRegion(int negroups, bool is_linear, int nangles = 1, bool needs_angular_flux = false); SourceRegion() = default; @@ -362,9 +359,9 @@ class SourceRegion { double volume_naive_ {0.0}; //!< Volume as integrated from this iteration only int position_recorded_ {0}; //!< Has the position been recorded yet? int external_source_present_ { - 0}; //!< Is an external source present in this region? + 0}; //!< Is an external source present in this region? int needs_angular_flux_ { - 0}; //!< Is angular flux tallying active in this region? + 0}; //!< Is angular flux tallying active in this region? int is_small_ {0}; //!< Is it "small", receiving < 1.5 hits per iteration? int n_hits_ {0}; //!< Number of total hits (ray crossings) // Mesh that subdivides this source region @@ -480,10 +477,7 @@ class SourceRegionContainer { return external_source_present_[sr]; } - int& needs_angular_flux(int64_t sr) - { - return needs_angular_flux_[sr]; - } + int& needs_angular_flux(int64_t sr) { return needs_angular_flux_[sr]; } const int needs_angular_flux(int64_t sr) const { return needs_angular_flux_[sr]; diff --git a/include/openmc/tallies/filter_meshangular.h b/include/openmc/tallies/filter_meshangular.h index 8535f5bf699..066619485fe 100644 --- a/include/openmc/tallies/filter_meshangular.h +++ b/include/openmc/tallies/filter_meshangular.h @@ -6,7 +6,7 @@ namespace openmc { //============================================================================== -//! Indexes the direction of particle events to a mesh. +//! Indexes the direction of particle events to a mesh. //============================================================================== class MeshAngularFilter : public MeshFilter { @@ -22,7 +22,6 @@ class MeshAngularFilter : public MeshFilter { void to_statepoint(hid_t filter_group) const override; - //---------------------------------------------------------------------------- // Accessors diff --git a/openmc/filter.py b/openmc/filter.py index 00a2f31014c..607d387a698 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1349,13 +1349,157 @@ def get_pandas_dataframe(self, data_size, stride, **kwargs): # Initialize a Pandas DataFrame from the mesh dictionary return pd.concat([df, pd.DataFrame(filter_dict)]) -class MeshAngularFilter(Filter): +class MeshAngularFilter(MeshFilter): """Bins tally events based on incident particle's direction, using an angular mesh. - + + Parameters + ---------- + mesh : openmc.MeshBase + The mesh object that events will be tallied onto + filter_id : int + Unique identifier for the filter + + Attributes + ---------- + mesh : openmc.MeshBase + The mesh object that events will be tallied onto + translation : Iterable of float + This array specifies a vector that is used to translate (shift) + the mesh for this filter + id : int + Unique identifier for the filter + bins : list of tuple + A list of mesh indices / surfaces for each filter bin, e.g. [(1, 1, + 'x-min out'), (1, 1, 'x-min in'), ...]. Surface names use the mesh's + axis labels (e.g. r/phi/z for a cylindrical mesh). + num_bins : Integral + The number of filter bins + """ - def __init__(self): - pass + def __init__(self, mesh, filter_id=None): + self.mesh = mesh + self.id = filter_id + self._rotation = None + + def __repr__(self): + string = type(self).__name__ + '\n' + string += '{: <16}=\t{}\n'.format('\tMesh ID', self.mesh.id) + string += '{: <16}=\t{}\n'.format('\tID', self.id) + string += '{: <16}=\t{}\n'.format('\tRotation', self.rotation) + return string + + @mesh.setter + def mesh(self, mesh): + cv.check_type('filter mesh', mesh, openmc.UnitSpherePointset) + self._mesh = mesh + self.bins = list(mesh.indices) + + def translation(self): + raise AttributeError( + "MeshAngularFilter instances do not permit translation.") + + @classmethod + def from_hdf5(cls, group, **kwargs): + if group['type'][()].decode() != cls.short_name.lower(): + raise ValueError("Expected HDF5 data for filter type '" + + cls.short_name.lower() + "' but got '" + + group['type'][()].decode() + " instead") + + if 'meshes' not in kwargs: + raise ValueError(cls.__name__ + " requires a 'meshes' keyword " + "argument.") + + mesh_id = group['bins'][()] + mesh_obj = kwargs['meshes'][mesh_id] + filter_id = int(group.name.split('/')[-1].lstrip('filter ')) + + out = cls(mesh_obj, filter_id=filter_id) + + rotation = group.get('rotation') + if rotation: + out.rotation = rotation[()] + + return out + + def get_pandas_dataframe(self, data_size, stride, **kwargs): + """Builds a Pandas DataFrame for MeshAngularFilter's bins. + + This method constructs a Pandas DataFrame object for the filter with + columns annotated by filter bin information. This is a helper method for + :meth:`Tally.get_pandas_dataframe`. + + Parameters + ---------- + data_size : int + The total number of bins in the tally corresponding to this filter + stride : int + Stride in memory for the filter + + Returns + ------- + pandas.DataFrame + A Pandas DataFrame with columns describing the mesh cell indices + corresponding to each filter bin. Column names are element index for + AngularMesh). The number of rows in the DataFrame is the same + as the total number of bins in the corresponding tally, with the + filter bin appropriately tiled to map to the corresponding tally + bins. + + See also + -------- + Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() + + """ + # Initialize dictionary to build Pandas Multi-index column + filter_dict = {} + + # Append mesh ID as outermost index of multi-index + mesh_key = f'mesh {self.mesh.id}' + + # Determine index base (0-based for angular meshes) + idx_start = 0 + + # Generate a multi-index sub-column for each axis + for label, dim_size in zip(self.mesh.axis_labels, self.mesh.dimension): + filter_dict[mesh_key, label] = _repeat_and_tile( + np.arange(idx_start, idx_start + dim_size), stride, data_size) + stride *= dim_size + + return pd.DataFrame(filter_dict) + + def to_xml_element(self): + """Return XML Element representing the Filter. + + Returns + ------- + element : lxml.etree._Element + XML element containing filter data + + """ + element = ET.Element('filter') + element.set('id', str(self.id)) + element.set('type', self.short_name.lower()) + subelement = ET.SubElement(element, 'bins') + subelement.text = str(self.mesh.id) + if self.rotation is not None: + element.set('rotation', ' '.join(map(str, self.rotation.ravel()))) + return element + + @classmethod + def from_xml_element(cls, elem: ET.Element, **kwargs) -> MeshFilter: + mesh_id = int(get_text(elem, 'bins')) + mesh_obj = kwargs['meshes'][mesh_id] + filter_id = int(get_text(elem, "id")) + out = cls(mesh_obj, filter_id=filter_id) + + rotation = get_elem_list(elem, 'rotation', float) or [] + if rotation: + if len(rotation) == 3: + out.rotation = rotation + elif len(rotation) == 9: + out.rotation = np.array(rotation).reshape(3, 3) + return out class CollisionFilter(Filter): diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 8ced8417220..237dadad9ba 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -59,7 +59,7 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) } } - // Count the number of angular bins for each SourceRegion if performing + // Count the number of angular bins for each SourceRegion if performing // angular flux tallying and store the angle set. initialize_angular_quadrature(); @@ -412,7 +412,7 @@ void FlatSourceDomain::compute_k_eff() k_eff_ = k_eff_new; } -// Scan all tallies for a MeshAngularFilter and determine where angular flux +// Scan all tallies for a MeshAngularFilter and determine where angular flux // tallying will occur and on how many angles void FlatSourceDomain::initialize_angular_quadrature() { @@ -445,7 +445,7 @@ void FlatSourceDomain::initialize_angular_quadrature() fatal_error("MeshAngularFilter must reference a UnitSpherePointset " "mesh for tallying in Random Ray."); } - // if we've already found an angular tally that uses a different mesh, + // if we've already found an angular tally that uses a different mesh, // throw error if (angular_mesh_ && angular_mesh_ != this_mesh) { fatal_error( @@ -498,7 +498,7 @@ void FlatSourceDomain::initialize_angular_quadrature() nangles_ = angular_mesh_ ? angular_mesh_->points_.size() : 1; } -// Determines whether a source region with the given cell/material/mesh +// Determines whether a source region with the given cell/material/mesh // should have angular flux tallied. bool FlatSourceDomain::tally_angular_flux_applies( int cell_idx, int material, int mesh_idx) const @@ -509,12 +509,11 @@ bool FlatSourceDomain::tally_angular_flux_applies( if (angular_target_cells_.count(cell_idx)) { return true; } - if (material != MATERIAL_VOID && - angular_target_materials_.count(material)) { + if (material != MATERIAL_VOID && angular_target_materials_.count(material)) { return true; } if (mesh_idx != C_NONE && angular_target_meshes_.count(mesh_idx)) { - // will flag every source region this mesh applies to, whether or + // will flag every source region this mesh applies to, whether or // not the region actually falls in a bin return true; } @@ -647,7 +646,7 @@ void FlatSourceDomain::convert_source_regions_to_tallies(int64_t start_sr_id) // Reset all the filter matches for the next tally event. for (auto& match : p.filter_matches()) match.bins_present_ = false; - + // Now loop over angle-dependent tallies if (source_regions_.needs_angular_flux(sr)) { for (int a = 0; a < source_regions_.nangles(); a++) { @@ -814,12 +813,13 @@ void FlatSourceDomain::random_ray_tally() // Determine numerical score value for (auto& task : source_regions_.tally_task(sr, g)) { - // If the current task belongs to an angle-dependent tally, replace + // If the current task belongs to an angle-dependent tally, replace // scalar flux with angular flux at the task's angle. - double task_flux = (task.angle_bin == C_NONE) - ? flux - : source_regions_.angular_flux_new(sr, g, task.angle_bin) * - source_normalization_factor; + double task_flux = + (task.angle_bin == C_NONE) + ? flux + : source_regions_.angular_flux_new(sr, g, task.angle_bin) * + source_normalization_factor; double score = 0.0; switch (task.score_type) { @@ -2037,15 +2037,15 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const // If tallying angular flux, this function is used to determine which angular // bin the current ray contributes to. Rays are assigned to bins based on the -// unit-sphere Voronoi diagram generated from the "quadrature" angle set, +// unit-sphere Voronoi diagram generated from the "quadrature" angle set, // stored in the referenced angular mesh. int FlatSourceDomain::get_angular_bin(Direction u) const { return angular_mesh_->get_bin(u); } -// Returns the representative direction of angular quadrature bin a. Used in -// convert_source_regions_to_tallies() to link angular filter bins to specific +// Returns the representative direction of angular quadrature bin a. Used in +// convert_source_regions_to_tallies() to link angular filter bins to specific // quadrature angles. Direction FlatSourceDomain::angular_quadrature_direction(int a) const { diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 103a9b99a32..1a975e966e0 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -22,12 +22,12 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) volume_naive_(&sr.volume_naive_), position_recorded_(&sr.position_recorded_), external_source_present_(&sr.external_source_present_), - needs_angular_flux_(&sr.needs_angular_flux_), - position_(&sr.position_), centroid_(&sr.centroid_), - centroid_iteration_(&sr.centroid_iteration_), centroid_t_(&sr.centroid_t_), - mom_matrix_(&sr.mom_matrix_), mom_matrix_t_(&sr.mom_matrix_t_), - volume_task_(&sr.volume_task_), mesh_(&sr.mesh_), - parent_sr_(&sr.parent_sr_), scalar_flux_old_(sr.scalar_flux_old_.data()), + needs_angular_flux_(&sr.needs_angular_flux_), position_(&sr.position_), + centroid_(&sr.centroid_), centroid_iteration_(&sr.centroid_iteration_), + centroid_t_(&sr.centroid_t_), mom_matrix_(&sr.mom_matrix_), + mom_matrix_t_(&sr.mom_matrix_t_), volume_task_(&sr.volume_task_), + mesh_(&sr.mesh_), parent_sr_(&sr.parent_sr_), + scalar_flux_old_(sr.scalar_flux_old_.data()), scalar_flux_new_(sr.scalar_flux_new_.data()), source_(sr.source_.data()), external_source_(sr.external_source_.data()), scalar_flux_final_(sr.scalar_flux_final_.data()), @@ -42,8 +42,8 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) //============================================================================== // SourceRegion implementation //============================================================================== -SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles, - bool needs_angular_flux) +SourceRegion::SourceRegion( + int negroups, bool is_linear, int nangles, bool needs_angular_flux) { if (settings::run_mode == RunMode::EIGENVALUE) { // If in eigenvalue mode, set starting flux to guess of 1 @@ -59,7 +59,7 @@ SourceRegion::SourceRegion(int negroups, bool is_linear, int nangles, source_.assign(negroups, 0.0); scalar_flux_final_.assign(negroups, 0.0); // Only allocate angular flux storage for regions that need it - needs_angular_flux_= needs_angular_flux; + needs_angular_flux_ = needs_angular_flux; if (needs_angular_flux_) { angular_flux_new_.assign(negroups * nangles, 0.0f); } From 210a5b52cefedcd28c8dc8cf38d61194a21b6a9d Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Wed, 26 Aug 2026 17:17:18 -0400 Subject: [PATCH 08/37] angular distributions init --- include/openmc/distribution_multi.h | 40 ++++ include/openmc/mesh.h | 41 ++++ openmc/mesh.py | 321 ++++++++++++++++++++++++++++ openmc/stats/multivariate.py | 113 ++++++++++ src/distribution_multi.cpp | 90 ++++++++ src/mesh.cpp | 199 ++++++++++++++++- 6 files changed, 803 insertions(+), 1 deletion(-) diff --git a/include/openmc/distribution_multi.h b/include/openmc/distribution_multi.h index a72780737a6..0737a98f65d 100644 --- a/include/openmc/distribution_multi.h +++ b/include/openmc/distribution_multi.h @@ -135,6 +135,46 @@ class Monodirectional : public UnitSphereDistribution { std::pair sample(uint64_t* seed) const override; }; +//============================================================================== +//! MeshAngular distribution +//============================================================================== + +class MeshAngular : public UnitSphereDistribution { +public: + MeshAngular() {}; + explicit MeshAngular(pugi::xml_node node); + + //! Sample a direction from the distribution + //! \param seed Pseudorandom number seed pointer + //! \return (sampled Direction, sample weight) + std::pair sample(uint64_t* seed) const override; + + //! Sample the mesh for an element and direction from that element + //! \param seed Pseudorandom number seed pointer + //! \return Sampled element index and direction within that element + std::pair sample_mesh(uint64_t* seed) const; + + //! Sample a mesh element + //! \param seed Pseudorandom number seed pointer + //! \return Sampled element index + int32_t sample_element_index(uint64_t* seed) const; + + //! Ensure that mesh elements are spherical triangles + void check_element_types() const; + + // Accessors + const Mesh* mesh() const { return model::meshes.at(mesh_idx_).get(); } + int32_t n_sources() const { return this->mesh()->n_bins(); } + + double total_strength() { return this->elem_idx_dist_.integral(); } + +private: + int32_t mesh_idx_ {C_NONE}; + DiscreteIndex elem_idx_dist_; //!< Distribution of mesh element indices + vector weight_; //!< Importance weights (empty if unbiased) + Direction v_ref_ {1.0, 0.0, 0.0}; //!< reference direction +}; + using UPtrAngle = unique_ptr; } // namespace openmc diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 3a4a0cd8ac2..ee3201fb5e3 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -902,6 +902,47 @@ class UnitSpherePointset : public AngularMesh { vector points_; }; +class UnitSphereTriangularMesh : public AngularMesh { +public: + UnitSphereTriangularMesh() = default; + explicit UnitSphereTriangularMesh(vector vertices); + UnitSphereTriangularMesh(pugi::xml_node node); + UnitSphereTriangularMesh(hid_t group); + + //! Direction and Position are the same type underneath--can override + Direction sample_element(int32_t bin, uint64_t* seed) const override; + + //! Point-location on an arbitrary spherical triangular mesh is + //! difficult, so we leave this unimplemented. + //! get_bin() would only be called on an angular mesh in case of + //! anisotropic effects, such as angle-dependent weight windows, which a + //! particle encounters during transport. + int get_bin(Direction u) const override + { + fatal_error("get_bin() is not supported for UnitSpereTriangularMesh"); + } + + int n_bins() const override { return static_cast(vertices_.size() / 9); } + + //! Return surface area of a specific triangle + double volume(int bin) const override; + + void material_volumes(int nx, int ny, int nz, int max_materials, + int32_t* materials, double* volumes, double* bboxes) const override + { + fatal_error( + "material_volumes() is not supported for UnitSphereTriangularMesh"); + } + + std::string get_mesh_type() const override { return mesh_type; } + static const std::string mesh_type; + + void to_hdf5_inner(hid_t group) const override; + + vector vertices_; + vector areas_; +}; + #ifdef OPENMC_DAGMC_ENABLED class MOABMesh : public UnstructuredMesh { diff --git a/openmc/mesh.py b/openmc/mesh.py index 46b17630727..570af4e16f0 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3515,6 +3515,327 @@ def from_xml_element(cls, elem: ET.Element): points = points.reshape(n, 3) return cls(points, mesh_id=mesh_id) + +class SphericalTriangle: + ''' + Primitive class storing information about a triangle defined by three + points on the surface of the unit sphere. Used to construct MeshAngular + distributions. + + On the unit sphere, the (surface) area of a spherical triangle is equal to + its "spherical excess." For a triangle with dihedral angles alpha, beta, + and gamma, the spherical excess is: + + E = alpha + beta + gamma - pi + + Citation: Van Oosterom, A; Strackee, J (1983), "The Solid Angle of a Plane + Triangle". IEEE Transactions on Biomedical Engineering, BME-30 (2): + 125–126. doi:10.1109/TBME.1983.325207 + + Parameters + ---------- + vertices : iterable of float + Unit-vector vertices of the triangle. Must be either a numpy + array or a nested list and have shape (3,3), where each row provides + the [x, y, z] components of one such vector. + area : float, optional + Surface area of the triangle, equal to the solid angle it subtends + with respect to the origin. Will be automatically calculated if not + provided. + + Attributes + ---------- + vertices : numpy array of shape (3, 3) + Array wherein each row stores the coordinates of one of the 3 corners + of the triangle + area : float + Area of the triangle + ''' + def __init__( + self, + vertices, + area=None + ): + self._vertices = vertices + + if area is None: + a, b, c = self.vertices + num = np.dot(a, np.cross(b, c)) + denom = 1 + np.dot(a, b) + np.dot(b, c) + np.dot(c, a) + area = 2 * np.arctan2(num, denom) + + self._area = area + + @property + def vertices(self): + return self._vertices + + @vertices.setter + def vertices(self, pointset): + cv.check_type("angular mesh vertices", pointset, Iterable, Real) + pointset = np.asarray(pointset) + if pointset.shape != (3,3): + raise ValueError( + "Vertex array for SphericalTriangle must have shape (3,3).") + self._vertices = pointset + + @property + def area(self): + return self._area + + @area.setter + def area(self, a): + cv.check_type("SphericalTriangle area", a, Real) + cv.check_greater_than("SphericalTriangle area", a, 0.0) + self._area = a + + def centroid(self): + """Return centroid of SphericalTriangle.""" + centroid = self.vertices.mean(axis=0) + return centroid / np.linalg.norm(centroid) + +class UnitSphereTriangularMesh(AngularMesh): + """Basic triangular mesh of the surface of the unit sphere. Used to + construct MeshAngular distributions. + + Parameters + ---------- + triangles : iterable of SphericalTriangle + Triangular mesh cells on the unit sphere + mesh_id : int + Unique identifier for the mesh + name : str + Name of the mesh + + Attributes + ---------- + id : int + Unique identifier for the mesh + name : str + Name of the mesh + triangles : numpy array of SphericalTriangle + Triangular mesh cells on the unit sphere + """ + def __init__( + self, + triangles, + mesh_id: int | None = None, + name: str = '', + ): + super().__init__(mesh_id, name) + self.triangles = triangles + + @property + def triangles(self): + return self._triangles + + @triangles.setter + def triangles(self, tris): + cv.check_type("angular mesh cells", tris, Iterable, SphericalTriangle) + tris = np.asarray(tris).flatten() + # Check that the set is at least large enough to tile the unit sphere + cv.check_greater_than("angular mesh size", len(tris), 4, True) + self._triangles = tris + + @property + def n_elements(self): + return len(self.triangles) + + @property + def dimension(self): + return (self.n_elements,) + + @property + def n_dimension(self): + return 2 + + @property + def lower_left(self): + return np.array((-1., -1., -1.)) + + @property + def upper_right(self): + return np.array((1., 1., 1.)) + + @property + def axis_labels(self): + return ('element_index',) + + @property + def indices(self): + return [(i,) for i in range(self.n_elements)] + + @property + def centroids(self): + return np.array([tri.centroid() for tri in self.triangles]) + + @property + def vertices(self): + """Return all unique vertices of the mesh in one (N,3) array.""" + verts = np.concatenate([tri.vertices for tri in self.triangles], axis=0) + verts = np.unique(verts, axis=0) + return verts + + @property + def volumes(self): + """Area of each SphericalTriangle in the mesh.""" + return np.array([tri.area for tri in self.triangles]) + + # override non-applicable methods of MeshBase + def get_homogenized_materials(self, *args, **kwargs): + raise NotImplementedError( + "Material attributes are not available for AngularMesh.") + + def material_volumes(self, *args, **kwargs): + raise NotImplementedError( + "Material attributes are not available for AngularMesh.") + + def sample_element(self, element_idx, seed=None): + """Sample a direction uniformly from within a given SphericalTriangle + in the mesh. + + Uses the sampling algorithm of Arvo, James, “Analytic Methods for + Simulated Light Transport.” PhD Thesis, Yale University, December 1995. + + Parameters + ---------- + element_idx : int + Index of the triangular mesh element to sample from. + seed : int or None + Initial random number seed. + + Returns + ------- + numpy.ndarray + Sampled direction in Cartesian coordinates. + + """ + rng = np.random.RandomState(seed) + tri = self.triangles[element_idx] + # Step 0: compute deterministic quantities: + # the cosine of the arclength c (from A to B), + # the (normalized) component of C orthogonal to A, + # and dihedral angle alpha (& sines/cosines) + A = np.array(tri.vertices[0]) + B = np.array(tri.vertices[1]) + C = np.array(tri.vertices[2]) + + cos_c_arc = np.dot(A, B) # used later + c_orth_a = C - np.dot(C, A)*A + c_orth_a /= np.linalg.norm(c_orth_a) # used later + + n_BA = np.cross(B,A) + n_AC = np.cross(A,C) + cos_a = np.dot(n_BA, n_AC) # used later + alpha = np.acos(cos_a) # used later + sin_a = np.sin(alpha) # used later + + # Find area of subtriangle + sub_area = rng.uniform(0., 1.0, 1)*tri.area + + # Save the sine and cosine of the angle (A-hat) - alpha + s = np.sin(sub_area - alpha) + t = np.cos(sub_area - alpha) + + # Compute the pair (u,v) that determines beta-hat + u = t - cos_a + v = s + sin_a*cos_c_arc + + # Let q be the cosine of the new edge length b-hat + numer = (v*t - u*s)*cos_a - v + denom = (v*s + u*t)*sin_a + q = numer/denom + + # Compute the third vertex of the subtriangle + C_hat = q*A + np.sqrt(1 - q**2)*c_orth_a + + # Use the other random variable to select cos(theta) + z = 1 - rng.uniform(0., 1.0, 1)*(1 - np.dot(C_hat, B)) + + # Construct corresponding point on the sphere + c_hat_orth_b = C_hat - np.dot(C_hat, B)*B + c_hat_orth_b /= np.linalg.norm(c_hat_orth_b) + + P = z*B + np.sqrt(1 - z**2)*c_hat_orth_b + + # error-check: make sure P is a unit vector + mag_p = np.linalg.norm(P) + if np.abs(mag_p - 1.0) > 1e-14: + print(f"P (magnitude {mag_p}) was not a unit vector!") + P /= mag_p + + return P + + @classmethod + def from_hdf5(cls, group: h5py.Group, mesh_id: int, name: str): + tri_verts = np.asarray(group['vertices'][()]) + areas = np.asarray(group['areas'][()]) + n = len(areas) + tri_verts = tri_verts.reshape(n, 3, 3) + + triangles = [ + SphericalTriangle(tri_verts[i], area=float(areas[i])) + for i in range(n) + ] + + return cls(triangles, mesh_id=mesh_id, name=name) + + def to_xml_element(self): + """Return XML representation of the mesh + + Returns + ------- + element : lxml.etree._Element + XML element containing mesh data + + """ + element = super().to_xml_element() + element.set("type", "angular") + + # Flatten to a (3*N, 3) array + all_vertices = np.concatenate( + [tri.vertices for tri in self.triangles], axis=0) + + subelement = ET.SubElement(element, "vertices") + subelement.text = ' '.join(map(str, all_vertices.flatten())) + + subelement = ET.SubElement(element, "areas") + subelement.text = ' '.join(str(tri.area) for tri in self.triangles) + + return element + + @classmethod + def from_xml_element(cls, elem: ET.Element): + """Generate an angular mesh from an XML element + + Parameters + ---------- + elem : lxml.etree._Element + XML element + + Returns + ------- + openmc.AngularMesh + Angular mesh object + + """ + mesh_id = int(get_text(elem, 'id')) + + flat_vertices = np.array(get_elem_list(elem, "vertices", float)) + areas = get_elem_list(elem, "areas", float) + + n = flat_vertices.size // 9 + tri_vertices = flat_vertices.reshape(n, 3, 3) + + triangles = [ + SphericalTriangle(tri_vertices[i], area=areas[i]) + for i in range(n) + ] + + return cls(triangles, mesh_id=mesh_id) + +def triangularize_unit_sphere_mesh(mesh : UnitSpherePointset, data = None): + pass def _read_meshes(elem): diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index f7a2156945e..336d81e6e43 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -330,6 +330,119 @@ def from_xml_element(cls, elem: ET.Element): return monodirectional +class MeshAngular(UnitSphere): + """Mesh-based angular distribution. + + """ + def __init__(self, mesh, strengths=None, bias: Sequence[float] | None = None): + self.mesh = mesh + self.strengths = strengths + self.bias = bias + + @property + def mesh(self): + return self._mesh + + @mesh.setter + def mesh(self, mesh): + if mesh is not None: + cv.check_type('mesh instance', mesh, UnitSphereTriangularMesh) + self._mesh = mesh + + @property + def strengths(self): + return self._strengths + + @strengths.setter + def strengths(self, given_strengths): + if given_strengths is not None: + cv.check_type('strengths array passed in', given_strengths, Iterable, Real) + given_strengths = np.asarray(given_strengths, dtype=float).flatten() + if len(given_strengths) != len(self.mesh.n_elements): + raise AttributeError( + "Strengths array must have same dimension as angular mesh.") + else: + self._strengths = given_strengths + else: + # Default to isotropic + self._strengths = (1/(4*PI)) * self.mesh.volumes + + @property + def bias(self): + return self._bias + + @bias.setter + def bias(self, given_bias): + if given_bias is not None: + cv.check_type('Biasing strengths array', given_bias, Iterable, Real) + bias_array = np.asarray(given_bias, dtype=float).flatten() + if bias_array.size != self.strengths.size: + raise ValueError( + 'Bias strengths array must have same size as strengths array.') + else: + self._bias = bias_array + else: + self._bias = None + + @property + def num_strength_bins(self): + if self.strengths is None: + raise ValueError('Strengths are not set') + return self.strengths.size + + def to_xml_element(self): + """Return XML representation of the spatial distribution + + Returns + ------- + element : lxml.etree._Element + XML element containing spatial distribution data + + """ + element = ET.Element('space') + + element.set('type', 'mesh_angular') + element.set("mesh_id", str(self.mesh.id)) + + if self.strengths is not None: + subelement = ET.SubElement(element, 'strengths') + subelement.text = ' '.join(str(e) for e in self.strengths) + + if self.bias is not None: + Univariate._append_array_bias_to_xml(self, element) + + return element + + @classmethod + def from_xml_element(cls, elem, meshes): + """Generate spatial distribution from an XML element + + Parameters + ---------- + elem : lxml.etree._Element + XML element + meshes : dict + A dictionary with mesh IDs as keys and openmc.MeshBase instances as + values + + Returns + ------- + openmc.stats.MeshSpatial + Spatial distribution generated from XML element + + """ + + mesh_id = int(get_text(elem, "mesh_id")) + + # check if this mesh has been read in from another location already + if mesh_id not in meshes: + raise ValueError(f'Could not locate mesh with ID "{mesh_id}"') + + strengths = get_elem_list(elem, 'strengths', float) + bias_strengths = Univariate._read_array_bias_from_xml(elem) + return cls(meshes[mesh_id], strengths, bias=bias_strengths) + + class Spatial(ABC): """Distribution of locations in three-dimensional Euclidean space. diff --git a/src/distribution_multi.cpp b/src/distribution_multi.cpp index 47785649b53..b10c3237db7 100644 --- a/src/distribution_multi.cpp +++ b/src/distribution_multi.cpp @@ -189,4 +189,94 @@ std::pair Monodirectional::sample(uint64_t* seed) const return {u_ref_, 1.0}; } +//============================================================================== +// MeshAngular implementation +//============================================================================== + +MeshAngular::MeshAngular(pugi::xml_node node) : UnitSphereDistribution {node} +{ + auto spatial_type = get_node_value(node, "type", true, true); + if (spatial_type != "mesh_angular") { + fatal_error( + fmt::format("Incorrect angular type '{}' for a MeshAngular distribution", + spatial_type)); + } + + int32_t mesh_id = std::stoi(get_node_value(node, "mesh_id")); + // Get pointer to spatial distribution + mesh_idx_ = model::mesh_map.at(mesh_id); + + check_element_types(); + + size_t n_bins = this->n_sources(); + std::vector strengths(n_bins, 1.0); + + // Create cdfs for sampling for an element over a mesh + if (check_for_node(node, "strengths")) { + strengths = get_node_array(node, "strengths"); + if (strengths.size() != n_bins) { + fatal_error( + fmt::format("Number of entries in the source strengths array {} does " + "not match the number of entities in mesh {} ({}).", + strengths.size(), mesh_id, n_bins)); + } + } + + elem_idx_dist_.assign(strengths); + + if (check_for_node(node, "bias")) { + pugi::xml_node bias_node = node.child("bias"); + + if (check_for_node(bias_node, "strengths")) { + std::vector bias_strengths(n_bins, 1.0); + bias_strengths = get_node_array(node, "strengths"); + + if (bias_strengths.size() != n_bins) { + fatal_error( + fmt::format("Number of entries in the bias strengths array {} does " + "not match the number of entities in mesh {} ({}).", + bias_strengths.size(), mesh_id, n_bins)); + } + + // Compute importance weights + weight_ = compute_importance_weights(strengths, bias_strengths); + + // Re-initialize DiscreteIndex with bias strengths for sampling + elem_idx_dist_.assign(bias_strengths); + } else { + fatal_error(fmt::format( + "Bias node for mesh {} found without strengths array.", mesh_id)); + } + } +} + +void MeshAngular::check_element_types() const +{ + const auto trimesh_ptr = + dynamic_cast(this->mesh()); + if (!trimesh_ptr) { + fatal_error("MeshAngular distribution must use a mesh of type " + "UnitSphereTriangularMesh."); + } +} + +int32_t MeshAngular::sample_element_index(uint64_t* seed) const +{ + return elem_idx_dist_.sample(seed); +} + +std::pair MeshAngular::sample_mesh(uint64_t* seed) const +{ + // Sample the CDF defined in initialization above + int32_t elem_idx = this->sample_element_index(seed); + return {elem_idx, mesh()->sample_element(elem_idx, seed)}; +} + +std::pair MeshAngular::sample(uint64_t* seed) const +{ + auto [elem_idx, u] = this->sample_mesh(seed); + double wgt = weight_.empty() ? 1.0 : weight_[elem_idx]; + return {u, wgt}; +} + } // namespace openmc diff --git a/src/mesh.cpp b/src/mesh.cpp index b9d0d76d8d2..5b8a21197e5 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2430,7 +2430,7 @@ double SphericalMesh::volume(const MeshIndex& ijk) const } //============================================================================== -// Angular mesh implementations +// Unit sphere pointset mesh implementation //============================================================================== const std::string UnitSpherePointset::mesh_type = "angular_pointset"; @@ -2502,6 +2502,203 @@ int UnitSpherePointset::get_bin(Direction u) const return best; } +//============================================================================== +// Unit sphere triangular mesh implementation +//============================================================================== + +const std::string UnitSphereTriangularMesh::mesh_type = + "triangular_unit_sphere"; + +UnitSphereTriangularMesh::UnitSphereTriangularMesh(vector vertices) + : vertices_(std::move(vertices)) +{ + if (flat.size() % 9 != 0) { + fatal_error(fmt::format("Vertex array for triangular unit sphere mesh {} " + "does not describe a whole number of triangles.", + id_)); + } + + // Calculate spherical triangle areas if provided only vertices + int n = this->n_bins(); + areas_.resize(n); + + for (int i = 0; i < n; ++i) { + int offset = 9 * i; + + Direction a { + vertices_[offset], vertices_[offset + 1], vertices_[offset + 2]}; + + Direction b { + vertices_[offset + 3], vertices_[offset + 4], vertices_[offset + 5]}; + + Direction c { + vertices_[offset + 6], vertices_[offset + 7], vertices_[offset + 8]}; + + double num = a.dot(b.cross(c)); + double denom = 1.0 + a.dot(b) + b.dot(c) + c.dot(a); + double area = 2.0 * std::atan2(num, denom); + + if (area <= 0.0) { + fatal_error(fmt::format( + "Triangle {} in UnitSphereTriangularMesh has non-positive area.", i)); + } + + areas_[i] = area; + } +} + +UnitSphereTriangularMesh::UnitSphereTriangularMesh(pugi::xml_node node) + : AngularMesh(node) +{ + if (check_for_node(node, "type")) { + auto temp = get_node_value(node, "type", true, true); + if (temp != mesh_type) + fatal_error(fmt::format("Invalid mesh type: {}", temp)); + } + + vertices_ = get_node_array(node, "vertices"); + if (vertices_.size() % 9 != 0) { + fatal_error(fmt::format("Vertex array for triangular unit sphere mesh {} " + "does not describe a whole number of triangles.", + id_)); + } + + areas_ = get_node_array(node, "areas"); + if (areas_.size() != vertices_.size() % 9) { + fatal_error(fmt::format("Area array for triangular unit sphere mesh {} " + "contains the wrong number of elements.", + id_)); + } + + for (int i = 0; i < this->n_bins(); ++i) { + if (areas_[i] <= 0.0) { + fatal_error(fmt::format( + "Triangle {} in UnitSphereTriangularMesh has non-positive area.", i)); + } + } +} + +UnitSphereTriangularMesh::UnitSphereTriangularMesh(hid_t group) + : AngularMesh(group) +{ + // Check mesh type + if (object_exists(group, "type")) { + std::string temp; + read_dataset(group, "type", temp); + + if (temp != mesh_type) { + fatal_error(fmt::format("Invalid mesh type: {}", temp)); + } + } + + read_dataset(group, "vertices", vertices_); + + if (vertices_.size() % 9 != 0) { + fatal_error(fmt::format( + "Vertex dataset for UnitSphereTriangularMesh {} does not contain " + "a whole number of triangles.", + id_)); + } + + read_dataset(group, "areas", areas_); + + if (areas_.size() != static_cast(this->n_bins())) { + fatal_error( + fmt::format("Number of triangle areas ({}) does not match number of " + "triangles ({}) for UnitSphereTriangularMesh {}.", + areas_.size(), this->n_bins(), id_)); + } + + for (int i = 0; i < this->n_bins(); ++i) { + if (areas_[i] <= 0.0) { + fatal_error(fmt::format("Triangle {} in UnitSphereTriangularMesh {} has " + "non-positive area.", + i, id_)); + } + } +} + +double volume(int bin) const +{ + return areas_[bin]; +} + +void UnitSphereTriangularMesh::to_hdf5_inner(hid_t mesh_group) const +{ + write_dataset(mesh_group, "vertices", vertices_); + write_dataset(mesh_group, "areas", areas_); +} + +Direction UnitSphereTriangularMesh::sample_element( + const MeshIndex& ijk, uint64_t* seed) const +{ + int offset = 9 * bin; + + Direction a {vertices_[offset], vertices_[offset + 1], vertices_[offset + 2]}; + + Direction b { + vertices_[offset + 3], vertices_[offset + 4], vertices_[offset + 5]}; + + Direction c { + vertices_[offset + 6], vertices_[offset + 7], vertices_[offset + 8]}; + + // Step 0: deterministic quantities + double cos_c_arc = a.dot(b); + + // Component of c orthogonal to a + Direction c_orth_a = c - a.dot(c) * a; + + c_orth_a /= c_orth_a.norm(); + + Direction n_BA = b.cross(a); + n_BA /= n_BA.norm(); + + Direction n_AC = a.cross(c); + n_AC /= n_AC.norm(); + + double cos_a = n_BA.dot(n_AC); + cos_a = std::clamp(cos_a, -1.0, 1.0); + + double alpha = std::acos(cos_a); + double sin_a = std::sin(alpha); + + // Find area of subtriangle + double sub_area = prn(seed) * areas_[bin]; + + double s = std::sin(sub_area - alpha); + double t = std::cos(sub_area - alpha); + + double u = t - cos_a; + double v = s + sin_a * cos_c_arc; + + // Let q be the cosine of the new edge length b-hat + double numer = (v * t - u * s) * cos_a - v; + double denom = (v * s + u * t) * sin_a; + double q = numer / denom; + q = std::clamp(q, -1.0, 1.0); + + // Compute the third vertex of the subtriangle + double sin_b_hat = std::sqrt(std::max(0.0, 1.0 - q * q)); + + Direction c_hat = q * a + sin_b_hat * c_orth_a; + + // Use the other random variable to select cos(theta) + double z = 1.0 - prn(seed) * (1 - c_hat.dot(b)); + z = std::clamp(z, -1.0, 1.0); + + // Construct corresponding point on the sphere + Direction c_hat_orth_b = c_hat - c_hat.dot(b) * b; + c_hat_orth_b /= c_hat_orth_b.norm(); + + double sqrt_term = std::sqrt(std::max(0.0, 1.0 - z * z)); + + Direction P = z * b + sqrt_term * c_hat_orth_b; + + // error-check: make sure P is a unit vector + P /= P.norm(); + + return P; +} //============================================================================== // Helper functions for the C API From c4ab204518b595aefaaf376453876ae466876542 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Wed, 26 Aug 2026 17:38:23 -0400 Subject: [PATCH 09/37] mesh triangularizer function --- openmc/mesh.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/openmc/mesh.py b/openmc/mesh.py index 570af4e16f0..583cd880dee 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3834,8 +3834,62 @@ def from_xml_element(cls, elem: ET.Element): return cls(triangles, mesh_id=mesh_id) -def triangularize_unit_sphere_mesh(mesh : UnitSpherePointset, data = None): - pass +def triangularize_unit_sphere_mesh(mesh, data = None): + """ + Parameters + ---------- + mesh : UnitSpherePointset + Pointset mesh on which data is represented + data : ndarray + + Returns + ------- + faces : list[SphericalTriangle] + List of M triangular mesh cells with geometric info + new_data : (M,) ndarray + New list of data points associated with each triangle + in the subdivided mesh + """ + sv = SphericalVoronoi(mesh.points) + sv.sort_vertices_of_regions() + + faces = [] + new_data = [] + + for pole_index, region in enumerate(sv.regions): + + pole = points[pole_index] + verts = sv.vertices[region] + + n = len(verts) + areas = np.empty(n) + + # Compute area of each spherical triangle + for i in range(n): + v1 = verts[i] + v2 = verts[(i + 1) % n] + + num = np.dot(pole, np.cross(v1, v2)) + denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) + areas[i] = 2 * np.arctan2(num, denom) + + total_area = areas.sum() + + for i in range(n): + v1 = verts[i] + v2 = verts[(i + 1) % n] + + triangle = np.stack((pole, v1, v2)) + + faces.append( + SphericalTriangle( + vertices=triangle, + area=areas[i] + ) + ) + new_data.append(scores[pole_index] * areas[i] / total_area) + + return faces, np.asarray(new_data) def _read_meshes(elem): From 4728328d430a67155018600c30fa8f22a7a1712d Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 27 Aug 2026 10:22:18 -0400 Subject: [PATCH 10/37] MeshAngularFilter in lib, updating angular flux accumulation flag --- include/openmc/capi.h | 2 ++ openmc/filter.py | 22 +++++++++++++--- openmc/lib/filter.py | 49 +++++++++++++++++++++++++++++++++++ openmc/mesh.py | 29 ++++++++++++++++++++- src/random_ray/random_ray.cpp | 36 ++++++------------------- 5 files changed, 106 insertions(+), 32 deletions(-) diff --git a/include/openmc/capi.h b/include/openmc/capi.h index 9f6987d74ed..85df39c3772 100644 --- a/include/openmc/capi.h +++ b/include/openmc/capi.h @@ -144,6 +144,8 @@ int openmc_mesh_get_n_elements(int32_t index, size_t* n); int openmc_mesh_get_volumes(int32_t index, double* volumes); int openmc_mesh_material_volumes(int32_t index, int nx, int ny, int nz, int max_mats, int32_t* materials, double* volumes, double* bboxes); +int openmc_meshangular_filter_get_mesh(int32_t index, int32_t* index_mesh); +int openmc_meshangular_filter_set_mesh(int32_t index, int32_t index_mesh); int openmc_meshsurface_filter_get_mesh(int32_t index, int32_t* index_mesh); int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh); int openmc_new_filter(const char* type, int32_t* index); diff --git a/openmc/filter.py b/openmc/filter.py index 607d387a698..5f990862c72 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1364,9 +1364,25 @@ class MeshAngularFilter(MeshFilter): ---------- mesh : openmc.MeshBase The mesh object that events will be tallied onto - translation : Iterable of float - This array specifies a vector that is used to translate (shift) - the mesh for this filter + rotation : Iterable of float + This array specifies the angles in degrees about the x, y, and z axes + that the mesh should be rotated. The rotation applied is an intrinsic + rotation with specified Tait-Bryan angles. That is to say, if the angles + are :math:`(\phi, \theta, \psi)`, then the rotation matrix applied is + :math:`R_z(\psi) R_y(\theta) R_x(\phi)` or + + .. math:: + + \left [ \begin{array}{ccc} \cos\theta \cos\psi & -\cos\phi \sin\psi + + \sin\phi \sin\theta \cos\psi & \sin\phi \sin\psi + \cos\phi + \sin\theta \cos\psi \\ \cos\theta \sin\psi & \cos\phi \cos\psi + + \sin\phi \sin\theta \sin\psi & -\sin\phi \cos\psi + \cos\phi + \sin\theta \sin\psi \\ -\sin\theta & \sin\phi \cos\theta & \cos\phi + \cos\theta \end{array} \right ] + + A rotation matrix can also be specified directly by setting this + attribute to a nested list (or 2D numpy array) that specifies each + element of the matrix. id : int Unique identifier for the filter bins : list of tuple diff --git a/openmc/lib/filter.py b/openmc/lib/filter.py index edda4ed77c6..a6ddd970272 100644 --- a/openmc/lib/filter.py +++ b/openmc/lib/filter.py @@ -475,6 +475,49 @@ def rotation(self, rotation_data): class MeshAngularFilter(MeshFilter): """Angular mesh filter stored internally. + + This class exposes a MeshSurface filter that is stored internally in the + OpenMC library. To obtain a view of a MeshSurface filter with a given ID, + use the :data:`openmc.lib.filters` mapping. + + Parameters + ---------- + mesh : openmc.MeshBase + The mesh object that events will be tallied onto + filter_id : int + Unique identifier for the filter + + Attributes + ---------- + mesh : openmc.MeshBase + The mesh object that events will be tallied onto + rotation : Iterable of float + This array specifies the angles in degrees about the x, y, and z axes + that the mesh should be rotated. The rotation applied is an intrinsic + rotation with specified Tait-Bryan angles. That is to say, if the angles + are :math:`(\phi, \theta, \psi)`, then the rotation matrix applied is + :math:`R_z(\psi) R_y(\theta) R_x(\phi)` or + + .. math:: + + \left [ \begin{array}{ccc} \cos\theta \cos\psi & -\cos\phi \sin\psi + + \sin\phi \sin\theta \cos\psi & \sin\phi \sin\psi + \cos\phi + \sin\theta \cos\psi \\ \cos\theta \sin\psi & \cos\phi \cos\psi + + \sin\phi \sin\theta \sin\psi & -\sin\phi \cos\psi + \cos\phi + \sin\theta \sin\psi \\ -\sin\theta & \sin\phi \cos\theta & \cos\phi + \cos\theta \end{array} \right ] + + A rotation matrix can also be specified directly by setting this + attribute to a nested list (or 2D numpy array) that specifies each + element of the matrix. + id : int + Unique identifier for the filter + bins : list of tuple + A list of mesh indices / surfaces for each filter bin, e.g. [(1, 1, + 'x-min out'), (1, 1, 'x-min in'), ...]. Surface names use the mesh's + axis labels (e.g. r/phi/z for a cylindrical mesh). + num_bins : Integral + The number of filter bins """ filter_type = 'meshangular' @@ -483,6 +526,12 @@ def __init__(self, mesh=None, uid=None, new=True, index=None): super().__init__(uid, new, index) if mesh is not None: self.mesh = mesh + + @property + def mesh(self): + index_mesh = c_int32() + _dll.openmc_meshangular_filter_get_mesh(self._index, index_mesh) + return _get_mesh(index_mesh.value) @mesh.setter def mesh(self, mesh): diff --git a/openmc/mesh.py b/openmc/mesh.py index 46b17630727..667e34f7f98 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3357,7 +3357,34 @@ def from_xml_element(cls, elem: ET.Element): return cls(filename, library, mesh_id, '', length_multiplier, options) class AngularMesh(MeshBase): - """Base class for angular meshes of the unit sphere.""" + """Base class for angular meshes of the unit sphere. + + Parameters + ---------- + mesh_id : int + Unique identifier for the mesh + name : str + Name of the mesh + + Attributes + ---------- + id : int + Unique identifier for the mesh + name : str + Name of the mesh + lower_left : Iterable of float + The lower-left coordinates ([-1.0, -1.0, -1.0] for the unit sphere) + upper_right : Iterable of float + The upper-right coordinates ([1.0, 1.0, 1.0] for the unit sphere) + bounding_box : openmc.BoundingBox + Axis-aligned bounding box of the mesh as defined by the upper-right and + lower-left coordinates. + indices : Iterable of tuple + An iterable of mesh indices for each mesh element, e.g. [(1, 1, 1), (2, 1, 1), ...] + n_elements : int + Number of elements in the mesh + + """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) diff --git a/src/random_ray/random_ray.cpp b/src/random_ray/random_ray.cpp index a6f8592daab..de56c39a51c 100644 --- a/src/random_ray/random_ray.cpp +++ b/src/random_ray/random_ray.cpp @@ -457,13 +457,8 @@ void RandomRay::attenuate_flux_flat_source( if (is_active) { // Accumulate delta psi into new estimate of source region flux for // this iteration - if (srh.external_source_present()) { - // Accumulate angular flux data in regions with external source - // for later source biasing. - // - // TODO: replace the above condition with a different - // SourceRegionHandle flag to enable angular flux tallying more - // generally. + if (srh.needs_angular_flux()) { + // Accumulate angular flux data in regions where it is tallied int a = angular_bin(); for (int g = 0; g < negroups_; g++) { srh.scalar_flux_new(g) += delta_psi_[g]; @@ -512,13 +507,8 @@ void RandomRay::attenuate_flux_flat_source_void( // Accumulate delta psi into new estimate of source region flux for // this iteration - if (srh.external_source_present()) { - // Accumulate angular flux data in regions with external source - // for later source biasing. - // - // TODO: replace the above condition with a different - // SourceRegionHandle flag to enable angular flux tallying more - // generally. + if (srh.needs_angular_flux()) { + // Accumulate angular flux data in regions where it is tallied int a = angular_bin(); for (int g = 0; g < negroups_; g++) { srh.scalar_flux_new(g) += angular_flux_[g] * distance; @@ -656,13 +646,8 @@ void RandomRay::attenuate_flux_linear_source( if (is_active) { // Accumulate deltas into the new estimate of source region flux for this // iteration - if (srh.external_source_present()) { - // Accumulate angular flux data in regions with external source - // for later source biasing. - // - // TODO: replace the above condition with a different - // SourceRegionHandle flag to enable angular flux tallying more - // generally. + if (srh.needs_angular_flux()) { + // Accumulate angular flux data in regions where it is tallied int a = angular_bin(); for (int g = 0; g < negroups_; g++) { srh.scalar_flux_new(g) += delta_psi_[g]; @@ -775,13 +760,8 @@ void RandomRay::attenuate_flux_linear_source_void( // Accumulate delta psi into new estimate of source region flux for // this iteration, and update flux momements - if (srh.external_source_present()) { - // Accumulate angular flux data in regions with external source - // for later source biasing. - // - // TODO: replace the above condition with a different - // SourceRegionHandle flag to enable angular flux tallying more - // generally. + if (srh.needs_angular_flux()) { + // Accumulate angular flux data in regions where it is tallied int a = angular_bin(); for (int g = 0; g < negroups_; g++) { srh.scalar_flux_new(g) += angular_flux_[g] * distance; From e1c866f63ab67a1db5aeefbef0841cec981ae4d8 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 27 Aug 2026 12:30:21 -0400 Subject: [PATCH 11/37] fix cpp syntax --- CMakeLists.txt | 1 + include/openmc/mesh.h | 22 ++++++++++------ .../openmc/random_ray/flat_source_domain.h | 2 +- include/openmc/tallies/filter_meshangular.h | 10 ++++---- openmc/filter.py | 25 ++++++------------- src/random_ray/flat_source_domain.cpp | 4 +-- src/tallies/filter_meshangular.cpp | 4 +-- 7 files changed, 33 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c3e6a947d2..75ca6a35e4d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -461,6 +461,7 @@ list(APPEND libopenmc_SOURCES src/tallies/filter_material.cpp src/tallies/filter_materialfrom.cpp src/tallies/filter_mesh.cpp + src/tallies/filter_meshangular.cpp src/tallies/filter_meshborn.cpp src/tallies/filter_meshmaterial.cpp src/tallies/filter_meshsurface.cpp diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 3a4a0cd8ac2..8b5fa08810d 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -262,7 +262,7 @@ class Mesh { //! element //! \param[inout] materials Array storing material indices //! \param[inout] volumes Array storing volumes - void material_volumes(int nx, int ny, int nz, int max_materials, + virtual void material_volumes(int nx, int ny, int nz, int max_materials, int32_t* materials, double* volumes) const; //! Determine volume and bounding boxes of materials within each mesh element @@ -275,7 +275,7 @@ class Mesh { //! \param[inout] materials Array storing material indices //! \param[inout] volumes Array storing volumes //! \param[inout] bboxes Array storing bounding boxes (n_elems, table_size, 6) - void material_volumes(int nx, int ny, int nz, int max_materials, + virtual void material_volumes(int nx, int ny, int nz, int max_materials, int32_t* materials, double* volumes, double* bboxes) const; //! Determine bounding box of mesh @@ -856,6 +856,18 @@ class AngularMesh : public Mesh { return {{}, {}}; } + void material_volumes(int nx, int ny, int nz, int max_materials, + int32_t* materials, double* volumes) const override + { + fatal_error("material_volumes() is not supported for angular meshes"); + } + + void material_volumes(int nx, int ny, int nz, int max_materials, + int32_t* materials, double* volumes, double* bboxes) const override + { + fatal_error("material_volumes() is not supported for angular meshes"); + } + std::string bin_label(int bin) const override { return fmt::format("Element Index ({})", bin); @@ -888,12 +900,6 @@ class UnitSpherePointset : public AngularMesh { fatal_error("Volume calculation over UnitSpherePointset is not supported"); } - void material_volumes(int nx, int ny, int nz, int max_materials, - int32_t* materials, double* volumes, double* bboxes) const override - { - fatal_error("material_volumes() is not supported for UnitSpherePointset"); - } - std::string get_mesh_type() const override { return mesh_type; } static const std::string mesh_type; diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index b3b0ab6277c..14de817dd46 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -74,7 +74,7 @@ class FlatSourceDomain { SourceRegionKey lookup_source_region_key(const GeometryState& p) const; int64_t lookup_mesh_bin(int64_t sr, Position r) const; int lookup_mesh_idx(int64_t sr) const; - int get_angular_bin(Direction u) const; + int lookup_angular_bin(Direction u) const; Direction angular_quadrature_direction(int a) const; bool tally_angular_flux_applies( int cell_idx, int material, int mesh_idx) const; diff --git a/include/openmc/tallies/filter_meshangular.h b/include/openmc/tallies/filter_meshangular.h index 066619485fe..668b74f77f4 100644 --- a/include/openmc/tallies/filter_meshangular.h +++ b/include/openmc/tallies/filter_meshangular.h @@ -1,5 +1,5 @@ -#ifndef OPENMC_TALLIES_FILTER_MESHSURFACE_H -#define OPENMC_TALLIES_FILTER_MESHSURFACE_H +#ifndef OPENMC_TALLIES_FILTER_MESHANGULAR_H +#define OPENMC_TALLIES_FILTER_MESHANGULAR_H #include "openmc/tallies/filter_mesh.h" @@ -25,16 +25,16 @@ class MeshAngularFilter : public MeshFilter { //---------------------------------------------------------------------------- // Accessors - void set_translation(const Position& translation) const override + void set_translation(const Position& translation) override { fatal_error("Angular mesh filters do not permit translation."); } - void set_translation(const double translation[3]) const override + void set_translation(const double translation[3]) override { fatal_error("Angular mesh filters do not permit translation."); } }; } // namespace openmc -#endif // OPENMC_TALLIES_FILTER_MESHSURFACE_H +#endif // OPENMC_TALLIES_FILTER_MESHANGULAR_H diff --git a/openmc/filter.py b/openmc/filter.py index 5f990862c72..96aaadfcbe3 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1366,23 +1366,10 @@ class MeshAngularFilter(MeshFilter): The mesh object that events will be tallied onto rotation : Iterable of float This array specifies the angles in degrees about the x, y, and z axes - that the mesh should be rotated. The rotation applied is an intrinsic - rotation with specified Tait-Bryan angles. That is to say, if the angles - are :math:`(\phi, \theta, \psi)`, then the rotation matrix applied is - :math:`R_z(\psi) R_y(\theta) R_x(\phi)` or - - .. math:: - - \left [ \begin{array}{ccc} \cos\theta \cos\psi & -\cos\phi \sin\psi - + \sin\phi \sin\theta \cos\psi & \sin\phi \sin\psi + \cos\phi - \sin\theta \cos\psi \\ \cos\theta \sin\psi & \cos\phi \cos\psi + - \sin\phi \sin\theta \sin\psi & -\sin\phi \cos\psi + \cos\phi - \sin\theta \sin\psi \\ -\sin\theta & \sin\phi \cos\theta & \cos\phi - \cos\theta \end{array} \right ] - - A rotation matrix can also be specified directly by setting this - attribute to a nested list (or 2D numpy array) that specifies each - element of the matrix. + that the mesh should be rotated. A rotation matrix can also be + specified directly by setting this attribute to a nested list + (or 2D numpy array) that specifies each element of the matrix. See + also: MeshFilter.rotation. id : int Unique identifier for the filter bins : list of tuple @@ -1404,6 +1391,10 @@ def __repr__(self): string += '{: <16}=\t{}\n'.format('\tID', self.id) string += '{: <16}=\t{}\n'.format('\tRotation', self.rotation) return string + + @property + def mesh(self): + return self._mesh @mesh.setter def mesh(self, mesh): diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 237dadad9ba..cd4e71b0a40 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -16,7 +16,7 @@ #include "openmc/tallies/filter_cell.h" #include "openmc/tallies/filter_material.h" #include "openmc/tallies/filter_mesh.h" -#include "openmc/tallies/filter_mesh_angular.h" +#include "openmc/tallies/filter_meshangular.h" #include "openmc/tallies/tally.h" #include "openmc/tallies/tally_scoring.h" #include "openmc/timer.h" @@ -2039,7 +2039,7 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const // bin the current ray contributes to. Rays are assigned to bins based on the // unit-sphere Voronoi diagram generated from the "quadrature" angle set, // stored in the referenced angular mesh. -int FlatSourceDomain::get_angular_bin(Direction u) const +int FlatSourceDomain::lookup_angular_bin(Direction u) const { return angular_mesh_->get_bin(u); } diff --git a/src/tallies/filter_meshangular.cpp b/src/tallies/filter_meshangular.cpp index c0409a9eaf6..619020861b6 100644 --- a/src/tallies/filter_meshangular.cpp +++ b/src/tallies/filter_meshangular.cpp @@ -1,4 +1,4 @@ -#include "openmc/tallies/filter_meshsurface.h" +#include "openmc/tallies/filter_meshangular.h" #include "openmc/capi.h" #include "openmc/constants.h" @@ -14,7 +14,7 @@ void MeshAngularFilter::get_all_bins( if (!rotation_.empty()) { u = u.rotate(rotation_); } - auto bin = model::meshes[mesh_]->get_bin(r); + auto bin = model::meshes[mesh_]->get_bin(u); if (bin >= 0) { match.bins_.push_back(bin); match.weights_.push_back(1.0); From 3f8ca2bf6ebc37d460e4052e61ebd132a8aec8c0 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 27 Aug 2026 16:43:01 -0400 Subject: [PATCH 12/37] MeshAngularFilter bugfixes --- openmc/filter.py | 15 ++++++++++++++- openmc/model/funcs.py | 8 ++++---- src/mesh.cpp | 3 ++- src/random_ray/random_ray_simulation.cpp | 5 +++-- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index 96aaadfcbe3..a550d1b9447 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -912,6 +912,11 @@ def mesh(self): @mesh.setter def mesh(self, mesh): cv.check_type('filter mesh', mesh, openmc.MeshBase) + if isinstance(mesh, openmc.AngularMesh): + raise TypeError( + "Angular mesh classes cannot be used with spatial MeshFilter classes." + ) + self._mesh = mesh if isinstance(mesh, openmc.UnstructuredMesh): if mesh.has_statepoint_data: @@ -1137,6 +1142,10 @@ def mesh(self): @mesh.setter def mesh(self, mesh): cv.check_type('filter mesh', mesh, openmc.MeshBase) + if isinstance(mesh, openmc.AngularMesh): + raise TypeError( + "Angular mesh classes cannot be used with spatial MeshFilter classes." + ) self._mesh = mesh @Filter.bins.setter @@ -1279,6 +1288,10 @@ def shape(self): @MeshFilter.mesh.setter def mesh(self, mesh): cv.check_type('filter mesh', mesh, openmc.MeshBase) + if isinstance(mesh, openmc.AngularMesh): + raise TypeError( + "Angular mesh classes cannot be used with spatial MeshFilter classes." + ) self._mesh = mesh # Take the product of mesh indices and surface-crossing names, using @@ -1380,7 +1393,7 @@ class MeshAngularFilter(MeshFilter): The number of filter bins """ - def __init__(self, mesh, filter_id=None): + def __init__(self, mesh, filter_id=None): self.mesh = mesh self.id = filter_id self._rotation = None diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index 784ce5e4f77..45c11ebfe3b 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -573,8 +573,8 @@ def icosphere_sn(nu: int = 1, point_type: str = "centroids"): Subdivision frequency point_type: str Keyword specifying whether to return the vertices ("vertices", - "vertex", or "vert") or centroids ("centroids", "centroid", or - "cent") of the subtriangles on the icosphere + "vertex", "vert" or "verts") or centroids ("centroids", "centroid", + "cent" or "cents") of the subtriangles on the icosphere Returns ------- @@ -585,9 +585,9 @@ def icosphere_sn(nu: int = 1, point_type: str = "centroids"): """ # check pointset type match point_type: - case "vertices" | "vertex" | "vert" : + case "vertices" | "vertex" | "vert" | "verts": return_type = "vert" - case "centroids" | "centroid" | "cent": + case "centroids" | "centroid" | "cent" | "cents": return_type = "cent" case _: return ValueError(f"Unknown pointset type specified (got {point_type})") diff --git a/src/mesh.cpp b/src/mesh.cpp index b9d0d76d8d2..9e687a98b12 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -342,6 +342,8 @@ const std::unique_ptr& Mesh::create( model::meshes.push_back(make_unique(dataset)); } else if (mesh_type == SphericalMesh::mesh_type) { model::meshes.push_back(make_unique(dataset)); + } else if (mesh_type == UnitSpherePointset::mesh_type) { + model::meshes.push_back(make_unique(dataset)); #ifdef OPENMC_DAGMC_ENABLED } else if (mesh_type == UnstructuredMesh::mesh_type && mesh_library == MOABMesh::mesh_lib_type) { @@ -2502,7 +2504,6 @@ int UnitSpherePointset::get_bin(Direction u) const return best; } - //============================================================================== // Helper functions for the C API //============================================================================== diff --git a/src/random_ray/random_ray_simulation.cpp b/src/random_ray/random_ray_simulation.cpp index 11bd8eec8c0..a98849d1690 100644 --- a/src/random_ray/random_ray_simulation.cpp +++ b/src/random_ray/random_ray_simulation.cpp @@ -61,13 +61,14 @@ void validate_random_ray_inputs() case FilterType::ENERGY: case FilterType::MATERIAL: case FilterType::MESH: + case FilterType::MESH_ANGULAR: case FilterType::UNIVERSE: case FilterType::PARTICLE: break; default: fatal_error("Invalid filter specified. Only cell, cell_instance, " - "distribcell, energy, material, mesh, and universe filters " - "are supported in random ray mode."); + "distribcell, energy, material, mesh, mesh_angular, and " + "universe filters are supported in random ray mode."); } } } From bd202c91579cc8599dd310567b23a6da6df1e604 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 28 Aug 2026 15:09:54 -0400 Subject: [PATCH 13/37] typename consistency and triangularization function polish --- include/openmc/distribution_multi.h | 1 + include/openmc/mesh.h | 9 +--- openmc/lib/mesh.py | 6 ++- openmc/mesh.py | 81 ++++++++++++++++++++--------- openmc/stats/multivariate.py | 4 +- src/distribution_multi.cpp | 3 ++ src/mesh.cpp | 15 ++---- 7 files changed, 74 insertions(+), 45 deletions(-) diff --git a/include/openmc/distribution_multi.h b/include/openmc/distribution_multi.h index 0737a98f65d..dbf3e4aacc6 100644 --- a/include/openmc/distribution_multi.h +++ b/include/openmc/distribution_multi.h @@ -8,6 +8,7 @@ #include "openmc/distribution.h" #include "openmc/error.h" #include "openmc/position.h" +#include "openmc/mesh.h" namespace openmc { diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index e6787dcc583..81a008187cc 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -931,14 +931,7 @@ class UnitSphereTriangularMesh : public AngularMesh { int n_bins() const override { return static_cast(vertices_.size() / 9); } //! Return surface area of a specific triangle - double volume(int bin) const override; - - void material_volumes(int nx, int ny, int nz, int max_materials, - int32_t* materials, double* volumes, double* bboxes) const override - { - fatal_error( - "material_volumes() is not supported for UnitSphereTriangularMesh"); - } + double volume(int bin) const override { return areas_[bin]; } std::string get_mesh_type() const override { return mesh_type; } static const std::string mesh_type; diff --git a/openmc/lib/mesh.py b/openmc/lib/mesh.py index f176422fbca..7082c19582b 100644 --- a/openmc/lib/mesh.py +++ b/openmc/lib/mesh.py @@ -733,13 +733,17 @@ class UnstructuredMesh(Mesh): class UnitSpherePointset(Mesh): pass +class UnitSphereTriangularMesh(Mesh): + pass + _MESH_TYPE_MAP = { 'regular': RegularMesh, 'rectilinear': RectilinearMesh, 'cylindrical': CylindricalMesh, 'spherical': SphericalMesh, 'unstructured': UnstructuredMesh, - 'unitsphere_pointset': UnitSpherePointset + 'angular_pointset': UnitSpherePointset, + 'angular_triangular': UnitSphereTriangularMesh } diff --git a/openmc/mesh.py b/openmc/mesh.py index 8bf62d751ea..d45d95626c3 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -11,6 +11,7 @@ import h5py import lxml.etree as ET import numpy as np +from scipy.spatial import SphericalVoronoi import openmc import openmc.checkvalue as cv @@ -309,6 +310,8 @@ def from_hdf5(cls, group: h5py.Group): return UnstructuredMesh.from_hdf5(group, mesh_id, mesh_name) elif mesh_type == 'angular_pointset': return UnitSpherePointset.from_hdf5(group, mesh_id, mesh_name) + elif mesh_type == 'angular_triangular': + return UnitSphereTriangularMesh.from_hdf5(group, mesh_id, mesh_name) else: raise ValueError('Unrecognized mesh type: "' + mesh_type + '"') @@ -358,6 +361,8 @@ def from_xml_element(cls, elem: ET.Element): mesh = UnstructuredMesh.from_xml_element(elem) elif mesh_type == 'angular_pointset': mesh = UnitSpherePointset.from_xml_element(elem) + elif mesh_type == 'angular_triangular': + mesh = UnitSphereTriangularMesh.from_xml_element(elem) else: raise ValueError(f'Unrecognized mesh type "{mesh_type}" found.') @@ -3708,15 +3713,6 @@ def volumes(self): """Area of each SphericalTriangle in the mesh.""" return np.array([tri.area for tri in self.triangles]) - # override non-applicable methods of MeshBase - def get_homogenized_materials(self, *args, **kwargs): - raise NotImplementedError( - "Material attributes are not available for AngularMesh.") - - def material_volumes(self, *args, **kwargs): - raise NotImplementedError( - "Material attributes are not available for AngularMesh.") - def sample_element(self, element_idx, seed=None): """Sample a direction uniformly from within a given SphericalTriangle in the mesh. @@ -3752,8 +3748,11 @@ def sample_element(self, element_idx, seed=None): c_orth_a /= np.linalg.norm(c_orth_a) # used later n_BA = np.cross(B,A) - n_AC = np.cross(A,C) - cos_a = np.dot(n_BA, n_AC) # used later + n_BA /= np.linalg.norm(n_BA) + n_AC = np.cross(A, C) + n_AC /= np.linalg.norm(n_AC) + + cos_a = np.clip(np.dot(n_BA, n_AC), -1.0, 1.0) # used later alpha = np.acos(cos_a) # used later sin_a = np.sin(alpha) # used later @@ -3771,13 +3770,14 @@ def sample_element(self, element_idx, seed=None): # Let q be the cosine of the new edge length b-hat numer = (v*t - u*s)*cos_a - v denom = (v*s + u*t)*sin_a - q = numer/denom + q = np.clip(numer/denom, -1.0, 1.0) # Compute the third vertex of the subtriangle C_hat = q*A + np.sqrt(1 - q**2)*c_orth_a # Use the other random variable to select cos(theta) z = 1 - rng.uniform(0., 1.0, 1)*(1 - np.dot(C_hat, B)) + z = np.clip(z, -1.0, 1.0) # Construct corresponding point on the sphere c_hat_orth_b = C_hat - np.dot(C_hat, B)*B @@ -3817,7 +3817,7 @@ def to_xml_element(self): """ element = super().to_xml_element() - element.set("type", "angular") + element.set("type", "angular_triangular") # Flatten to a (3*N, 3) array all_vertices = np.concatenate( @@ -3862,30 +3862,55 @@ def from_xml_element(cls, elem: ET.Element): return cls(triangles, mesh_id=mesh_id) def triangularize_unit_sphere_mesh(mesh, data = None): - """ + """Convert a UnitSpherePointset to a UnitSphereTriangularMesh. + + This function takes a UnitSpherePointset, as well as an optional + dataset defined on said mesh, and converts it to a triangular mesh of the + unit sphere by performing a star triangularization of the Voronoi cells + generated by the UnitSpherePointset. If a dataset is provided, new data + values are computed based on each new mesh cell's area fraction of the + original Voronoi cell. Hence, the data must be provided in an array with + the same number of elements as there are points in the UnitSpherePointset, + and organized such that when the array is flattened in row-major (C-style) + order, the sequential order of the data values corresponds to their + respective points in the UnitSpherePointset. + Parameters ---------- mesh : UnitSpherePointset - Pointset mesh on which data is represented - data : ndarray + Pointset mesh of N points + data : iterable of float + Array of scalar data represented on the pointset. Must also contain N + entries. Returns ------- - faces : list[SphericalTriangle] - List of M triangular mesh cells with geometric info - new_data : (M,) ndarray - New list of data points associated with each triangle - in the subdivided mesh + new_mesh : UnitSphereTriangularMesh + Angular mesh of M SphericalTriangle cells + new_data : (M,) ndarray of float + New array of data points associated with each triangle in the + subdivided mesh """ + cv.check_type("mesh for triangularization", mesh, UnitSpherePointset) + cv.check_type("data for triangularization", data, Iterable, Real, none_ok=True) + if data is not None: + data = np.asarray(data).flatten() + if len(data) != len(mesh.points): + raise ValueError( + f"Number of entries in data array does not match number of points " + f"in UnitSpherePointset for triangularization " + f"(expected {len(mesh.points)})" + ) + new_data = [] + sv = SphericalVoronoi(mesh.points) sv.sort_vertices_of_regions() faces = [] - new_data = [] for pole_index, region in enumerate(sv.regions): - pole = points[pole_index] + pole = mesh.points[pole_index] verts = sv.vertices[region] n = len(verts) @@ -3914,9 +3939,15 @@ def triangularize_unit_sphere_mesh(mesh, data = None): area=areas[i] ) ) - new_data.append(scores[pole_index] * areas[i] / total_area) + if data is not None: + new_data.append(data[pole_index] * areas[i] / total_area) + + new_mesh = UnitSphereTriangularMesh(faces) - return faces, np.asarray(new_data) + if data is not None: + return new_mesh, np.asarray(new_data) + else: + return new_mesh def _read_meshes(elem): diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index 336d81e6e43..138dab84147 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -61,6 +61,8 @@ def from_xml_element(cls, elem): return Isotropic.from_xml_element(elem) elif distribution == 'monodirectional': return Monodirectional.from_xml_element(elem) + elif distribution == 'mesh-angular': + return MeshAngular.from_xml_element(elem) class PolarAzimuthal(UnitSphere): @@ -401,7 +403,7 @@ def to_xml_element(self): """ element = ET.Element('space') - element.set('type', 'mesh_angular') + element.set('type', 'mesh-angular') element.set("mesh_id", str(self.mesh.id)) if self.strengths is not None: diff --git a/src/distribution_multi.cpp b/src/distribution_multi.cpp index b10c3237db7..7e0b89de88e 100644 --- a/src/distribution_multi.cpp +++ b/src/distribution_multi.cpp @@ -5,6 +5,7 @@ #include "openmc/constants.h" #include "openmc/error.h" +#include "openmc/mesh.h" #include "openmc/math_functions.h" #include "openmc/random_dist.h" #include "openmc/random_lcg.h" @@ -25,6 +26,8 @@ unique_ptr UnitSphereDistribution::create( return UPtrAngle {new Monodirectional(node)}; } else if (type == "mu-phi") { return UPtrAngle {new PolarAzimuthal(node)}; + } else if (type == "mesh-angular") { + return UPtrAngle {new MeshAngular(node)}; } else { fatal_error(fmt::format( "Invalid angular distribution for external source: {}", type)); diff --git a/src/mesh.cpp b/src/mesh.cpp index 82f3f565e75..34a9d8c725e 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -344,6 +344,8 @@ const std::unique_ptr& Mesh::create( model::meshes.push_back(make_unique(dataset)); } else if (mesh_type == UnitSpherePointset::mesh_type) { model::meshes.push_back(make_unique(dataset)); + } else if (mesh_type == UnitSphereTriangularMesh::mesh_type) { + model::meshes.push_back(make_unique(dataset)); #ifdef OPENMC_DAGMC_ENABLED } else if (mesh_type == UnstructuredMesh::mesh_type && mesh_library == MOABMesh::mesh_lib_type) { @@ -2508,13 +2510,12 @@ int UnitSpherePointset::get_bin(Direction u) const // Unit sphere triangular mesh implementation //============================================================================== -const std::string UnitSphereTriangularMesh::mesh_type = - "triangular_unit_sphere"; +const std::string UnitSphereTriangularMesh::mesh_type = "angular_triangular"; UnitSphereTriangularMesh::UnitSphereTriangularMesh(vector vertices) : vertices_(std::move(vertices)) { - if (flat.size() % 9 != 0) { + if (vertices.size() % 9 != 0) { fatal_error(fmt::format("Vertex array for triangular unit sphere mesh {} " "does not describe a whole number of triangles.", id_)); @@ -2620,19 +2621,13 @@ UnitSphereTriangularMesh::UnitSphereTriangularMesh(hid_t group) } } -double volume(int bin) const -{ - return areas_[bin]; -} - void UnitSphereTriangularMesh::to_hdf5_inner(hid_t mesh_group) const { write_dataset(mesh_group, "vertices", vertices_); write_dataset(mesh_group, "areas", areas_); } -Direction UnitSphereTriangularMesh::sample_element( - const MeshIndex& ijk, uint64_t* seed) const +Direction UnitSphereTriangularMesh::sample_element(int32_t bin, uint64_t* seed) const { int offset = 9 * bin; From 101fa8fc209011fd42be79f87b43a0d56f3e846c Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 28 Aug 2026 15:25:59 -0400 Subject: [PATCH 14/37] angular_pointset typename consistency --- openmc/lib/mesh.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/lib/mesh.py b/openmc/lib/mesh.py index f176422fbca..c445b3cbc17 100644 --- a/openmc/lib/mesh.py +++ b/openmc/lib/mesh.py @@ -739,7 +739,7 @@ class UnitSpherePointset(Mesh): 'cylindrical': CylindricalMesh, 'spherical': SphericalMesh, 'unstructured': UnstructuredMesh, - 'unitsphere_pointset': UnitSpherePointset + 'angular_pointset': UnitSpherePointset } From 14e92b8235653665d9f98fdf725abe75538f0b73 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 28 Aug 2026 17:12:27 -0400 Subject: [PATCH 15/37] auto source bias init --- include/openmc/weight_windows.h | 2 ++ openmc/weight_windows.py | 27 ++++++++++++++++++++++++++- src/weight_windows.cpp | 3 +++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index d0b385d169d..2d8a76f4a2a 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -230,6 +230,8 @@ class WeightWindowsGenerator { // Local FW-CADIS target tallies std::vector targets_; + // FW-CADIS source biasing + bool source_biasing_; }; //============================================================================== diff --git a/openmc/weight_windows.py b/openmc/weight_windows.py index 63af2596efc..dcb7350b9bd 100644 --- a/openmc/weight_windows.py +++ b/openmc/weight_windows.py @@ -10,7 +10,7 @@ import h5py import openmc -from openmc.mesh import MeshBase, RectilinearMesh, CylindricalMesh, SphericalMesh, UnstructuredMesh +from openmc.mesh import MeshBase, RectilinearMesh, CylindricalMesh, SphericalMesh, UnstructuredMesh, UnitSpherePointset from openmc.tallies import Tallies import openmc.checkvalue as cv from openmc.checkvalue import PathLike @@ -502,6 +502,8 @@ class WeightWindowGenerator: The weight window generation methodology applied during an update. targets : :class:`openmc.Tallies` or iterable of int Target tallies for local variance reduction via FW-CADIS. + source_biasing : bool + Whether to perform automated biasing of fixed sources via FW-CADIS. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -523,6 +525,8 @@ class WeightWindowGenerator: The weight window generation methodology applied during an update. targets : :class:`openmc.Tallies` or numpy.ndarray Target tallies for local variance reduction via FW-CADIS. + source_biasing : bool + Whether to perform automated biasing of fixed sources via FW-CADIS. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -543,6 +547,7 @@ def __init__( particle_type: str | int | openmc.ParticleType = 'neutron', method: str = 'magic', targets: openmc.Tallies | Iterable[int] | None = None, + source_biasing: bool = False, max_realizations: int = 1, update_interval: int = 1, on_the_fly: bool = True @@ -556,6 +561,7 @@ def __init__( self.particle_type = particle_type self.method = method self.targets = targets + self.source_biasing = source_biasing self.max_realizations = max_realizations self.update_interval = update_interval self.on_the_fly = on_the_fly @@ -566,6 +572,7 @@ def __repr__(self): string += f'\t{"Particle:":<20}=\t{str(self.particle_type)}\n' string += f'\t{"Energy Bounds:":<20}=\t{self.energy_bounds}\n' string += f'\t{"Method":<20}=\t{self.method}\n' + string += f'\t{"Source Biasing":<20}=\t{self.source_biasing}\n' string += f'\t{"Max Realizations:":<20}=\t{self.max_realizations}\n' string += f'\t{"Update Interval:":<20}=\t{self.update_interval}\n' string += f'\t{"On The Fly:":<20}=\t{self.on_the_fly}\n' @@ -635,6 +642,19 @@ def targets(self, t): t = np.asarray(list(t), dtype=int) self._targets = t + @property + def source_biasing(self) -> bool: + return self._source_biasing + + @source_biasing.setter + def source_biasing(self, sb: bool): + cv.check_type('automated source biasing', sb, bool) + if sb == True and self.method != 'fw_cadis': + raise ValueError( + "Automated source biasing is only enabled via the " \ + "fw_cadis update method.") + self._source_biasing = sb + @property def max_realizations(self) -> int: return self._max_realizations @@ -744,6 +764,9 @@ def to_xml_element(self): targets_elem = ET.SubElement(element, 'targets') targets_elem.text = ' '.join(str(tally_id) for tally_id in self.targets) + if self.source_biasing: + sb_elem = ET.SubElement(element, 'source_biasing') + sb_elem.text = str(self.source_biasing).lower() if self.update_parameters is not None: self._update_parameters_subelement(element) @@ -789,6 +812,8 @@ def from_xml_element(cls, elem: ET.Element, meshes: dict) -> Self: else: wwg.targets = get_elem_list(elem, "targets") + if elem.find('source_biasing') is not None: + wwg.source_biasing = bool(get_text(elem, 'source_biasing')) if elem.find('update_parameters') is not None: update_parameters = {} params_elem = elem.find('update_parameters') diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index d3565eaaf63..b7073637caa 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -808,6 +808,9 @@ WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node) std::end(FlatSourceDomain::fw_cadis_local_targets_), std::begin(targets_), std::end(targets_)); } + if (check_for_node(node, "source_biasing")) { + source_biasing_ = get_node_value_bool(node, "source_biasing"); + } } else { fatal_error(fmt::format( "Unknown weight window update method '{}' specified", method_string)); From 925741dcceaad339ac6e14e5946aff77c2929290 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 10 Sep 2026 12:31:59 -0400 Subject: [PATCH 16/37] source bias tallies and creating biased sources --- include/openmc/capi.h | 1 + include/openmc/constants.h | 1 + include/openmc/settings.h | 2 + include/openmc/source.h | 52 ++++ include/openmc/tallies/filter.h | 1 + include/openmc/weight_windows.h | 90 ++++++- openmc/lib/mesh.py | 26 ++ openmc/mesh.py | 82 ++++-- openmc/settings.py | 51 +++- openmc/source.py | 457 +++++++++++++++++++++++++++++++- openmc/weight_windows.py | 62 +++++ src/mesh.cpp | 15 +- src/settings.cpp | 6 + src/source.cpp | 121 +++++++++ src/tallies/filter.cpp | 2 + src/weight_windows.cpp | 396 +++++++++++++++++++++++++++ 16 files changed, 1326 insertions(+), 39 deletions(-) diff --git a/include/openmc/capi.h b/include/openmc/capi.h index 85df39c3772..5019b453fbd 100644 --- a/include/openmc/capi.h +++ b/include/openmc/capi.h @@ -138,6 +138,7 @@ int openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh); int openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh); int openmc_mesh_filter_get_translation(int32_t index, double translation[3]); int openmc_mesh_filter_set_translation(int32_t index, double translation[3]); +int openmc_mesh_get_bin(int32_t index, const double xyz[3], int32_t* bin); int openmc_mesh_get_id(int32_t index, int32_t* id); int openmc_mesh_set_id(int32_t index, int32_t id); int openmc_mesh_get_n_elements(int32_t index, size_t* n); diff --git a/include/openmc/constants.h b/include/openmc/constants.h index a1d94e5819e..fd4051262ac 100644 --- a/include/openmc/constants.h +++ b/include/openmc/constants.h @@ -35,6 +35,7 @@ constexpr array VERSION_VOXEL {2, 0}; constexpr array VERSION_MGXS_LIBRARY {1, 0}; constexpr array VERSION_PROPERTIES {1, 1}; constexpr array VERSION_WEIGHT_WINDOWS {1, 0}; +constexpr array VERSION_SOURCE_BIAS {1, 0}; constexpr array VERSION_COLLISION_TRACK {1, 2}; // ============================================================================ diff --git a/include/openmc/settings.h b/include/openmc/settings.h index 3ad5f502c95..dd416577384 100644 --- a/include/openmc/settings.h +++ b/include/openmc/settings.h @@ -116,6 +116,8 @@ extern std::string path_sourcepoint; //!< path to a source file extern std::string path_statepoint; //!< path to a statepoint file extern std::string weight_windows_file; //!< Location of weight window file to //!< load on simulation initialization +extern std::string source_bias_file; //!< Location of source bias file from + //!< FW-CADIS extern std::string properties_file; //!< Location of properties file to //!< load on simulation initialization diff --git a/include/openmc/source.h b/include/openmc/source.h index 51b54a1d106..a99b7631cf0 100644 --- a/include/openmc/source.h +++ b/include/openmc/source.h @@ -217,6 +217,58 @@ class CompiledSourceWrapper : public Source { typedef unique_ptr create_compiled_source_t(std::string parameters); +//============================================================================== +//! Source that samples a phase-space voxel (spatial mesh element, angular mesh +//! element, energy group) -- from a Discrete distribution, then draws uniform +//! samples from within each phase-space subelement. Allows spatial, angular, +//! and energy distributions to be correlated. +//! +//! Used primarily for source biasing. +//============================================================================== + +class CorrelatedSource : public Source { +public: + // Constructors + explicit CorrelatedSource(pugi::xml_node node); + + //! Sample a phase-space voxel from the biased distribution, then a + //! position within its spatial mesh element, a direction within its + //! angular mesh element (or isotropic, if this source has no angular + //! mesh), and a representative energy within its energy group + //! \param[inout] seed Pseudorandom seed pointer + //! \return Sampled site + SourceSite sample(uint64_t* seed) const override; + + double strength() const override { return voxel_dist_.integral(); } + + // Accessors + int32_t spatial_mesh_idx() const { return spatial_mesh_idx_; } + int32_t angle_mesh_idx() const { return angle_mesh_idx_; } + const vector& group_bounds() const { return group_bounds_; } + +protected: + bool constraints_applied() const override { return true; } + +private: + // Data members + int32_t spatial_mesh_idx_ {C_NONE}; //!< Index into model::meshes + int32_t angle_mesh_idx_ {C_NONE}; //!< Index into model::meshes, or C_NONE + vector group_bounds_; //!< Energy group boundaries [eV] + + int64_t spatial_bins_ {0}; + int64_t angle_bins_ {1}; + int64_t energy_bins_ {1}; + + ParticleType particle_ {ParticleType::neutron()}; //!< Particle type emitted + + //! Selects a flat index into (spatial, angle, energy) space, in row-major + //! (spatial, angle, energy) order, weighted by the "strengths" array. + DiscreteIndex voxel_dist_; + + //! Per-voxel weight (1 / flux), indexed the same way as voxel_dist_. + vector weights_; +}; + //============================================================================== //! Mesh-based source with different distributions for each element //============================================================================== diff --git a/include/openmc/tallies/filter.h b/include/openmc/tallies/filter.h index d78ddadcf72..e63003372ef 100644 --- a/include/openmc/tallies/filter.h +++ b/include/openmc/tallies/filter.h @@ -43,6 +43,7 @@ enum class FilterType { PARTICLE_PRODUCTION, POLAR, REACTION, + SOURCE_BIAS, SPHERICAL_HARMONICS, SPATIAL_LEGENDRE, SURFACE, diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index 2d8a76f4a2a..f8eb239167f 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -1,6 +1,7 @@ #ifndef OPENMC_WEIGHT_WINDOWS_H #define OPENMC_WEIGHT_WINDOWS_H +#include #include #include @@ -13,6 +14,7 @@ #include "openmc/particle_type.h" #include "openmc/span.h" #include "openmc/tallies/tally.h" +#include "openmc/tensor.h" #include "openmc/vector.h" namespace openmc { @@ -25,18 +27,22 @@ enum class WeightWindowUpdateMethod { MAGIC, FW_CADIS }; constexpr double DEFAULT_WEIGHT_CUTOFF {1.0e-38}; // default low weight cutoff +constexpr std::array VERSION_SOURCE_BIAS {1, 0}; + //============================================================================== // Global variables //============================================================================== class WeightWindows; class WeightWindowsGenerator; +class SourceBias; namespace variance_reduction { extern std::unordered_map ww_map; extern vector> weight_windows; extern vector> weight_windows_generators; +extern vector> source_biases; } // namespace variance_reduction @@ -201,6 +207,84 @@ class WeightWindows { int32_t mesh_idx_ {-1}; //!< Index in meshes vector }; +class SourceBias { +public: + //---------------------------------------------------------------------------- + // Constructors + + //! \param[in] spatial_mesh_idx Index into model::meshes for the spatial + //! mesh over which the source is biased + //! \param[in] angle_mesh_idx Index into model::meshes for the angular mesh + //! used to bias emission direction, or C_NONE for isotropic emission + //! \param[in] energy_bounds Energy group boundaries [eV] + //! \param[in] ww_id ID of the WeightWindows object this source bias is + //! generated alongside (used to name this object's HDF5 group) + SourceBias(int32_t spatial_mesh_idx, int32_t angle_mesh_idx, + vector energy_bounds, int32_t ww_id); + + //---------------------------------------------------------------------------- + // Methods + + //! \param[in] tally Tally with a "flux" score, a mesh filter matching + //! spatial_mesh_idx_, an energy filter matching energy_bounds_ (if + //! energy_bounds_ is non-empty), and a mesh-angular filter matching + //! angle_mesh_idx_ (if angle_mesh_idx_ != C_NONE) + void update(const Tally* tally); + + //! Write SourceBias data to an HDF5 group + void to_hdf5(hid_t group) const; + + //---------------------------------------------------------------------------- + // Accessors + + int32_t spatial_mesh_idx() const { return spatial_mesh_idx_; } + int32_t angle_mesh_idx() const { return angle_mesh_idx_; } + //! Estimate the unbiased external source's strength as a function of + //! spatial mesh element, angular mesh element, and energy group, assuming + //! isotropic emission when no angular mesh is present. + //! + //! If a file named "forward_source_mesh.h5" is present, it is used directly + //! in place of sampling model::external_sources. Its spatial mesh, angular + //! mesh, and energy group structure are checked against spatial_mesh_, + //! angle_mesh_, and energy_bounds_ before use. + //! + //! Otherwise, group probabilities are read exactly from each source's + //! Discrete energy spectrum, while the spatial and angular dimensions are + //! estimated by binning samples into (spatial_mesh_, angle_mesh_). + //! + //! \param[in] n_samples_per_source Number of trial (position, direction) + //! pairs to draw per external source. Unused if + //! "forward_source_mesh.h5" is present. + void compute_unbiased_strength(int64_t n_samples_per_source = 1000000); + + const tensor::Tensor& unbiased_strength() const + { + return unbiased_strength_; + } + +private: + //! Read a precomputed unbiased source strength distribution from a + //! "forward_source_mesh.h5"-format file + void load_forward_source_mesh(const std::string& path); + + //---------------------------------------------------------------------------- + // Data members + + int32_t spatial_mesh_idx_; //!< Index into model::meshes + int32_t angle_mesh_idx_; //!< Index into model::meshes, or C_NONE + vector energy_bounds_; //!< Energy group boundaries [eV] + int32_t ww_id_; //!< ID of the associated WeightWindows + + //! Un-normalized mean flux. Shape: (spatial_bins, angle_bins, + //! energy_bins). angle_bins == 1 when angle_mesh_idx_ == C_NONE. + tensor::Tensor flux_; + + //! Estimated relative strength of the unbiased external source as a function + //! of (spatial mesh element, angular mesh element, energy group), assuming + //! isotropic emission when angle_mesh_idx_ == C_NONE. + tensor::Tensor unbiased_strength_; +}; + class WeightWindowsGenerator { public: // Constructors @@ -214,7 +298,9 @@ class WeightWindowsGenerator { // Data members int32_t tally_idx_; //!< Index of the tally used to update the weight windows - int32_t ww_idx_; //!< Index of the weight windows object being generated + int32_t sb_tally_idx_ {C_NONE}; //!< Index of tally used to update source bias + int32_t sb_idx_ {C_NONE}; //!< Index into variance_reduction::source_biases + int32_t ww_idx_; //!< Index of the weight windows object being generated WeightWindowUpdateMethod method_; //!< Method used to update weight window. int32_t max_realizations_; //!< Maximum number of tally realizations int32_t update_interval_; //!< Determines how often updates occur @@ -232,6 +318,8 @@ class WeightWindowsGenerator { std::vector targets_; // FW-CADIS source biasing bool source_biasing_; + int32_t angle_mesh_idx_ {C_NONE}; // BoundingBox: ll[ll == -inf] = -np.inf ur[ur == -inf] = -np.inf return BoundingBox(ll, ur) + + def get_bin(self, xyz) -> int: + """Return the index of the mesh element containing a point. + + Parameters + ---------- + xyz : iterable of float + Cartesian coordinates of a point (e.g. a position, or a + Cartesian direction vector if this mesh is used to discretize + the unit sphere) + + Returns + ------- + int + Index of the mesh element containing the point, or -1 if the + point is not inside any element of the mesh + + """ + xyz = np.asarray(xyz, dtype=np.double) + bin_ = c_int32() + _dll.openmc_mesh_get_bin( + self._index, xyz.ctypes.data_as(POINTER(c_double)), bin_) + return bin_.value def material_volumes( self, diff --git a/openmc/mesh.py b/openmc/mesh.py index d45d95626c3..33346f20c9f 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3861,48 +3861,73 @@ def from_xml_element(cls, elem: ET.Element): return cls(triangles, mesh_id=mesh_id) -def triangularize_unit_sphere_mesh(mesh, data = None): +def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): """Convert a UnitSpherePointset to a UnitSphereTriangularMesh. - This function takes a UnitSpherePointset, as well as an optional - dataset defined on said mesh, and converts it to a triangular mesh of the - unit sphere by performing a star triangularization of the Voronoi cells - generated by the UnitSpherePointset. If a dataset is provided, new data - values are computed based on each new mesh cell's area fraction of the - original Voronoi cell. Hence, the data must be provided in an array with - the same number of elements as there are points in the UnitSpherePointset, - and organized such that when the array is flattened in row-major (C-style) - order, the sequential order of the data values corresponds to their - respective points in the UnitSpherePointset. + This function takes a UnitSpherePointset, as well as optional dataset(s) + defined on said mesh, and converts it to a triangular mesh of the unit + sphere by performing a star triangularization of the Voronoi cells + generated by the UnitSpherePointset. + + Two different methods are provided for redistributing provided data onto + the triangularized mesh: + + - Data provided in the `data` field is treated as extensive + (e.g. a probability mass or reaction rate): new values are computed + based on each new mesh cell's area fraction of the original Voronoi + cell, so that summing the new values over all triangles belonging to a + given original point reproduces that point's original value. + - `broadcast_data` is treated as intensive: each triangle within a + subdivided Voronoi cell inherits the parent point's value, unchanged. + + Both `data` and `broadcast_data` must have as their leading axis the + dimension which indexes along the pointset (i.e., being of size N); any + trailing axes are carried through unchanged. Parameters ---------- mesh : UnitSpherePointset Pointset mesh of N points - data : iterable of float - Array of scalar data represented on the pointset. Must also contain N - entries. + data : numpy.ndarray, optional + Extensive per-point data of shape (N, ...) to redistribute + proportionally to area. + broadcast_data : numpy.ndarray, optional + Intensive per-point data of shape (N, ...) to copy unchanged onto + every new triangle belonging to its parent point. Returns ------- new_mesh : UnitSphereTriangularMesh Angular mesh of M SphericalTriangle cells - new_data : (M,) ndarray of float - New array of data points associated with each triangle in the - subdivided mesh + new_data : (M, ...) ndarray of float + Only returned if `data` was provided. + new_broadcast_data : (M, ...) ndarray of float + Only returned if `broadcast_data` was provided. """ cv.check_type("mesh for triangularization", mesh, UnitSpherePointset) - cv.check_type("data for triangularization", data, Iterable, Real, none_ok=True) + n_points = len(mesh.points) + if data is not None: - data = np.asarray(data).flatten() - if len(data) != len(mesh.points): + data = np.asarray(data) + if data.shape[0] != n_points: raise ValueError( - f"Number of entries in data array does not match number of points " - f"in UnitSpherePointset for triangularization " - f"(expected {len(mesh.points)})" + f"First dimension of data array ({data.shape[0]}) does not " + f"match number of points in UnitSpherePointset for " + f"triangularization (expected {n_points})" ) new_data = [] + if broadcast_data is not None: + broadcast_data = np.asarray(broadcast_data) + if broadcast_data.shape[0] != n_points: + raise ValueError( + f"First dimension of broadcast_data array " + f"({broadcast_data.shape[0]}) does not match number of " + f"points in UnitSpherePointset for triangularization " + f"(expected {n_points})" + ) + new_broadcast_data = [] + sv = SphericalVoronoi(mesh.points) sv.sort_vertices_of_regions() @@ -3941,13 +3966,18 @@ def triangularize_unit_sphere_mesh(mesh, data = None): ) if data is not None: new_data.append(data[pole_index] * areas[i] / total_area) + if broadcast_data is not None: + new_broadcast_data.append(broadcast_data[pole_index]) new_mesh = UnitSphereTriangularMesh(faces) + results = [new_mesh] if data is not None: - return new_mesh, np.asarray(new_data) - else: - return new_mesh + results.append(np.asarray(new_data)) + if broadcast_data is not None: + results.append(np.asarray(new_broadcast_data)) + + return tuple(results) if len(results) > 1 else new_mesh def _read_meshes(elem): diff --git a/openmc/settings.py b/openmc/settings.py index 3d75ee80dc2..85745d734ae 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -14,7 +14,7 @@ from openmc.stats.multivariate import MeshSpatial from ._xml import clean_indentation, get_elem_list, get_text from .mesh import _read_meshes, RegularMesh, MeshBase -from .source import SourceBase, MeshSource, IndependentSource +from .source import SourceBase, MeshSource, IndependentSource, CorrelatedSource from .utility_funcs import input_path, set_xml_input_path from .volume import VolumeCalculation from .weight_windows import WeightWindows, WeightWindowGenerator, WeightWindowsList @@ -395,6 +395,10 @@ class Settings: Path to a weight window file to load during simulation initialization .. versionadded::0.14.0 + + source_bias_file: Pathlike + Path to a file containing source biasing parameters generated via FW-CADIS + write_initial_source : bool Indicate whether to write the initial source distribution to file """ @@ -493,6 +497,7 @@ def __init__(self, **kwargs): self._weight_windows_on = None self._shared_secondary_bank = None self._weight_windows_file = None + self._source_bias_file = None self._weight_window_checkpoints = {} self._max_history_splits = None self._max_tracks = None @@ -1382,6 +1387,18 @@ def weight_windows_file(self, value: PathLike | None): else: cv.check_type('weight windows file', value, PathLike) self._weight_windows_file = input_path(value) + + @property + def source_bias_file(self) -> PathLike | None: + return self._source_bias_file + + @source_bias_file.setter + def source_bias_file(self, value: PathLike | None): + if value is None: + self._source_bias_file = None + else + cv.check_type('source bias file', value, PathLike) + self._source_bias_file = input_path(value) @property def weight_window_generators(self) -> list[WeightWindowGenerator]: @@ -1554,7 +1571,7 @@ def _create_source_subelement(self, root, mesh_memo=None): path = f"./mesh[@id='{source.space.mesh.id}']" if root.find(path) is None: root.append(source.space.mesh.to_xml_element()) - if isinstance(source, MeshSource): + if isinstance(source, [MeshSource, CorrelatedSource]): path = f"./mesh[@id='{source.mesh.id}']" if root.find(path) is None: root.append(source.mesh.to_xml_element()) @@ -1957,21 +1974,28 @@ def _create_weight_window_generators_subelement(self, root, mesh_memo=None): # ensure that mesh elements are created if needed for wwg in self.weight_window_generators: - if mesh_memo is not None and wwg.mesh.id in mesh_memo: - continue + for mesh in (wwg.mesh, wwg.angular_biasing_quadrature): + if mesh_memo is not None and mesh.id in mesh_memo: + continue - # See if a element already exists -- if not, add it - path = f"./mesh[@id='{wwg.mesh.id}']" - if root.find(path) is None: - root.append(wwg.mesh.to_xml_element()) - if mesh_memo is not None: - mesh_memo.add(wwg.mesh.id) + # See if a element already exists -- if not, add it + path = f"./mesh[@id='{mesh.id}']" + if root.find(path) is None: + root.append(mesh.to_xml_element()) + if mesh_memo is not None: + mesh_memo.add(mesh.id) def _create_weight_windows_file_element(self, root): if self.weight_windows_file is not None: element = ET.Element("weight_windows_file") element.text = str(self.weight_windows_file) root.append(element) + + def _create_source_bias_file_element(self, root): + if self.source_bias_file is not None: + element = ET.element("source_bias_file") + element.text = str(self.source_bias_file) + root.append(element) def _create_weight_window_checkpoints_subelement(self, root): if not self._weight_window_checkpoints: @@ -2464,6 +2488,11 @@ def _weight_windows_file_from_xml_element(self, root): if text is not None: self.weight_windows_file = text + def _source_bias_file_from_xml_element(self, root): + text = get_text(root, "source_bias_file") + if text is not None: + self.source_bias_file = text + def _weight_window_checkpoints_from_xml_element(self, root): elem = root.find('weight_window_checkpoints') if elem is None: @@ -2629,6 +2658,7 @@ def to_xml_element(self, mesh_memo=None): self._create_shared_secondary_bank_subelement(element) self._create_weight_window_generators_subelement(element, mesh_memo) self._create_weight_windows_file_element(element) + self._create_source_bias_file_element(element) self._create_weight_window_checkpoints_subelement(element) self._create_max_history_splits_subelement(element) self._create_max_tracks_subelement(element) @@ -2746,6 +2776,7 @@ def from_xml_element(cls, elem, meshes=None): settings._weight_windows_on_from_xml_element(elem) settings._shared_secondary_bank_from_xml_element(elem) settings._weight_windows_file_from_xml_element(elem) + settings._source_bias_file_from_xml_element(elem) settings._weight_window_generators_from_xml_element(elem, meshes) settings._weight_window_checkpoints_from_xml_element(elem) settings._max_history_splits_from_xml_element(elem) diff --git a/openmc/source.py b/openmc/source.py index e68bdd5cf25..f775df8e0ee 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -17,12 +17,34 @@ from openmc.stats.multivariate import UnitSphere, Spatial from openmc.stats.univariate import Univariate from ._xml import get_elem_list, get_text -from .mesh import MeshBase, StructuredMesh, UnstructuredMesh +from .mesh import MeshBase, StructuredMesh, UnstructuredMesh, UnitSpherePointset, triangularize_unit_sphere_mesh from .particle_type import ParticleType from .statepoint import _VERSION_STATEPOINT from .utility_funcs import input_path +def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: + """Return the flattened mesh bin index containing each point, or -1 for + points outside the mesh. + + Parameters + ---------- + lib_mesh + An ``openmc.lib`` mesh object (e.g. ``openmc.lib.meshes[mesh_id]``) + points : numpy.ndarray + Array of shape (N, 3) giving Cartesian points to look up + + Returns + ------- + numpy.ndarray + Array of shape (N,) giving the bin index of each point, or -1 if + the point is outside the mesh + """ + bins = np.empty(len(points), dtype=int) + for i, p in enumerate(points): + bins[i] = lib_mesh.get_bin(p) + return bins + class SourceBase(ABC): """Base class for external sources @@ -208,6 +230,189 @@ def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase: else: raise ValueError( f'Source type {source_type} is not recognized') + + def write_source_mesh( + self, + space_mesh: openmc.MeshBase, + angle_mesh: openmc.MeshBase | None, + energy_bins: Sequence[float], + min_samples: int = 10_000, + min_avg_samples_per_voxel: float = 30.0, + max_samples: int | None = None, + filename: PathLike = 'forward_source_mesh.h5', + region_size: float = 1.0e5, + **init_kwargs, + ) -> None: + """Precompute this source's strength on a (space, angle, energy) grid + and write it to an HDF5 file for FW-CADIS source biasing. + + This is meant to accommodate biasing sources that aren't + :class:`IndependentSource` instances, under the assumption that a + geometrically simpler "lookalike" :class:`IndependentSource` is used + in the Random Ray solve to estimate adjoint flux data. + + Parameters + ---------- + space_mesh : openmc.MeshBase + Spatial mesh to bin sampled source positions into. Should match + the mesh that will be used for the corresponding random ray + source-biasing tally. + angle_mesh : openmc.MeshBase or None + Angular mesh (over the unit sphere) to bin sampled source + directions into. If None, emission is recorded as a single + (isotropic) angle bin. + energy_bins : sequence of float + Ascending energy group boundaries in [eV], matching the group + structure used for the corresponding random ray source-biasing + tally. + min_samples : int + Number of source sites to sample. + min_avg_samples_per_voxel : float + Target average number of samples per occupied (spatial, angle, + energy) voxel. + max_samples : int or None + Maximum total number of source sites sampled. Issues a warning + if this cap is reached before min_avg_samples_per_voxel is + satisfied. Defaults to ``10 * min_samples``. + filename : path-like + Path to write the resulting HDF5 file to. + region_size : float + Half-width in [cm] of the placeholder void region this source is + sampled within. Must be large enough to contain the full + spatial extent of both this source and space_mesh -- increase + this if source sites are unexpectedly missing from the result. + **init_kwargs + Keyword arguments passed to :func:`openmc.lib.init` (via + :class:`openmc.lib.TemporarySession`) + + See Also + -------- + openmc.Model.sample_external_source + """ + import openmc.lib + + if max_samples is None: + max_samples = 10 * min_samples + if max_samples < min_samples: + raise ValueError( + f'max_samples ({max_samples}) must be >= min_samples ' + f'({min_samples}).') + + energy_bins = np.asarray(energy_bins, dtype=float) + if energy_bins.ndim != 1 or energy_bins.size < 2: + raise ValueError( + 'energy_bins must be a 1-D sequence with at least two ' + 'entries.') + n_energy = energy_bins.size - 1 + + n_space = space_mesh.n_elements + n_angle = angle_mesh.n_elements if angle_mesh is not None else 1 + + # Build a minimal model containing only this source + half = region_size + box = openmc.model.RectangularParallelepiped( + -half, half, -half, half, -half, half, boundary_type='vacuum') + placeholder_cell = openmc.Cell(region=-box) + placeholder_universe = openmc.Universe(cells=[placeholder_cell]) + + model = openmc.Model() + model.geometry.root_universe = placeholder_universe + model.settings.run_mode = 'fixed source' + model.settings.source = [self] + + # Attach the meshes to a tally so they are available through + # openmc.lib after init; the tally itself is never actually scored. + filters = [openmc.MeshFilter(space_mesh)] + if angle_mesh is not None: + filters.append(openmc.MeshFilter(angle_mesh)) + dummy_tally = openmc.Tally() + dummy_tally.filters = filters + dummy_tally.scores = ['flux'] + model.tallies = openmc.Tallies([dummy_tally]) + + init_kwargs.setdefault('output', False) + init_kwargs.setdefault('args', ['-c']) + + S = np.zeros((n_space, n_angle, n_energy)) + + with openmc.lib.TemporarySession(model, **init_kwargs): + space_lib_mesh = openmc.lib.meshes[space_mesh.id] + angle_lib_mesh = ( + openmc.lib.meshes[angle_mesh.id] + if angle_mesh is not None else None + ) + + while True: + batch_size = min(min_samples, max_samples - n_drawn) + if batch_size <= 0: + break + + data = openmc.lib.sample_external_source( + n_samples=batch_size, as_array=True) + n_drawn += batch_size + + r = np.stack( + [data['r']['x'], data['r']['y'], data['r']['z']], + axis=-1) + u = np.stack( + [data['u']['x'], data['u']['y'], data['u']['z']], + axis=-1) + E = data['E'] + + space_bin = _mesh_bin_indices(space_lib_mesh, r) + valid = space_bin >= 0 + + if angle_lib_mesh is not None: + angle_bin = _mesh_bin_indices(angle_lib_mesh, u) + valid &= angle_bin >= 0 + else: + angle_bin = np.zeros(len(r), dtype=int) + + energy_bin = np.digitize(E, energy_bins) - 1 + valid &= (energy_bin >= 0) & (energy_bin < n_energy) + + np.add.at( + counts, + (space_bin[valid], angle_bin[valid], energy_bin[valid]), + 1.0) + + # Average samples per voxel among voxels sampled at least + # once so far. counts.sum() equals the sum over just the + # occupied voxels, since unoccupied ones are still zero. + n_occupied = np.count_nonzero(counts > 0) + avg_per_voxel = ( + counts.sum() / n_occupied if n_occupied else 0.0) + + if avg_per_voxel >= min_avg_samples_per_voxel: + break + if n_drawn >= max_samples: + break + + if avg_per_voxel < min_avg_samples_per_voxel: + warnings.warn( + f"write_source_mesh reached max_samples ({max_samples}) " + f"with an average of only {avg_per_voxel:.1f} samples per " + f"occupied voxel (wanted {min_avg_samples_per_voxel}). " + "Consider raising max_samples or coarsening " + "space_mesh/angle_mesh/energy_bins." + ) + + # Normalize by the total number of samples drawn, including rejected + # sites, so that source support falling outside + # space_mesh/angle_mesh/energy_bins correctly shows up as + # unrepresented probability mass rather than being renormalized away + S /= min_samples + + with h5py.File(filename, 'w') as fh: + fh.attrs['filetype'] = np.bytes_('forward_source') + fh.attrs['version'] = np.array([1, 0]) + fh.create_dataset('spatial_mesh', data=space_mesh.id) + # -1 used for angle-independent biasing + fh.create_dataset( + 'angle_mesh', + data=angle_mesh.id if angle_mesh is not None else -1) + fh.create_dataset('energy_bounds', data=energy_bins) + fh.create_dataset('unbiased_source_strength', data=S) @staticmethod def _get_constraints(elem: ET.Element) -> dict[str, Any]: @@ -658,6 +863,256 @@ def from_xml_element(cls, elem: ET.Element, meshes) -> openmc.MeshSource: e) for e in elem.iterchildren('source')] constraints = cls._get_constraints(elem) return cls(mesh, sources, constraints=constraints) + +class CorrelatedSource(SourceBase): + """A source that samples a precomputed, spatially- and (optionally) + angularly-biased phase-space distribution. + + This is normally constructed from a "source_bias.h5" file produced by + FW-CADIS source biasing (see the C++ ``SourceBias`` class in + ``openmc/weight_windows.h`` and ``openmc_weight_windows_export``), + which stores a biased source strength B(r, Omega, g) and a per-voxel + weight 1/flux(r, Omega, g) on a (spatial mesh, angular mesh, energy + group) grid. If the angular mesh is a :class:`UnitSpherePointset` (the + only angular mesh type that currently supports point-location, i.e. + tallying -- see ``AngularMesh`` in ``mesh.h``), it is converted here to + a :class:`UnitSphereTriangularMesh` (which instead supports direction + sampling) via a star triangulation of its spherical Voronoi diagram, + using :func:`scipy.spatial.SphericalVoronoi` (see + :func:`triangularize_unit_sphere_mesh`). This conversion happens once, + in Python, at construction time; the fully-processed result -- the + (possibly larger, after triangulation) biased strength and weight + arrays, plus mesh references -- is written directly to XML, so the C++ + side never reads source_bias.h5 or performs any triangulation itself + (see ``CorrelatedSource`` in ``openmc/source.h``/``source.cpp``). + + B is treated as *extensive* (a probability mass) when redistributed + across new triangles, while the weight is treated as *intensive* and + simply copied unchanged to every new triangle belonging to its parent + point -- subdividing the angular bin for sampling purposes shouldn't + dilute a purely directional correction factor. + + .. versionadded:: TODO + + Parameters + ---------- + filename : path-like + Path to a "source_bias.h5" file. + constraints : dict + Constraints on sampled source particles; see :class:`SourceBase`. + + Attributes + ---------- + mesh : openmc.MeshBase + Spatial mesh source positions are sampled from. + angle_mesh : openmc.MeshBase or None + Angular mesh source directions are sampled from (a + UnitSphereTriangularMesh if the source was angularly biased), or + None if emission is isotropic. + energy_bounds : numpy.ndarray or None + Energy group boundaries [eV], or None if there is a single group. + strengths : numpy.ndarray + Biased source strength B(r, Omega, g), flattened in row-major + (spatial, angle, energy) order. + weights : numpy.ndarray + Per-voxel weight (1 / flux), in the same order as `strengths`. + strength : float + Total source strength (sum of `strengths`). + type : str + Indicator of source type: 'dependent' + + """ + + def __init__( + self, + filename: PathLike, + constraints: dict[str, Any] | None = None, + ): + super().__init__(strength=None, constraints=constraints) + self._load(filename) + + @property + def type(self) -> str: + return "dependent" + + @property + def mesh(self) -> MeshBase: + return self._mesh + + @property + def angle_mesh(self) -> MeshBase | None: + return self._angle_mesh + + @property + def energy_bounds(self) -> np.ndarray | None: + return self._energy_bounds + + @property + def strengths(self) -> np.ndarray: + return self._strengths + + @property + def weights(self) -> np.ndarray: + return self._weights + + @property + def strength(self) -> float: + return float(np.sum(self._strengths)) + + @strength.setter + def strength(self, val): + if val is not None: + cv.check_type('dependent source strength', val, Real) + current = self.strength if self.strength != 0.0 else 1.0 + self._strengths = self._strengths * (val / current) + + def _load(self, filename: PathLike): + """Read source_bias.h5, triangulating the angular mesh (if present + and if it is a UnitSpherePointset) in the process. + + The HDF5 layout read here (dataset names/shapes, the "-1" sentinel + for "no angular mesh", and mesh subgroups named "mesh ") mirrors + ``SourceBias::to_hdf5()`` on the C++ side (see ``weight_windows.cpp``) + and ``Mesh::to_hdf5()`` in ``mesh.cpp``. + """ + filename = Path(filename) + + with h5py.File(filename, 'r') as fh: + filetype = fh.attrs['filetype'] + if isinstance(filetype, bytes): + filetype = filetype.decode() + if filetype != 'source_bias': + raise ValueError( + f"File '{filename}' is not a source bias file " + f"(filetype='{filetype}').") + + sb_names = [k for k in fh.keys() if k.startswith('source_bias_')] + if len(sb_names) != 1: + raise ValueError( + f"File '{filename}' contains {len(sb_names)} source " + "bias groups; CorrelatedSource currently requires " + "exactly one.") + sb_group = fh[sb_names[0]] + + mesh_group = fh['meshes'] + + spatial_mesh_id = int(np.asarray(sb_group['spatial_mesh'])) + angle_mesh_id = int(np.asarray(sb_group['angle_mesh'])) + + # Mesh subgroups are named "mesh " (matching the C++ + # Mesh::to_hdf5() convention) -- MeshBase.from_hdf5() parses the + # ID directly out of the group's own name, so the lookup key + # must match that exactly. + spatial_mesh = MeshBase.from_hdf5( + mesh_group[f'mesh {spatial_mesh_id}']) + + energy_bounds = np.asarray(sb_group['energy_bounds']) + n_energy = max(len(energy_bounds) - 1, 1) + n_space = spatial_mesh.n_elements + + biased_strength = np.asarray(sb_group['biased_source_strength']) + weights = np.asarray(sb_group['weights']) + # Expected shape: (n_space, n_angle, n_energy) + n_angle = biased_strength.shape[1] + + if angle_mesh_id != -1: + angle_mesh = MeshBase.from_hdf5( + mesh_group[f'mesh {angle_mesh_id}']) + else: + angle_mesh = None + + if angle_mesh is not None and isinstance(angle_mesh, UnitSpherePointset): + # triangularize_unit_sphere_mesh expects point-major data, with + # the angle/point dimension leading; reshape from our (spatial, + # angle, energy) layout accordingly, treating (spatial, energy) + # as one flattened "extra" block per point. + b_point_major = np.moveaxis(biased_strength, 1, 0).reshape( + n_angle, n_space * n_energy) + w_point_major = np.moveaxis(weights, 1, 0).reshape( + n_angle, n_space * n_energy) + + angle_mesh, new_b, new_w = triangularize_unit_sphere_mesh( + angle_mesh, data=b_point_major, broadcast_data=w_point_major) + + n_angle = angle_mesh.n_elements + biased_strength = np.moveaxis( + new_b.reshape(n_angle, n_space, n_energy), 0, 1) + weights = np.moveaxis( + new_w.reshape(n_angle, n_space, n_energy), 0, 1) + + self._mesh = spatial_mesh + self._angle_mesh = angle_mesh + self._energy_bounds = energy_bounds if len(energy_bounds) > 0 else None + # Flatten to row-major (spatial, angle, energy) order, matching what + # CorrelatedSource's C++ constructor expects to find in "strengths"/ + # "weights". + self._strengths = biased_strength.ravel() + self._weights = weights.ravel() + + def populate_xml_element(self, elem: ET.Element): + """Add necessary source information to an XML element + + Returns + ------- + element : lxml.etree._Element + XML element containing source data + + """ + elem.set("mesh", str(self.mesh.id)) + if self.angle_mesh is not None: + elem.set("angle_mesh", str(self.angle_mesh.id)) + if self.energy_bounds is not None: + subelem = ET.SubElement(elem, "energy_bounds") + subelem.text = ' '.join(str(e) for e in self.energy_bounds) + subelem = ET.SubElement(elem, "strengths") + subelem.text = ' '.join(str(s) for s in self.strengths) + subelem = ET.SubElement(elem, "weights") + subelem.text = ' '.join(str(w) for w in self.weights) + + @classmethod + def from_xml_element(cls, elem: ET.Element, meshes) -> CorrelatedSource: + """ + Generate CorrelatedSource from an XML element + + Parameters + ---------- + elem : lxml.etree._Element + XML element + meshes : dict + A dictionary with mesh IDs as keys and openmc.MeshBase instances + as values + + Returns + ------- + openmc.CorrelatedSource + CorrelatedSource generated from the XML element + + """ + # Bypass __init__ (which reads directly from an HDF5 file) since + # everything needed is already present in the XML -- source_bias.h5 + # itself does not need to exist at this point. + source = cls.__new__(cls) + SourceBase.__init__( + source, strength=None, constraints=cls._get_constraints(elem)) + + mesh_id = int(get_text(elem, 'mesh')) + source._mesh = meshes[mesh_id] + + angle_mesh_id = get_text(elem, 'angle_mesh') + source._angle_mesh = ( + meshes[int(angle_mesh_id)] if angle_mesh_id is not None else None) + + energy_bounds_text = get_text(elem, 'energy_bounds') + source._energy_bounds = ( + np.array([float(x) for x in energy_bounds_text.split()]) + if energy_bounds_text is not None else None) + + source._strengths = np.array( + [float(x) for x in get_text(elem, 'strengths').split()]) + source._weights = np.array( + [float(x) for x in get_text(elem, 'weights').split()]) + + return source def Source(*args, **kwargs): diff --git a/openmc/weight_windows.py b/openmc/weight_windows.py index dcb7350b9bd..27be289fd7f 100644 --- a/openmc/weight_windows.py +++ b/openmc/weight_windows.py @@ -504,6 +504,9 @@ class WeightWindowGenerator: Target tallies for local variance reduction via FW-CADIS. source_biasing : bool Whether to perform automated biasing of fixed sources via FW-CADIS. + angular_biasing_quadrature : :class:`openmc.UnitSpherePointset`, optional + Optional set of angles to generate source biasing parameters on. + Defaults to None for biasing as a function of space and energy only. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -527,6 +530,9 @@ class WeightWindowGenerator: Target tallies for local variance reduction via FW-CADIS. source_biasing : bool Whether to perform automated biasing of fixed sources via FW-CADIS. + angular_biasing_quadrature : openmc.UnitSpherePointset or None + Optional set of angles to generate source biasing parameters on. + Defaults to None for biasing as a function of space and energy only. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -548,6 +554,7 @@ def __init__( method: str = 'magic', targets: openmc.Tallies | Iterable[int] | None = None, source_biasing: bool = False, + angular_biasing_quadrature: openmc.UnitSpherePointset | None = None, max_realizations: int = 1, update_interval: int = 1, on_the_fly: bool = True @@ -562,6 +569,7 @@ def __init__( self.method = method self.targets = targets self.source_biasing = source_biasing + self.angular_biasing_quadrature = angular_biasing_quadrature self.max_realizations = max_realizations self.update_interval = update_interval self.on_the_fly = on_the_fly @@ -654,6 +662,53 @@ def source_biasing(self, sb: bool): "Automated source biasing is only enabled via the " \ "fw_cadis update method.") self._source_biasing = sb + + @property + def angular_biasing_quadrature(self) -> openmc.UnitSpherePointset: + return self._angular_biasing_quadrature + + @angular_biasing_quadrature.setter + def angular_biasing_quadrature(self, angle_mesh): + if angle_mesh is None: + self._angular_biasing_quadrature = angle_mesh + elif self.source_biasing != True: + raise ValueError( + "Cannot specify an angular biasing quadrature while source " \ + "biasing is not active.") + else: + cv.check_type('angular biasing quadrature', angle_mesh, UnitSpherePointset) + angles = angle_mesh.points + if len(angles) < 8: + raise ValueError( + "Angular biasing quadrature requires at least 8 angles (1 in each octant).") + + # Make sure there is at least one angle in each octant, since Voronoi cells that + # are too large could produce triangles we may not be able to sample from, e.g. + # with antipodal vertices or area >= 2pi. + # scipy.spatial.SphericalVoronoi performs a check that the provided angle set + # spans R3, but requiring one angle in each octant is a stronger condition that + # also prevents clustering points within one hemisphere. + + x_pos = angles[:, 0] >= 0 + y_pos = angles[:, 1] >= 0 + z_pos = angles[:, 2] >= 0 + + octants = np.zeros(len(angles), dtype=int) + octants[ x_pos & y_pos & z_pos] = 1 + octants[~x_pos & y_pos & z_pos] = 2 + octants[~x_pos & ~y_pos & z_pos] = 3 + octants[ x_pos & ~y_pos & z_pos] = 4 + octants[ x_pos & y_pos & ~z_pos] = 5 + octants[~x_pos & y_pos & ~z_pos] = 6 + octants[~x_pos & ~y_pos & ~z_pos] = 7 + octants[ x_pos & ~y_pos & ~z_pos] = 8 + + if len(np.unique(octants)) < 8: + raise ValueError( + "Angular quadrature provided for source biasing does not have at least one " \ + "angle in each octant.") + + self._angular_biasing_quadrature = angle_mesh @property def max_realizations(self) -> int: @@ -767,6 +822,9 @@ def to_xml_element(self): if self.source_biasing: sb_elem = ET.SubElement(element, 'source_biasing') sb_elem.text = str(self.source_biasing).lower() + if self.angular_biasing_quadrature is not None: + angle_mesh_elem = ET.SubElement(element, 'angular_biasing_quadrature') + angle_mesh_elem.text = str(self.angular_biasing_quadrature.id) if self.update_parameters is not None: self._update_parameters_subelement(element) @@ -814,6 +872,10 @@ def from_xml_element(cls, elem: ET.Element, meshes: dict) -> Self: if elem.find('source_biasing') is not None: wwg.source_biasing = bool(get_text(elem, 'source_biasing')) + if elem.find('angular_biasing_quadrature') is not None: + angle_mesh_id = int(get_text(elem, 'angular_biasing_quadrature')) + angle_mesh = meshes[angle_mesh_id] + wwg.angular_biasing_quadrature = angle_mesh if elem.find('update_parameters') is not None: update_parameters = {} params_elem = elem.find('update_parameters') diff --git a/src/mesh.cpp b/src/mesh.cpp index 34a9d8c725e..1a58de7940c 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2627,7 +2627,8 @@ void UnitSphereTriangularMesh::to_hdf5_inner(hid_t mesh_group) const write_dataset(mesh_group, "areas", areas_); } -Direction UnitSphereTriangularMesh::sample_element(int32_t bin, uint64_t* seed) const +Direction UnitSphereTriangularMesh::sample_element( + int32_t bin, uint64_t* seed) const { int offset = 9 * bin; @@ -2809,6 +2810,18 @@ extern "C" int openmc_add_unstructured_mesh( return 0; } +extern "C" int openmc_mesh_get_bin( + int32_t index, const double xyz[3], int32_t* bin) +{ + if (index < 0 || index >= model::meshes.size()) { + set_errmsg("Index in meshes array is out of bounds."); + return OPENMC_E_OUT_OF_BOUNDS; + } + Position r {xyz[0], xyz[1], xyz[2]}; + *bin = model::meshes[index]->get_bin(r); + return 0; +} + //! Return the index in the meshes array of a mesh with a given ID extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index) { diff --git a/src/settings.cpp b/src/settings.cpp index 15a7b9c27c9..056017ee749 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -98,6 +98,7 @@ std::string path_sourcepoint; std::string path_statepoint; const char* path_statepoint_c {path_statepoint.c_str()}; std::string weight_windows_file; +std::string source_bias_file; std::string properties_file; int32_t n_inactive {0}; @@ -1250,6 +1251,11 @@ void read_settings_xml(pugi::xml_node root) weight_windows_on = true; } + // read FW-CADIS biased source + if (check_for_node(root, "source_bias_file")) { + source_bias_file = get_node_value(root, "source_bias_file"); + } + // read settings for weight windows value, this will override // the automatic setting even if weight windows are present if (check_for_node(root, "weight_windows_on")) { diff --git a/src/source.cpp b/src/source.cpp index f951722cc18..00d4e184fd3 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -28,6 +28,7 @@ #include "openmc/math_functions.h" #include "openmc/mcpl_interface.h" #include "openmc/memory.h" +#include "openmc/mesh.h" #include "openmc/message_passing.h" #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" @@ -108,6 +109,8 @@ unique_ptr Source::create(pugi::xml_node node) return make_unique(node); } else if (source_type == "tokamak") { return make_unique(node); + } else if (source_type == "correlated") { + return make_unique(node); } else { fatal_error(fmt::format("Invalid source type '{}' found.", source_type)); } @@ -702,6 +705,124 @@ SourceSite MeshSource::sample(uint64_t* seed) const return source(element)->sample_with_constraints(seed); } +//============================================================================== +// CorrelatedSource implementation +//============================================================================== + +CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) +{ + // Note: Source(node) reads strength/constraints from XML for consistency + // with other source types, but neither is actually used at sample time -- + // strength() is overridden to derive strength from the voxel data, and + // constraints_applied() == true means domain/energy/time constraints are + // never re-checked (the imported voxel probabilities are assumed to reflect + // only phase space actually populated by the original source). + int32_t mesh_id = std::stoi(get_node_value(node, "mesh")); + if (model::mesh_map.count(mesh_id) == 0) { + fatal_error(fmt::format( + "Spatial mesh {} referenced by a CorrelatedSource does not exist.", + mesh_id)); + } + spatial_mesh_idx_ = model::mesh_map.at(mesh_id); + + if (check_for_node(node, "angle_mesh")) { + int32_t angle_mesh_id = std::stoi(get_node_value(node, "angle_mesh")); + if (model::mesh_map.count(angle_mesh_id) == 0) { + fatal_error( + fmt::format("Angular mesh {} referenced by a CorrelatedSource does " + "not exist.", + angle_mesh_id)); + } + int32_t angle_mesh_idx = model::mesh_map.at(angle_mesh_id); + auto* angle_mesh_ptr = dynamic_cast( + model::meshes[angle_mesh_idx].get()); + if (!angle_mesh_ptr) { + fatal_error( + fmt::format("Angular mesh {} referenced by a CorrelatedSource is not " + "a UnitSphereTriangularMesh instance.", + angle_mesh_id)); + } + angle_mesh_idx_ = angle_mesh_idx; + } else { + angle_mesh_idx_ = C_NONE; + } + + if (check_for_node(node, "energy_bounds")) { + group_bounds_ = get_node_array(node, "energy_bounds"); + } + + spatial_bins_ = model::meshes[spatial_mesh_idx_]->n_bins(); + angle_bins_ = + angle_mesh_idx_ == C_NONE ? 1 : model::meshes[angle_mesh_idx_]->n_bins(); + energy_bins_ = group_bounds_.empty() ? 1 : group_bounds_.size() - 1; + + size_t n_voxels = + static_cast(spatial_bins_ * angle_bins_ * energy_bins_); + + // "strengths" flattened in row-major (spatial, angle, energy) order + vector strengths = get_node_array(node, "strengths"); + if (strengths.size() != n_voxels) { + fatal_error(fmt::format( + "Number of entries in the 'strengths' array for a CorrelatedSource " + "({}) does not match the number of (spatial, angle, energy) voxels " + "implied by its mesh(es) and energy bounds ({}).", + strengths.size(), n_voxels)); + } + + weights_ = get_node_array(node, "weights"); + if (weights_.size() != n_voxels) { + fatal_error(fmt::format( + "Number of entries in the 'weights' array for a CorrelatedSource " + "({}) does not match the number of (spatial, angle, energy) voxels " + "implied by its mesh(es) and energy bounds ({}).", + weights_.size(), n_voxels)); + } + + voxel_dist_.assign(strengths); + + if (check_for_node(node, "particle")) { + auto tmp_str = get_node_value(node, "particle", false, true); + particle_ = ParticleType {tmp_str}; + } + validate_particle_type(particle_, "CorrelatedSource"); +} + +SourceSite CorrelatedSource::sample(uint64_t* seed) const +{ + SourceSite site {}; + site.particle = particle_; + + // Select a phase-space voxel (m, a, g) + size_t flat = voxel_dist_.sample(seed); + int64_t g = static_cast(flat % energy_bins_); + int64_t a = static_cast((flat / energy_bins_) % angle_bins_); + int64_t m = static_cast(flat / (energy_bins_ * angle_bins_)); + + // Sample a position uniformly within the selected spatial mesh element + site.r = model::meshes[spatial_mesh_idx_]->sample_element( + static_cast(m), seed); + + // Sample a direction within the selected angular mesh element, or + // isotropic if no angular dependence + if (angle_mesh_idx_ != C_NONE) { + site.u = model::meshes[angle_mesh_idx_]->sample_element( + static_cast(a), seed); + } else { + site.u = isotropic_direction(seed); + } + + // Energy is sampled from the selected group uniformly in lethargy + if (!group_bounds_.empty()) { + double e_lo = group_bounds_[g]; + double e_hi = group_bounds_[g + 1]; + site.E = e_lo * std::pow(e_hi / e_lo, prn(seed)) + } + + site.wgt = weights_[flat]; + + return site; +} + //============================================================================== // TokamakSource implementation //============================================================================== diff --git a/src/tallies/filter.cpp b/src/tallies/filter.cpp index 0db8d7f1568..9be0013c5aa 100644 --- a/src/tallies/filter.cpp +++ b/src/tallies/filter.cpp @@ -157,6 +157,8 @@ Filter* Filter::create(const std::string& type, int32_t id) return Filter::create(id); } else if (type == "reaction") { return Filter::create(id); + } else if (type == "sourcebias") { + return Filter::create(id); } else if (type == "surface") { return Filter::create(id); } else if (type == "spatiallegendre") { diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index b7073637caa..116bf803812 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -10,9 +10,11 @@ #include "openmc/error.h" #include "openmc/file_utils.h" +#include "openmc/geometry.h" #include "openmc/hdf5_interface.h" #include "openmc/mesh.h" #include "openmc/message_passing.h" +#include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/output.h" #include "openmc/particle.h" @@ -22,8 +24,10 @@ #include "openmc/search.h" #include "openmc/settings.h" #include "openmc/simulation.h" +#include "openmc/source.h" #include "openmc/tallies/filter_energy.h" #include "openmc/tallies/filter_mesh.h" +#include "openmc/tallies/filter_meshangular.h" #include "openmc/tallies/filter_particle.h" #include "openmc/tallies/tally.h" #include "openmc/xml_interface.h" @@ -41,6 +45,7 @@ namespace variance_reduction { std::unordered_map ww_map; openmc::vector> weight_windows; openmc::vector> weight_windows_generators; +openmc::vector> source_biases; } // namespace variance_reduction @@ -753,6 +758,310 @@ void WeightWindows::to_hdf5(hid_t group) const close_group(ww_group); } +//============================================================================== +// SourceBias implementation +//============================================================================== + +SourceBias::SourceBias(int32_t spatial_mesh_idx, int32_t angle_mesh_idx, + vector energy_bounds, int32_t ww_id) + : spatial_mesh_idx_(spatial_mesh_idx), angle_mesh_idx_(angle_mesh_idx), + energy_bounds_(std::move(energy_bounds)), ww_id_(ww_id) +{ + int64_t spatial_bins = model::meshes[spatial_mesh_idx_]->n_bins(); + int64_t angle_bins = + angle_mesh_idx_ == C_NONE ? 1 : model::meshes[angle_mesh_idx_]->n_bins(); + int64_t energy_bins = energy_bounds_.empty() ? 1 : energy_bounds_.size() - 1; + + flux_ = tensor::Tensor({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(energy_bins)}); +} + +void SourceBias::update(const Tally* tally) +{ + int score_index = tally->score_index("flux"); + if (score_index == C_NONE) { + fatal_error(fmt::format("A 'flux' score is required on tally {} used " + "for source biasing.", + tally->id())); + } + + const int64_t spatial_bins = flux_.shape(0); + const int64_t angle_bins = flux_.shape(1); + const int64_t energy_bins = flux_.shape(2); + + const auto& results = tally->results(); + + const int n_filters = static_cast(tally->filters().size()); + std::vector filt_shape(n_filters); + std::vector filt_stride(n_filters, 1); + for (int i = 0; i < n_filters; ++i) { + filt_shape[i] = model::tally_filters[tally->filters(i)]->n_bins(); + } + for (int i = n_filters - 2; i >= 0; --i) { + filt_stride[i] = filt_stride[i + 1] * filt_shape[i + 1]; + } + + std::vector filter_types = tally->filter_types(); + auto position_of = [&filter_types](FilterType type) -> int { + auto it = std::find(filter_types.begin(), filter_types.end(), type); + return it == filter_types.end() + ? -1 + : static_cast(it - filter_types.begin()); + }; + + const int pos_mesh = position_of(FilterType::MESH); + const int pos_energy = position_of(FilterType::ENERGY); + const int pos_angle = position_of(FilterType::MESH_ANGULAR); + + if (pos_mesh == -1) { + fatal_error(fmt::format( + "Tally {} used for source biasing is missing a spatial mesh filter.", + tally->id())); + } + if (angle_bins > 1 && pos_angle == -1) { + fatal_error( + fmt::format("Tally {} used for source biasing is missing the expected " + "mesh-angular filter.", + tally->id())); + } + + const int i_sum = static_cast(TallyResult::SUM); + const int64_t n = tally->n_realizations_; + +#pragma omp parallel for collapse(3) schedule(static) + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + for (int64_t e = 0; e < energy_bins; ++e) { + int64_t flat = m * filt_stride[pos_mesh]; + if (pos_energy != -1) + flat += e * filt_stride[pos_energy]; + if (pos_angle != -1) + flat += a * filt_stride[pos_angle]; + + flux_(m, a, e) = n > 0 ? results(flat, score_index, i_sum) / n : 0.0; + } + } + } +} + +void SourceBias::to_hdf5(hid_t group) const +{ + hid_t sb_group = create_group(group, fmt::format("source_bias_{}", ww_id_)); + + write_dataset( + sb_group, "spatial_mesh", model::meshes[spatial_mesh_idx_]->id()); + write_dataset(sb_group, "angle_mesh", + angle_mesh_idx_ == C_NONE ? C_NONE : model::meshes[angle_mesh_idx_]->id()); + write_dataset(sb_group, "energy_bounds", energy_bounds_); + // Get biased source strength B(r,Omega,g) = flux(r,Omega,g) * + // unbiased_strength(r,Omega,g) and the per-voxel weight 1/flux(r,Omega,g) + const int64_t spatial_bins = flux_.shape(0); + const int64_t angle_bins = flux_.shape(1); + const int64_t energy_bins = flux_.shape(2); + + tensor::Tensor biased_strength({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(energy_bins)}); + tensor::Tensor weights({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(energy_bins)}); + + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + for (int64_t e = 0; e < energy_bins; ++e) { + double psi = flux_(m, a, e); + biased_strength(m, a, e) = psi * unbiased_strength_(m, a, e); + // A weight is only meaningful where the biased distribution can + // actually place a particle (psi > 0, so B could be nonzero there). + // Elsewhere B is guaranteed to be 0 too (since B = psi * S), so a + // Discrete distribution built from B will never select that voxel + // and this placeholder value is never used. + weights(m, a, e) = psi > 0.0 ? 1.0 / psi : 0.0; + } + } + } + + write_dataset(sb_group, "biased_source_strength", biased_strength); + write_dataset(sb_group, "weights", weights); + + close_group(sb_group); +} + +void SourceBias::compute_unbiased_strength(int64_t n_samples_per_source) +{ + const int64_t spatial_bins = flux_.shape(0); + const int64_t angle_bins = flux_.shape(1); + const int64_t energy_bins = flux_.shape(2); + + unbiased_strength_ = + tensor::Tensor({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(energy_bins)}); + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + for (int64_t e = 0; e < energy_bins; ++e) { + unbiased_strength_(m, a, e) = 0.0; + } + } + } + + // A precomputed file takes priority over sampling model::external_sources + const std::string fwd_path = "forward_source_mesh.h5"; + if (file_exists(fwd_path)) { + load_forward_source_mesh(fwd_path); + return; + } + + Mesh* spatial_mesh = model::meshes[spatial_mesh_idx_].get(); + Mesh* angle_mesh = + angle_mesh_idx_ == C_NONE ? nullptr : model::meshes[angle_mesh_idx_].get(); + + // Normalize by total strength across all forward external sources + double total_strength = 0.0; + for (const auto& source_ptr : model::external_sources) { + auto* is = dynamic_cast(source_ptr.get()); + if (!is) { + fatal_error("Computing an unbiased source strength distribution " + "requires all external sources to be independent " + "sources."); + } + total_strength += is->strength(); + } + if (total_strength <= 0.0) { + fatal_error("Total external source strength must be positive to " + "compute an unbiased source strength distribution."); + } + + // Fixed local seed, not part of the sequence used for transport + uint64_t seed = 1; + + tensor::Tensor spatial_angle_counts( + {static_cast(spatial_bins), static_cast(angle_bins)}); + + for (const auto& source_ptr : model::external_sources) { + Source* s = source_ptr.get(); + auto* is = dynamic_cast(s); + double relative_strength = is->strength() / total_strength; + + auto* energy_dist = dynamic_cast(is->energy()); + if (!energy_dist) { + fatal_error( + "Source biasing requires all external sources to use a Discrete " + "(multigroup) energy distribution, matching the requirement for " + "random ray fixed source problems."); + } + vector group_prob(energy_bins, 0.0); + const auto& e_vals = energy_dist->x(); + const auto& e_probs = energy_dist->prob(); + for (std::size_t i = 0; i < e_vals.size(); ++i) { + int g = data::mg.get_group_index(e_vals[i]); + if (g >= 0 && g < energy_bins) + group_prob[g] += e_probs[i]; + } + + // Monte Carlo estimate of the joint (spatial, angular) distribution. + // Energy is not sampled when solver type is Random Ray. + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + spatial_angle_counts(m, a) = 0.0; + } + } + + for (int64_t i = 0; i < n_samples_per_source; ++i) { + SourceSite site = is->sample(&seed); + + int32_t m = spatial_mesh->get_bin(site.r); + if (m < 0) + continue; + + int32_t a = angle_mesh ? angle_mesh->get_bin(site.u) : 0; + if (angle_mesh && a < 0) + continue; + + spatial_angle_counts(m, a) += 1.0; + } + + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + double frac = spatial_angle_counts(m, a) / n_samples_per_source; + if (frac == 0.0) + continue; + for (int64_t e = 0; e < energy_bins; ++e) { + unbiased_strength_(m, a, e) += + relative_strength * frac * group_prob[e]; + } + } + } + } +} + +void SourceBias::load_forward_source_mesh(const std::string& path) +{ + hid_t file = file_open(path, 'r'); + + std::string filetype; + read_attribute(file, "filetype", filetype); + if (filetype != "forward_source") { + file_close(file); + fatal_error(fmt::format("File '{}' is not a forward source file.", path)); + } + + std::array file_version; + read_attribute(file, "version", file_version); + if (file_version[0] != VERSION_SOURCE_BIAS[0]) { + file_close(file); + fatal_error(fmt::format("File '{}' has version {} which is incompatible " + "with the expected version ({}).", + path, file_version, VERSION_SOURCE_BIAS)); + } + + // Check that the file's spatial mesh matches the one this SourceBias was + // built with. + int32_t spatial_mesh_id; + read_dataset(file, "spatial_mesh", spatial_mesh_id); + int32_t expected_spatial_id = model::meshes[spatial_mesh_idx_]->id(); + if (spatial_mesh_id != expected_spatial_id) { + file_close(file); + fatal_error(fmt::format( + "Spatial mesh in '{}' (id {}) does not match the spatial mesh used " + "for source biasing (id {}).", + path, spatial_mesh_id, expected_spatial_id)); + } + + int32_t angle_mesh_id; + read_dataset(file, "angle_mesh", angle_mesh_id); + int32_t expected_angle_id = + angle_mesh_idx_ == C_NONE ? C_NONE : model::meshes[angle_mesh_idx_]->id(); + if (angle_mesh_id != expected_angle_id) { + file_close(file); + fatal_error(fmt::format( + "Angular mesh in '{}' (id {}) does not match the angular mesh used " + "for source biasing (id {}, or none expected).", + path, angle_mesh_id, expected_angle_id)); + } + + vector file_energy_bounds; + read_dataset(file, "energy_bounds", file_energy_bounds); + if (file_energy_bounds.size() != energy_bounds_.size()) { + file_close(file); + fatal_error(fmt::format( + "Energy group structure in '{}' ({} boundaries) does not match the " + "structure used for source biasing ({} boundaries).", + path, file_energy_bounds.size(), energy_bounds_.size())); + } + for (std::size_t i = 0; i < energy_bounds_.size(); ++i) { + double tol = 1e-6 * std::max(1.0, std::abs(energy_bounds_[i])); + if (std::abs(file_energy_bounds[i] - energy_bounds_[i]) > tol) { + file_close(file); + fatal_error(fmt::format( + "Energy group boundary {} in '{}' ({}) does not match the value " + "used for source biasing ({}).", + i, path, file_energy_bounds[i], energy_bounds_[i])); + } + } + + read_dataset(file, "unbiased_source_strength", unbiased_strength_); + + file_close(file); +} + WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node) { // read information from the XML node @@ -810,6 +1119,12 @@ WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node) } if (check_for_node(node, "source_biasing")) { source_biasing_ = get_node_value_bool(node, "source_biasing"); + if (source_biasing_ && + check_for_node(node, "angular_biasing_quadrature")) { + int32_t angle_mesh_id = + std::stoi(get_node_value(node, "angular_biasing_quadrature")); + angle_mesh_idx_ = model::mesh_map[angle_mesh_id]; + } } } else { fatal_error(fmt::format( @@ -898,6 +1213,39 @@ void WeightWindowsGenerator::create_tally() auto pf = dynamic_cast(particle_filter); pf->set_particles({&particle_type, 1}); ww_tally->add_filter(particle_filter); + + if (!source_biasing_ || method_ != WeightWindowUpdateMethod::FW_CADIS) { + // technically the second condition isn't totally absolute + return; + } + + // Now add a tally for source biasing + Tally* sb_tally = Tally::create(); + sb_tally_idx_ = model::tally_map[sb_tally->id()]; + sb_tally->set_scores({"flux"}); + + // Add same particle, energy, and spatial mesh filters + for (int i = 0; i < ww_tally->filters().size(); ++i) { + sb_tally->add_filter(model::tally_filters[ww_tally->filters(i)].get()); + } + + // Add angular dependency if requested + if (angle_mesh_idx_ != C_NONE) { + auto meshangle_filter = Filter::create("meshangular"); + auto maf = dynamic_cast(meshangle_filter); + maf->set_mesh(angle_mesh_idx_); + sb_tally->add_filter(meshangle_filter); + } + + // Create the object that will hold the accumulated flux data used to + // build a biased forward source once the simulation finishes + auto sb = std::make_unique( + mesh_idx, angle_mesh_idx_, e_bounds, wws->id()); + sb_idx_ = static_cast(variance_reduction::source_biases.size()); + variance_reduction::source_biases.push_back(std::move(sb)); + + // Pre-compute unbiased source strength distribution + variance_reduction::source_biases[sb_idx_]->compute_unbiased_strength(); } void WeightWindowsGenerator::update() const @@ -925,6 +1273,15 @@ void WeightWindowsGenerator::update() const if (!on_the_fly_) tally->reset(); + // Update the source bias flux data the same way, from its own tally + if (source_biasing_ && method_ == WeightWindowUpdateMethod::FW_CADIS) { + Tally* sb_tally = model::tallies[sb_tally_idx_].get(); + variance_reduction::source_biases[sb_idx_]->update(sb_tally); + + if (!on_the_fly_) + sb_tally->reset(); + } + // TODO: deactivate or remove tally once weight window generation is // complete } @@ -1366,6 +1723,45 @@ extern "C" int openmc_weight_windows_export(const char* filename) file_close(ww_file); + // If any source biasing data has been generated, export it too + if (!variance_reduction::source_biases.empty()) { + std::string sb_name = "source_bias.h5"; + + write_message( + fmt::format("Exporting source bias data to {}...", sb_name), 5); + + hid_t sb_file = file_open(sb_name, 'w'); + + write_attribute(sb_file, "filetype", "source_bias"); + write_attribute(sb_file, "version", VERSION_SOURCE_BIAS); + + hid_t sb_mesh_group = create_group(sb_file, "meshes"); + std::vector sb_mesh_ids; + + auto write_mesh_once = [&](int32_t mesh_idx) { + if (mesh_idx == C_NONE) + return; + int32_t mesh_id = model::meshes[mesh_idx]->id(); + if (std::find(sb_mesh_ids.begin(), sb_mesh_ids.end(), mesh_id) != + sb_mesh_ids.end()) + return; + sb_mesh_ids.push_back(mesh_id); + model::meshes[mesh_idx]->to_hdf5(sb_mesh_group); + }; + + for (const auto& sb : variance_reduction::source_biases) { + sb->to_hdf5(sb_file); + write_mesh_once(sb->spatial_mesh_idx()); + write_mesh_once(sb->angle_mesh_idx()); + } + + write_attribute(sb_mesh_group, "n_meshes", sb_mesh_ids.size()); + write_attribute(sb_mesh_group, "ids", sb_mesh_ids); + close_group(sb_mesh_group); + + file_close(sb_file); + } + return 0; } From 0a9566c8bc890b3e5de77969080f43756be74bad Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 10 Sep 2026 12:57:24 -0400 Subject: [PATCH 17/37] formatting c++ and py --- include/openmc/tallies/filter.h | 1 - include/openmc/weight_windows.h | 2 -- openmc/lib/filter.py | 16 ++++++++-------- openmc/settings.py | 2 +- src/source.cpp | 2 +- src/tallies/filter.cpp | 2 -- 6 files changed, 10 insertions(+), 15 deletions(-) diff --git a/include/openmc/tallies/filter.h b/include/openmc/tallies/filter.h index e63003372ef..d78ddadcf72 100644 --- a/include/openmc/tallies/filter.h +++ b/include/openmc/tallies/filter.h @@ -43,7 +43,6 @@ enum class FilterType { PARTICLE_PRODUCTION, POLAR, REACTION, - SOURCE_BIAS, SPHERICAL_HARMONICS, SPATIAL_LEGENDRE, SURFACE, diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index f8eb239167f..894d2aca0ca 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -27,8 +27,6 @@ enum class WeightWindowUpdateMethod { MAGIC, FW_CADIS }; constexpr double DEFAULT_WEIGHT_CUTOFF {1.0e-38}; // default low weight cutoff -constexpr std::array VERSION_SOURCE_BIAS {1, 0}; - //============================================================================== // Global variables //============================================================================== diff --git a/openmc/lib/filter.py b/openmc/lib/filter.py index a6ddd970272..943573381b1 100644 --- a/openmc/lib/filter.py +++ b/openmc/lib/filter.py @@ -495,17 +495,17 @@ class MeshAngularFilter(MeshFilter): This array specifies the angles in degrees about the x, y, and z axes that the mesh should be rotated. The rotation applied is an intrinsic rotation with specified Tait-Bryan angles. That is to say, if the angles - are :math:`(\phi, \theta, \psi)`, then the rotation matrix applied is - :math:`R_z(\psi) R_y(\theta) R_x(\phi)` or + are :math:`(phi, theta, psi)`, then the rotation matrix applied is + :math:`R_z(psi) R_y(theta) R_x(phi)` or .. math:: - \left [ \begin{array}{ccc} \cos\theta \cos\psi & -\cos\phi \sin\psi - + \sin\phi \sin\theta \cos\psi & \sin\phi \sin\psi + \cos\phi - \sin\theta \cos\psi \\ \cos\theta \sin\psi & \cos\phi \cos\psi + - \sin\phi \sin\theta \sin\psi & -\sin\phi \cos\psi + \cos\phi - \sin\theta \sin\psi \\ -\sin\theta & \sin\phi \cos\theta & \cos\phi - \cos\theta \end{array} \right ] + left [ begin{array}{ccc} cos(theta) cos(psi) & -cos(phi) sin(psi) + + sin(phi) sin(theta) cos(psi) & sin(phi) sin(psi) + cos(phi) + sin(theta) cos(psi) cos(theta) sin(psi) & cos(phi) cos(psi) + + sin(phi) sin(theta) sin(psi) & -sin(phi) cos(psi) + cos(phi) + sin(theta) sin(psi) -sin(theta) & sin(phi) cos(theta) & cos(phi) + cos(theta) end{array} right ] A rotation matrix can also be specified directly by setting this attribute to a nested list (or 2D numpy array) that specifies each diff --git a/openmc/settings.py b/openmc/settings.py index 85745d734ae..cdc789cb007 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1396,7 +1396,7 @@ def source_bias_file(self) -> PathLike | None: def source_bias_file(self, value: PathLike | None): if value is None: self._source_bias_file = None - else + else: cv.check_type('source bias file', value, PathLike) self._source_bias_file = input_path(value) diff --git a/src/source.cpp b/src/source.cpp index 00d4e184fd3..b046d6400e1 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -815,7 +815,7 @@ SourceSite CorrelatedSource::sample(uint64_t* seed) const if (!group_bounds_.empty()) { double e_lo = group_bounds_[g]; double e_hi = group_bounds_[g + 1]; - site.E = e_lo * std::pow(e_hi / e_lo, prn(seed)) + site.E = e_lo * std::pow(e_hi / e_lo, prn(seed)); } site.wgt = weights_[flat]; diff --git a/src/tallies/filter.cpp b/src/tallies/filter.cpp index 9be0013c5aa..0db8d7f1568 100644 --- a/src/tallies/filter.cpp +++ b/src/tallies/filter.cpp @@ -157,8 +157,6 @@ Filter* Filter::create(const std::string& type, int32_t id) return Filter::create(id); } else if (type == "reaction") { return Filter::create(id); - } else if (type == "sourcebias") { - return Filter::create(id); } else if (type == "surface") { return Filter::create(id); } else if (type == "spatiallegendre") { From b682c5a3035c781de381e3a7ec03954577d0ab68 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Sat, 12 Sep 2026 18:17:06 -0400 Subject: [PATCH 18/37] write_source_mesh() uses MeshAngularFilter --- openmc/source.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmc/source.py b/openmc/source.py index f775df8e0ee..a8d61a651e0 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -234,7 +234,7 @@ def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase: def write_source_mesh( self, space_mesh: openmc.MeshBase, - angle_mesh: openmc.MeshBase | None, + angle_mesh: openmc.UnitSpherePointset | None, energy_bins: Sequence[float], min_samples: int = 10_000, min_avg_samples_per_voxel: float = 30.0, @@ -324,7 +324,7 @@ def write_source_mesh( # openmc.lib after init; the tally itself is never actually scored. filters = [openmc.MeshFilter(space_mesh)] if angle_mesh is not None: - filters.append(openmc.MeshFilter(angle_mesh)) + filters.append(openmc.MeshAngularFilter(angle_mesh)) dummy_tally = openmc.Tally() dummy_tally.filters = filters dummy_tally.scores = ['flux'] From a70ec594dea4ca1d9165e4f2acfde23eda5aef4d Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Sat, 12 Sep 2026 18:19:57 -0400 Subject: [PATCH 19/37] fix settings source subelement to-xml --- openmc/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmc/settings.py b/openmc/settings.py index cdc789cb007..976533c6831 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1571,7 +1571,7 @@ def _create_source_subelement(self, root, mesh_memo=None): path = f"./mesh[@id='{source.space.mesh.id}']" if root.find(path) is None: root.append(source.space.mesh.to_xml_element()) - if isinstance(source, [MeshSource, CorrelatedSource]): + if isinstance(source, (MeshSource, CorrelatedSource)): path = f"./mesh[@id='{source.mesh.id}']" if root.find(path) is None: root.append(source.mesh.to_xml_element()) From 992bec74eabbf384e3632feb204675ce9669d875 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Sat, 12 Sep 2026 18:27:44 -0400 Subject: [PATCH 20/37] write_source_mesh() variable scoping --- openmc/source.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/openmc/source.py b/openmc/source.py index a8d61a651e0..2440941aa55 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -333,7 +333,9 @@ def write_source_mesh( init_kwargs.setdefault('output', False) init_kwargs.setdefault('args', ['-c']) - S = np.zeros((n_space, n_angle, n_energy)) + counts = np.zeros((n_space, n_angle, n_energy)) + n_drawn = 0 + avg_per_voxel = 0.0 with openmc.lib.TemporarySession(model, **init_kwargs): space_lib_mesh = openmc.lib.meshes[space_mesh.id] @@ -401,7 +403,7 @@ def write_source_mesh( # sites, so that source support falling outside # space_mesh/angle_mesh/energy_bins correctly shows up as # unrepresented probability mass rather than being renormalized away - S /= min_samples + S = counts / n_drawn with h5py.File(filename, 'w') as fh: fh.attrs['filetype'] = np.bytes_('forward_source') From ac1d6dcd3216fff2f14226e1f8f2f3949ca0a098 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Sat, 12 Sep 2026 19:41:50 -0400 Subject: [PATCH 21/37] sample data reshape, working write_source_mesh() --- openmc/source.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/openmc/source.py b/openmc/source.py index 2440941aa55..c03a1bde04e 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -291,6 +291,7 @@ def write_source_mesh( """ import openmc.lib + min_samples = int(min_samples) if max_samples is None: max_samples = 10 * min_samples if max_samples < min_samples: @@ -353,12 +354,8 @@ def write_source_mesh( n_samples=batch_size, as_array=True) n_drawn += batch_size - r = np.stack( - [data['r']['x'], data['r']['y'], data['r']['z']], - axis=-1) - u = np.stack( - [data['u']['x'], data['u']['y'], data['u']['z']], - axis=-1) + r = np.asarray(data['r']) + u = np.asarray(data['u']) E = data['E'] space_bin = _mesh_bin_indices(space_lib_mesh, r) From 3c3fe8bc5c90976962080689835076e84e3b9478 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 14 Sep 2026 08:15:54 -0400 Subject: [PATCH 22/37] correlated source type written to xml --- openmc/source.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openmc/source.py b/openmc/source.py index c03a1bde04e..d5f2ffba048 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -918,7 +918,7 @@ class CorrelatedSource(SourceBase): strength : float Total source strength (sum of `strengths`). type : str - Indicator of source type: 'dependent' + Indicator of source type: 'correlated' """ @@ -932,7 +932,7 @@ def __init__( @property def type(self) -> str: - return "dependent" + return "correlated" @property def mesh(self) -> MeshBase: @@ -961,7 +961,7 @@ def strength(self) -> float: @strength.setter def strength(self, val): if val is not None: - cv.check_type('dependent source strength', val, Real) + cv.check_type('correlated source strength', val, Real) current = self.strength if self.strength != 0.0 else 1.0 self._strengths = self._strengths * (val / current) From 124978a7069b45b0fd51a8c49adc74180c8ef8a4 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 14 Sep 2026 08:37:47 -0400 Subject: [PATCH 23/37] deconflict CorrelatedSource energy bin boundaries with existing energy_bounds xml tag --- openmc/source.py | 4 ++-- src/source.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openmc/source.py b/openmc/source.py index d5f2ffba048..4bba4014b40 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -1061,7 +1061,7 @@ def populate_xml_element(self, elem: ET.Element): if self.angle_mesh is not None: elem.set("angle_mesh", str(self.angle_mesh.id)) if self.energy_bounds is not None: - subelem = ET.SubElement(elem, "energy_bounds") + subelem = ET.SubElement(elem, "group_bounds") subelem.text = ' '.join(str(e) for e in self.energy_bounds) subelem = ET.SubElement(elem, "strengths") subelem.text = ' '.join(str(s) for s in self.strengths) @@ -1101,7 +1101,7 @@ def from_xml_element(cls, elem: ET.Element, meshes) -> CorrelatedSource: source._angle_mesh = ( meshes[int(angle_mesh_id)] if angle_mesh_id is not None else None) - energy_bounds_text = get_text(elem, 'energy_bounds') + energy_bounds_text = get_text(elem, 'group_bounds') source._energy_bounds = ( np.array([float(x) for x in energy_bounds_text.split()]) if energy_bounds_text is not None else None) diff --git a/src/source.cpp b/src/source.cpp index b046d6400e1..a37d6270b72 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -747,8 +747,8 @@ CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) angle_mesh_idx_ = C_NONE; } - if (check_for_node(node, "energy_bounds")) { - group_bounds_ = get_node_array(node, "energy_bounds"); + if (check_for_node(node, "group_bounds")) { + group_bounds_ = get_node_array(node, "group_bounds"); } spatial_bins_ = model::meshes[spatial_mesh_idx_]->n_bins(); From 82d0db28587c73a218eb727e284c901d838c6f0d Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 14 Sep 2026 09:13:32 -0400 Subject: [PATCH 24/37] fix CorrelatedSource angular mesh reading --- openmc/settings.py | 6 ++++++ src/mesh.cpp | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/openmc/settings.py b/openmc/settings.py index 976533c6831..82cb0d2982c 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1577,6 +1577,12 @@ def _create_source_subelement(self, root, mesh_memo=None): root.append(source.mesh.to_xml_element()) if mesh_memo is not None: mesh_memo.add(source.mesh.id) + if isinstance(source, CorrelatedSource) and source.angle_mesh is not None: + path = f"./mesh[@id='{source.angle_mesh.id}']" + if root.find(path) is None: + root.append(source.angle_mesh.to_xml_element()) + if mesh_memo is not None: + mesh_memo.add(source.angle_mesh.id) def _create_volume_calcs_subelement(self, root): for calc in self.volume_calculations: diff --git a/src/mesh.cpp b/src/mesh.cpp index 1a58de7940c..541fab55266 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2567,7 +2567,7 @@ UnitSphereTriangularMesh::UnitSphereTriangularMesh(pugi::xml_node node) } areas_ = get_node_array(node, "areas"); - if (areas_.size() != vertices_.size() % 9) { + if (areas_.size() != vertices_.size() / 9) { fatal_error(fmt::format("Area array for triangular unit sphere mesh {} " "contains the wrong number of elements.", id_)); From 97c5367c075a028997655797c2f0e9c3c1075cda Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 14 Sep 2026 09:40:25 -0400 Subject: [PATCH 25/37] Check vertex ordering in mesh triangularization to ensure positive areas --- openmc/mesh.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/openmc/mesh.py b/openmc/mesh.py index 33346f20c9f..3add92e0181 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3939,16 +3939,26 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): verts = sv.vertices[region] n = len(verts) - areas = np.empty(n) - # Compute area of each spherical triangle - for i in range(n): - v1 = verts[i] - v2 = verts[(i + 1) % n] - - num = np.dot(pole, np.cross(v1, v2)) - denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) - areas[i] = 2 * np.arctan2(num, denom) + def _fan_areas(verts): + areas = np.empty(n) + for i in range(n): + v1 = verts[i] + v2 = verts[(i + 1) % n] + num = np.dot(pole, np.cross(v1, v2)) + denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) + areas[i] = 2 * np.arctan2(num, denom) + return areas + + areas = _fan_areas(verts) + # SphericalVoronoi.sort_vertices_of_regions() does not guarantee a + # globally consistent winding order across all regions. If our function + # returns a negative area, reverse the order of the non-pole vertices + # to correct it. + + if areas.sum() < 0: + verts = verts[::-1] + areas = _fan_areas(verts) total_area = areas.sum() From a722938dbe32d94559b9e6fc7632ff37285e1a99 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 14 Sep 2026 20:29:25 -0400 Subject: [PATCH 26/37] catch nonpositive flux regions in SB update; remove duplicate vertices in mesh triangularization --- openmc/mesh.py | 53 ++++++++++++++++++++++++++++++++---------- src/weight_windows.cpp | 30 ++++++++++++++++++------ 2 files changed, 64 insertions(+), 19 deletions(-) diff --git a/openmc/mesh.py b/openmc/mesh.py index 3add92e0181..4a06ed382c6 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3937,10 +3937,50 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): pole = mesh.points[pole_index] verts = sv.vertices[region] + _, unique_idx = np.unique(np.round(verts, decimals=10), axis=0, + return_index=True) + verts = verts[np.sort(unique_idx)] n = len(verts) - def _fan_areas(verts): + ref = verts[0] - np.dot(pole, verts[0]) * pole + ref_norm = np.linalg.norm(ref) + if ref_norm < 1e-10: + # verts[0] happens to be (nearly) parallel to pole; fall back + # to a different, guaranteed non-parallel reference vector + fallback = (np.array([1.0, 0.0, 0.0]) if abs(pole[0]) < 0.9 + else np.array([0.0, 1.0, 0.0])) + ref = fallback - np.dot(pole, fallback) * pole + ref_norm = np.linalg.norm(ref) + ref /= ref_norm + + angles = np.empty(n) + for i in range(n): + v = verts[i] - np.dot(pole, verts[i]) * pole + v_norm = np.linalg.norm(v) + if v_norm > 1e-10: + v = v / v_norm + cos_a = np.clip(np.dot(ref, v), -1.0, 1.0) + sin_a = np.dot(pole, np.cross(ref, v)) + angles[i] = np.arctan2(sin_a, cos_a) + + verts = verts[np.argsort(angles)] + + areas = np.empty(n) + for i in range(n): + v1 = verts[i] + v2 = verts[(i + 1) % n] + num = np.dot(pole, np.cross(v1, v2)) + denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) + areas[i] = 2 * np.arctan2(num, denom) + + # The sort above guarantees a *consistent* winding (all triangles + # in the fan will agree in sign with each other), but not which + # overall rotational sense (CW vs CCW) that is -- it depends on an + # arbitrary choice baked into the ref/pole/v triple product above. + # Check once per region and flip if needed. + if areas.sum() < 0: + verts = verts[::-1] areas = np.empty(n) for i in range(n): v1 = verts[i] @@ -3948,17 +3988,6 @@ def _fan_areas(verts): num = np.dot(pole, np.cross(v1, v2)) denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) areas[i] = 2 * np.arctan2(num, denom) - return areas - - areas = _fan_areas(verts) - # SphericalVoronoi.sort_vertices_of_regions() does not guarantee a - # globally consistent winding order across all regions. If our function - # returns a negative area, reverse the order of the non-pole vertices - # to correct it. - - if areas.sum() < 0: - verts = verts[::-1] - areas = _fan_areas(verts) total_area = areas.sum() diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index 116bf803812..10a55bd7580 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -839,6 +839,9 @@ void SourceBias::update(const Tally* tally) flat += a * filt_stride[pos_angle]; flux_(m, a, e) = n > 0 ? results(flat, score_index, i_sum) / n : 0.0; + + double raw_sum = results(flat, score_index, i_sum); + flux_(m, a, e) = (n > 0 && raw_sum > 0.0) ? raw_sum / n : 0.0; } } } @@ -864,17 +867,30 @@ void SourceBias::to_hdf5(hid_t group) const tensor::Tensor weights({static_cast(spatial_bins), static_cast(angle_bins), static_cast(energy_bins)}); + double total_B = 0.0; + double total_S = 0.0; + + for (int64_t m = 0; m < spatial_bins; ++m) { + for (int64_t a = 0; a < angle_bins; ++a) { + for (int64_t e = 0; e < energy_bins; ++e) { + double psi = flux_(m, a, e); + double b = psi * unbiased_strength_(m, a, e); + + biased_strength(m, a, e) = b; + total_B += b; + total_S += unbiased_strength_(m, a, e); + } + } + } + + // The correct per-voxel weight is [sum(B)/sum(S)] / flux(voxel) + double weight_norm = (total_S > 0.0) ? total_B / total_S : 1.0; + for (int64_t m = 0; m < spatial_bins; ++m) { for (int64_t a = 0; a < angle_bins; ++a) { for (int64_t e = 0; e < energy_bins; ++e) { double psi = flux_(m, a, e); - biased_strength(m, a, e) = psi * unbiased_strength_(m, a, e); - // A weight is only meaningful where the biased distribution can - // actually place a particle (psi > 0, so B could be nonzero there). - // Elsewhere B is guaranteed to be 0 too (since B = psi * S), so a - // Discrete distribution built from B will never select that voxel - // and this placeholder value is never used. - weights(m, a, e) = psi > 0.0 ? 1.0 / psi : 0.0; + weights(m, a, e) = psi > 0.0 ? weight_norm / psi : 0.0; } } } From 371a4d08428874e2569e082134bac160861dcd93 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 17 Sep 2026 09:12:07 -0400 Subject: [PATCH 27/37] Add source to angular flux and reweight biased source samples to conserve probability mass --- include/openmc/source.h | 3 -- openmc/mesh.py | 7 ++-- openmc/settings.py | 2 +- src/random_ray/flat_source_domain.cpp | 54 ++++++++++++++++++++++++++- src/source.cpp | 8 ++++ src/weight_windows.cpp | 34 +++++++++++------ 6 files changed, 88 insertions(+), 20 deletions(-) diff --git a/include/openmc/source.h b/include/openmc/source.h index a99b7631cf0..1030f6ecc16 100644 --- a/include/openmc/source.h +++ b/include/openmc/source.h @@ -246,9 +246,6 @@ class CorrelatedSource : public Source { int32_t angle_mesh_idx() const { return angle_mesh_idx_; } const vector& group_bounds() const { return group_bounds_; } -protected: - bool constraints_applied() const override { return true; } - private: // Data members int32_t spatial_mesh_idx_ {C_NONE}; //!< Index into model::meshes diff --git a/openmc/mesh.py b/openmc/mesh.py index 4a06ed382c6..054da919607 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3974,10 +3974,9 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) areas[i] = 2 * np.arctan2(num, denom) - # The sort above guarantees a *consistent* winding (all triangles - # in the fan will agree in sign with each other), but not which - # overall rotational sense (CW vs CCW) that is -- it depends on an - # arbitrary choice baked into the ref/pole/v triple product above. + # The sort above guarantees a consistent winding (all triangles + # in the fan will agree in sign with each other), but not the + # overall rotational sense of the winding. # Check once per region and flip if needed. if areas.sum() < 0: verts = verts[::-1] diff --git a/openmc/settings.py b/openmc/settings.py index 82cb0d2982c..01dc92217f5 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1981,7 +1981,7 @@ def _create_weight_window_generators_subelement(self, root, mesh_memo=None): # ensure that mesh elements are created if needed for wwg in self.weight_window_generators: for mesh in (wwg.mesh, wwg.angular_biasing_quadrature): - if mesh_memo is not None and mesh.id in mesh_memo: + if mesh is None or (mesh_memo is not None and mesh.id in mesh_memo): continue # See if a element already exists -- if not, add it diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index cd4e71b0a40..739ba7a482c 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -228,12 +228,36 @@ void FlatSourceDomain::set_flux_to_flux_plus_source( 0.5f * source_regions_.external_source(sr, g) * source_regions_.volume_sq(sr); } + // Divide source term evenly among angular bins + if (source_regions_.needs_angular_flux(sr)) { + float source_term = 0.0f; + if (settings::run_mode == RunMode::FIXED_SOURCE) { + source_term = + source_regions_.external_source(sr, g) / source_regions_.nangles(); + } + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) /= volume; + if (settings::run_mode == RunMode::FIXED_SOURCE) { + source_regions_.angular_flux_new(sr, g, a) += + 0.5f * source_term * source_regions_.volume_sq(sr); + } + } + } } else { double sigma_t = sigma_t_[(material * ntemperature_ + temp) * negroups_ + g] * source_regions_.density_mult(sr); source_regions_.scalar_flux_new(sr, g) /= (sigma_t * volume); source_regions_.scalar_flux_new(sr, g) += source_regions_.source(sr, g); + // Divide source term evenly among angular bins + if (source_regions_.needs_angular_flux(sr)) { + float source_term = + source_regions_.source(sr, g) / source_regions_.nangles(); + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) /= (sigma_t * volume); + source_regions_.angular_flux_new(sr, g, a) += source_term; + } + } } } @@ -241,16 +265,38 @@ void FlatSourceDomain::set_flux_to_old_flux(int64_t sr, int g) { source_regions_.scalar_flux_new(sr, g) = source_regions_.scalar_flux_old(sr, g); + if (source_regions_.needs_angular_flux(sr)) { + // To minimize memory use, we don't store the previous iteration's + // angular fluxes. Recognizing that this case only occurs in the few + // percent or less of source regions missed during an iteration, we + // approximate the angular flux by dividing the scalar flux estimate + // evenly across all angles. + double isotropic_flux = + source_regions_.scalar_flux_new(sr, g) / source_regions_.nangles(); + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) = isotropic_flux; + } + } } void FlatSourceDomain::set_flux_to_source(int64_t sr, int g) { source_regions_.scalar_flux_new(sr, g) = source_regions_.source(sr, g); + if (source_regions_.needs_angular_flux(sr)) { + // Divide source term evenly across angles + float source_term = + source_regions_.source(sr, g) / source_regions_.nangles(); + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) = source_term; + } + } } // Combine transport flux contributions and flat source contributions from the // previous iteration to generate this iteration's estimate of scalar flux. -// Not performed for angular flux as sources are isotropic +// Source terms are evenly distributed across angular flux as sources are +// isotropic; this however assumes that the reference angles' Voronoi cells +// subtend approximately equal solid angles on the surface of the unit sphere. int64_t FlatSourceDomain::add_source_to_scalar_flux() { int64_t n_hits = 0; @@ -2041,6 +2087,12 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const // stored in the referenced angular mesh. int FlatSourceDomain::lookup_angular_bin(Direction u) const { + if (solve_ == RandomRaySolve::ADJOINT) { + // Flip direction in adjoint mode, since the ray is actually traveling in + // the direction -(Omega), whereas we want to tally the importance of a + // particle traveling in the forward direction Omega + u = -u; + } return angular_mesh_->get_bin(u); } diff --git a/src/source.cpp b/src/source.cpp index a37d6270b72..6eb3478ca35 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -6,6 +6,7 @@ #include // for max #include // for sin, cos, abs +#include // for accumulate #include // for move #ifdef HAS_DYNAMIC_LINKING @@ -768,6 +769,13 @@ CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) "implied by its mesh(es) and energy bounds ({}).", strengths.size(), n_voxels)); } + double total_strength = + std::accumulate(strengths.begin(), strengths.end(), 0.0); + if (std::fabs(total_strength - 1.0) > FP_PRECISION) { + for (auto& element : strengths) { + element /= total_strength; + } + } weights_ = get_node_array(node, "weights"); if (weights_.size() != n_voxels) { diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index 10a55bd7580..6aacf22bd3e 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -838,8 +838,6 @@ void SourceBias::update(const Tally* tally) if (pos_angle != -1) flat += a * filt_stride[pos_angle]; - flux_(m, a, e) = n > 0 ? results(flat, score_index, i_sum) / n : 0.0; - double raw_sum = results(flat, score_index, i_sum); flux_(m, a, e) = (n > 0 && raw_sum > 0.0) ? raw_sum / n : 0.0; } @@ -867,30 +865,44 @@ void SourceBias::to_hdf5(hid_t group) const tensor::Tensor weights({static_cast(spatial_bins), static_cast(angle_bins), static_cast(energy_bins)}); - double total_B = 0.0; - double total_S = 0.0; - + // Calculate biasing parameters and simultaneously check to see if any + // voxels containing probability mass associated with the unbiased source + // have not been sampled. + double total_strength = 0.0; + double total_missed_S = 0.0; for (int64_t m = 0; m < spatial_bins; ++m) { for (int64_t a = 0; a < angle_bins; ++a) { for (int64_t e = 0; e < energy_bins; ++e) { double psi = flux_(m, a, e); double b = psi * unbiased_strength_(m, a, e); - biased_strength(m, a, e) = b; - total_B += b; - total_S += unbiased_strength_(m, a, e); + total_strength += b; + if (psi <= 0.0) { + total_missed_S += unbiased_strength_(m, a, e); + } } } } - // The correct per-voxel weight is [sum(B)/sum(S)] / flux(voxel) - double weight_norm = (total_S > 0.0) ? total_B / total_S : 1.0; + if (total_missed_S > TINY_BIT) { + fatal_error(fmt::format("Biased source does not sample whole support of " + "the unbiased source. Probability mass lost in " + "regions with nonpositive adjoint flux: {}.", + total_missed_S)); + } + // Rescale biased strengths so that they add up to probability 1.0. + // This would be done anyway by the DiscreteIndex inside of CorrelatedSource + // when sampling a phase space bin, but the normalization should be done + // beforehand so that source's .strength() attribute still appears as 1.0. + // Also apply sample weight of (total_strength / psi) so that total + // probability mass still equals 1.0. for (int64_t m = 0; m < spatial_bins; ++m) { for (int64_t a = 0; a < angle_bins; ++a) { for (int64_t e = 0; e < energy_bins; ++e) { double psi = flux_(m, a, e); - weights(m, a, e) = psi > 0.0 ? weight_norm / psi : 0.0; + weights(m, a, e) = psi > 0.0 ? total_strength / psi : 0.0; + biased_strength(m, a, e) /= total_strength; } } } From b60ee95787cc4b6bf9eabc0f32b45132e133b3ed Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 8 Oct 2026 12:32:45 -0400 Subject: [PATCH 28/37] Move write_forward_source_mesh to model to capture all forward sources simultaneously --- openmc/model/model.py | 173 +++++++++++++++++++++++++++++++++++ openmc/source.py | 205 ------------------------------------------ 2 files changed, 173 insertions(+), 205 deletions(-) diff --git a/openmc/model/model.py b/openmc/model/model.py index e64ea3f6205..7bf6e0e39a7 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1542,6 +1542,179 @@ def sample_external_source( return openmc.lib.sample_external_source( n_samples=n_samples, prn_seed=prn_seed, as_array=as_array ) + + def write_forward_source_mesh( + self, + space_mesh: openmc.MeshBase, + angle_mesh: openmc.UnitSpherePointset | None, + energy_bins: Sequence[float], + min_samples: int = 10000, + min_samples_per_voxel: float = 30.0, + max_samples: int | None = None, + filename: PathLike = 'forward_source_mesh.h5', + **init_kwargs, + ) -> None: + """Precompute this source's strength on a (space, angle, energy) grid + and write it to an HDF5 file for FW-CADIS source biasing. + + This is meant to accommodate biasing sources that aren't + :class:`IndependentSource` instances, under the assumption that a + geometrically simpler "lookalike" :class:`IndependentSource` is used + in the Random Ray solve to estimate adjoint source strengths. + + Parameters + ---------- + space_mesh : openmc.MeshBase + Spatial mesh to bin sampled source positions into. Should match + the mesh that will be used for the corresponding random ray + source-biasing tally. + angle_mesh : openmc.MeshBase or None + Angular mesh (over the unit sphere) to bin sampled source + directions into. If None, emission is recorded as a single + (isotropic) angle bin. + energy_bins : sequence of float + Ascending energy group boundaries in [eV], matching the group + structure used for the corresponding random ray source-biasing + tally. + min_samples : int + Number of source sites to sample. + min_samples_per_voxel : float + Minimum median number of samples per occupied (spatial, angle, + energy) voxel. + max_samples : int or None + Maximum total number of source sites sampled. Issues a warning + if this cap is reached before min_samples_per_voxel is + satisfied. Defaults to ``10 * min_samples``. + filename : path-like + Path to write the resulting HDF5 file to. + **init_kwargs + Keyword arguments passed to :func:`openmc.lib.init` (via + :class:`openmc.lib.TemporarySession`) + """ + import openmc.lib + + # Verify that the model run mode is fixed source + if self.settings.run_mode != 'fixed source': + raise ValueError( + f'Forward source mesh cannot be written in ' + f'{self.settings.run_mode} mode (requires ''fixed source'').') + + min_samples = int(min_samples) + if max_samples is None: + max_samples = 10 * min_samples + if max_samples < min_samples: + raise ValueError( + f'max_samples ({max_samples}) must be >= min_samples ' + f'({min_samples}).') + + energy_bins = np.asarray(energy_bins, dtype=float) + if energy_bins.ndim != 1 or energy_bins.size < 2: + raise ValueError( + 'energy_bins must be a 1-D sequence with at least two ' + 'entries.') + n_energy = energy_bins.size - 1 + + n_space = space_mesh.n_elements + n_angle = angle_mesh.n_elements if angle_mesh is not None else 1 + + # Attach the meshes to a dummy tally so that openmc.lib mesh + # objects exist for bin lookup later. + filters = [openmc.MeshFilter(space_mesh)] + if angle_mesh is not None: + filters.append(openmc.MeshAngularFilter(angle_mesh)) + dummy_tally = openmc.Tally() + dummy_tally.filters = filters + dummy_tally.scores = ['flux'] + self.tallies.append(dummy_tally) + + init_kwargs.setdefault('output', False) + init_kwargs.setdefault('args', ['-c']) + + counts = np.zeros((n_space, n_angle, n_energy)) + n_drawn = 0 + median = 0.0 + + # Helper function to return the flattened mesh bin index of each + # sample, or -1 for points not inside the mesh + def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: + bins = np.empty(len(points), dtype=int) + for i, p in enumerate(points): + bins[i] = lib_mesh.get_bin(p) + return bins + + with openmc.lib.TemporarySession(self, **init_kwargs): + space_lib_mesh = openmc.lib.meshes[space_mesh.id] + angle_lib_mesh = ( + openmc.lib.meshes[angle_mesh.id] + if angle_mesh is not None else None + ) + + while True: + batch_size = min(min_samples, max_samples - n_drawn) + if batch_size <= 0: + break + + data = openmc.lib.sample_external_source( + n_samples=batch_size, as_array=True) + n_drawn += batch_size + + r = np.asarray(data['r']) + u = np.asarray(data['u']) + E = data['E'] + + space_bin = _mesh_bin_indices(space_lib_mesh, r) + valid = space_bin >= 0 + + if angle_lib_mesh is not None: + angle_bin = _mesh_bin_indices(angle_lib_mesh, u) + valid &= angle_bin >= 0 + else: + angle_bin = np.zeros(len(r), dtype=int) + + energy_bin = np.digitize(E, energy_bins) - 1 + valid &= (energy_bin >= 0) & (energy_bin < n_energy) + + np.add.at( + counts, + (space_bin[valid], angle_bin[valid], energy_bin[valid]), + 1.0) + + # Compute median samples per voxel among voxels sampled at + # least once so far + median = np.median(counts[counts != 0]) + + if median >= min_samples_per_voxel: + break + if n_drawn >= max_samples: + break + + if median < min_samples_per_voxel: + warnings.warn( + f"write_source_mesh reached max_samples ({max_samples}) " + f"with a median count of only {median:.1f} samples per " + f"occupied voxel (targeted {min_samples_per_voxel}). " + "Consider raising max_samples or coarsening " + "space_mesh/angle_mesh/energy_bins." + ) + + # Normalize by the total number of samples drawn, including rejected + # sites, so that the mesh accurately describes source support falling + # only inside space_mesh/angle_mesh/energy_bins + S = counts / n_drawn + + with h5py.File(filename, 'w') as fh: + fh.attrs['filetype'] = np.bytes_('forward_source') + fh.attrs['version'] = np.array([1, 0]) + fh.create_dataset('spatial_mesh', data=space_mesh.id) + # -1 used for angle-independent biasing + fh.create_dataset( + 'angle_mesh', + data=angle_mesh.id if angle_mesh is not None else -1) + fh.create_dataset('energy_bounds', data=energy_bins) + fh.create_dataset('unbiased_source_strength', data=S) + + # Remove the dummy tally from earlier + self.tallies.remove(dummy_tally) def apply_tally_results(self, statepoint: PathLike | openmc.StatePoint): """Apply results from a statepoint to tally objects on the Model diff --git a/openmc/source.py b/openmc/source.py index 4bba4014b40..fbd134a7b20 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -22,29 +22,6 @@ from .statepoint import _VERSION_STATEPOINT from .utility_funcs import input_path - -def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: - """Return the flattened mesh bin index containing each point, or -1 for - points outside the mesh. - - Parameters - ---------- - lib_mesh - An ``openmc.lib`` mesh object (e.g. ``openmc.lib.meshes[mesh_id]``) - points : numpy.ndarray - Array of shape (N, 3) giving Cartesian points to look up - - Returns - ------- - numpy.ndarray - Array of shape (N,) giving the bin index of each point, or -1 if - the point is outside the mesh - """ - bins = np.empty(len(points), dtype=int) - for i, p in enumerate(points): - bins[i] = lib_mesh.get_bin(p) - return bins - class SourceBase(ABC): """Base class for external sources @@ -230,188 +207,6 @@ def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase: else: raise ValueError( f'Source type {source_type} is not recognized') - - def write_source_mesh( - self, - space_mesh: openmc.MeshBase, - angle_mesh: openmc.UnitSpherePointset | None, - energy_bins: Sequence[float], - min_samples: int = 10_000, - min_avg_samples_per_voxel: float = 30.0, - max_samples: int | None = None, - filename: PathLike = 'forward_source_mesh.h5', - region_size: float = 1.0e5, - **init_kwargs, - ) -> None: - """Precompute this source's strength on a (space, angle, energy) grid - and write it to an HDF5 file for FW-CADIS source biasing. - - This is meant to accommodate biasing sources that aren't - :class:`IndependentSource` instances, under the assumption that a - geometrically simpler "lookalike" :class:`IndependentSource` is used - in the Random Ray solve to estimate adjoint flux data. - - Parameters - ---------- - space_mesh : openmc.MeshBase - Spatial mesh to bin sampled source positions into. Should match - the mesh that will be used for the corresponding random ray - source-biasing tally. - angle_mesh : openmc.MeshBase or None - Angular mesh (over the unit sphere) to bin sampled source - directions into. If None, emission is recorded as a single - (isotropic) angle bin. - energy_bins : sequence of float - Ascending energy group boundaries in [eV], matching the group - structure used for the corresponding random ray source-biasing - tally. - min_samples : int - Number of source sites to sample. - min_avg_samples_per_voxel : float - Target average number of samples per occupied (spatial, angle, - energy) voxel. - max_samples : int or None - Maximum total number of source sites sampled. Issues a warning - if this cap is reached before min_avg_samples_per_voxel is - satisfied. Defaults to ``10 * min_samples``. - filename : path-like - Path to write the resulting HDF5 file to. - region_size : float - Half-width in [cm] of the placeholder void region this source is - sampled within. Must be large enough to contain the full - spatial extent of both this source and space_mesh -- increase - this if source sites are unexpectedly missing from the result. - **init_kwargs - Keyword arguments passed to :func:`openmc.lib.init` (via - :class:`openmc.lib.TemporarySession`) - - See Also - -------- - openmc.Model.sample_external_source - """ - import openmc.lib - - min_samples = int(min_samples) - if max_samples is None: - max_samples = 10 * min_samples - if max_samples < min_samples: - raise ValueError( - f'max_samples ({max_samples}) must be >= min_samples ' - f'({min_samples}).') - - energy_bins = np.asarray(energy_bins, dtype=float) - if energy_bins.ndim != 1 or energy_bins.size < 2: - raise ValueError( - 'energy_bins must be a 1-D sequence with at least two ' - 'entries.') - n_energy = energy_bins.size - 1 - - n_space = space_mesh.n_elements - n_angle = angle_mesh.n_elements if angle_mesh is not None else 1 - - # Build a minimal model containing only this source - half = region_size - box = openmc.model.RectangularParallelepiped( - -half, half, -half, half, -half, half, boundary_type='vacuum') - placeholder_cell = openmc.Cell(region=-box) - placeholder_universe = openmc.Universe(cells=[placeholder_cell]) - - model = openmc.Model() - model.geometry.root_universe = placeholder_universe - model.settings.run_mode = 'fixed source' - model.settings.source = [self] - - # Attach the meshes to a tally so they are available through - # openmc.lib after init; the tally itself is never actually scored. - filters = [openmc.MeshFilter(space_mesh)] - if angle_mesh is not None: - filters.append(openmc.MeshAngularFilter(angle_mesh)) - dummy_tally = openmc.Tally() - dummy_tally.filters = filters - dummy_tally.scores = ['flux'] - model.tallies = openmc.Tallies([dummy_tally]) - - init_kwargs.setdefault('output', False) - init_kwargs.setdefault('args', ['-c']) - - counts = np.zeros((n_space, n_angle, n_energy)) - n_drawn = 0 - avg_per_voxel = 0.0 - - with openmc.lib.TemporarySession(model, **init_kwargs): - space_lib_mesh = openmc.lib.meshes[space_mesh.id] - angle_lib_mesh = ( - openmc.lib.meshes[angle_mesh.id] - if angle_mesh is not None else None - ) - - while True: - batch_size = min(min_samples, max_samples - n_drawn) - if batch_size <= 0: - break - - data = openmc.lib.sample_external_source( - n_samples=batch_size, as_array=True) - n_drawn += batch_size - - r = np.asarray(data['r']) - u = np.asarray(data['u']) - E = data['E'] - - space_bin = _mesh_bin_indices(space_lib_mesh, r) - valid = space_bin >= 0 - - if angle_lib_mesh is not None: - angle_bin = _mesh_bin_indices(angle_lib_mesh, u) - valid &= angle_bin >= 0 - else: - angle_bin = np.zeros(len(r), dtype=int) - - energy_bin = np.digitize(E, energy_bins) - 1 - valid &= (energy_bin >= 0) & (energy_bin < n_energy) - - np.add.at( - counts, - (space_bin[valid], angle_bin[valid], energy_bin[valid]), - 1.0) - - # Average samples per voxel among voxels sampled at least - # once so far. counts.sum() equals the sum over just the - # occupied voxels, since unoccupied ones are still zero. - n_occupied = np.count_nonzero(counts > 0) - avg_per_voxel = ( - counts.sum() / n_occupied if n_occupied else 0.0) - - if avg_per_voxel >= min_avg_samples_per_voxel: - break - if n_drawn >= max_samples: - break - - if avg_per_voxel < min_avg_samples_per_voxel: - warnings.warn( - f"write_source_mesh reached max_samples ({max_samples}) " - f"with an average of only {avg_per_voxel:.1f} samples per " - f"occupied voxel (wanted {min_avg_samples_per_voxel}). " - "Consider raising max_samples or coarsening " - "space_mesh/angle_mesh/energy_bins." - ) - - # Normalize by the total number of samples drawn, including rejected - # sites, so that source support falling outside - # space_mesh/angle_mesh/energy_bins correctly shows up as - # unrepresented probability mass rather than being renormalized away - S = counts / n_drawn - - with h5py.File(filename, 'w') as fh: - fh.attrs['filetype'] = np.bytes_('forward_source') - fh.attrs['version'] = np.array([1, 0]) - fh.create_dataset('spatial_mesh', data=space_mesh.id) - # -1 used for angle-independent biasing - fh.create_dataset( - 'angle_mesh', - data=angle_mesh.id if angle_mesh is not None else -1) - fh.create_dataset('energy_bounds', data=energy_bins) - fh.create_dataset('unbiased_source_strength', data=S) @staticmethod def _get_constraints(elem: ET.Element) -> dict[str, Any]: From 2991a6d2d7e5d7bfa3bb1ba73fadac9657108d4e Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 9 Oct 2026 16:24:23 -0400 Subject: [PATCH 29/37] Allow renamed forward source mesh, UnitSphere mesh triangulation by Delaunay and ear-clipping, remove unused settings.source_bias_file --- include/openmc/settings.h | 2 - include/openmc/weight_windows.h | 31 ++-- openmc/mesh.py | 272 +++++++++++++++++++++++++++----- openmc/settings.py | 29 ---- openmc/source.py | 8 +- openmc/weight_windows.py | 36 ++++- src/settings.cpp | 6 - src/weight_windows.cpp | 16 +- 8 files changed, 296 insertions(+), 104 deletions(-) diff --git a/include/openmc/settings.h b/include/openmc/settings.h index dd416577384..3ad5f502c95 100644 --- a/include/openmc/settings.h +++ b/include/openmc/settings.h @@ -116,8 +116,6 @@ extern std::string path_sourcepoint; //!< path to a source file extern std::string path_statepoint; //!< path to a statepoint file extern std::string weight_windows_file; //!< Location of weight window file to //!< load on simulation initialization -extern std::string source_bias_file; //!< Location of source bias file from - //!< FW-CADIS extern std::string properties_file; //!< Location of properties file to //!< load on simulation initialization diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index 894d2aca0ca..b650674f095 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -217,8 +217,10 @@ class SourceBias { //! \param[in] energy_bounds Energy group boundaries [eV] //! \param[in] ww_id ID of the WeightWindows object this source bias is //! generated alongside (used to name this object's HDF5 group) + //! \param[in] forward_source_mesh Path to unbiased source strength mesh file SourceBias(int32_t spatial_mesh_idx, int32_t angle_mesh_idx, - vector energy_bounds, int32_t ww_id); + vector energy_bounds, int32_t ww_id, + std::string forward_source_mesh); //---------------------------------------------------------------------------- // Methods @@ -237,22 +239,24 @@ class SourceBias { int32_t spatial_mesh_idx() const { return spatial_mesh_idx_; } int32_t angle_mesh_idx() const { return angle_mesh_idx_; } + std::string forward_source_mesh() const { return forward_source_mesh_; } //! Estimate the unbiased external source's strength as a function of //! spatial mesh element, angular mesh element, and energy group, assuming //! isotropic emission when no angular mesh is present. //! - //! If a file named "forward_source_mesh.h5" is present, it is used directly - //! in place of sampling model::external_sources. Its spatial mesh, angular - //! mesh, and energy group structure are checked against spatial_mesh_, - //! angle_mesh_, and energy_bounds_ before use. + //! If the source strengths are already written to a file + //! such as "forward_source_mesh.h5", that data is used directly in place of + //! sampling model::external_sources. Its spatial mesh, angular mesh, and + //! energy group structure are checked against spatial_mesh_, angle_mesh_, + //! and energy_bounds_ before use. //! //! Otherwise, group probabilities are read exactly from each source's //! Discrete energy spectrum, while the spatial and angular dimensions are //! estimated by binning samples into (spatial_mesh_, angle_mesh_). //! //! \param[in] n_samples_per_source Number of trial (position, direction) - //! pairs to draw per external source. Unused if - //! "forward_source_mesh.h5" is present. + //! pairs to draw per external source. Unused if forward source mesh file + //! is present. void compute_unbiased_strength(int64_t n_samples_per_source = 1000000); const tensor::Tensor& unbiased_strength() const @@ -262,16 +266,17 @@ class SourceBias { private: //! Read a precomputed unbiased source strength distribution from a - //! "forward_source_mesh.h5"-format file + //! forward source mesh file void load_forward_source_mesh(const std::string& path); //---------------------------------------------------------------------------- // Data members - int32_t spatial_mesh_idx_; //!< Index into model::meshes - int32_t angle_mesh_idx_; //!< Index into model::meshes, or C_NONE - vector energy_bounds_; //!< Energy group boundaries [eV] - int32_t ww_id_; //!< ID of the associated WeightWindows + int32_t spatial_mesh_idx_; //!< Index into model::meshes + int32_t angle_mesh_idx_; //!< Index into model::meshes, or C_NONE + vector energy_bounds_; //!< Energy group boundaries [eV] + int32_t ww_id_; //!< ID of the associated WeightWindows + std::string forward_source_mesh_; //!< Path to unbiased source strengths file //! Un-normalized mean flux. Shape: (spatial_bins, angle_bins, //! energy_bins). angle_bins == 1 when angle_mesh_idx_ == C_NONE. @@ -318,6 +323,8 @@ class WeightWindowsGenerator { bool source_biasing_; int32_t angle_mesh_idx_ {C_NONE}; // 3: + m = len(indices) + ear_found = False + for ii in range(m): + i_prev = indices[(ii - 1) % m] + i_curr = indices[ii] + i_next = indices[(ii + 1) % m] + a, b, c = points_2d[i_prev], points_2d[i_curr], points_2d[i_next] + + cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if not cross > 0: + continue + + # Make sure there are no other polygon vertices inside the + # candidate triangle + occupied = False + for k in indices: + if k in (i_prev, i_curr, i_next): + continue + + def _sign(p1, p2, p3): + return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]) + + d1 = _sign(points_2d[k], a, b) + d2 = _sign(points_2d[k], b, c) + d3 = _sign(points_2d[k], c, a) + has_neg = (d1 < 0) or (d2 < 0) or (d3 < 0) + has_pos = (d1 > 0) or (d2 > 0) or (d3 > 0) + + # determine if point p lies inside (or on the boundary of) + # triangle abc, assuming a, b, c are given in CCW order + if not (has_neg and has_pos): + occupied = True + break + if occupied: + continue + + triangles.append((i_prev, i_curr, i_next)) + indices.pop(ii) + ear_found = True + break + + if not ear_found: + # fall back to fan triangulation of remaining polygon + for ii in range(1, len(indices) - 1): + triangles.append((indices[0], indices[ii], indices[ii + 1])) + indices = [] + break + + if len(indices) == 3: + triangles.append(tuple(indices)) + + return triangles + +def triangulate_unit_sphere_mesh(mesh, data=None, broadcast_data=None, method='delaunay'): """Convert a UnitSpherePointset to a UnitSphereTriangularMesh. This function takes a UnitSpherePointset, as well as optional dataset(s) defined on said mesh, and converts it to a triangular mesh of the unit - sphere by performing a star triangularization of the Voronoi cells - generated by the UnitSpherePointset. + sphere by performing a Delaunay, ear-clipping, or star triangulation of + the Voronoi cells generated by the UnitSpherePointset. + + By default, a Delaunay triangulation of the vertices of each region in + the spherical Voronoi diagram is performed. The ear-clipping and star + triangulation algorithms may be selected instead for faster execution, but + do not offer the same optimization of triangle shape for sampling. Star + triangulation additionally produces m triangles from a Voronoi cell with m + vertices, while Delaunay and ear-clipping algorithms yield (m-2) triangles. - Two different methods are provided for redistributing provided data onto - the triangularized mesh: + Two different methods are also provided for redistributing scalar data onto + the triangulated mesh: - Data provided in the `data` field is treated as extensive (e.g. a probability mass or reaction rate): new values are computed @@ -3894,6 +4050,9 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): broadcast_data : numpy.ndarray, optional Intensive per-point data of shape (N, ...) to copy unchanged onto every new triangle belonging to its parent point. + method : {'delaunay', 'ear clipping', 'star'} + Method by which to perform the triangulation of the Voronoi region + about each point. Returns ------- @@ -3904,7 +4063,7 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): new_broadcast_data : (M, ...) ndarray of float Only returned if `broadcast_data` was provided. """ - cv.check_type("mesh for triangularization", mesh, UnitSpherePointset) + cv.check_type("mesh for triangulation", mesh, UnitSpherePointset) n_points = len(mesh.points) if data is not None: @@ -3913,7 +4072,7 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): raise ValueError( f"First dimension of data array ({data.shape[0]}) does not " f"match number of points in UnitSpherePointset for " - f"triangularization (expected {n_points})" + f"triangulation (expected {n_points})" ) new_data = [] @@ -3923,7 +4082,7 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): raise ValueError( f"First dimension of broadcast_data array " f"({broadcast_data.shape[0]}) does not match number of " - f"points in UnitSpherePointset for triangularization " + f"points in UnitSpherePointset for triangulation " f"(expected {n_points})" ) new_broadcast_data = [] @@ -3953,8 +4112,13 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): ref = fallback - np.dot(pole, fallback) * pole ref_norm = np.linalg.norm(ref) ref /= ref_norm + # Second basis vector in the plane normal to the pole, used for + # Delaunay and ear-clipping triangulation + perp = np.cross(pole, ref) angles = np.empty(n) + coords_2d = np.empty((n, 2)) # vertex coordinates for Delaunay + # and ear-clipping for i in range(n): v = verts[i] - np.dot(pole, verts[i]) * pole v_norm = np.linalg.norm(v) @@ -3963,49 +4127,75 @@ def triangularize_unit_sphere_mesh(mesh, data=None, broadcast_data=None): cos_a = np.clip(np.dot(ref, v), -1.0, 1.0) sin_a = np.dot(pole, np.cross(ref, v)) angles[i] = np.arctan2(sin_a, cos_a) + coords_2d[i] = (np.dot(ref, v), np.dot(perp, v)) - verts = verts[np.argsort(angles)] + order = np.argsort(angles) + verts = verts[order] + coords_2d = coords_2d[order] - areas = np.empty(n) - for i in range(n): - v1 = verts[i] - v2 = verts[(i + 1) % n] - num = np.dot(pole, np.cross(v1, v2)) - denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) - areas[i] = 2 * np.arctan2(num, denom) - - # The sort above guarantees a consistent winding (all triangles - # in the fan will agree in sign with each other), but not the - # overall rotational sense of the winding. - # Check once per region and flip if needed. - if areas.sum() < 0: - verts = verts[::-1] + # Get areas corresponding to a star (centroid-fan) triangulation of + # the region and use them to determine correct vertex winding + def _fan_areas(verts): areas = np.empty(n) for i in range(n): v1 = verts[i] v2 = verts[(i + 1) % n] - num = np.dot(pole, np.cross(v1, v2)) - denom = 1 + np.dot(pole, v1) + np.dot(v1, v2) + np.dot(v2, pole) - areas[i] = 2 * np.arctan2(num, denom) + areas[i] = _spherical_triangle_area(pole, v1, v2) + + return areas - total_area = areas.sum() + areas = _fan_areas(verts) - for i in range(n): - v1 = verts[i] - v2 = verts[(i + 1) % n] + # The sort above gives a consistent winding linking all triangles + # but not the overall rotational sense of the winding. Check sign and + # flip if needed. + if areas.sum() < 0: + verts = verts[::-1] + coords_2d = coords_2d[::-1] + areas = _fan_areas(verts) - triangle = np.stack((pole, v1, v2)) + total_area = areas.sum() - faces.append( - SphericalTriangle( - vertices=triangle, - area=areas[i] - ) - ) - if data is not None: - new_data.append(data[pole_index] * areas[i] / total_area) - if broadcast_data is not None: - new_broadcast_data.append(broadcast_data[pole_index]) + if method == 'star': + for i in range(n): + v1 = verts[i] + v2 = verts[(i + 1) % n] + faces.append(SphericalTriangle( + vertices=np.stack((pole, v1, v2)), area=areas[i])) + if data is not None: + new_data.append(data[pole_index] * areas[i] / total_area) + if broadcast_data is not None: + new_broadcast_data.append(broadcast_data[pole_index]) + else: + if method == 'delaunay': + triangles = _delaunay_triangulate_convex_2d(coords_2d) + elif method == 'ear clipping': + triangles = _ear_clip_2d(coords_2d) + else: + raise ValueError( + f"{method} is not a recognized triangulation method (must be " + f"one of ''delaunay'',''star'' or ''ear clipping'').") + tri_areas = np.array([ + _spherical_triangle_area(verts[i], verts[j], verts[k]) + for i, j, k in triangles + ]) + # Near-degenerate triangles (nearly all points on same great-circle + # arc) may give small, negative areas and may break the sampling + # algorithm, so we neglect them + tri_areas = np.clip(tri_areas, 0.0, None) + tri_total = tri_areas.sum() + # Rescale to match total area we calculated earlier + if tri_total > 0: + tri_areas *= total_area / tri_total + + for (i, j, k), area in zip(triangles, tri_areas): + faces.append(SphericalTriangle( + vertices=np.stack((verts[i], verts[j], verts[k])), + area=area)) + if data is not None: + new_data.append(data[pole_index] * area / total_area) + if broadcast_data is not None: + new_broadcast_data.append(broadcast_data[pole_index]) new_mesh = UnitSphereTriangularMesh(faces) diff --git a/openmc/settings.py b/openmc/settings.py index 01dc92217f5..6cfa673a7c9 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -395,9 +395,6 @@ class Settings: Path to a weight window file to load during simulation initialization .. versionadded::0.14.0 - - source_bias_file: Pathlike - Path to a file containing source biasing parameters generated via FW-CADIS write_initial_source : bool Indicate whether to write the initial source distribution to file @@ -497,7 +494,6 @@ def __init__(self, **kwargs): self._weight_windows_on = None self._shared_secondary_bank = None self._weight_windows_file = None - self._source_bias_file = None self._weight_window_checkpoints = {} self._max_history_splits = None self._max_tracks = None @@ -1387,18 +1383,6 @@ def weight_windows_file(self, value: PathLike | None): else: cv.check_type('weight windows file', value, PathLike) self._weight_windows_file = input_path(value) - - @property - def source_bias_file(self) -> PathLike | None: - return self._source_bias_file - - @source_bias_file.setter - def source_bias_file(self, value: PathLike | None): - if value is None: - self._source_bias_file = None - else: - cv.check_type('source bias file', value, PathLike) - self._source_bias_file = input_path(value) @property def weight_window_generators(self) -> list[WeightWindowGenerator]: @@ -1996,12 +1980,6 @@ def _create_weight_windows_file_element(self, root): element = ET.Element("weight_windows_file") element.text = str(self.weight_windows_file) root.append(element) - - def _create_source_bias_file_element(self, root): - if self.source_bias_file is not None: - element = ET.element("source_bias_file") - element.text = str(self.source_bias_file) - root.append(element) def _create_weight_window_checkpoints_subelement(self, root): if not self._weight_window_checkpoints: @@ -2494,11 +2472,6 @@ def _weight_windows_file_from_xml_element(self, root): if text is not None: self.weight_windows_file = text - def _source_bias_file_from_xml_element(self, root): - text = get_text(root, "source_bias_file") - if text is not None: - self.source_bias_file = text - def _weight_window_checkpoints_from_xml_element(self, root): elem = root.find('weight_window_checkpoints') if elem is None: @@ -2664,7 +2637,6 @@ def to_xml_element(self, mesh_memo=None): self._create_shared_secondary_bank_subelement(element) self._create_weight_window_generators_subelement(element, mesh_memo) self._create_weight_windows_file_element(element) - self._create_source_bias_file_element(element) self._create_weight_window_checkpoints_subelement(element) self._create_max_history_splits_subelement(element) self._create_max_tracks_subelement(element) @@ -2782,7 +2754,6 @@ def from_xml_element(cls, elem, meshes=None): settings._weight_windows_on_from_xml_element(elem) settings._shared_secondary_bank_from_xml_element(elem) settings._weight_windows_file_from_xml_element(elem) - settings._source_bias_file_from_xml_element(elem) settings._weight_window_generators_from_xml_element(elem, meshes) settings._weight_window_checkpoints_from_xml_element(elem) settings._max_history_splits_from_xml_element(elem) diff --git a/openmc/source.py b/openmc/source.py index fbd134a7b20..1c7a9663e5c 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -17,7 +17,7 @@ from openmc.stats.multivariate import UnitSphere, Spatial from openmc.stats.univariate import Univariate from ._xml import get_elem_list, get_text -from .mesh import MeshBase, StructuredMesh, UnstructuredMesh, UnitSpherePointset, triangularize_unit_sphere_mesh +from .mesh import MeshBase, StructuredMesh, UnstructuredMesh, UnitSpherePointset, triangulate_unit_sphere_mesh from .particle_type import ParticleType from .statepoint import _VERSION_STATEPOINT from .utility_funcs import input_path @@ -673,7 +673,7 @@ class CorrelatedSource(SourceBase): a :class:`UnitSphereTriangularMesh` (which instead supports direction sampling) via a star triangulation of its spherical Voronoi diagram, using :func:`scipy.spatial.SphericalVoronoi` (see - :func:`triangularize_unit_sphere_mesh`). This conversion happens once, + :func:`triangulate_unit_sphere_mesh`). This conversion happens once, in Python, at construction time; the fully-processed result -- the (possibly larger, after triangulation) biased strength and weight arrays, plus mesh references -- is written directly to XML, so the C++ @@ -816,7 +816,7 @@ def _load(self, filename: PathLike): angle_mesh = None if angle_mesh is not None and isinstance(angle_mesh, UnitSpherePointset): - # triangularize_unit_sphere_mesh expects point-major data, with + # triangulate_unit_sphere_mesh expects point-major data, with # the angle/point dimension leading; reshape from our (spatial, # angle, energy) layout accordingly, treating (spatial, energy) # as one flattened "extra" block per point. @@ -825,7 +825,7 @@ def _load(self, filename: PathLike): w_point_major = np.moveaxis(weights, 1, 0).reshape( n_angle, n_space * n_energy) - angle_mesh, new_b, new_w = triangularize_unit_sphere_mesh( + angle_mesh, new_b, new_w = triangulate_unit_sphere_mesh( angle_mesh, data=b_point_major, broadcast_data=w_point_major) n_angle = angle_mesh.n_elements diff --git a/openmc/weight_windows.py b/openmc/weight_windows.py index 27be289fd7f..a37272899c2 100644 --- a/openmc/weight_windows.py +++ b/openmc/weight_windows.py @@ -17,6 +17,7 @@ from ._xml import get_elem_list, get_text, clean_indentation from .mixin import IDManagerMixin from .particle_type import ParticleType +from .utility_funcs import input_path class WeightWindows(IDManagerMixin): @@ -504,6 +505,9 @@ class WeightWindowGenerator: Target tallies for local variance reduction via FW-CADIS. source_biasing : bool Whether to perform automated biasing of fixed sources via FW-CADIS. + forward_source_mesh_file : Pathlike + Path to a forward source mesh file storing unbiased source strengths + in each phase space voxel. angular_biasing_quadrature : :class:`openmc.UnitSpherePointset`, optional Optional set of angles to generate source biasing parameters on. Defaults to None for biasing as a function of space and energy only. @@ -530,6 +534,9 @@ class WeightWindowGenerator: Target tallies for local variance reduction via FW-CADIS. source_biasing : bool Whether to perform automated biasing of fixed sources via FW-CADIS. + forward_source_mesh_file : Pathlike + Path to a forward source mesh file storing unbiased source strengths + in each phase space voxel. angular_biasing_quadrature : openmc.UnitSpherePointset or None Optional set of angles to generate source biasing parameters on. Defaults to None for biasing as a function of space and energy only. @@ -554,6 +561,7 @@ def __init__( method: str = 'magic', targets: openmc.Tallies | Iterable[int] | None = None, source_biasing: bool = False, + forward_source_mesh_file: PathLike | None = None, angular_biasing_quadrature: openmc.UnitSpherePointset | None = None, max_realizations: int = 1, update_interval: int = 1, @@ -569,6 +577,7 @@ def __init__( self.method = method self.targets = targets self.source_biasing = source_biasing + self.forward_source_mesh_file = forward_source_mesh_file self.angular_biasing_quadrature = angular_biasing_quadrature self.max_realizations = max_realizations self.update_interval = update_interval @@ -662,6 +671,22 @@ def source_biasing(self, sb: bool): "Automated source biasing is only enabled via the " \ "fw_cadis update method.") self._source_biasing = sb + + @property + def forward_source_mesh_file(self) -> PathLike: + return self._forward_source_mesh_file + + @forward_source_mesh_file.setter + def forward_source_mesh_file(self, f: PathLike): + if f is None: + self._weight_windows_file = None + elif self.source_biasing != True: + raise ValueError( + "Forward source mesh file is not required when source " \ + "biasing is not active.") + else: + cv.check_type('weight windows file', f, PathLike) + self._forward_source_mesh_file = input_path(f) @property def angular_biasing_quadrature(self) -> openmc.UnitSpherePointset: @@ -822,9 +847,12 @@ def to_xml_element(self): if self.source_biasing: sb_elem = ET.SubElement(element, 'source_biasing') sb_elem.text = str(self.source_biasing).lower() - if self.angular_biasing_quadrature is not None: - angle_mesh_elem = ET.SubElement(element, 'angular_biasing_quadrature') - angle_mesh_elem.text = str(self.angular_biasing_quadrature.id) + if self.angular_biasing_quadrature is not None: + angle_mesh_elem = ET.SubElement(element, 'angular_biasing_quadrature') + angle_mesh_elem.text = str(self.angular_biasing_quadrature.id) + if self.forward_source_mesh_file is not None: + fwd_src_mesh_elem = ET.SubElement(element, 'forward_source_mesh') + fwd_src_mesh_elem.text = str(self.forward_source_mesh_file) if self.update_parameters is not None: self._update_parameters_subelement(element) @@ -872,6 +900,8 @@ def from_xml_element(cls, elem: ET.Element, meshes: dict) -> Self: if elem.find('source_biasing') is not None: wwg.source_biasing = bool(get_text(elem, 'source_biasing')) + if elem.find('forward_source_mesh') is not None: + wwg.forward_source_mesh_file = get_text(elem, 'forward_source_mesh') if elem.find('angular_biasing_quadrature') is not None: angle_mesh_id = int(get_text(elem, 'angular_biasing_quadrature')) angle_mesh = meshes[angle_mesh_id] diff --git a/src/settings.cpp b/src/settings.cpp index 056017ee749..15a7b9c27c9 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -98,7 +98,6 @@ std::string path_sourcepoint; std::string path_statepoint; const char* path_statepoint_c {path_statepoint.c_str()}; std::string weight_windows_file; -std::string source_bias_file; std::string properties_file; int32_t n_inactive {0}; @@ -1251,11 +1250,6 @@ void read_settings_xml(pugi::xml_node root) weight_windows_on = true; } - // read FW-CADIS biased source - if (check_for_node(root, "source_bias_file")) { - source_bias_file = get_node_value(root, "source_bias_file"); - } - // read settings for weight windows value, this will override // the automatic setting even if weight windows are present if (check_for_node(root, "weight_windows_on")) { diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index 6aacf22bd3e..8df452b0327 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -763,9 +763,10 @@ void WeightWindows::to_hdf5(hid_t group) const //============================================================================== SourceBias::SourceBias(int32_t spatial_mesh_idx, int32_t angle_mesh_idx, - vector energy_bounds, int32_t ww_id) + vector energy_bounds, int32_t ww_id, std::string forward_source_mesh) : spatial_mesh_idx_(spatial_mesh_idx), angle_mesh_idx_(angle_mesh_idx), - energy_bounds_(std::move(energy_bounds)), ww_id_(ww_id) + energy_bounds_(std::move(energy_bounds)), ww_id_(ww_id), + forward_source_mesh_(forward_source_mesh) { int64_t spatial_bins = model::meshes[spatial_mesh_idx_]->n_bins(); int64_t angle_bins = @@ -931,9 +932,8 @@ void SourceBias::compute_unbiased_strength(int64_t n_samples_per_source) } // A precomputed file takes priority over sampling model::external_sources - const std::string fwd_path = "forward_source_mesh.h5"; - if (file_exists(fwd_path)) { - load_forward_source_mesh(fwd_path); + if (file_exists(forward_source_mesh_)) { + load_forward_source_mesh(forward_source_mesh_); return; } @@ -1153,6 +1153,9 @@ WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node) std::stoi(get_node_value(node, "angular_biasing_quadrature")); angle_mesh_idx_ = model::mesh_map[angle_mesh_id]; } + if (source_biasing_ && check_for_node(node, "forward_source_mesh")) { + forward_source_mesh_ = get_node_value(node, "forward_source_mesh"); + } } } else { fatal_error(fmt::format( @@ -1243,7 +1246,6 @@ void WeightWindowsGenerator::create_tally() ww_tally->add_filter(particle_filter); if (!source_biasing_ || method_ != WeightWindowUpdateMethod::FW_CADIS) { - // technically the second condition isn't totally absolute return; } @@ -1268,7 +1270,7 @@ void WeightWindowsGenerator::create_tally() // Create the object that will hold the accumulated flux data used to // build a biased forward source once the simulation finishes auto sb = std::make_unique( - mesh_idx, angle_mesh_idx_, e_bounds, wws->id()); + mesh_idx, angle_mesh_idx_, e_bounds, wws->id(), forward_source_mesh_); sb_idx_ = static_cast(variance_reduction::source_biases.size()); variance_reduction::source_biases.push_back(std::move(sb)); From 274014fc08efcc3e2c9fa3e511ddb9c536a69b81 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Thu, 15 Oct 2026 15:52:38 -0400 Subject: [PATCH 30/37] accumulate angular flux in forward source locations only during source biasing --- .../openmc/random_ray/flat_source_domain.h | 2 +- src/random_ray/flat_source_domain.cpp | 109 +++++++++++++++--- 2 files changed, 97 insertions(+), 14 deletions(-) diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index 14de817dd46..5c290b2b199 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -186,7 +186,7 @@ class FlatSourceDomain { vector tally_is_angular_; std::unordered_set angular_target_cells_; std::unordered_set angular_target_materials_; - std::unordered_set angular_target_meshes_; + std::unordered_set angular_target_spatial_meshes_; bool tally_angular_flux_everywhere_ {false}; double diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 739ba7a482c..c55c879e532 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -295,7 +295,7 @@ void FlatSourceDomain::set_flux_to_source(int64_t sr, int g) // Combine transport flux contributions and flat source contributions from the // previous iteration to generate this iteration's estimate of scalar flux. // Source terms are evenly distributed across angular flux as sources are -// isotropic; this however assumes that the reference angles' Voronoi cells +// isotropic; this however assumes that the reference angles' Voronoi cells // subtend approximately equal solid angles on the surface of the unit sphere. int64_t FlatSourceDomain::add_source_to_scalar_flux() { @@ -466,9 +466,19 @@ void FlatSourceDomain::initialize_angular_quadrature() tally_is_angular_.assign(model::tallies.size(), false); angular_target_cells_.clear(); angular_target_materials_.clear(); - angular_target_meshes_.clear(); + angular_target_spatial_meshes_.clear(); tally_angular_flux_everywhere_ = false; + // If FW-CADIS source biasing is active, flag its tally + int sb_tally = C_NONE; + for (const auto& wwg : variance_reduction::weight_windows_generators) { + if (wwg->sb_tally_idx_ != C_NONE && + wwg->sb_tally_idx_ < static_cast(model::tallies.size())) { + sb_tally = wwg->sb_tally_idx_; + break; + } + } + for (int i_tally = 0; i_tally < model::tallies.size(); i_tally++) { Tally& tally {*model::tallies[i_tally]}; @@ -515,6 +525,7 @@ void FlatSourceDomain::initialize_angular_quadrature() tally_materials.push_back(m); } } else if (auto* mesh_filter = dynamic_cast(filt)) { + // Already caught angular-type mesh filters; only spatial remain has_spatial_filter = true; tally_meshes.push_back(mesh_filter->mesh()); } @@ -530,14 +541,86 @@ void FlatSourceDomain::initialize_angular_quadrature() continue; } - for (int32_t c : tally_cells) { - angular_target_cells_.insert(c); - } - for (int32_t m : tally_materials) { - angular_target_materials_.insert(m); - } - for (int32_t m : tally_meshes) { - angular_target_meshes_.insert(m); + if (i_tally == sb_tally) { + // If this is the source biasing tally, flag only the cells with a + // forward external source present. But we'll need to borrow syntax from + // convert_external_sources() to locate these sources. This should only + // have to occur once (or twice, if eventually supported for photons). + for (int es = 0; es < model::external_sources.size(); es++) { + // Extract source information + Source* s = model::external_sources[es].get(); + IndependentSource* is = dynamic_cast(s); + const std::unordered_set& domain_ids = is->domain_ids(); + + // If there is no domain constraint specified, then this must be a point + // source. + if (is->domain_ids().size() == 0) { + + // Extract the point source coordinate and find its cell + auto sp = dynamic_cast(is->space()); + GeometryState gs; + gs.r() = sp->r(); + gs.r_last() = sp->r(); + gs.u() = {1.0, 0.0, 0.0}; + bool found = exhaustive_find_cell(gs); + if (!found) { + fatal_error(fmt::format("Could not find cell containing external " + "point source at {}", + sp->r())); + } + angular_target_cells_.insert(gs.lowest_coord().cell()); + + } else { + // If not a point source, then use the volumetric domain constraints + // to determine the location of the forward source. + if (is->domain_type() == Source::DomainType::MATERIAL) { + for (int32_t material_id : domain_ids) { + int32_t i_mat = model::material_map[material_id]; + angular_target_materials_.insert(i_mat); + } + } else if (is->domain_type() == Source::DomainType::CELL) { + for (int32_t cell_id : domain_ids) { + int32_t i_cell = model::cell_map[cell_id]; + Cell& cell = *model::cells[i_cell]; + if (cell.type_ == Fill::MATERIAL) { + angular_target_cells_.insert(i_cell); + } else { + for (const auto& pair : cell.get_contained_cells(0, nullptr)) { + angular_target_cells_.insert(pair.first); + } + } + } + } else if (is->domain_type() == Source::DomainType::UNIVERSE) { + for (int32_t universe_id : domain_ids) { + int32_t i_universe = model::universe_map[universe_id]; + Universe& universe = *model::universes[i_universe]; + for (int32_t i_cell : universe.cells_) { + Cell& cell = *model::cells[i_cell]; + if (cell.type_ == Fill::MATERIAL) { + angular_target_cells_.insert(i_cell); + } else { + for (const auto& pair : + cell.get_contained_cells(0, nullptr)) { + angular_target_cells_.insert(pair.first); + } + } + } + } + } + } + } + } else { + // If this is not the source biasing tally, flag all cells, materials, + // and meshes in the spatial domain of the tally for angular flux scoring + for (int32_t c : tally_cells) { + angular_target_cells_.insert(c); + } + for (int32_t m : tally_materials) { + angular_target_materials_.insert(m); + } + for (int32_t m : tally_meshes) { + angular_target_spatial_meshes_.insert(m); + } } } @@ -558,7 +641,7 @@ bool FlatSourceDomain::tally_angular_flux_applies( if (material != MATERIAL_VOID && angular_target_materials_.count(material)) { return true; } - if (mesh_idx != C_NONE && angular_target_meshes_.count(mesh_idx)) { + if (mesh_idx != C_NONE && angular_target_spatial_meshes_.count(mesh_idx)) { // will flag every source region this mesh applies to, whether or // not the region actually falls in a bin return true; @@ -2088,8 +2171,8 @@ int64_t FlatSourceDomain::lookup_mesh_bin(int64_t sr, Position r) const int FlatSourceDomain::lookup_angular_bin(Direction u) const { if (solve_ == RandomRaySolve::ADJOINT) { - // Flip direction in adjoint mode, since the ray is actually traveling in - // the direction -(Omega), whereas we want to tally the importance of a + // Flip direction in adjoint mode, since the ray is actually traveling in + // the direction -(Omega), whereas we want to tally the importance of a // particle traveling in the forward direction Omega u = -u; } From a122b0a52c9714fbcf43960b9e524ba80714c222 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 30 Oct 2026 10:03:50 -0400 Subject: [PATCH 31/37] Refactor CorrelatedSource to treat continuous, discrete or mixed energy distributions --- include/openmc/source.h | 15 +- include/openmc/weight_windows.h | 19 +- openmc/model/model.py | 131 ++++++++- openmc/source.py | 472 +++++++++++++++++++++++--------- src/source.cpp | 110 +++++--- src/weight_windows.cpp | 98 ++++++- 6 files changed, 653 insertions(+), 192 deletions(-) diff --git a/include/openmc/source.h b/include/openmc/source.h index 1030f6ecc16..3f9531d1436 100644 --- a/include/openmc/source.h +++ b/include/openmc/source.h @@ -239,8 +239,6 @@ class CorrelatedSource : public Source { //! \return Sampled site SourceSite sample(uint64_t* seed) const override; - double strength() const override { return voxel_dist_.integral(); } - // Accessors int32_t spatial_mesh_idx() const { return spatial_mesh_idx_; } int32_t angle_mesh_idx() const { return angle_mesh_idx_; } @@ -250,16 +248,25 @@ class CorrelatedSource : public Source { // Data members int32_t spatial_mesh_idx_ {C_NONE}; //!< Index into model::meshes int32_t angle_mesh_idx_ {C_NONE}; //!< Index into model::meshes, or C_NONE - vector group_bounds_; //!< Energy group boundaries [eV] + vector group_bounds_; //!< Continuum energy group bounds [eV] int64_t spatial_bins_ {0}; int64_t angle_bins_ {1}; - int64_t energy_bins_ {1}; + int64_t energy_bins_ {0}; + + int64_t n_discrete_ {0}; //!< Number of discrete source energies + vector discrete_energies_; //!< Discrete source energies E_k [eV] + int64_t n_continuum_voxels_ {0}; //!< Phase space voxels not associated + //!< with a discrete emission energy + std::string energy_distribution_type_ { + "continuous"}; //!< One of {"continuous", "discrete", "mixed"} ParticleType particle_ {ParticleType::neutron()}; //!< Particle type emitted //! Selects a flat index into (spatial, angle, energy) space, in row-major //! (spatial, angle, energy) order, weighted by the "strengths" array. + //! The distribution spans continuum voxels first, followed by any voxels + //! with discrete (deterministic) emission energy. DiscreteIndex voxel_dist_; //! Per-voxel weight (1 / flux), indexed the same way as voxel_dist_. diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index b650674f095..450ff5d050a 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -272,11 +272,15 @@ class SourceBias { //---------------------------------------------------------------------------- // Data members - int32_t spatial_mesh_idx_; //!< Index into model::meshes - int32_t angle_mesh_idx_; //!< Index into model::meshes, or C_NONE - vector energy_bounds_; //!< Energy group boundaries [eV] - int32_t ww_id_; //!< ID of the associated WeightWindows - std::string forward_source_mesh_; //!< Path to unbiased source strengths file + int32_t spatial_mesh_idx_; //!< Index into model::meshes + int32_t angle_mesh_idx_; //!< Index into model::meshes, or C_NONE + vector energy_bounds_; //!< Energy group boundaries [eV] + vector discrete_energies_; //!< Energies of a Discrete-type unbiased + //!< source spectrum + int32_t ww_id_; //!< ID of the associated WeightWindows + std::string forward_source_mesh_; //!< Path to unbiased source strengths file + + std::string energy_distribution_type_ {"continuous"}; //!< Source dist type //! Un-normalized mean flux. Shape: (spatial_bins, angle_bins, //! energy_bins). angle_bins == 1 when angle_mesh_idx_ == C_NONE. @@ -286,6 +290,11 @@ class SourceBias { //! of (spatial mesh element, angular mesh element, energy group), assuming //! isotropic emission when angle_mesh_idx_ == C_NONE. tensor::Tensor unbiased_strength_; + + //! Estimated relative strength of the unbiased external source as a function + //! of (spatial mesh element, angular mesh element, emission energy), given + //! a source with discrete energies rather than a continuous spectrum. + tensor::Tensor unbiased_strength_discrete_; }; class WeightWindowsGenerator { diff --git a/openmc/model/model.py b/openmc/model/model.py index 7bf6e0e39a7..815e3dacbe5 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1598,6 +1598,10 @@ def write_forward_source_mesh( raise ValueError( f'Forward source mesh cannot be written in ' f'{self.settings.run_mode} mode (requires ''fixed source'').') + + if self.settings.energy_mode == 'multi-group': + raise RuntimeError( + "Forward source meshes can only be generated in continuous-energy mode.") min_samples = int(min_samples) if max_samples is None: @@ -1607,6 +1611,80 @@ def write_forward_source_mesh( f'max_samples ({max_samples}) must be >= min_samples ' f'({min_samples}).') + # Determine energy distribution type of the forward source + # (continuous, discrete, mixed). + # + # This first function returns a tuple (atoms, has_continuous) + # where atoms is a Set of discrete energies, and has_continuous + # indicates whether there is a continuous portion to the support. + def _support_type(dist): + # DecaySpectrum could be either Discrete or Tabular underneath + if isinstance(dist, openmc.stats.DecaySpectrum): + recast = dist.to_distribution() + if recast is None: + return set(), False + return _support_type(recast) + + sup = dist.support + if isinstance(sup, set): + return set(sup), False + if isinstance(sup, dict): + return set(sup.get('discrete', set())), bool(sup.get('continuous')) + if isinstance(sup, tuple): + return set(), True + raise TypeError(f"Unrecognized support type for {type(dist).__name__}") + + # Extract the individual energy distribution objects from a given source + def _extract_energy_dist(source): + if isinstance(source, openmc.IndependentSource): + return [source.energy] if source.energy is not None else [] + elif isinstance(source, openmc.TokamakSource): + return list(source.energy) + elif isinstance(source, openmc.MeshSource): + dists = [] + for sub in np.asarray(source.sources).ravel(order='F'): + dists.extend(_extract_energy_dist(sub)) + return dists + else: + raise AttributeError( + f"Cannot extract energy distribution of {type(source).__name__}") + + # Function to iterate through sources and return all discrete energies, + # plus whether its support has any continuous part. In the event that a + # source was not classifiable, the default behavior treats the sources + # as having only continuous support. + def _collect_source_atoms(sources): + atoms = set() + has_continuous = False + try: + for src in sources: + dists = _extract_energy_dist(src) + if not dists: + has_continuous = True # source has default Watt dist + for d in dists: + a, c = _support_type(d) + atoms |= a + has_continuous |= c + except (AttributeError, TypeError, NotImplementedError): + return np.empty(0), False, False + return np.array(sorted(atoms), dtype=float), has_continuous, True + + atoms, has_continuous, classifiable = _collect_source_atoms( + self.settings.source) + if not classifiable: + warnings.warn( + "Could not determine the support type of at least one forward " \ + "source energy distribution. Source energy distribution will " \ + "be treated as continuous. ") + n_atoms = atoms.size + + if n_atoms == 0: + energy_distribution = 'continuous' + elif has_continuous: + energy_distribution = 'mixed' + else: + energy_distribution = 'discrete' + energy_bins = np.asarray(energy_bins, dtype=float) if energy_bins.ndim != 1 or energy_bins.size < 2: raise ValueError( @@ -1625,12 +1703,14 @@ def write_forward_source_mesh( dummy_tally = openmc.Tally() dummy_tally.filters = filters dummy_tally.scores = ['flux'] + dummy_tally_id = dummy_tally.id self.tallies.append(dummy_tally) init_kwargs.setdefault('output', False) init_kwargs.setdefault('args', ['-c']) counts = np.zeros((n_space, n_angle, n_energy)) + counts_discrete = np.zeros((n_space, n_angle, n_atoms)) n_drawn = 0 median = 0.0 @@ -1641,6 +1721,20 @@ def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: for i, p in enumerate(points): bins[i] = lib_mesh.get_bin(p) return bins + + # Helper function to map each sample's energy to the index of an + # "atom" in a discrete source energy spectrum. If a match is not + # found, an index of -1 is assigned, corresponding to the continuum. + def _atom_indices(E): + if n_atoms == 0: + return np.full(E.shape, -1, dtype=int) + pos = np.searchsorted(atoms, E) + best = np.full(E.shape, -1, dtype=int) + for c in (np.clip(pos - 1, 0, n_atoms - 1), + np.clip(pos, 0, n_atoms - 1)): + close = np.isclose(E, atoms[c], rtol=1.0e-9, atol=0.0) + best = np.where(close & (best < 0), c, best) + return best with openmc.lib.TemporarySession(self, **init_kwargs): space_lib_mesh = openmc.lib.meshes[space_mesh.id] @@ -1671,21 +1765,30 @@ def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: else: angle_bin = np.zeros(len(r), dtype=int) + # Identify samples coming from discrete source energies, if any + atom_bin = _atom_indices(E) + is_disc = atom_bin >= 0 + + cont = valid & ~is_disc energy_bin = np.digitize(E, energy_bins) - 1 - valid &= (energy_bin >= 0) & (energy_bin < n_energy) + cont &= (energy_bin >= 0) & (energy_bin < n_energy) + np.add.at(counts, + (space_bin[cont], angle_bin[cont], energy_bin[cont]), 1.0) - np.add.at( - counts, - (space_bin[valid], angle_bin[valid], energy_bin[valid]), - 1.0) + if n_atoms: + disc = valid & is_disc + np.add.at(counts_discrete, + (space_bin[disc], angle_bin[disc], atom_bin[disc]), 1.0) + + occupied = np.concatenate( + [counts[counts != 0], counts_discrete[counts_discrete != 0]]) # Compute median samples per voxel among voxels sampled at # least once so far - median = np.median(counts[counts != 0]) + if occupied.size: + median = np.median(occupied) - if median >= min_samples_per_voxel: - break - if n_drawn >= max_samples: + if median >= min_samples_per_voxel or n_drawn >= max_samples: break if median < min_samples_per_voxel: @@ -1701,10 +1804,12 @@ def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: # sites, so that the mesh accurately describes source support falling # only inside space_mesh/angle_mesh/energy_bins S = counts / n_drawn + S_discrete = counts_discrete / n_drawn with h5py.File(filename, 'w') as fh: fh.attrs['filetype'] = np.bytes_('forward_source') fh.attrs['version'] = np.array([1, 0]) + fh.attrs['energy_distribution_type'] = np.bytes_(energy_distribution) fh.create_dataset('spatial_mesh', data=space_mesh.id) # -1 used for angle-independent biasing fh.create_dataset( @@ -1712,9 +1817,15 @@ def _mesh_bin_indices(lib_mesh, points: np.ndarray) -> np.ndarray: data=angle_mesh.id if angle_mesh is not None else -1) fh.create_dataset('energy_bounds', data=energy_bins) fh.create_dataset('unbiased_source_strength', data=S) + if n_atoms: + fh.create_dataset('discrete_energies', data=atoms) + fh.create_dataset('unbiased_source_strength_discrete', data=S_discrete) # Remove the dummy tally from earlier - self.tallies.remove(dummy_tally) + for i, tally in enumerate(self.tallies): + if tally.id == dummy_tally_id: + del self.tallies[i] + break def apply_tally_results(self, statepoint: PathLike | openmc.StatePoint): """Apply results from a statepoint to tally objects on the Model diff --git a/openmc/source.py b/openmc/source.py index 1c7a9663e5c..74538dde686 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -17,7 +17,7 @@ from openmc.stats.multivariate import UnitSphere, Spatial from openmc.stats.univariate import Univariate from ._xml import get_elem_list, get_text -from .mesh import MeshBase, StructuredMesh, UnstructuredMesh, UnitSpherePointset, triangulate_unit_sphere_mesh +from .mesh import MeshBase, StructuredMesh, UnstructuredMesh, UnitSpherePointset, UnitSphereTriangularMesh, triangulate_unit_sphere_mesh from .particle_type import ParticleType from .statepoint import _VERSION_STATEPOINT from .utility_funcs import input_path @@ -202,6 +202,8 @@ def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase: return FileSource.from_xml_element(elem) elif source_type == 'mesh': return MeshSource.from_xml_element(elem, meshes) + elif source_type == 'correlated': + return CorrelatedSource.from_xml_element(elem, meshes) elif source_type == 'tokamak': return TokamakSource.from_xml_element(elem) else: @@ -659,95 +661,258 @@ def from_xml_element(cls, elem: ET.Element, meshes) -> openmc.MeshSource: return cls(mesh, sources, constraints=constraints) class CorrelatedSource(SourceBase): - """A source that samples a precomputed, spatially- and (optionally) - angularly-biased phase-space distribution. - - This is normally constructed from a "source_bias.h5" file produced by - FW-CADIS source biasing (see the C++ ``SourceBias`` class in - ``openmc/weight_windows.h`` and ``openmc_weight_windows_export``), - which stores a biased source strength B(r, Omega, g) and a per-voxel - weight 1/flux(r, Omega, g) on a (spatial mesh, angular mesh, energy - group) grid. If the angular mesh is a :class:`UnitSpherePointset` (the - only angular mesh type that currently supports point-location, i.e. - tallying -- see ``AngularMesh`` in ``mesh.h``), it is converted here to - a :class:`UnitSphereTriangularMesh` (which instead supports direction - sampling) via a star triangulation of its spherical Voronoi diagram, - using :func:`scipy.spatial.SphericalVoronoi` (see - :func:`triangulate_unit_sphere_mesh`). This conversion happens once, - in Python, at construction time; the fully-processed result -- the - (possibly larger, after triangulation) biased strength and weight - arrays, plus mesh references -- is written directly to XML, so the C++ - side never reads source_bias.h5 or performs any triangulation itself - (see ``CorrelatedSource`` in ``openmc/source.h``/``source.cpp``). - - B is treated as *extensive* (a probability mass) when redistributed - across new triangles, while the weight is treated as *intensive* and - simply copied unchanged to every new triangle belonging to its parent - point -- subdividing the angular bin for sampling purposes shouldn't - dilute a purely directional correction factor. + """A source with correlated spatial, angular, and energy distributions. + + The sampling probabilities and weights associated with each voxel in a + particular phase space discretization are usually supplied by a source bias + file constructed by the FW-CADIS :class:`WeightWindowGenerator`. This file, + by default named "source_bias.h5", stores a biased source strength + B(r, Omega, g) and a per-voxel weight, as well as IDs of a spatial mesh and + optional angular mesh, and an energy group structure. If the unbiased + forward source had a discrete or mixed energy spectrum, the file also + contains the discrete emission energy values and the biased source strengths + and weights associated with each. + + During sampling, the strengths assigned to each phase space voxel + (r, Omega, g) are used to construct a discrete probability mass function, + and after a particular voxel has been selected, samples are drawn uniformly + from its interior. If there is no triangular unit sphere mesh to partition + angle, particles are emitted isotropically. In the case of a + continuous-energy source spectrum, the energy of the sampled source site is + sampled uniformly in lethargy over the particular group, or uniformly in + energy if the group's lower bound is zero. Finally, the sample is assigned + the weight associated with the voxel it came from. + + If the angular mesh read from the source bias file is an instance of + :class:`UnitSpherePointset`, it is converted upon initialization to + a :class:`UnitSphereTriangularMesh`, which is necessary for the sampling + algorithm. See :func:`triangulate_unit_sphere_mesh` for the method by which + this is done. + + This class may also be instantiated and supplied a spatial mesh, energy + group structure, optional angular mesh and discrete energy values, and + source strengths and weights associated with each phase space voxel from + within the Python API. In this case, only a :class:TriangularUnitSphereMesh + may be provided to partition angle, with source strength and weight data + calculated accordingly. .. versionadded:: TODO Parameters ---------- - filename : path-like + filename : path-like or None Path to a "source_bias.h5" file. + particle : str or int or openmc.ParticleType + Source particle type (name, PDG number, or type). Overridden by the + particle type recorded in the source bias file, if present. + strength : float + Total strength multiplier of the source (default is 1.0). constraints : dict - Constraints on sampled source particles; see :class:`SourceBase`. + Constraints on sampled source particles. Attributes ---------- mesh : openmc.MeshBase Spatial mesh source positions are sampled from. angle_mesh : openmc.MeshBase or None - Angular mesh source directions are sampled from (a - UnitSphereTriangularMesh if the source was angularly biased), or - None if emission is isotropic. + Angular mesh source directions are sampled over (a + UnitSphereTriangularMesh if anisotropic), or None if emission is + isotropic. energy_bounds : numpy.ndarray or None - Energy group boundaries [eV], or None if there is a single group. + Energy group boundaries [eV], or None if the source energy distribution + is discrete. + energy_distribution_type : {'continuous', 'discrete', 'mixed'} + Support type of the source's energy distribution. Distribution is + treated as 'continuous' by default. strengths : numpy.ndarray - Biased source strength B(r, Omega, g), flattened in row-major + Source probabilities B(r, Omega, g) associated with each phase-space + voxel with a continuous energy distribution, flattened in row-major (spatial, angle, energy) order. weights : numpy.ndarray - Per-voxel weight (1 / flux), in the same order as `strengths`. + Per-voxel weights (1 / flux) of continuum voxels, in the same order as + `strengths`. + discrete_energies : numpy.ndarray or None + Discrete emission energies [eV] associated with a 'discrete' or 'mixed' + source spectrum, or None if the source spectrum is continuous only. + strengths_discrete : numpy.ndarray + Source probabilities B(r, Omega, E_k) associated with a finite + space-angle voxel (r, Omega) and a particular discrete source + energy E_k, flattened in row-major (spatial, angle, energy) order. + weights_discrete : numpy.ndarray + Weights corresponding to samples using a discrete energy distribution. strength : float - Total source strength (sum of `strengths`). + Total strength multiplier of the source, not to be confused with + `strengths` type : str Indicator of source type: 'correlated' + particle : openmc.ParticleType + Source particle type (name, PDG number, or type). Overridden by the + particle type recorded in the source bias file, if present. """ def __init__( self, - filename: PathLike, + filename: PathLike | None = None, + strength: float | None = 1.0, + particle: str | int | ParticleType = 'neutron', constraints: dict[str, Any] | None = None, ): - super().__init__(strength=None, constraints=constraints) - self._load(filename) + super().__init__(strength=strength, constraints=constraints) + self._mesh = None + self._angle_mesh = None + self._energy_bounds = None + self._energy_distribution_type = 'continuous' + self._discrete_energies = None + self._strengths = None + self._weights = None + self._strengths_discrete = None + self._weights_discrete = None + self.particle = particle + if filename is not None: + self._load(filename) @property def type(self) -> str: return "correlated" + + @property + def particle(self) -> ParticleType: + return self._particle + + @particle.setter + def particle(self, particle): + self._particle = ParticleType(particle) + + @property + def energy_distribution_type(self) -> str: + return self._energy_distribution_type + + @energy_distribution_type.setter + def energy_distribution_type(self, dist_type): + if isinstance(dist_type, bytes): + dist_type = dist_type.decode() + if dist_type not in {'continuous', 'discrete', 'mixed'}: + raise ValueError( + f"Unknown energy distribution type '{dist_type}' given for " + f"CorrelatedSource. Accepted types are 'continuous', " + f"'discrete', and 'mixed'.") + + self._energy_distribution_type = dist_type @property def mesh(self) -> MeshBase: return self._mesh + + @mesh.setter + def mesh(self, m): + cv.check_type("spatial mesh", m, MeshBase) + self._mesh = m @property def angle_mesh(self) -> MeshBase | None: return self._angle_mesh + + @angle_mesh.setter + def angle_mesh(self, m): + cv.check_type("angular mesh", m, UnitSphereTriangularMesh, none_ok=True) + self._angle_mesh = m @property def energy_bounds(self) -> np.ndarray | None: return self._energy_bounds + + @energy_bounds.setter + def energy_bounds(self, e): + if e is not None: + e = np.asarray(e, dtype=float).ravel() + bad = e < 0.0 + if not np.all(np.isfinite(e)) or np.any(bad): + raise ValueError( + "CorrelatedSource.energy_bounds entries must be finite " + "and nonnegative.") + + self._energy_bounds = e + + @property + def discrete_energies(self) -> np.ndarray | None: + return self._discrete_energies + + @discrete_energies.setter + def discrete_energies(self, e): + if e is not None: + e = np.asarray(e, dtype=float).ravel() + bad = e <= 0.0 + if not np.all(np.isfinite(e)) or np.any(bad): + raise ValueError( + "CorrelatedSource.discrete_energies entries must be finite " + "and positive.") + + self._discrete_energies = e @property def strengths(self) -> np.ndarray: return self._strengths + + @strengths.setter + def strengths(self, s): + if s is not None: + s = np.asarray(s, dtype=float).ravel() + bad = s < 0.0 + if not np.all(np.isfinite(s)) or np.any(bad): + raise ValueError( + "CorrelatedSource.strengths entries must be finite " + "and positive.") + + self._strengths = s @property def weights(self) -> np.ndarray: return self._weights + + @weights.setter + def weights(self, w): + if w is not None: + w = np.asarray(w, dtype=float).ravel() + bad = w < 0.0 + if not np.all(np.isfinite(w)) or np.any(bad): + raise ValueError( + "CorrelatedSource.weights entries must be finite " + "and positive.") + + self._weights = w + + @property + def strengths_discrete(self) -> np.ndarray | None: + return self._strengths_discrete + + @strengths_discrete.setter + def strengths_discrete(self, s): + if s is not None: + s = np.asarray(s, dtype=float).ravel() + bad = s < 0.0 + if not np.all(np.isfinite(s)) or np.any(bad): + raise ValueError( + "CorrelatedSource.strengths_discrete entries must be finite " + "and positive.") + + self._strengths_discrete = s + + @property + def weights_discrete(self) -> np.ndarray | None: + return self._weights_discrete + + @weights_discrete.setter + def weights_discrete(self, w): + if w is not None: + w = np.asarray(w, dtype=float).ravel() + bad = w < 0.0 + if not np.all(np.isfinite(w)) or np.any(bad): + raise ValueError( + "CorrelatedSource.weights_discrete entries must be finite " + "and positive.") + + self._weights_discrete = w @property def strength(self) -> float: @@ -761,14 +926,8 @@ def strength(self, val): self._strengths = self._strengths * (val / current) def _load(self, filename: PathLike): - """Read source_bias.h5, triangulating the angular mesh (if present - and if it is a UnitSpherePointset) in the process. + # Read source_bias.h5, triangulating the angular mesh if needed - The HDF5 layout read here (dataset names/shapes, the "-1" sentinel - for "no angular mesh", and mesh subgroups named "mesh ") mirrors - ``SourceBias::to_hdf5()`` on the C++ side (see ``weight_windows.cpp``) - and ``Mesh::to_hdf5()`` in ``mesh.cpp``. - """ filename = Path(filename) with h5py.File(filename, 'r') as fh: @@ -784,64 +943,75 @@ def _load(self, filename: PathLike): if len(sb_names) != 1: raise ValueError( f"File '{filename}' contains {len(sb_names)} source " - "bias groups; CorrelatedSource currently requires " - "exactly one.") + "bias groups; CorrelatedSource supports only one.") sb_group = fh[sb_names[0]] - mesh_group = fh['meshes'] - spatial_mesh_id = int(np.asarray(sb_group['spatial_mesh'])) - angle_mesh_id = int(np.asarray(sb_group['angle_mesh'])) - - # Mesh subgroups are named "mesh " (matching the C++ - # Mesh::to_hdf5() convention) -- MeshBase.from_hdf5() parses the - # ID directly out of the group's own name, so the lookup key - # must match that exactly. + self.energy_distribution_type = sb_group.attrs.get( + 'energy_distribution_type', b'continuous') + + blocks = {} # dict to separate parameters based on distribution support + if self.energy_distribution_type != 'discrete': + energy_bounds = sb_group['energy_bounds'][()] + blocks['continuum'] = (sb_group['biased_source_strength'][()], + sb_group['weights'][()]) + if self.energy_distribution_type != 'continuous': + discrete_energies = sb_group['discrete_energies'][()] + blocks['discrete'] = ( + sb_group['biased_source_strength_discrete'][()], + sb_group['weights_discrete'][()]) + + # Particle type reader for if photon SB is eventually implemented + particle = sb_group.attrs.get('particle_type') + if particle is not None: + if isinstance(particle, bytes): + particle = particle.decode() + self.particle = particle + + spatial_mesh_id = int(sb_group['spatial_mesh'][()]) + angle_mesh_id = int(sb_group['angle_mesh'][()]) spatial_mesh = MeshBase.from_hdf5( mesh_group[f'mesh {spatial_mesh_id}']) - - energy_bounds = np.asarray(sb_group['energy_bounds']) - n_energy = max(len(energy_bounds) - 1, 1) - n_space = spatial_mesh.n_elements - - biased_strength = np.asarray(sb_group['biased_source_strength']) - weights = np.asarray(sb_group['weights']) - # Expected shape: (n_space, n_angle, n_energy) - n_angle = biased_strength.shape[1] - - if angle_mesh_id != -1: - angle_mesh = MeshBase.from_hdf5( - mesh_group[f'mesh {angle_mesh_id}']) - else: - angle_mesh = None - - if angle_mesh is not None and isinstance(angle_mesh, UnitSpherePointset): - # triangulate_unit_sphere_mesh expects point-major data, with - # the angle/point dimension leading; reshape from our (spatial, - # angle, energy) layout accordingly, treating (spatial, energy) - # as one flattened "extra" block per point. - b_point_major = np.moveaxis(biased_strength, 1, 0).reshape( - n_angle, n_space * n_energy) - w_point_major = np.moveaxis(weights, 1, 0).reshape( - n_angle, n_space * n_energy) - - angle_mesh, new_b, new_w = triangulate_unit_sphere_mesh( - angle_mesh, data=b_point_major, broadcast_data=w_point_major) - + angle_mesh = (MeshBase.from_hdf5(mesh_group[f'mesh {angle_mesh_id}']) + if angle_mesh_id != -1 else None) + + if isinstance(angle_mesh, UnitSpherePointset): + # triangulate_unit_sphere_mesh expects point-major data, with the + # angle/point dimension leading. Triangulate both datasets at + # once for efficiency + shapes = [s.shape for s, _ in blocks.values()] + n_cols = [n_s * n_e for n_s, _, n_e in shapes] + + def point_major(arrays): + return np.concatenate( + [np.moveaxis(a, 1, 0).reshape(a.shape[1], n) + for a, n in zip(arrays, n_cols)], axis=1) + + angle_mesh, new_s, new_w = triangulate_unit_sphere_mesh( + angle_mesh, + data=point_major([s for s, _ in blocks.values()]), + broadcast_data=point_major([w for _, w in blocks.values()])) + + # Split the columns back into blocks and restore + # (spatial, angle, energy) ordering n_angle = angle_mesh.n_elements - biased_strength = np.moveaxis( - new_b.reshape(n_angle, n_space, n_energy), 0, 1) - weights = np.moveaxis( - new_w.reshape(n_angle, n_space, n_energy), 0, 1) - - self._mesh = spatial_mesh - self._angle_mesh = angle_mesh - self._energy_bounds = energy_bounds if len(energy_bounds) > 0 else None - # Flatten to row-major (spatial, angle, energy) order, matching what - # CorrelatedSource's C++ constructor expects to find in "strengths"/ - # "weights". - self._strengths = biased_strength.ravel() - self._weights = weights.ravel() + splits = np.cumsum(n_cols)[:-1] + for key, (n_s, _, n_e), s, w in zip( + list(blocks), shapes, + np.split(new_s, splits, axis=1), + np.split(new_w, splits, axis=1)): + blocks[key] = tuple( + np.moveaxis(x.reshape(n_angle, n_s, n_e), 0, 1) + for x in (s, w)) + + self.mesh = spatial_mesh + self.angle_mesh = angle_mesh + if 'continuum' in blocks: + self.energy_bounds = energy_bounds + self.strengths, self.weights = blocks['continuum'] + if 'discrete' in blocks: + self.discrete_energies = discrete_energies + self.strengths_discrete, self.weights_discrete = blocks['discrete'] def populate_xml_element(self, elem: ET.Element): """Add necessary source information to an XML element @@ -852,16 +1022,57 @@ def populate_xml_element(self, elem: ET.Element): XML element containing source data """ + if self.mesh is None: + raise ValueError("CorrelatedSource.mesh must be set before export.") + if self.strengths is None and self.discrete_energies is None: + raise ValueError( + "CorrelatedSource requires a continuum block ('strengths'), " + "a discrete block ('discrete_energies'), or both.") + + elem.set("particle", str(self.particle)) elem.set("mesh", str(self.mesh.id)) + n_space_angle = self.mesh.n_elements if self.angle_mesh is not None: elem.set("angle_mesh", str(self.angle_mesh.id)) - if self.energy_bounds is not None: - subelem = ET.SubElement(elem, "group_bounds") - subelem.text = ' '.join(str(e) for e in self.energy_bounds) - subelem = ET.SubElement(elem, "strengths") - subelem.text = ' '.join(str(s) for s in self.strengths) - subelem = ET.SubElement(elem, "weights") - subelem.text = ' '.join(str(w) for w in self.weights) + n_space_angle *= self.angle_mesh.n_elements + + def write_array(tag, attr, n_expected=None): + values = getattr(self, attr) + if values is None: + raise ValueError(f"CorrelatedSource.{attr} must be set when " + "its energy distribution type is present.") + if n_expected is not None and len(values) != n_expected: + raise ValueError( + f"Length of CorrelatedSource.{attr} ({len(values)}) does " + f"not match the number of phase-space voxels " + f"({n_expected}).") + ET.SubElement(elem, tag).text = ' '.join(str(x) for x in values) + + # Continuum values + if self.strengths is not None: + if self.energy_distribution_type == 'discrete': + raise ValueError( + f"CorrelatedSource has energy distribution type 'discrete' " + f"but was found to contain a 'strengths' array with " + f"{len(self.strengths)} elements.") + write_array('group_bounds', 'energy_bounds') + n_cont = n_space_angle * (len(self.energy_bounds) - 1) + write_array('strengths', 'strengths', n_cont) + write_array('weights', 'weights', n_cont) + + # Discrete values + if self.discrete_energies is not None: + if self.energy_distribution_type == 'continuous': + raise ValueError( + f"CorrelatedSource has energy distribution type 'continuous' " + f"but was found to contain a 'discrete_energies' array with " + f"{len(self.discrete_energies)} elements.") + n_disc = n_space_angle * len(self.discrete_energies) + write_array('discrete_energies', 'discrete_energies') + write_array('strengths_discrete', 'strengths_discrete', n_disc) + write_array('weights_discrete', 'weights_discrete', n_disc) + + elem.set("energy_distribution_type", self.energy_distribution_type) @classmethod def from_xml_element(cls, elem: ET.Element, meshes) -> CorrelatedSource: @@ -882,29 +1093,46 @@ def from_xml_element(cls, elem: ET.Element, meshes) -> CorrelatedSource: CorrelatedSource generated from the XML element """ - # Bypass __init__ (which reads directly from an HDF5 file) since - # everything needed is already present in the XML -- source_bias.h5 - # itself does not need to exist at this point. - source = cls.__new__(cls) - SourceBase.__init__( - source, strength=None, constraints=cls._get_constraints(elem)) + source = cls(constraints=cls._get_constraints(elem)) - mesh_id = int(get_text(elem, 'mesh')) - source._mesh = meshes[mesh_id] + # Total source strength multiplier, not a probability array + strength = get_text(elem, 'strength') + if strength is not None: + source.strength = float(strength) + + particle = get_text(elem, 'particle') + if particle is not None: + source.particle = particle + + source.mesh = meshes[int(get_text(elem, 'mesh'))] angle_mesh_id = get_text(elem, 'angle_mesh') - source._angle_mesh = ( + source.angle_mesh = ( meshes[int(angle_mesh_id)] if angle_mesh_id is not None else None) - energy_bounds_text = get_text(elem, 'group_bounds') - source._energy_bounds = ( - np.array([float(x) for x in energy_bounds_text.split()]) - if energy_bounds_text is not None else None) + dist_type = get_text(elem, 'energy_distribution_type') + source.energy_distribution_type = ( + dist_type if dist_type is not None else 'continuous') - source._strengths = np.array( - [float(x) for x in get_text(elem, 'strengths').split()]) - source._weights = np.array( - [float(x) for x in get_text(elem, 'weights').split()]) + if elem.find('strengths') is not None: + if source.energy_distribution_type == 'discrete': + raise ValueError( + "Continuum 'strengths' array found on CorrelatedSource with " + "energy distribution type 'discrete'.") + source.energy_bounds = get_elem_list(elem, 'group_bounds', float) + source.strengths = get_elem_list(elem, 'strengths', float) + source.weights = get_elem_list(elem, 'weights', float) + if elem.find('discrete_energies') is not None: + if source.energy_distribution_type == 'continuous': + raise ValueError( + "'discrete_energies' array found on CorrelatedSource with " + "energy distribution type 'continuous'.") + source.discrete_energies = get_elem_list( + elem, 'discrete_energies', float) + source.strengths_discrete = get_elem_list( + elem, 'strengths_discrete', float) + source.weights_discrete = get_elem_list( + elem, 'weights_discrete', float) return source diff --git a/src/source.cpp b/src/source.cpp index 6eb3478ca35..29959464ab3 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -712,12 +712,6 @@ SourceSite MeshSource::sample(uint64_t* seed) const CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) { - // Note: Source(node) reads strength/constraints from XML for consistency - // with other source types, but neither is actually used at sample time -- - // strength() is overridden to derive strength from the voxel data, and - // constraints_applied() == true means domain/energy/time constraints are - // never re-checked (the imported voxel probabilities are assumed to reflect - // only phase space actually populated by the original source). int32_t mesh_id = std::stoi(get_node_value(node, "mesh")); if (model::mesh_map.count(mesh_id) == 0) { fatal_error(fmt::format( @@ -748,45 +742,66 @@ CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) angle_mesh_idx_ = C_NONE; } - if (check_for_node(node, "group_bounds")) { - group_bounds_ = get_node_array(node, "group_bounds"); + if (check_for_node(node, "energy_distribution_type")) { + energy_distribution_type_ = + get_node_value(node, "energy_distribution_type"); } spatial_bins_ = model::meshes[spatial_mesh_idx_]->n_bins(); angle_bins_ = angle_mesh_idx_ == C_NONE ? 1 : model::meshes[angle_mesh_idx_]->n_bins(); - energy_bins_ = group_bounds_.empty() ? 1 : group_bounds_.size() - 1; - size_t n_voxels = - static_cast(spatial_bins_ * angle_bins_ * energy_bins_); + // Voxel strengths and weights are flattened in row-major (spatial, angle, + // energy) order, with the continuous-energy phase space voxels first, + // then the discrete-energy block + vector strengths; + if (check_for_node(node, "strengths")) { + group_bounds_ = get_node_array(node, "group_bounds"); + if (group_bounds_.size() < 2) { + fatal_error("CorrelatedSource 'group_bounds' must contain at least two " + "entries."); + } + energy_bins_ = static_cast(group_bounds_.size()) - 1; + n_continuum_voxels_ = spatial_bins_ * angle_bins_ * energy_bins_; + + strengths = get_node_array(node, "strengths"); + weights_ = get_node_array(node, "weights"); + if (static_cast(strengths.size()) != n_continuum_voxels_ || + static_cast(weights_.size()) != n_continuum_voxels_) { + fatal_error(fmt::format( + "CorrelatedSource continuum strength/weight arrays ({}, {} entries) " + "do not match the number of (spatial, angle, energy) voxels ({}).", + strengths.size(), weights_.size(), n_continuum_voxels_)); + } + } - // "strengths" flattened in row-major (spatial, angle, energy) order - vector strengths = get_node_array(node, "strengths"); - if (strengths.size() != n_voxels) { - fatal_error(fmt::format( - "Number of entries in the 'strengths' array for a CorrelatedSource " - "({}) does not match the number of (spatial, angle, energy) voxels " - "implied by its mesh(es) and energy bounds ({}).", - strengths.size(), n_voxels)); - } - double total_strength = - std::accumulate(strengths.begin(), strengths.end(), 0.0); - if (std::fabs(total_strength - 1.0) > FP_PRECISION) { - for (auto& element : strengths) { - element /= total_strength; + // Append the discrete (atom) block, if present + if (check_for_node(node, "discrete_energies")) { + discrete_energies_ = get_node_array(node, "discrete_energies"); + n_discrete_ = static_cast(discrete_energies_.size()); + + auto s_disc = get_node_array(node, "strengths_discrete"); + auto w_disc = get_node_array(node, "weights_discrete"); + int64_t n_disc_vox = spatial_bins_ * angle_bins_ * n_discrete_; + if (static_cast(s_disc.size()) != n_disc_vox || + static_cast(w_disc.size()) != n_disc_vox) { + fatal_error(fmt::format( + "CorrelatedSource discrete strength/weight arrays ({}, {} entries) " + "do not match the number of (spatial, angle, atom) voxels ({}).", + s_disc.size(), w_disc.size(), n_disc_vox)); } + strengths.insert(strengths.end(), s_disc.begin(), s_disc.end()); + weights_.insert(weights_.end(), w_disc.begin(), w_disc.end()); } - weights_ = get_node_array(node, "weights"); - if (weights_.size() != n_voxels) { - fatal_error(fmt::format( - "Number of entries in the 'weights' array for a CorrelatedSource " - "({}) does not match the number of (spatial, angle, energy) voxels " - "implied by its mesh(es) and energy bounds ({}).", - weights_.size(), n_voxels)); + auto is_negative = [](int x) { return x < 0; }; + if (std::any_of(strengths.begin(), strengths.end(), is_negative) || + std::any_of(weights_.begin(), weights_.end(), is_negative)) { + fatal_error("CorrelatedSource requires all continuum/discrete voxel " + "strengths and weights to be nonnegative."); } - voxel_dist_.assign(strengths); + voxel_dist_.assign(strengths); // performs normalization if (check_for_node(node, "particle")) { auto tmp_str = get_node_value(node, "particle", false, true); @@ -802,9 +817,25 @@ SourceSite CorrelatedSource::sample(uint64_t* seed) const // Select a phase-space voxel (m, a, g) size_t flat = voxel_dist_.sample(seed); - int64_t g = static_cast(flat % energy_bins_); - int64_t a = static_cast((flat / energy_bins_) % angle_bins_); - int64_t m = static_cast(flat / (energy_bins_ * angle_bins_)); + int64_t m, a; + bool discrete = static_cast(flat) >= n_continuum_voxels_; + + if (!discrete) { + int64_t g = static_cast(flat % energy_bins_); + a = static_cast((flat / energy_bins_) % angle_bins_); + m = static_cast(flat / (energy_bins_ * angle_bins_)); + double e_lo = group_bounds_[g]; + double e_hi = group_bounds_[g + 1]; + // sample uniformly in lethargy, except if e_lo is 0 + site.E = + (e_lo > 0.0) ? e_lo * std::pow(e_hi / e_lo, prn(seed)) : e_hi * prn(seed); + } else { + int64_t j = static_cast(flat) - n_continuum_voxels_; + int64_t k = j % n_discrete_; + a = (j / n_discrete_) % angle_bins_; + m = j / (n_discrete_ * angle_bins_); + site.E = discrete_energies_[k]; + } // Sample a position uniformly within the selected spatial mesh element site.r = model::meshes[spatial_mesh_idx_]->sample_element( @@ -819,13 +850,6 @@ SourceSite CorrelatedSource::sample(uint64_t* seed) const site.u = isotropic_direction(seed); } - // Energy is sampled from the selected group uniformly in lethargy - if (!group_bounds_.empty()) { - double e_lo = group_bounds_[g]; - double e_hi = group_bounds_[g + 1]; - site.E = e_lo * std::pow(e_hi / e_lo, prn(seed)); - } - site.wgt = weights_[flat]; return site; diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index 8df452b0327..f8d96e9ecbb 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -850,6 +850,9 @@ void SourceBias::to_hdf5(hid_t group) const { hid_t sb_group = create_group(group, fmt::format("source_bias_{}", ww_id_)); + write_attribute( + sb_group, "energy_distribution_type", energy_distribution_type_); + write_dataset( sb_group, "spatial_mesh", model::meshes[spatial_mesh_idx_]->id()); write_dataset(sb_group, "angle_mesh", @@ -860,11 +863,34 @@ void SourceBias::to_hdf5(hid_t group) const const int64_t spatial_bins = flux_.shape(0); const int64_t angle_bins = flux_.shape(1); const int64_t energy_bins = flux_.shape(2); + const int64_t n_atoms = static_cast(discrete_energies_.size()); + + const bool has_continuum = (energy_distribution_type_ != "discrete"); + const int64_t n_cont_e = has_continuum ? energy_bins : 0; tensor::Tensor biased_strength({static_cast(spatial_bins), - static_cast(angle_bins), static_cast(energy_bins)}); + static_cast(angle_bins), static_cast(n_cont_e)}); tensor::Tensor weights({static_cast(spatial_bins), - static_cast(angle_bins), static_cast(energy_bins)}); + static_cast(angle_bins), static_cast(n_cont_e)}); + + tensor::Tensor biased_discrete, wgts_discrete; + if (n_atoms > 0) { + biased_discrete = tensor::Tensor({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(n_atoms)}); + wgts_discrete = tensor::Tensor({static_cast(spatial_bins), + static_cast(angle_bins), static_cast(n_atoms)}); + } + + // Function to get the energy group containing a discrete energy value + auto group_of = [&](double E) -> int64_t { + if (energy_bins <= 1) + return 0; + if (E <= energy_bounds_.front()) + return 0; + if (E >= energy_bounds_.back()) + return energy_bins - 1; + return lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E); + }; // Calculate biasing parameters and simultaneously check to see if any // voxels containing probability mass associated with the unbiased source @@ -873,7 +899,7 @@ void SourceBias::to_hdf5(hid_t group) const double total_missed_S = 0.0; for (int64_t m = 0; m < spatial_bins; ++m) { for (int64_t a = 0; a < angle_bins; ++a) { - for (int64_t e = 0; e < energy_bins; ++e) { + for (int64_t e = 0; e < n_cont_e; ++e) { double psi = flux_(m, a, e); double b = psi * unbiased_strength_(m, a, e); biased_strength(m, a, e) = b; @@ -885,6 +911,22 @@ void SourceBias::to_hdf5(hid_t group) const } } + // Do the same for any discrete emission energies of the unbiased + // source spectrum, using the adjoint angular flux of the group containing + // the discrete energy to determine biased source strength + for (int64_t k = 0; k < n_atoms; ++k) { + int64_t g = group_of(discrete_energies_[k]); + for (int64_t m = 0; m < spatial_bins; ++m) + for (int64_t a = 0; a < angle_bins; ++a) { + double psi = flux_(m, a, g); + double b = psi * unbiased_strength_discrete_(m, a, k); + biased_discrete(m, a, k) = b; + total_strength += b; + if (psi <= 0.0) + total_missed_S += unbiased_strength_discrete_(m, a, k); + } + } + if (total_missed_S > TINY_BIT) { fatal_error(fmt::format("Biased source does not sample whole support of " "the unbiased source. Probability mass lost in " @@ -894,23 +936,35 @@ void SourceBias::to_hdf5(hid_t group) const // Rescale biased strengths so that they add up to probability 1.0. // This would be done anyway by the DiscreteIndex inside of CorrelatedSource - // when sampling a phase space bin, but the normalization should be done - // beforehand so that source's .strength() attribute still appears as 1.0. - // Also apply sample weight of (total_strength / psi) so that total - // probability mass still equals 1.0. + // when sampling a phase space bin. + // Also apply sample weight of (total_strength / psi) so that expected mass + // per voxel equals the unbiased strength in each voxel. for (int64_t m = 0; m < spatial_bins; ++m) { for (int64_t a = 0; a < angle_bins; ++a) { - for (int64_t e = 0; e < energy_bins; ++e) { + for (int64_t e = 0; e < n_cont_e; ++e) { double psi = flux_(m, a, e); weights(m, a, e) = psi > 0.0 ? total_strength / psi : 0.0; biased_strength(m, a, e) /= total_strength; } + + for (int64_t k = 0; k < n_atoms; ++k) { + double psi = flux_(m, a, group_of(discrete_energies_[k])); + wgts_discrete(m, a, k) = psi > 0.0 ? total_strength / psi : 0.0; + biased_discrete(m, a, k) /= total_strength; + } } } write_dataset(sb_group, "biased_source_strength", biased_strength); write_dataset(sb_group, "weights", weights); + if (energy_distribution_type_ != "continuous") { + write_dataset(sb_group, "discrete_energies", discrete_energies_); + + write_dataset(sb_group, "biased_source_strength_discrete", biased_discrete); + write_dataset(sb_group, "weights_discrete", wgts_discrete); + } + close_group(sb_group); } @@ -1087,6 +1141,34 @@ void SourceBias::load_forward_source_mesh(const std::string& path) read_dataset(file, "unbiased_source_strength", unbiased_strength_); + // Read source strengths at discrete energies if source is mixed or discrete + if (attribute_exists(file, "energy_distribution_type")) { + read_attribute(file, "energy_distribution_type", energy_distribution_type_); + } else { + energy_distribution_type_ = "continuous"; + } + + if (object_exists(file, "discrete_energies")) { + read_dataset(file, "discrete_energies", discrete_energies_); + read_dataset( + file, "unbiased_source_strength_discrete", unbiased_strength_discrete_); + + if (discrete_energies_.size() > 0 && + energy_distribution_type_ == "continuous") { + fatal_error(fmt::format( + "Forward source mesh for biasing has type 'continuous' but contains " + "{} discrete emission energies.", + discrete_energies_.size())); + } else if (energy_distribution_type_ != "continuous" && + discrete_energies_.size() == 0) { + fatal_error("Forward source mesh for biasing has 'discrete' or 'mixed' " + "type but contains zero discrete emission energies."); + } + } else if (energy_distribution_type_ != "continuous") { + fatal_error("Forward source mesh for biasing has 'discrete' or 'mixed' " + "type but discrete emission energies could not be found."); + } + file_close(file); } From 3e405cc02398bddf6eceafc282b39603169b25f3 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 30 Oct 2026 10:17:30 -0400 Subject: [PATCH 32/37] Remove runtime forward source meshing from SourceBias as it was incompatible with different treatments for discrete and continuous energy distributions --- openmc/weight_windows.py | 2 +- src/weight_windows.cpp | 88 ++-------------------------------------- 2 files changed, 5 insertions(+), 85 deletions(-) diff --git a/openmc/weight_windows.py b/openmc/weight_windows.py index a37272899c2..4481872dcbc 100644 --- a/openmc/weight_windows.py +++ b/openmc/weight_windows.py @@ -507,7 +507,7 @@ class WeightWindowGenerator: Whether to perform automated biasing of fixed sources via FW-CADIS. forward_source_mesh_file : Pathlike Path to a forward source mesh file storing unbiased source strengths - in each phase space voxel. + in each phase space voxel. Required for automated source biasing. angular_biasing_quadrature : :class:`openmc.UnitSpherePointset`, optional Optional set of angles to generate source biasing parameters on. Defaults to None for biasing as a function of space and energy only. diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index f8d96e9ecbb..175a40a5b5d 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -985,93 +985,13 @@ void SourceBias::compute_unbiased_strength(int64_t n_samples_per_source) } } - // A precomputed file takes priority over sampling model::external_sources if (file_exists(forward_source_mesh_)) { load_forward_source_mesh(forward_source_mesh_); - return; - } - - Mesh* spatial_mesh = model::meshes[spatial_mesh_idx_].get(); - Mesh* angle_mesh = - angle_mesh_idx_ == C_NONE ? nullptr : model::meshes[angle_mesh_idx_].get(); - - // Normalize by total strength across all forward external sources - double total_strength = 0.0; - for (const auto& source_ptr : model::external_sources) { - auto* is = dynamic_cast(source_ptr.get()); - if (!is) { - fatal_error("Computing an unbiased source strength distribution " - "requires all external sources to be independent " - "sources."); - } - total_strength += is->strength(); - } - if (total_strength <= 0.0) { - fatal_error("Total external source strength must be positive to " - "compute an unbiased source strength distribution."); - } - - // Fixed local seed, not part of the sequence used for transport - uint64_t seed = 1; - - tensor::Tensor spatial_angle_counts( - {static_cast(spatial_bins), static_cast(angle_bins)}); - - for (const auto& source_ptr : model::external_sources) { - Source* s = source_ptr.get(); - auto* is = dynamic_cast(s); - double relative_strength = is->strength() / total_strength; - - auto* energy_dist = dynamic_cast(is->energy()); - if (!energy_dist) { - fatal_error( - "Source biasing requires all external sources to use a Discrete " - "(multigroup) energy distribution, matching the requirement for " - "random ray fixed source problems."); - } - vector group_prob(energy_bins, 0.0); - const auto& e_vals = energy_dist->x(); - const auto& e_probs = energy_dist->prob(); - for (std::size_t i = 0; i < e_vals.size(); ++i) { - int g = data::mg.get_group_index(e_vals[i]); - if (g >= 0 && g < energy_bins) - group_prob[g] += e_probs[i]; - } - - // Monte Carlo estimate of the joint (spatial, angular) distribution. - // Energy is not sampled when solver type is Random Ray. - for (int64_t m = 0; m < spatial_bins; ++m) { - for (int64_t a = 0; a < angle_bins; ++a) { - spatial_angle_counts(m, a) = 0.0; - } - } - - for (int64_t i = 0; i < n_samples_per_source; ++i) { - SourceSite site = is->sample(&seed); - - int32_t m = spatial_mesh->get_bin(site.r); - if (m < 0) - continue; - - int32_t a = angle_mesh ? angle_mesh->get_bin(site.u) : 0; - if (angle_mesh && a < 0) - continue; - - spatial_angle_counts(m, a) += 1.0; - } - - for (int64_t m = 0; m < spatial_bins; ++m) { - for (int64_t a = 0; a < angle_bins; ++a) { - double frac = spatial_angle_counts(m, a) / n_samples_per_source; - if (frac == 0.0) - continue; - for (int64_t e = 0; e < energy_bins; ++e) { - unbiased_strength_(m, a, e) += - relative_strength * frac * group_prob[e]; - } - } - } + } else { + fatal_error(fmt::format( + "Could not locate forward source mesh file '{}'.", forward_source_mesh_)) } + return; } void SourceBias::load_forward_source_mesh(const std::string& path) From 77085f8a308ad7338d314d1cfaccc5f1a894b42e Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Wed, 18 Nov 2026 14:54:27 -0500 Subject: [PATCH 33/37] C++ formatting fixes for source region --- include/openmc/random_ray/source_region.h | 16 ++++++++-------- src/random_ray/flat_source_domain.cpp | 2 +- src/random_ray/source_region.cpp | 3 ++- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/include/openmc/random_ray/source_region.h b/include/openmc/random_ray/source_region.h index 3e4b02df4a9..77b6c1bf198 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -204,7 +204,7 @@ class SourceRegionHandle { float* external_source_ = nullptr; double* scalar_flux_final_ = nullptr; // Non-null only when angular flux is tallied in a SR - double* angular_flux_new_; + double* angular_flux_new_ = nullptr; // Non-null only for the adaptive volume estimator family double* scalar_flux_t_ = nullptr; @@ -498,11 +498,11 @@ class SourceRegionContainer { public: //---------------------------------------------------------------------------- // Constructors - SourceRegionContainer(int negroups, bool is_linear, int nangles = 1, - bool is_adaptive, bool is_strict_adaptive, bool track_extents) - : negroups_(negroups), is_linear_(is_linear), nangles_(nangles), - is_adaptive_(is_adaptive), is_strict_adaptive_(is_strict_adaptive), - track_extents_(track_extents) + SourceRegionContainer(int negroups, bool is_linear, bool is_adaptive, + bool is_strict_adaptive, bool track_extents, int nangles = 1) + : negroups_(negroups), is_linear_(is_linear), is_adaptive_(is_adaptive), + is_strict_adaptive_(is_strict_adaptive), track_extents_(track_extents), + nangles_(nangles) {} SourceRegionContainer() = default; @@ -511,8 +511,8 @@ class SourceRegionContainer { //! container from scratch after load balancing. SourceRegionContainer empty_like() const { - return SourceRegionContainer( - negroups_, is_linear_, is_adaptive_, is_strict_adaptive_, track_extents_); + return SourceRegionContainer(negroups_, is_linear_, is_adaptive_, + is_strict_adaptive_, track_extents_, nangles_); } //---------------------------------------------------------------------------- diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 37100ac805d..53cebaa5f70 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -74,7 +74,7 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) resolved_volume_estimator_ == RandomRayVolumeEstimator::STRICT_ADAPTIVE; // The sampled bounding boxes exist only for the source gradient limiter source_regions_ = SourceRegionContainer(negroups_, is_linear, nangles_, - is_adaptive, is_strict_adaptive, is_linear && source_gradient_limiter_, ); + is_adaptive, is_strict_adaptive, is_linear && source_gradient_limiter_); // Initialize tally volumes if (volume_normalized_flux_tallies_) { diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 92658b6a1b2..2701e4d2cc0 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -95,7 +95,8 @@ SourceRegion::SourceRegion( } SourceRegion::SourceRegion(const SourceRegionHandle& handle) - : SourceRegion(handle.negroups_, handle.is_linear_) + : SourceRegion(handle.negroups_, handle.is_linear_, handle.nangles_, + handle.needs_angular_flux_) { scalars_.material_ = handle.material(); scalars_.is_small_ = handle.is_small(); From c17398dad6b0bcef7b54d3c2b5571920341d1213 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Fri, 20 Nov 2026 16:54:13 -0500 Subject: [PATCH 34/37] Formatting errors and domain decomposition support for angular flux tallying; adding angular flux accumulation to set_flux_to functions in LS domains --- include/openmc/distribution_multi.h | 6 ++--- include/openmc/random_ray/decomposition_map.h | 1 + .../openmc/random_ray/flat_source_domain.h | 8 +++--- include/openmc/random_ray/random_ray.h | 2 ++ src/distribution_multi.cpp | 2 +- src/random_ray/decomposition_map.cpp | 21 +++++++++++++++ src/random_ray/flat_source_domain.cpp | 14 +++------- src/random_ray/linear_source_domain.cpp | 27 +++++++++++++++++++ src/random_ray/random_ray.cpp | 2 ++ src/random_ray/ray_bank.cpp | 1 + src/random_ray/source_region.cpp | 27 ++++++++++++++++--- 11 files changed, 89 insertions(+), 22 deletions(-) diff --git a/include/openmc/distribution_multi.h b/include/openmc/distribution_multi.h index dbf3e4aacc6..05e9fe64cd3 100644 --- a/include/openmc/distribution_multi.h +++ b/include/openmc/distribution_multi.h @@ -7,8 +7,8 @@ #include "openmc/distribution.h" #include "openmc/error.h" -#include "openmc/position.h" #include "openmc/mesh.h" +#include "openmc/position.h" namespace openmc { @@ -171,8 +171,8 @@ class MeshAngular : public UnitSphereDistribution { private: int32_t mesh_idx_ {C_NONE}; - DiscreteIndex elem_idx_dist_; //!< Distribution of mesh element indices - vector weight_; //!< Importance weights (empty if unbiased) + DiscreteIndex elem_idx_dist_; //!< Distribution of mesh element indices + vector weight_; //!< Importance weights (empty if unbiased) Direction v_ref_ {1.0, 0.0, 0.0}; //!< reference direction }; diff --git a/include/openmc/random_ray/decomposition_map.h b/include/openmc/random_ray/decomposition_map.h index b79dfe8d00b..bf6e1d5fa3f 100644 --- a/include/openmc/random_ray/decomposition_map.h +++ b/include/openmc/random_ray/decomposition_map.h @@ -122,6 +122,7 @@ class DecompositionMap { // Miscellaneous uint64_t n_base_sr_; int negroups_; + int nangles_ {1}; double max_domain_length_; bool is_linear_; bool is_adaptive_; diff --git a/include/openmc/random_ray/flat_source_domain.h b/include/openmc/random_ray/flat_source_domain.h index ec117269b90..6d0a0e119d4 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -139,6 +139,8 @@ class FlatSourceDomain { static double diagonal_stabilization_rho_; // Adjusts strength of diagonal stabilization // for transport corrected MGXS data + // Number of bins for any angular tallies + static int nangles_; // Static variables to store source region meshes and domains static std::unordered_map>> @@ -255,8 +257,7 @@ class FlatSourceDomain { void set_flux_to_source(int64_t sr, int g); virtual void set_flux_to_old_flux(int64_t sr, int g); virtual double flux_additive_term(int64_t sr, int g, bool batch_volume) const; - virtual double angular_flux_additive_term( - int64_t sr, int g, bool batch_volume) const; + double angular_flux_additive_term(int64_t sr, int g, bool batch_volume) const; double stabilized_flux(int64_t sr, int g, double phi_new) const; //! Adaptive-estimator "strong source" test. Returns true if, in any group, @@ -273,8 +274,7 @@ class FlatSourceDomain { //---------------------------------------------------------------------------- // Private data members - int negroups_; // Number of energy groups in simulation - int nangles_ {1}; // Number of bins for any angular flux tallies + int negroups_; // Number of energy groups in simulation const UnitSpherePointset* angular_mesh_ {nullptr}; vector tally_is_angular_; diff --git a/include/openmc/random_ray/random_ray.h b/include/openmc/random_ray/random_ray.h index 2306ea891dc..be8aa25d20d 100644 --- a/include/openmc/random_ray/random_ray.h +++ b/include/openmc/random_ray/random_ray.h @@ -26,6 +26,7 @@ struct RayBufferContainer { // early-return in attenuate_flux_inner() happens before n_event() is // incremented, so max_particle_events cannot bound a forwarding loop. int n_transfers; + int angular_bin; vector angular_flux; int surface; bool is_active; @@ -61,6 +62,7 @@ struct RayBufferContainer { struct RayExchangeData { Position position; Direction direction; + int angular_bin; double distance_travelled; double advance_distance; int n_transfers; diff --git a/src/distribution_multi.cpp b/src/distribution_multi.cpp index 7e0b89de88e..2a5b5654be1 100644 --- a/src/distribution_multi.cpp +++ b/src/distribution_multi.cpp @@ -5,8 +5,8 @@ #include "openmc/constants.h" #include "openmc/error.h" -#include "openmc/mesh.h" #include "openmc/math_functions.h" +#include "openmc/mesh.h" #include "openmc/random_dist.h" #include "openmc/random_lcg.h" #include "openmc/xml_interface.h" diff --git a/src/random_ray/decomposition_map.cpp b/src/random_ray/decomposition_map.cpp index 7ed1321319c..eef8ae2f312 100644 --- a/src/random_ray/decomposition_map.cpp +++ b/src/random_ray/decomposition_map.cpp @@ -27,6 +27,7 @@ DecompositionMap::DecompositionMap() {} void DecompositionMap::initialize() { negroups_ = data::mg.num_energy_groups_; + nangles_ = FlatSourceDomain::nangles_; estimated_rank_load_fractions_.resize(mpi::n_procs, 0.0); measured_rank_load_fractions_.resize(mpi::n_procs, 0.0); estimated_rank_load_totals_.resize(mpi::n_procs, 0.0); @@ -542,6 +543,10 @@ void DecompositionMap::send_sr_data( if (is_linear_) { num_vector_messages += 4; } + bool send_angular = sr_send.scalars_.needs_angular_flux_; + if (send_angular) { + num_vector_messages += 1; + } // The sampled bounding box lives outside ScalarSourceRegionFields, so it // needs a message of its own when the source gradient limiter is enabled bool send_extent = is_linear_ && FlatSourceDomain::source_gradient_limiter_; @@ -590,6 +595,16 @@ void DecompositionMap::send_sr_data( 6, mpi::intracomm, &requests[req_idx]); req_idx++; + if (send_angular) { + if (sr_send.angular_flux_new_.size() != negroups_ * nangles_) { + fatal_error("Angular flux storage missing for source region flagged " + "for angular flux tallying."); + } + MPI_Isend(sr_send.angular_flux_new_.data(), negroups_ * nangles_, + MPI_DOUBLE, receiver, 13, mpi::intracomm, &requests[req_idx]); + req_idx++; + } + if (is_linear_) { MPI_Isend(sr_send.source_gradients_.data(), 3 * negroups_, MPI_DOUBLE, receiver, 7, mpi::intracomm, &requests[req_idx]); @@ -660,6 +675,12 @@ void DecompositionMap::receive_sr_data(int sender, SourceRegion& sr_recv) MPI_Recv(sr_recv.scalar_flux_final_.data(), negroups_, MPI_DOUBLE, sender, 6, mpi::intracomm, MPI_STATUS_IGNORE); + if (sr_recv.scalars_.needs_angular_flux_) { + sr_recv.angular_flux_new_.assign(negroups_ * nangles_, 0.0); + MPI_Recv(sr_recv.angular_flux_new_.data(), negroups_ * nangles_, MPI_DOUBLE, + sender, 13, mpi::intracomm, MPI_STATUS_IGNORE); + } + if (is_linear_) { MPI_Recv(sr_recv.source_gradients_.data(), 3 * negroups_, MPI_DOUBLE, sender, 7, mpi::intracomm, MPI_STATUS_IGNORE); diff --git a/src/random_ray/flat_source_domain.cpp b/src/random_ray/flat_source_domain.cpp index 31512c5c5d5..5fb8e8ad74a 100644 --- a/src/random_ray/flat_source_domain.cpp +++ b/src/random_ray/flat_source_domain.cpp @@ -46,6 +46,7 @@ double FlatSourceDomain::diagonal_stabilization_rho_ {1.0}; std::unordered_map>> FlatSourceDomain::mesh_domain_map_; std::vector FlatSourceDomain::fw_cadis_local_targets_; +int FlatSourceDomain::nangles_ {1}; FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) { @@ -73,8 +74,8 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) bool is_strict_adaptive = resolved_volume_estimator_ == RandomRayVolumeEstimator::STRICT_ADAPTIVE; // The sampled bounding boxes exist only for the source gradient limiter - source_regions_ = SourceRegionContainer(negroups_, is_linear, nangles_, - is_adaptive, is_strict_adaptive, is_linear && source_gradient_limiter_); + source_regions_ = SourceRegionContainer(negroups_, is_linear, is_adaptive, + is_strict_adaptive, is_linear && source_gradient_limiter_, nangles_); // Initialize tally volumes if (volume_normalized_flux_tallies_) { @@ -399,14 +400,7 @@ double FlatSourceDomain::flux_additive_term( double FlatSourceDomain::angular_flux_additive_term( int64_t sr, int g, bool batch_volume) const { - if (source_regions_.material(sr) == MATERIAL_VOID) { - if (settings::run_mode == RunMode::FIXED_SOURCE) { - return 0.5f * source_regions_.external_source(sr, g) * - source_regions_.volume_sq(sr) / source_regions_.nangles(); - } - return 0.0; - } - return source_regions_.source(sr, g) / source_regions_.nangles(); + return flux_additive_term(sr, g, batch_volume) / source_regions_.nangles(); } void FlatSourceDomain::set_flux_to_flux_plus_source( diff --git a/src/random_ray/linear_source_domain.cpp b/src/random_ray/linear_source_domain.cpp index 5152b9e50a6..52cc344b7a4 100644 --- a/src/random_ray/linear_source_domain.cpp +++ b/src/random_ray/linear_source_domain.cpp @@ -184,6 +184,13 @@ void LinearSourceDomain::normalize_flux_and_volumes( source_regions_.flux_moments_new(se) *= normalization_factor; } +// Normalize angular flux in the same way +#pragma omp parallel for + for (int64_t sea = 0; sea < source_regions_.n_source_angular_elements(); + sea++) { + source_regions_.angular_flux_new(sea) *= normalization_factor; + } + // Accumulate cell-wise ray length tallies collected this iteration, then // update the simulation-averaged cell-wise volume estimates #pragma omp parallel for @@ -268,6 +275,13 @@ void LinearSourceDomain::set_flux_to_flux_plus_source( source_regions_.scalar_flux_new(sr, g) /= volume; source_regions_.scalar_flux_new(sr, g) += flux_additive_term(sr, g, batch_volume); + if (source_regions_.needs_angular_flux(sr)) { + double flux_addition = angular_flux_additive_term(sr, g, batch_volume); + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) /= volume; + source_regions_.angular_flux_new(sr, g, a) += flux_addition; + } + } } // If a source region is small, then the moments are likely noisy, so we zero // them. This is reasonable, given that small regions can get by with a flat @@ -285,6 +299,19 @@ void LinearSourceDomain::set_flux_to_old_flux(int64_t sr, int g) source_regions_.scalar_flux_old(sr, g); source_regions_.flux_moments_new(sr, g) = source_regions_.flux_moments_old(sr, g); + + if (source_regions_.needs_angular_flux(sr)) { + // To minimize memory use, we don't store the previous iteration's + // angular fluxes. Recognizing that this case only occurs in the few + // percent or less of source regions missed during an iteration, we + // approximate the angular flux by dividing the scalar flux estimate + // evenly across all angles. + double isotropic_flux = + source_regions_.scalar_flux_new(sr, g) / source_regions_.nangles(); + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) = isotropic_flux; + } + } } void LinearSourceDomain::accumulate_iteration_flux() diff --git a/src/random_ray/random_ray.cpp b/src/random_ray/random_ray.cpp index 6397cf6a8c0..6bc28217b37 100644 --- a/src/random_ray/random_ray.cpp +++ b/src/random_ray/random_ray.cpp @@ -980,6 +980,7 @@ void RandomRay::restart_ray(FlatSourceDomain* domain, RayExchangeData& data, } u() = data.direction; + angular_bin_ = data.angular_bin; // The buffered coordinate levels hold the ray's state at the last geometry // update, so the ray still has to be advanced to the point at which it left @@ -1176,6 +1177,7 @@ void RandomRay::pack_ray_for_buffer( exchange_data_.advance_distance = advance_distance; exchange_data_.n_transfers = ++n_transfers_; exchange_data_.direction = u(); + exchange_data_.angular_bin = angular_bin_; exchange_data_.angular_flux = angular_flux_; exchange_data_.distance_travelled = distance_buffer; exchange_data_.surface = surface(); diff --git a/src/random_ray/ray_bank.cpp b/src/random_ray/ray_bank.cpp index 8fc30f027f6..a717895c223 100644 --- a/src/random_ray/ray_bank.cpp +++ b/src/random_ray/ray_bank.cpp @@ -66,6 +66,7 @@ void RayBank::buffer_ray_data_to_send(RandomRay& ray, FlatSourceDomain* domain) rd.distance_travelled = rbc.distance_travelled; rd.advance_distance = rbc.advance_distance; rd.n_transfers = rbc.n_transfers; + rd.angular_bin = rbc.angular_bin; rd.surface = rbc.surface; rd.is_active = rbc.is_active; rd.ray_id = rbc.ray_id; diff --git a/src/random_ray/source_region.cpp b/src/random_ray/source_region.cpp index 2701e4d2cc0..5e81032bfc7 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -40,7 +40,6 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) scalar_flux_new_(sr.scalar_flux_new_.data()), source_(sr.source_.data()), external_source_(sr.external_source_.data()), scalar_flux_final_(sr.scalar_flux_final_.data()), - angular_flux_new_(sr.angular_flux_new_.data()), source_gradients_(sr.source_gradients_.data()), flux_moments_old_(sr.flux_moments_old_.data()), flux_moments_new_(sr.flux_moments_new_.data()), @@ -52,6 +51,8 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) // and this pointer is null-tested to mean "field absent" scalar_flux_t_ = sr.scalar_flux_t_.empty() ? nullptr : sr.scalar_flux_t_.data(); + angular_flux_new_ = + sr.angular_flux_new_.empty() ? nullptr : sr.angular_flux_new_.data(); } //============================================================================== @@ -74,8 +75,8 @@ SourceRegion::SourceRegion( source_.assign(negroups, 0.0); scalar_flux_final_.assign(negroups, 0.0); // Only allocate angular flux storage for regions that need it - needs_angular_flux_ = needs_angular_flux; - if (needs_angular_flux_) { + scalars_.needs_angular_flux_ = needs_angular_flux; + if (needs_angular_flux) { angular_flux_new_.assign(negroups * nangles, 0.0f); } // Only the adaptive estimator family reads this, and this constructor runs @@ -96,7 +97,7 @@ SourceRegion::SourceRegion( SourceRegion::SourceRegion(const SourceRegionHandle& handle) : SourceRegion(handle.negroups_, handle.is_linear_, handle.nangles_, - handle.needs_angular_flux_) + handle.needs_angular_flux()) { scalars_.material_ = handle.material(); scalars_.is_small_ = handle.is_small(); @@ -154,6 +155,11 @@ SourceRegion::SourceRegion(const SourceRegionHandle& handle) } tally_task_[g] = handle.tally_task(g); } + if (handle.angular_flux_new_) { + for (int ga = 0; ga < handle.negroups_ * handle.nangles_; ++ga) { + angular_flux_new_[ga] = handle.angular_flux_new_[ga]; + } + } if (settings::run_mode == RunMode::FIXED_SOURCE) { scalars_.external_source_present_ = handle.external_source_present(); for (int g = 0; g < scalar_flux_new_.size(); g++) { @@ -203,6 +209,19 @@ void SourceRegion::merge(SourceRegion& sr_add, bool is_linear) flux_moments_new_[g] += sr_add.flux_moments_new_[g]; } } + + scalars_.needs_angular_flux_ = + std::max(scalars_.needs_angular_flux_, sr_add.scalars_.needs_angular_flux_); + + if (!sr_add.angular_flux_new_.empty()) { + if (angular_flux_new_.empty()) { + angular_flux_new_.assign(sr_add.angular_flux_new_.size(), 0.0); + } +#pragma omp simd + for (size_t i = 0; i < angular_flux_new_.size(); ++i) { + angular_flux_new_[i] += sr_add.angular_flux_new_[i]; + } + } } //============================================================================== From d089d63775dfa10dff022f5b2920374a10eb0e96 Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 23 Nov 2026 14:53:56 -0500 Subject: [PATCH 35/37] Add error on AngularMesh::next_mesh_crossing() and fix UnitSphereTriangularMesh vertices check --- include/openmc/mesh.h | 7 +++++++ src/mesh.cpp | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 72744b4356f..6584beb5adc 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -922,6 +922,13 @@ class AngularMesh : public Mesh { fatal_error("Angular meshes do not support spatial tracklength tallies."); } + MeshCrossing next_mesh_crossing( + int current_bin, Position r, Direction u) const override + { + fatal_error("Angular meshes do not support spatial mesh crossings."); + return {INFTY, C_NONE}; + } + void surface_bins_crossed(Position r0, Position r1, const Direction& u, vector& bins) const override { diff --git a/src/mesh.cpp b/src/mesh.cpp index 074d47f985e..f860b268a4e 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -2702,7 +2702,7 @@ const std::string UnitSphereTriangularMesh::mesh_type = "angular_triangular"; UnitSphereTriangularMesh::UnitSphereTriangularMesh(vector vertices) : vertices_(std::move(vertices)) { - if (vertices.size() % 9 != 0) { + if (vertices_.size() % 9 != 0) { fatal_error(fmt::format("Vertex array for triangular unit sphere mesh {} " "does not describe a whole number of triangles.", id_)); From bf34383fad269d9180c75c19c2563f19833eb61f Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 23 Nov 2026 15:11:21 -0500 Subject: [PATCH 36/37] formatting in weight_windows.cpp --- src/weight_windows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index ef634a7416d..f528469f8ab 100644 --- a/src/weight_windows.cpp +++ b/src/weight_windows.cpp @@ -990,7 +990,7 @@ void SourceBias::compute_unbiased_strength(int64_t n_samples_per_source) load_forward_source_mesh(forward_source_mesh_); } else { fatal_error(fmt::format( - "Could not locate forward source mesh file '{}'.", forward_source_mesh_)) + "Could not locate forward source mesh file '{}'.", forward_source_mesh_)); } return; } From 71f669bf1b3fd0d1f7e58ec86c78e0311aacc84d Mon Sep 17 00:00:00 2001 From: j-fletcher Date: Mon, 23 Nov 2026 16:08:50 -0500 Subject: [PATCH 37/37] default value for source_biasing_ and clear array to free memory --- include/openmc/weight_windows.h | 2 +- src/weight_windows.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index 450ff5d050a..1def1ea3be6 100644 --- a/include/openmc/weight_windows.h +++ b/include/openmc/weight_windows.h @@ -329,7 +329,7 @@ class WeightWindowsGenerator { // Local FW-CADIS target tallies std::vector targets_; // FW-CADIS source biasing - bool source_biasing_; + bool source_biasing_ {false}; int32_t angle_mesh_idx_ {C_NONE}; //