diff --git a/CMakeLists.txt b/CMakeLists.txt index d3a8282af6b..c7763e9faac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -421,6 +421,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/capi.h b/include/openmc/capi.h index 6c400844098..a09811d518d 100644 --- a/include/openmc/capi.h +++ b/include/openmc/capi.h @@ -148,6 +148,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_name(int32_t index, const char** name); @@ -156,6 +157,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_cylindrical_mesh_get_origin(int32_t index, double origin[3]); diff --git a/include/openmc/constants.h b/include/openmc/constants.h index d8cd522a862..ccf765f0834 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/distribution_multi.h b/include/openmc/distribution_multi.h index a72780737a6..05e9fe64cd3 100644 --- a/include/openmc/distribution_multi.h +++ b/include/openmc/distribution_multi.h @@ -7,6 +7,7 @@ #include "openmc/distribution.h" #include "openmc/error.h" +#include "openmc/mesh.h" #include "openmc/position.h" namespace openmc { @@ -135,6 +136,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 95a9e4db1a8..6584beb5adc 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -286,7 +286,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 @@ -302,7 +302,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 @@ -906,6 +906,129 @@ 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."); + } + + 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 + { + 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 {{}, {}}; + } + + 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); + } + + 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"); + } + + 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_; +}; + +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 { return areas_[bin]; } + + 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/include/openmc/particle.h b/include/openmc/particle.h index 6a672c7a16e..d1d3dd4f5a6 100644 --- a/include/openmc/particle.h +++ b/include/openmc/particle.h @@ -117,6 +117,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/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 031cc8b182a..6d0a0e119d4 100644 --- a/include/openmc/random_ray/flat_source_domain.h +++ b/include/openmc/random_ray/flat_source_domain.h @@ -2,6 +2,7 @@ #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" @@ -74,13 +75,14 @@ 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); bool is_geometry_3D(); 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(); @@ -118,6 +120,10 @@ 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 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; //---------------------------------------------------------------------------- // Static Data members @@ -133,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>> @@ -249,6 +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; + 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, @@ -266,6 +275,13 @@ class FlatSourceDomain { //---------------------------------------------------------------------------- // Private data members int negroups_; // Number of energy groups in simulation + 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_spatial_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/linear_source_domain.h b/include/openmc/random_ray/linear_source_domain.h index bdcb006d4a2..36ab2719786 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 e58d46f0f87..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; @@ -117,6 +119,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 initialize_ray(uint64_t ray_id, FlatSourceDomain* domain); void restart_ray(FlatSourceDomain* domain, RayExchangeData& data, @@ -125,6 +128,7 @@ class RandomRay : public Particle { SourceSite sample_prng(); SourceSite sample_halton(); SourceSite sample_s2(); + int angular_bin(); // accessor for current angular quadrature bin index bool has_left_subdomain(); void pack_ray_for_buffer(double distance_buffer, double advance_distance); @@ -157,6 +161,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 340f925a32a..77b6c1bf198 100644 --- a/include/openmc/random_ray/source_region.h +++ b/include/openmc/random_ray/source_region.h @@ -55,9 +55,13 @@ struct TallyTask { int64_t filter_idx; int score_idx; int score_type; - TallyTask(int tally_idx, int64_t filter_idx, int score_idx, int score_type) + // 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, + 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; @@ -66,7 +70,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 { @@ -77,6 +82,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; } }; @@ -148,6 +154,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}; @@ -168,6 +175,7 @@ class SourceRegionHandle { double* volume_naive_ = nullptr; int* position_recorded_ = nullptr; int* external_source_present_ = nullptr; + int* needs_angular_flux_ = nullptr; Position* position_ = nullptr; Position* centroid_ = nullptr; Position* centroid_iteration_ = nullptr; @@ -195,6 +203,8 @@ class SourceRegionHandle { float* source_ = nullptr; float* external_source_ = nullptr; double* scalar_flux_final_ = nullptr; + // Non-null only when angular flux is tallied in a SR + double* angular_flux_new_ = nullptr; // Non-null only for the adaptive volume estimator family double* scalar_flux_t_ = nullptr; @@ -256,6 +266,9 @@ 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_; } @@ -310,6 +323,15 @@ class SourceRegionHandle { double& scalar_flux_t(int g) { return scalar_flux_t_[g]; } const double scalar_flux_t(int g) const { return scalar_flux_t_[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]; } @@ -364,7 +386,9 @@ class ScalarSourceRegionFields { 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? int is_small_ {0}; //!< Is it "small", receiving < 1.5 hits per iteration? int n_negative_batches_ { 0}; //!< Number of batches in which this region's flux went negative @@ -402,7 +426,8 @@ class SourceRegion { public: //---------------------------------------------------------------------------- // Constructors - SourceRegion(int negroups, bool is_linear); + SourceRegion(int negroups, bool is_linear, int nangles = 1, + bool needs_angular_flux = false); SourceRegion(const SourceRegionHandle& handle); SourceRegion() = default; @@ -450,6 +475,9 @@ class SourceRegion { vector scalar_flux_t_; //!< Running flux sum used by the adaptive //!< volume estimator's demotion step + 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 @@ -471,9 +499,10 @@ class SourceRegionContainer { //---------------------------------------------------------------------------- // Constructors SourceRegionContainer(int negroups, bool is_linear, bool is_adaptive, - bool is_strict_adaptive, bool track_extents) + 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) + is_strict_adaptive_(is_strict_adaptive), track_extents_(track_extents), + nangles_(nangles) {} SourceRegionContainer() = default; @@ -482,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_); } //---------------------------------------------------------------------------- @@ -542,6 +571,12 @@ 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]; } @@ -686,6 +721,20 @@ class SourceRegionContainer { double& scalar_flux_t(int64_t se) { return scalar_flux_t_[se]; } const double scalar_flux_t(int64_t se) const { return scalar_flux_t_[se]; } + double& angular_flux_new(int64_t sr, int g, int 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_[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 + { + return angular_flux_new_[sea]; + } + 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]; } @@ -740,8 +789,11 @@ 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 angular_flux_new_.size(); } 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); @@ -752,6 +804,7 @@ class SourceRegionContainer { // Private Data Members int64_t n_source_regions_ {0}; int negroups_ {0}; + int nangles_ {1}; bool is_linear_ {false}; bool is_adaptive_ {false}; bool is_strict_adaptive_ {false}; @@ -777,6 +830,7 @@ class SourceRegionContainer { vector volume_naive_; vector position_recorded_; vector external_source_present_; + vector needs_angular_flux_; vector position_; vector centroid_; vector centroid_iteration_; @@ -807,6 +861,8 @@ class SourceRegionContainer { // solve. Allocated only for the adaptive volume estimator, which makes its // demotion decisions from it. vector scalar_flux_t_; + vector angular_flux_new_; + vector angular_flux_offset_; vector source_; vector external_source_; diff --git a/include/openmc/source.h b/include/openmc/source.h index f84f08dd38a..38fa0d7f63d 100644 --- a/include/openmc/source.h +++ b/include/openmc/source.h @@ -219,6 +219,62 @@ 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; + + // 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_; } + +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_; //!< Continuum energy group bounds [eV] + + int64_t spatial_bins_ {0}; + int64_t angle_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_. + 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 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..668b74f77f4 --- /dev/null +++ b/include/openmc/tallies/filter_meshangular.h @@ -0,0 +1,40 @@ +#ifndef OPENMC_TALLIES_FILTER_MESHANGULAR_H +#define OPENMC_TALLIES_FILTER_MESHANGULAR_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) override + { + fatal_error("Angular mesh filters do not permit translation."); + } + + void set_translation(const double translation[3]) override + { + fatal_error("Angular mesh filters do not permit translation."); + } +}; + +} // namespace openmc +#endif // OPENMC_TALLIES_FILTER_MESHANGULAR_H diff --git a/include/openmc/weight_windows.h b/include/openmc/weight_windows.h index d0b385d169d..1def1ea3be6 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 { @@ -31,12 +33,14 @@ constexpr double DEFAULT_WEIGHT_CUTOFF {1.0e-38}; // default low weight cutoff 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 +205,98 @@ 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) + //! \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, + std::string forward_source_mesh); + + //---------------------------------------------------------------------------- + // 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_; } + 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 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 file + //! 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 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] + 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. + 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_; + + //! 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 { public: // Constructors @@ -214,7 +310,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 @@ -230,6 +328,12 @@ class WeightWindowsGenerator { // Local FW-CADIS target tallies std::vector targets_; + // FW-CADIS source biasing + bool source_biasing_ {false}; + int32_t angle_mesh_idx_ {C_NONE}; // 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): """Bins tally events based on the number of collisions. diff --git a/openmc/lib/filter.py b/openmc/lib/filter.py index cd011dc5d42..943573381b1 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,78 @@ 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. + + 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' + + 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): + _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 +803,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 e53155cd615..fca96cb2993 100644 --- a/openmc/lib/mesh.py +++ b/openmc/lib/mesh.py @@ -60,6 +60,9 @@ c_int32, POINTER(c_double), POINTER(c_double)] _dll.openmc_mesh_bounding_box.restype = c_int _dll.openmc_mesh_bounding_box.errcheck = _error_handler +_dll.openmc_mesh_get_bin.argtypes = [c_int32, POINTER(c_double), POINTER(c_int32)] +_dll.openmc_mesh_get_bin.restype = c_int +_dll.openmc_mesh_get_bin.errcheck = _error_handler _dll.openmc_mesh_material_volumes.argtypes = [ c_int32, c_int, c_int, c_int, c_int, arr_2d_int32, arr_2d_double, c_void_p] @@ -274,6 +277,29 @@ def bounding_box(self) -> 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, @@ -927,13 +953,20 @@ def from_file(cls, filename, library, uid=None, length_multiplier=1.0, options, mesh_id, index) return cls(index=index.value) +class UnitSpherePointset(Mesh): + pass + +class UnitSphereTriangularMesh(Mesh): + pass _MESH_TYPE_MAP = { 'regular': RegularMesh, 'rectilinear': RectilinearMesh, 'cylindrical': CylindricalMesh, 'spherical': SphericalMesh, - 'unstructured': UnstructuredMesh + 'unstructured': UnstructuredMesh, + 'angular_pointset': UnitSpherePointset, + 'angular_triangular': UnitSphereTriangularMesh } diff --git a/openmc/mesh.py b/openmc/mesh.py index 5f688b1d518..01afbd78ef8 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 @@ -324,6 +325,10 @@ def from_hdf5(cls, group: h5py.Group): return SphericalMesh.from_hdf5(group, mesh_id, mesh_name) elif mesh_type in ('unstructured', 'xdg'): 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 + '"') @@ -371,6 +376,10 @@ 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) + elif mesh_type == 'angular_triangular': + mesh = UnitSphereTriangularMesh.from_xml_element(elem) else: raise ValueError(f'Unrecognized mesh type "{mesh_type}" found.') @@ -3607,6 +3616,852 @@ def from_xml_element(cls, elem: ET.Element): out.interface = interface return out +class AngularMesh(MeshBase): + """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) + + @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. + 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 direction vectors constituting the mesh. + """ + def __init__( + self, + points, + mesh_id: int | None = None, + name: str = '', + ): + super().__init__(mesh_id, name) + self.points = points + + @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 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) + + return cls(points, 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)) + + 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) + + 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]) + + 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_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 + + # 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 = 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 + 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_triangular") + + # 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 _spherical_triangle_area(a, b, c): + num = np.dot(a, np.cross(b, c)) + denom = 1 + np.dot(a, b) + np.dot(b, c) + np.dot(c, a) + return 2 * np.arctan2(num, denom) + +def _signed_area_2d(pts): + # shoelace formula for polygon area, positive for CCW vertex orientation + x = pts[:, 0] + y = pts[:, 1] + return 0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y) + +def _delaunay_triangulate_convex_2d(points_2d): + """Perform a Delaunay triangulation of the vertices of a polygon (in + CCW order) via edge flipping. + + Begin by calculating the fan triangulation from vertex 0, then + flip any edge that violates the condition that no other vertex + may be inside the circumcircle of a given triangle. Returns a list of + index triples into points_2d. + """ + n = len(points_2d) + if n == 3: + return [(0, 1, 2)] + + triangles = [[0, i, i + 1] for i in range(1, n - 1)] + + def shared_edge(t1, t2): + shared = [v for v in t1 if v in t2] + return tuple(shared) if len(shared) == 2 else None + + max_sweeps = n * n + for _ in range(max_sweeps): + changed = False + for ai in range(len(triangles)): + for bi in range(ai + 1, len(triangles)): + t_a, t_b = triangles[ai], triangles[bi] + edge = shared_edge(t_a, t_b) + if edge is None: + continue + u, v = edge + opp_a = [p for p in t_a if p not in edge][0] + opp_b = [p for p in t_b if p not in edge][0] + + pu, pv = points_2d[u], points_2d[v] + po_a, po_b = points_2d[opp_a], points_2d[opp_b] + + # Orient (pu, pv, po_a) CCW before the in-circle test + if _signed_area_2d(np.array([pu, pv, po_a])) < 0: + pu, pv = pv, pu + u, v = v, u + + # Test whether point po_b lies inside the circumcircle of + # triangle pu-pv-po_a + ax, ay = pu[0] - po_b[0], pu[1] - po_b[1] + bx, by = pv[0] - po_b[0], pv[1] - po_b[1] + cx, cy = po_a[0] - po_b[0], po_a[1] - po_b[1] + det = ( + (ax * ax + ay * ay) * (bx * cy - cx * by) + - (bx * bx + by * by) * (ax * cy - cx * ay) + + (cx * cx + cy * cy) * (ax * by - bx * ay) + ) + if det <= 1e-12: + continue + + # flip the shared edge u-v for opp_a-opp_b + new_t1 = [opp_a, opp_b, u] + new_t2 = [opp_a, opp_b, v] + if _signed_area_2d( + np.array([points_2d[i] for i in new_t1])) < 0: + new_t1 = new_t1[::-1] + if _signed_area_2d( + np.array([points_2d[i] for i in new_t2])) < 0: + new_t2 = new_t2[::-1] + triangles[ai] = new_t1 + triangles[bi] = new_t2 + changed = True + + if not changed: + break + + return [tuple(t) for t in triangles] + + +def _ear_clip_2d(points_2d): + """Perform an ear-clipping triangulation of a simple polygon given its + vertices in CCW order. Returns a list of index triples into points_2d. + + Falls back to fan triangulation from vertex 0 for any vertices left over if + no ear can be found, in case of a degeneracy (e.g. points nearly collinear + on a great-circle arc). + """ + n = len(points_2d) + indices = list(range(n)) + triangles = [] + + while len(indices) > 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 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 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 + 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 : 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. + method : {'delaunay', 'ear clipping', 'star'} + Method by which to perform the triangulation of the Voronoi region + about each point. + + Returns + ------- + new_mesh : UnitSphereTriangularMesh + Angular mesh of M SphericalTriangle cells + 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 triangulation", mesh, UnitSpherePointset) + n_points = len(mesh.points) + + if data is not None: + data = np.asarray(data) + if data.shape[0] != n_points: + raise ValueError( + f"First dimension of data array ({data.shape[0]}) does not " + f"match number of points in UnitSpherePointset for " + f"triangulation (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 triangulation " + f"(expected {n_points})" + ) + new_broadcast_data = [] + + sv = SphericalVoronoi(mesh.points) + sv.sort_vertices_of_regions() + + faces = [] + + for pole_index, region in enumerate(sv.regions): + + 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) + + 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 + # 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) + 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) + coords_2d[i] = (np.dot(ref, v), np.dot(perp, v)) + + order = np.argsort(angles) + verts = verts[order] + coords_2d = coords_2d[order] + + # 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] + areas[i] = _spherical_triangle_area(pole, v1, v2) + + return areas + + areas = _fan_areas(verts) + + # 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) + + total_area = areas.sum() + + 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) + + results = [new_mesh] + if data is not None: + 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): """Generate dictionary of meshes from a given XML node diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index e076b080a9d..45c11ebfe3b 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 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 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 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", "vert" or "verts") or centroids ("centroids", "centroid", + "cent" or "cents") 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" | "verts": + return_type = "vert" + case "centroids" | "centroid" | "cent" | "cents": + 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 diff --git a/openmc/model/model.py b/openmc/model/model.py index 5b44edfba9f..1c32a7ab795 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1580,6 +1580,290 @@ 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'').') + + 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: + max_samples = 10 * min_samples + if max_samples < min_samples: + raise ValueError( + 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( + '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'] + 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 + + # 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 + + # 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] + 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) + + # 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 + cont &= (energy_bin >= 0) & (energy_bin < n_energy) + np.add.at(counts, + (space_bin[cont], angle_bin[cont], energy_bin[cont]), 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 + if occupied.size: + median = np.median(occupied) + + if median >= min_samples_per_voxel or 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 + 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( + '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) + 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 + 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/settings.py b/openmc/settings.py index 98798040a2c..27a0df729e6 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -15,7 +15,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 .field import TemperatureField from .utility_funcs import input_path, set_xml_input_path from .volume import VolumeCalculation @@ -413,6 +413,7 @@ class Settings: Path to a weight window file to load during simulation initialization .. versionadded::0.14.0 + write_initial_source : bool Indicate whether to write the initial source distribution to file """ @@ -1594,12 +1595,18 @@ 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()) 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: @@ -2024,15 +2031,16 @@ 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 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 - 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: diff --git a/openmc/source.py b/openmc/source.py index c36540a33f0..7520942e4ca 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -19,12 +19,11 @@ 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, UnitSphereTriangularMesh, triangulate_unit_sphere_mesh from .particle_type import ParticleType from .statepoint import _VERSION_STATEPOINT from .utility_funcs import input_path - class SourceBase(ABC): """Base class for external sources @@ -205,6 +204,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) elif source_type == 'stellarator': @@ -662,6 +663,482 @@ 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 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 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. + + Attributes + ---------- + mesh : openmc.MeshBase + Spatial mesh source positions are sampled from. + angle_mesh : openmc.MeshBase or None + 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 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 + 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 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 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 | None = None, + strength: float | None = 1.0, + particle: str | int | ParticleType = 'neutron', + constraints: dict[str, Any] | None = None, + ): + 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: + return float(np.sum(self._strengths)) + + @strength.setter + def strength(self, val): + if val is not None: + 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) + + def _load(self, filename: PathLike): + # Read source_bias.h5, triangulating the angular mesh if needed + + 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 supports only one.") + sb_group = fh[sb_names[0]] + mesh_group = fh['meshes'] + + 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}']) + 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 + 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 + + Returns + ------- + element : lxml.etree._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)) + 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: + """ + 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 + + """ + source = cls(constraints=cls._get_constraints(elem)) + + # 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 = ( + meshes[int(angle_mesh_id)] if angle_mesh_id 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') + + 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 def Source(*args, **kwargs): diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index 3273dfd321a..bc687ddf658 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): @@ -330,6 +332,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/openmc/weight_windows.py b/openmc/weight_windows.py index 5d90e02a270..aae033715a8 100644 --- a/openmc/weight_windows.py +++ b/openmc/weight_windows.py @@ -10,13 +10,14 @@ 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 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): @@ -500,6 +501,14 @@ 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. + forward_source_mesh_file : Pathlike + Path to a forward source mesh file storing unbiased source strengths + 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. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -521,6 +530,14 @@ 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. + 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. max_realizations : int The upper limit for number of tally realizations when generating weight windows. @@ -541,6 +558,9 @@ def __init__( particle_type: str | int | openmc.ParticleType = 'neutron', 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, on_the_fly: bool = True @@ -554,6 +574,9 @@ def __init__( self.particle_type = particle_type 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 self.on_the_fly = on_the_fly @@ -564,6 +587,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' @@ -633,6 +657,82 @@ 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 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: + 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: return self._max_realizations @@ -742,6 +842,15 @@ 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.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) @@ -787,6 +896,14 @@ 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('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] + 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/boundary_condition.cpp b/src/boundary_condition.cpp index 9135c1782ab..30f2059ce12 100644 --- a/src/boundary_condition.cpp +++ b/src/boundary_condition.cpp @@ -42,6 +42,7 @@ void ReflectiveBC::handle_particle(Particle& p, const Surface& surf) const // normalize reflected u to ensure no floating point error leads to // unnormalized directions u /= u.norm(); + p.direction_changed(); // Handle the effects of the surface albedo on the particle's weight. BoundaryCondition::handle_albedo(p, surf); @@ -60,6 +61,7 @@ void WhiteBC::handle_particle(Particle& p, const Surface& surf) const // normalize outgoing u to ensure no floating point error leads to // unnormalized directions u /= u.norm(); + p.direction_changed(); // Handle the effects of the surface albedo on the particle's weight. BoundaryCondition::handle_albedo(p, surf); @@ -246,6 +248,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(); // normalize new_u to ensure no floating point error leads to unnormalized // directions diff --git a/src/distribution_multi.cpp b/src/distribution_multi.cpp index 47785649b53..2a5b5654be1 100644 --- a/src/distribution_multi.cpp +++ b/src/distribution_multi.cpp @@ -6,6 +6,7 @@ #include "openmc/constants.h" #include "openmc/error.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" @@ -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)); @@ -189,4 +192,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 cadc08ca2bf..f860b268a4e 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -360,6 +360,10 @@ const std::unique_ptr& Mesh::create(T dataset) 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)); + } else if (mesh_type == UnitSphereTriangularMesh::mesh_type) { + model::meshes.push_back(make_unique(dataset)); } else if (mesh_type == UnstructuredMesh::mesh_type) { model::meshes.push_back(UnstructuredMesh::create(dataset)); } else { @@ -2616,6 +2620,271 @@ double SphericalMesh::volume(const MeshIndex& ijk) const (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i); } +//============================================================================== +// Unit sphere pointset mesh implementation +//============================================================================== + +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]}); +} + +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); +} + +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; +} + +//============================================================================== +// Unit sphere triangular mesh implementation +//============================================================================== + +const std::string UnitSphereTriangularMesh::mesh_type = "angular_triangular"; + +UnitSphereTriangularMesh::UnitSphereTriangularMesh(vector vertices) + : vertices_(std::move(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_)); + } + + // 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_)); + } + } +} + +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( + int32_t bin, 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 //============================================================================== @@ -2731,6 +3000,18 @@ extern "C" int openmc_add_unstructured_mesh(const char filename[], 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/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 52a136211e4..5fb8e8ad74a 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" @@ -13,6 +14,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_meshangular.h" #include "openmc/tallies/tally.h" #include "openmc/tallies/tally_scoring.h" #include "openmc/timer.h" @@ -41,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_) { @@ -58,6 +64,10 @@ FlatSourceDomain::FlatSourceDomain() : negroups_(data::mg.num_energy_groups_) } } + // 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; bool is_adaptive = is_adaptive_family(resolved_volume_estimator_); @@ -65,7 +75,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, is_adaptive, - is_strict_adaptive, is_linear && source_gradient_limiter_); + is_strict_adaptive, is_linear && source_gradient_limiter_, nangles_); // Initialize tally volumes if (volume_normalized_flux_tallies_) { @@ -102,6 +112,12 @@ 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 < source_regions_.n_source_angular_elements(); + sea++) { + source_regions_.angular_flux_new(sea) = 0.0; + } } void FlatSourceDomain::accumulate_iteration_flux() @@ -317,7 +333,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; @@ -331,6 +347,13 @@ 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 < 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 @@ -374,6 +397,12 @@ double FlatSourceDomain::flux_additive_term( return source_regions_.source(sr, g); } +double FlatSourceDomain::angular_flux_additive_term( + int64_t sr, int g, bool batch_volume) const +{ + return flux_additive_term(sr, g, batch_volume) / source_regions_.nangles(); +} + void FlatSourceDomain::set_flux_to_flux_plus_source( int64_t sr, double volume, bool batch_volume, int g) { @@ -381,14 +410,31 @@ void FlatSourceDomain::set_flux_to_flux_plus_source( int temp = source_regions_.temperature_idx(sr); if (material == MATERIAL_VOID) { source_regions_.scalar_flux_new(sr, g) /= volume; + if (source_regions_.needs_angular_flux(sr)) { + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) /= volume; + } + } } 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); + if (source_regions_.needs_angular_flux(sr)) { + for (int a = 0; a < source_regions_.nangles(); a++) { + source_regions_.angular_flux_new(sr, g, a) /= (sigma_t * volume); + } + } } source_regions_.scalar_flux_new(sr, g) += flux_additive_term(sr, g, batch_volume); + // Divide source term evenly among angular bins + 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) += flux_addition; + } + } } // Applies the "diagonal stabilization" technique developed by Gunow et al. @@ -454,11 +500,31 @@ 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; + } + } } bool FlatSourceDomain::region_has_strong_source( @@ -497,6 +563,9 @@ bool FlatSourceDomain::region_has_strong_source( // 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 +// 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; @@ -857,6 +926,197 @@ 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_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]}; + + 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)) { + // Already caught angular-type mesh filters; only spatial remain + 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; + } + + 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); + } + } + } + + 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_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; + } + 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 @@ -902,6 +1162,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++) { @@ -944,6 +1207,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. @@ -975,6 +1243,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(); @@ -1118,17 +1417,25 @@ 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; } @@ -1137,7 +1444,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; } @@ -1146,7 +1453,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; } @@ -1159,7 +1466,7 @@ void FlatSourceDomain::random_ray_tally() case SCORE_KAPPA_FISSION: if (material != MATERIAL_VOID) { score = - flux * volume * + task_flux * volume * kappa_fission_[(material * ntemperature_ + temp) * negroups_ + g] * density_mult; @@ -2570,14 +2877,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}; - handle.key() = sr_key; - // Determine the material int gs_i_cell = gs.lowest_coord().cell(); Cell& cell = *model::cells[gs_i_cell]; @@ -2600,6 +2899,19 @@ 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.key() = sr_key; handle.material() = material; handle.temperature_idx() = temp; handle.density_mult() = cell.density_mult(gs.cell_instance()); @@ -2801,4 +3113,27 @@ bool FlatSourceDomain::is_geometry_3D() return false; } +// 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, +// 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); +} + +// 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/linear_source_domain.cpp b/src/random_ray/linear_source_domain.cpp index a3f6cee844b..52cc344b7a4 100644 --- a/src/random_ray/linear_source_domain.cpp +++ b/src/random_ray/linear_source_domain.cpp @@ -170,7 +170,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; @@ -184,6 +184,13 @@ void LinearSourceDomain::normalize_scalar_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 2364c090802..6bc28217b37 100644 --- a/src/random_ray/random_ray.cpp +++ b/src/random_ray/random_ray.cpp @@ -563,8 +563,17 @@ 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.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]; + 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 @@ -604,8 +613,17 @@ 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.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; + 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 @@ -734,9 +752,19 @@ 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.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]; + 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 @@ -846,9 +874,19 @@ 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.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; + 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 @@ -942,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 @@ -1138,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(); @@ -1210,4 +1250,12 @@ SourceSite RandomRay::sample_s2() return site; } +int RandomRay::angular_bin() +{ + if (angular_bin_ == C_NONE) { + angular_bin_ = domain_->lookup_angular_bin(u()); + } + return angular_bin_; +} + } // namespace openmc diff --git a/src/random_ray/random_ray_simulation.cpp b/src/random_ray/random_ray_simulation.cpp index 138a7c29ff7..51c578b65f4 100644 --- a/src/random_ray/random_ray_simulation.cpp +++ b/src/random_ray/random_ray_simulation.cpp @@ -65,13 +65,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."); } } } @@ -481,7 +482,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_); #ifdef OPENMC_MPI 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 5b65355b434..5e81032bfc7 100644 --- a/src/random_ray/source_region.cpp +++ b/src/random_ray/source_region.cpp @@ -11,7 +11,11 @@ namespace openmc { // SourceRegionHandle implementation //============================================================================== SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) - : negroups_(sr.scalar_flux_old_.size()), material_(&sr.scalars_.material_), + : 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.scalars_.material_), temperature_idx_(&sr.scalars_.temperature_idx_), density_mult_(&sr.scalars_.density_mult_), is_small_(&sr.scalars_.is_small_), @@ -24,6 +28,7 @@ SourceRegionHandle::SourceRegionHandle(SourceRegion& sr) volume_naive_(&sr.scalars_.volume_naive_), position_recorded_(&sr.scalars_.position_recorded_), external_source_present_(&sr.scalars_.external_source_present_), + needs_angular_flux_(&sr.scalars_.needs_angular_flux_), position_(&sr.scalars_.position_), centroid_(&sr.scalars_.centroid_), centroid_iteration_(&sr.scalars_.centroid_iteration_), centroid_t_(&sr.scalars_.centroid_t_), @@ -46,12 +51,15 @@ 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(); } //============================================================================== // SourceRegion implementation //============================================================================== -SourceRegion::SourceRegion(int negroups, bool is_linear) +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 @@ -66,6 +74,11 @@ 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); + // Only allocate angular flux storage for regions that need it + 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 // on the transport path for every newly discovered region, so do not pay // the allocation when the estimator will never look at it. @@ -83,7 +96,8 @@ SourceRegion::SourceRegion(int negroups, bool is_linear) } 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(); @@ -141,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++) { @@ -190,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]; + } + } } //============================================================================== @@ -220,6 +252,7 @@ void SourceRegionContainer::push_back(const SourceRegion& sr) volume_naive_.push_back(sr.scalars_.volume_naive_); position_recorded_.push_back(sr.scalars_.position_recorded_); external_source_present_.push_back(sr.scalars_.external_source_present_); + needs_angular_flux_.push_back(sr.scalars_.needs_angular_flux_); position_.push_back(sr.scalars_.position_); volume_task_.push_back(sr.volume_task_); mesh_.push_back(sr.scalars_.mesh_); @@ -265,6 +298,16 @@ void SourceRegionContainer::push_back(const SourceRegion& sr) // Tally tasks tally_task_.emplace_back(sr.tally_task_[g]); } + + // Angle- and energy-dependent flux + 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); + } } void SourceRegionContainer::assign( @@ -287,6 +330,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(); @@ -306,6 +350,8 @@ void SourceRegionContainer::assign( scalar_flux_new_.clear(); scalar_flux_final_.clear(); scalar_flux_t_.clear(); + angular_flux_new_.clear(); + angular_flux_offset_.clear(); source_.clear(); external_source_.clear(); @@ -337,6 +383,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); @@ -354,6 +401,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); @@ -367,6 +415,11 @@ SourceRegionHandle SourceRegionContainer::get_source_region_handle(int64_t sr) handle.external_source_ = nullptr; } handle.scalar_flux_final_ = &scalar_flux_final(sr, 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); handle.centroid_ = ¢roid(sr); handle.centroid_iteration_ = ¢roid_iteration(sr); @@ -424,6 +477,7 @@ void SourceRegionContainer::adjoint_reset() } std::fill(scalar_flux_new_.begin(), scalar_flux_new_.end(), 0.0); std::fill(scalar_flux_t_.begin(), scalar_flux_t_.end(), 0.0); + 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(), diff --git a/src/source.cpp b/src/source.cpp index da4bbab140d..8a0c94c845c 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -29,6 +29,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" @@ -111,6 +112,8 @@ unique_ptr Source::create(pugi::xml_node node) return make_unique(node); } else if (source_type == "stellarator") { return make_unique(node); + } else if (source_type == "correlated") { + return make_unique(node); } else { fatal_error(fmt::format("Invalid source type '{}' found.", source_type)); } @@ -705,6 +708,155 @@ SourceSite MeshSource::sample(uint64_t* seed) const return source(element)->sample_with_constraints(seed); } +//============================================================================== +// CorrelatedSource implementation +//============================================================================== + +CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node) +{ + 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_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(); + + // 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_)); + } + } + + // 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()); + } + + 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); // performs normalization + + 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 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( + 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); + } + + site.wgt = weights_[flat]; + + return site; +} + //============================================================================== // TokamakSource implementation //============================================================================== 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..619020861b6 --- /dev/null +++ b/src/tallies/filter_meshangular.cpp @@ -0,0 +1,49 @@ +#include "openmc/tallies/filter_meshangular.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(u); + 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 diff --git a/src/weight_windows.cpp b/src/weight_windows.cpp index f2765e3b084..d9765bcef8a 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 @@ -754,6 +759,340 @@ 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, 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), + forward_source_mesh_(forward_source_mesh) +{ + 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]; + + double raw_sum = results(flat, score_index, i_sum); + flux_(m, a, e) = (n > 0 && raw_sum > 0.0) ? raw_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_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", + 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); + 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(n_cont_e)}); + tensor::Tensor weights({static_cast(spatial_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 + // 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 < n_cont_e; ++e) { + double psi = flux_(m, a, e); + double b = psi * unbiased_strength_(m, a, e); + biased_strength(m, a, e) = b; + total_strength += b; + if (psi <= 0.0) { + total_missed_S += unbiased_strength_(m, a, e); + } + } + } + } + + // 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 " + "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. + // 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 < 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); +} + +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; + } + } + } + + if (file_exists(forward_source_mesh_)) { + load_forward_source_mesh(forward_source_mesh_); + } 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) +{ + 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_); + + // 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); +} + WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node) { // read information from the XML node @@ -809,6 +1148,18 @@ 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"); + 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]; + } + 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( "Unknown weight window update method '{}' specified", method_string)); @@ -895,6 +1246,38 @@ 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) { + 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(), forward_source_mesh_); + 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 @@ -922,6 +1305,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 } @@ -1057,6 +1449,7 @@ void free_memory_weight_windows() variance_reduction::ww_map.clear(); variance_reduction::weight_windows.clear(); variance_reduction::weight_windows_generators.clear(); + variance_reduction::source_biases.clear(); } void finalize_variance_reduction() @@ -1367,6 +1760,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; }