diff --git a/include/openmc/angle_energy.h b/include/openmc/angle_energy.h index e2f449c6a..ac931b1b5 100644 --- a/include/openmc/angle_energy.h +++ b/include/openmc/angle_energy.h @@ -14,11 +14,11 @@ namespace openmc { class AngleEnergy { public: - virtual void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const = 0; + virtual void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const = 0; virtual ~AngleEnergy() = default; }; -} +} // namespace openmc #endif // OPENMC_ANGLE_ENERGY_H diff --git a/include/openmc/boundary_condition.h b/include/openmc/boundary_condition.h index 7eb93a61d..0f16fa3b3 100644 --- a/include/openmc/boundary_condition.h +++ b/include/openmc/boundary_condition.h @@ -20,8 +20,7 @@ public: //! to directly modify anything about the particle, but it will do so //! indirectly by calling the particle's appropriate cross_*_bc function. //! \param surf The specific surface on the boundary the particle struck. - virtual void - handle_particle(Particle& p, const Surface& surf) const = 0; + virtual void handle_particle(Particle& p, const Surface& surf) const = 0; //! Return a string classification of this BC. virtual std::string type() const = 0; @@ -33,10 +32,9 @@ public: class VacuumBC : public BoundaryCondition { public: - void - handle_particle(Particle& p, const Surface& surf) const override; + void handle_particle(Particle& p, const Surface& surf) const override; - std::string type() const override {return "vacuum";} + std::string type() const override { return "vacuum"; } }; //============================================================================== @@ -45,10 +43,9 @@ public: class ReflectiveBC : public BoundaryCondition { public: - void - handle_particle(Particle& p, const Surface& surf) const override; + void handle_particle(Particle& p, const Surface& surf) const override; - std::string type() const override {return "reflective";} + std::string type() const override { return "reflective"; } }; //============================================================================== @@ -57,10 +54,9 @@ public: class WhiteBC : public BoundaryCondition { public: - void - handle_particle(Particle& p, const Surface& surf) const override; + void handle_particle(Particle& p, const Surface& surf) const override; - std::string type() const override {return "white";} + std::string type() const override { return "white"; } }; //============================================================================== @@ -69,11 +65,9 @@ public: class PeriodicBC : public BoundaryCondition { public: - PeriodicBC(int i_surf, int j_surf) - : i_surf_(i_surf), j_surf_(j_surf) - {}; + PeriodicBC(int i_surf, int j_surf) : i_surf_(i_surf), j_surf_(j_surf) {}; - std::string type() const override {return "periodic";} + std::string type() const override { return "periodic"; } protected: int i_surf_; @@ -88,8 +82,7 @@ class TranslationalPeriodicBC : public PeriodicBC { public: TranslationalPeriodicBC(int i_surf, int j_surf); - void - handle_particle(Particle& p, const Surface& surf) const override; + void handle_particle(Particle& p, const Surface& surf) const override; protected: //! Vector along which incident particles will be moved @@ -106,8 +99,7 @@ class RotationalPeriodicBC : public PeriodicBC { public: RotationalPeriodicBC(int i_surf, int j_surf); - void - handle_particle(Particle& p, const Surface& surf) const override; + void handle_particle(Particle& p, const Surface& surf) const override; protected: //! Angle about the axis by which particle coordinates will be rotated diff --git a/include/openmc/bremsstrahlung.h b/include/openmc/bremsstrahlung.h index bd9d012c1..2f7e41bf0 100644 --- a/include/openmc/bremsstrahlung.h +++ b/include/openmc/bremsstrahlung.h @@ -14,8 +14,8 @@ namespace openmc { class BremsstrahlungData { public: // Data - xt::xtensor pdf; //!< Bremsstrahlung energy PDF - xt::xtensor cdf; //!< Bremsstrahlung energy CDF + xt::xtensor pdf; //!< Bremsstrahlung energy PDF + xt::xtensor cdf; //!< Bremsstrahlung energy CDF xt::xtensor yield; //!< Photon yield }; @@ -32,8 +32,10 @@ public: namespace data { -extern xt::xtensor ttb_e_grid; //! energy T of incident electron in [eV] -extern xt::xtensor ttb_k_grid; //! reduced energy W/T of emitted photon +extern xt::xtensor + ttb_e_grid; //! energy T of incident electron in [eV] +extern xt::xtensor + ttb_k_grid; //! reduced energy W/T of emitted photon } // namespace data diff --git a/include/openmc/capi.h b/include/openmc/capi.h index 012c7c18a..0929a11f7 100644 --- a/include/openmc/capi.h +++ b/include/openmc/capi.h @@ -1,211 +1,231 @@ #ifndef OPENMC_CAPI_H #define OPENMC_CAPI_H -#include #include #include +#include #ifdef __cplusplus extern "C" { #endif - int openmc_calculate_volumes(); - int openmc_cell_filter_get_bins(int32_t index, const int32_t** cells, int32_t* n); - int openmc_cell_get_fill(int32_t index, int* type, int32_t** indices, int32_t* n); - int openmc_cell_get_id(int32_t index, int32_t* id); - int openmc_cell_get_temperature(int32_t index, const int32_t* instance, double* T); - int openmc_cell_get_translation(int32_t index, double xyz[]); - int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n); - int openmc_cell_get_name(int32_t index, const char** name); - int openmc_cell_get_num_instances(int32_t index, int32_t* num_instances); - int openmc_cell_set_name(int32_t index, const char* name); - int openmc_cell_set_fill(int32_t index, int type, int32_t n, const int32_t* indices); - int openmc_cell_set_id(int32_t index, int32_t id); - int openmc_cell_set_temperature(int32_t index, double T, const int32_t* instance, bool set_contained = false); - int openmc_cell_set_translation(int32_t index, const double xyz[]); - int openmc_cell_set_rotation(int32_t index, const double rot[], size_t rot_len); - int openmc_energy_filter_get_bins(int32_t index, const double** energies, size_t* n); - int openmc_energy_filter_set_bins(int32_t index, size_t n, const double* energies); - int openmc_energyfunc_filter_get_energy(int32_t index, size_t* n, const double** energy); - int openmc_energyfunc_filter_get_y(int32_t index, size_t* n, const double** y); - int openmc_energyfunc_filter_set_data(int32_t index, size_t n, - const double* energies, const double* y); - int openmc_extend_cells(int32_t n, int32_t* index_start, int32_t* index_end); - int openmc_extend_filters(int32_t n, int32_t* index_start, int32_t* index_end); - int openmc_extend_materials(int32_t n, int32_t* index_start, int32_t* index_end); - int openmc_extend_meshes(int32_t n, const char* type, int32_t* index_start, - int32_t* index_end); - int openmc_extend_tallies(int32_t n, int32_t* index_start, int32_t* index_end); - int openmc_filter_get_id(int32_t index, int32_t* id); - int openmc_filter_get_type(int32_t index, char* type); - int openmc_filter_set_id(int32_t index, int32_t id); - int openmc_finalize(); - int openmc_find_cell(const double* xyz, int32_t* index, int32_t* instance); - int openmc_cell_bounding_box(const int32_t index, double* llc, double* urc); - int openmc_global_bounding_box(double* llc, double* urc); - int openmc_fission_bank(void** ptr, int64_t* n); - int openmc_get_cell_index(int32_t id, int32_t* index); - int openmc_get_filter_index(int32_t id, int32_t* index); - void openmc_get_filter_next_id(int32_t* id); - int openmc_get_keff(double k_combined[]); - int openmc_get_material_index(int32_t id, int32_t* index); - int openmc_get_mesh_index(int32_t id, int32_t* index); - int openmc_get_n_batches(int* n_batches, bool get_max_batches); - int openmc_get_nuclide_index(const char name[], int* index); - int openmc_add_unstructured_mesh(const char filename[], const char library[], int* id); - int64_t openmc_get_seed(); - int openmc_get_tally_index(int32_t id, int32_t* index); - void openmc_get_tally_next_id(int32_t* id); - int openmc_global_tallies(double** ptr); - int openmc_hard_reset(); - int openmc_init(int argc, char* argv[], const void* intracomm); - bool openmc_is_statepoint_batch(); - int openmc_legendre_filter_get_order(int32_t index, int* order); - int openmc_legendre_filter_set_order(int32_t index, int order); - int openmc_load_nuclide(const char* name, const double* temps, int n); - int openmc_material_add_nuclide(int32_t index, const char name[], double density); - int openmc_material_get_densities(int32_t index, const int** nuclides, const double** densities, int* n); - int openmc_material_get_id(int32_t index, int32_t* id); - int openmc_material_get_fissionable(int32_t index, bool* fissionable); - int openmc_material_get_density(int32_t index, double* density); - int openmc_material_get_volume(int32_t index, double* volume); - int openmc_material_set_density(int32_t index, double density, const char* units); - int openmc_material_set_densities(int32_t index, int n, const char** name, const double* density); - int openmc_material_set_id(int32_t index, int32_t id); - int openmc_material_get_name(int32_t index, const char** name); - int openmc_material_set_name(int32_t index, const char* name); - int openmc_material_set_volume(int32_t index, double volume); - int openmc_material_filter_get_bins(int32_t index, const int32_t** bins, size_t* n); - int openmc_material_filter_set_bins(int32_t index, size_t n, const int32_t* bins); - 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_id(int32_t index, int32_t* id); - int openmc_mesh_set_id(int32_t index, int32_t id); - int openmc_meshsurface_filter_get_mesh(int32_t index, int32_t* index_mesh); - int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh); - int openmc_new_filter(const char* type, int32_t* index); - int openmc_next_batch(int* status); - int openmc_nuclide_name(int index, const char** name); - int openmc_plot_geometry(); - int openmc_id_map(const void* slice, int32_t* data_out); - int openmc_property_map(const void* slice, double* data_out); - int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, int* nx, - double** grid_y, int* ny, double** grid_z, int* nz); - int openmc_rectilinear_mesh_set_grid(int32_t index, const double* grid_x, - const int nx, const double* grid_y, const int ny, - const double* grid_z, const int nz); - int openmc_regular_mesh_get_dimension(int32_t index, int** id, int* n); - int openmc_regular_mesh_get_params(int32_t index, double** ll, double** ur, double** width, int* n); - int openmc_regular_mesh_set_dimension(int32_t index, int n, const int* dims); - int openmc_regular_mesh_set_params(int32_t index, int n, const double* ll, const double* ur, const double* width); - int openmc_reset(); - int openmc_reset_timers(); - int openmc_run(); - void openmc_set_seed(int64_t new_seed); - int openmc_set_n_batches(int32_t n_batches, bool set_max_batches, - bool add_statepoint_batch); - int openmc_simulation_finalize(); - int openmc_simulation_init(); - int openmc_source_bank(void** ptr, int64_t* n); - int openmc_spatial_legendre_filter_get_order(int32_t index, int* order); - int openmc_spatial_legendre_filter_get_params(int32_t index, int* axis, double* min, double* max); - int openmc_spatial_legendre_filter_set_order(int32_t index, int order); - int openmc_spatial_legendre_filter_set_params(int32_t index, const int* axis, - const double* min, const double* max); - int openmc_sphharm_filter_get_order(int32_t index, int* order); - int openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]); - int openmc_sphharm_filter_set_order(int32_t index, int order); - int openmc_sphharm_filter_set_cosine(int32_t index, const char cosine[]); - int openmc_statepoint_write(const char* filename, bool* write_source); - int openmc_tally_allocate(int32_t index, const char* type); - int openmc_tally_get_active(int32_t index, bool* active); - int openmc_tally_get_estimator(int32_t index, int* estimator); - int openmc_tally_get_id(int32_t index, int32_t* id); - int openmc_tally_get_filters(int32_t index, const int32_t** indices, size_t* n); - int openmc_tally_get_n_realizations(int32_t index, int32_t* n); - int openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n); - int openmc_tally_get_scores(int32_t index, int** scores, int* n); - int openmc_tally_get_type(int32_t index, int32_t* type); - int openmc_tally_get_writable(int32_t index, bool* writable); - int openmc_tally_reset(int32_t index); - int openmc_tally_results(int32_t index, double** ptr, size_t shape_[3]); - int openmc_tally_set_active(int32_t index, bool active); - int openmc_tally_set_estimator(int32_t index, const char* estimator); - int openmc_tally_set_filters(int32_t index, size_t n, const int32_t* indices); - int openmc_tally_set_id(int32_t index, int32_t id); - int openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides); - int openmc_tally_set_scores(int32_t index, int n, const char** scores); - int openmc_tally_set_type(int32_t index, const char* type); - int openmc_tally_set_writable(int32_t index, bool writable); - int openmc_zernike_filter_get_order(int32_t index, int* order); - int openmc_zernike_filter_get_params(int32_t index, double* x, double* y, double* r); - int openmc_zernike_filter_set_order(int32_t index, int order); - int openmc_zernike_filter_set_params(int32_t index, const double* x, - const double* y, const double* r); +int openmc_calculate_volumes(); +int openmc_cell_filter_get_bins( + int32_t index, const int32_t** cells, int32_t* n); +int openmc_cell_get_fill( + int32_t index, int* type, int32_t** indices, int32_t* n); +int openmc_cell_get_id(int32_t index, int32_t* id); +int openmc_cell_get_temperature( + int32_t index, const int32_t* instance, double* T); +int openmc_cell_get_translation(int32_t index, double xyz[]); +int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n); +int openmc_cell_get_name(int32_t index, const char** name); +int openmc_cell_get_num_instances(int32_t index, int32_t* num_instances); +int openmc_cell_set_name(int32_t index, const char* name); +int openmc_cell_set_fill( + int32_t index, int type, int32_t n, const int32_t* indices); +int openmc_cell_set_id(int32_t index, int32_t id); +int openmc_cell_set_temperature( + int32_t index, double T, const int32_t* instance, bool set_contained = false); +int openmc_cell_set_translation(int32_t index, const double xyz[]); +int openmc_cell_set_rotation(int32_t index, const double rot[], size_t rot_len); +int openmc_energy_filter_get_bins( + int32_t index, const double** energies, size_t* n); +int openmc_energy_filter_set_bins( + int32_t index, size_t n, const double* energies); +int openmc_energyfunc_filter_get_energy( + int32_t index, size_t* n, const double** energy); +int openmc_energyfunc_filter_get_y(int32_t index, size_t* n, const double** y); +int openmc_energyfunc_filter_set_data( + int32_t index, size_t n, const double* energies, const double* y); +int openmc_extend_cells(int32_t n, int32_t* index_start, int32_t* index_end); +int openmc_extend_filters(int32_t n, int32_t* index_start, int32_t* index_end); +int openmc_extend_materials( + int32_t n, int32_t* index_start, int32_t* index_end); +int openmc_extend_meshes( + int32_t n, const char* type, int32_t* index_start, int32_t* index_end); +int openmc_extend_tallies(int32_t n, int32_t* index_start, int32_t* index_end); +int openmc_filter_get_id(int32_t index, int32_t* id); +int openmc_filter_get_type(int32_t index, char* type); +int openmc_filter_set_id(int32_t index, int32_t id); +int openmc_finalize(); +int openmc_find_cell(const double* xyz, int32_t* index, int32_t* instance); +int openmc_cell_bounding_box(const int32_t index, double* llc, double* urc); +int openmc_global_bounding_box(double* llc, double* urc); +int openmc_fission_bank(void** ptr, int64_t* n); +int openmc_get_cell_index(int32_t id, int32_t* index); +int openmc_get_filter_index(int32_t id, int32_t* index); +void openmc_get_filter_next_id(int32_t* id); +int openmc_get_keff(double k_combined[]); +int openmc_get_material_index(int32_t id, int32_t* index); +int openmc_get_mesh_index(int32_t id, int32_t* index); +int openmc_get_n_batches(int* n_batches, bool get_max_batches); +int openmc_get_nuclide_index(const char name[], int* index); +int openmc_add_unstructured_mesh( + const char filename[], const char library[], int* id); +int64_t openmc_get_seed(); +int openmc_get_tally_index(int32_t id, int32_t* index); +void openmc_get_tally_next_id(int32_t* id); +int openmc_global_tallies(double** ptr); +int openmc_hard_reset(); +int openmc_init(int argc, char* argv[], const void* intracomm); +bool openmc_is_statepoint_batch(); +int openmc_legendre_filter_get_order(int32_t index, int* order); +int openmc_legendre_filter_set_order(int32_t index, int order); +int openmc_load_nuclide(const char* name, const double* temps, int n); +int openmc_material_add_nuclide( + int32_t index, const char name[], double density); +int openmc_material_get_densities( + int32_t index, const int** nuclides, const double** densities, int* n); +int openmc_material_get_id(int32_t index, int32_t* id); +int openmc_material_get_fissionable(int32_t index, bool* fissionable); +int openmc_material_get_density(int32_t index, double* density); +int openmc_material_get_volume(int32_t index, double* volume); +int openmc_material_set_density( + int32_t index, double density, const char* units); +int openmc_material_set_densities( + int32_t index, int n, const char** name, const double* density); +int openmc_material_set_id(int32_t index, int32_t id); +int openmc_material_get_name(int32_t index, const char** name); +int openmc_material_set_name(int32_t index, const char* name); +int openmc_material_set_volume(int32_t index, double volume); +int openmc_material_filter_get_bins( + int32_t index, const int32_t** bins, size_t* n); +int openmc_material_filter_set_bins( + int32_t index, size_t n, const int32_t* bins); +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_id(int32_t index, int32_t* id); +int openmc_mesh_set_id(int32_t index, int32_t id); +int openmc_meshsurface_filter_get_mesh(int32_t index, int32_t* index_mesh); +int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh); +int openmc_new_filter(const char* type, int32_t* index); +int openmc_next_batch(int* status); +int openmc_nuclide_name(int index, const char** name); +int openmc_plot_geometry(); +int openmc_id_map(const void* slice, int32_t* data_out); +int openmc_property_map(const void* slice, double* data_out); +int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, int* nx, + double** grid_y, int* ny, double** grid_z, int* nz); +int openmc_rectilinear_mesh_set_grid(int32_t index, const double* grid_x, + const int nx, const double* grid_y, const int ny, const double* grid_z, + const int nz); +int openmc_regular_mesh_get_dimension(int32_t index, int** id, int* n); +int openmc_regular_mesh_get_params( + int32_t index, double** ll, double** ur, double** width, int* n); +int openmc_regular_mesh_set_dimension(int32_t index, int n, const int* dims); +int openmc_regular_mesh_set_params(int32_t index, int n, const double* ll, + const double* ur, const double* width); +int openmc_reset(); +int openmc_reset_timers(); +int openmc_run(); +void openmc_set_seed(int64_t new_seed); +int openmc_set_n_batches( + int32_t n_batches, bool set_max_batches, bool add_statepoint_batch); +int openmc_simulation_finalize(); +int openmc_simulation_init(); +int openmc_source_bank(void** ptr, int64_t* n); +int openmc_spatial_legendre_filter_get_order(int32_t index, int* order); +int openmc_spatial_legendre_filter_get_params( + int32_t index, int* axis, double* min, double* max); +int openmc_spatial_legendre_filter_set_order(int32_t index, int order); +int openmc_spatial_legendre_filter_set_params( + int32_t index, const int* axis, const double* min, const double* max); +int openmc_sphharm_filter_get_order(int32_t index, int* order); +int openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]); +int openmc_sphharm_filter_set_order(int32_t index, int order); +int openmc_sphharm_filter_set_cosine(int32_t index, const char cosine[]); +int openmc_statepoint_write(const char* filename, bool* write_source); +int openmc_tally_allocate(int32_t index, const char* type); +int openmc_tally_get_active(int32_t index, bool* active); +int openmc_tally_get_estimator(int32_t index, int* estimator); +int openmc_tally_get_id(int32_t index, int32_t* id); +int openmc_tally_get_filters(int32_t index, const int32_t** indices, size_t* n); +int openmc_tally_get_n_realizations(int32_t index, int32_t* n); +int openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n); +int openmc_tally_get_scores(int32_t index, int** scores, int* n); +int openmc_tally_get_type(int32_t index, int32_t* type); +int openmc_tally_get_writable(int32_t index, bool* writable); +int openmc_tally_reset(int32_t index); +int openmc_tally_results(int32_t index, double** ptr, size_t shape_[3]); +int openmc_tally_set_active(int32_t index, bool active); +int openmc_tally_set_estimator(int32_t index, const char* estimator); +int openmc_tally_set_filters(int32_t index, size_t n, const int32_t* indices); +int openmc_tally_set_id(int32_t index, int32_t id); +int openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides); +int openmc_tally_set_scores(int32_t index, int n, const char** scores); +int openmc_tally_set_type(int32_t index, const char* type); +int openmc_tally_set_writable(int32_t index, bool writable); +int openmc_zernike_filter_get_order(int32_t index, int* order); +int openmc_zernike_filter_get_params( + int32_t index, double* x, double* y, double* r); +int openmc_zernike_filter_set_order(int32_t index, int order); +int openmc_zernike_filter_set_params( + int32_t index, const double* x, const double* y, const double* r); - //! Sets the mesh and energy grid for CMFD reweight - //! \param[in] meshtyally_id id of CMFD Mesh Tally - //! \param[in] cmfd_indices indices storing spatial and energy dimensions of CMFD problem - //! \param[in] norm CMFD normalization factor - void openmc_initialize_mesh_egrid(const int meshtally_id, const int* cmfd_indices, - const double norm); +//! Sets the mesh and energy grid for CMFD reweight +//! \param[in] meshtyally_id id of CMFD Mesh Tally +//! \param[in] cmfd_indices indices storing spatial and energy dimensions of +//! CMFD problem \param[in] norm CMFD normalization factor +void openmc_initialize_mesh_egrid( + const int meshtally_id, const int* cmfd_indices, const double norm); - //! Sets the mesh and energy grid for CMFD reweight - //! \param[in] feedback whether or not to run CMFD feedback - //! \param[in] cmfd_src computed CMFD source - void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src); +//! Sets the mesh and energy grid for CMFD reweight +//! \param[in] feedback whether or not to run CMFD feedback +//! \param[in] cmfd_src computed CMFD source +void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src); - //! Sets the fixed variables that are used for CMFD linear solver - //! \param[in] indptr CSR format index pointer array of loss matrix - //! \param[in] len_indptr length of indptr - //! \param[in] indices CSR format index array of loss matrix - //! \param[in] n_elements number of non-zero elements in CMFD loss matrix - //! \param[in] dim dimension n of nxn CMFD loss matrix - //! \param[in] spectral spectral radius of CMFD matrices and tolerances - //! \param[in] map coremap for problem, storing accelerated regions - //! \param[in] use_all_threads whether to use all threads when running CMFD solver - void openmc_initialize_linsolver(const int* indptr, int len_indptr, - const int* indices, int n_elements, - int dim, double spectral, - const int* map, bool use_all_threads); +//! Sets the fixed variables that are used for CMFD linear solver +//! \param[in] indptr CSR format index pointer array of loss matrix +//! \param[in] len_indptr length of indptr +//! \param[in] indices CSR format index array of loss matrix +//! \param[in] n_elements number of non-zero elements in CMFD loss matrix +//! \param[in] dim dimension n of nxn CMFD loss matrix +//! \param[in] spectral spectral radius of CMFD matrices and tolerances +//! \param[in] map coremap for problem, storing accelerated regions +//! \param[in] use_all_threads whether to use all threads when running CMFD +//! solver +void openmc_initialize_linsolver(const int* indptr, int len_indptr, + const int* indices, int n_elements, int dim, double spectral, const int* map, + bool use_all_threads); - //! Runs a Gauss Seidel linear solver to solve CMFD matrix equations - //! linear solver - //! \param[in] A_data CSR format data array of coefficient matrix - //! \param[in] b right hand side vector - //! \param[out] x unknown vector - //! \param[in] tol tolerance on final error - //! \return number of inner iterations required to reach convergence - int openmc_run_linsolver(const double* A_data, const double* b, - double* x, double tol); +//! Runs a Gauss Seidel linear solver to solve CMFD matrix equations +//! linear solver +//! \param[in] A_data CSR format data array of coefficient matrix +//! \param[in] b right hand side vector +//! \param[out] x unknown vector +//! \param[in] tol tolerance on final error +//! \return number of inner iterations required to reach convergence +int openmc_run_linsolver( + const double* A_data, const double* b, double* x, double tol); - //! Export physical properties for model - //! \param[in] filename Filename to write to - //! \return Error code - int openmc_properties_export(const char* filename); +//! Export physical properties for model +//! \param[in] filename Filename to write to +//! \return Error code +int openmc_properties_export(const char* filename); - //! Import physical properties for model - //! \param[in] filename Filename to read from - // \return Error code - int openmc_properties_import(const char* filename); +//! Import physical properties for model +//! \param[in] filename Filename to read from +// \return Error code +int openmc_properties_import(const char* filename); - // Error codes - extern int OPENMC_E_UNASSIGNED; - extern int OPENMC_E_ALLOCATE; - extern int OPENMC_E_OUT_OF_BOUNDS; - extern int OPENMC_E_INVALID_SIZE; - extern int OPENMC_E_INVALID_ARGUMENT; - extern int OPENMC_E_INVALID_TYPE; - extern int OPENMC_E_INVALID_ID; - extern int OPENMC_E_GEOMETRY; - extern int OPENMC_E_DATA; - extern int OPENMC_E_PHYSICS; - extern int OPENMC_E_WARNING; +// Error codes +extern int OPENMC_E_UNASSIGNED; +extern int OPENMC_E_ALLOCATE; +extern int OPENMC_E_OUT_OF_BOUNDS; +extern int OPENMC_E_INVALID_SIZE; +extern int OPENMC_E_INVALID_ARGUMENT; +extern int OPENMC_E_INVALID_TYPE; +extern int OPENMC_E_INVALID_ID; +extern int OPENMC_E_GEOMETRY; +extern int OPENMC_E_DATA; +extern int OPENMC_E_PHYSICS; +extern int OPENMC_E_WARNING; - // Global variables - extern char openmc_err_msg[256]; +// Global variables +extern char openmc_err_msg[256]; #ifdef __cplusplus } diff --git a/include/openmc/cell.h b/include/openmc/cell.h index 8d439b1bb..75d706535 100644 --- a/include/openmc/cell.h +++ b/include/openmc/cell.h @@ -7,9 +7,9 @@ #include #include -#include #include "hdf5.h" #include "pugixml.hpp" +#include #include "openmc/constants.h" #include "openmc/memory.h" // for unique_ptr @@ -24,18 +24,14 @@ namespace openmc { // Constants //============================================================================== -enum class Fill { - MATERIAL, - UNIVERSE, - LATTICE -}; +enum class Fill { MATERIAL, UNIVERSE, LATTICE }; // TODO: Convert to enum -constexpr int32_t OP_LEFT_PAREN {std::numeric_limits::max()}; -constexpr int32_t OP_RIGHT_PAREN {std::numeric_limits::max() - 1}; -constexpr int32_t OP_COMPLEMENT {std::numeric_limits::max() - 2}; +constexpr int32_t OP_LEFT_PAREN {std::numeric_limits::max()}; +constexpr int32_t OP_RIGHT_PAREN {std::numeric_limits::max() - 1}; +constexpr int32_t OP_COMPLEMENT {std::numeric_limits::max() - 2}; constexpr int32_t OP_INTERSECTION {std::numeric_limits::max() - 3}; -constexpr int32_t OP_UNION {std::numeric_limits::max() - 4}; +constexpr int32_t OP_UNION {std::numeric_limits::max() - 4}; //============================================================================== // Global variables @@ -48,29 +44,27 @@ class Universe; class UniversePartitioner; namespace model { - extern std::unordered_map cell_map; - extern vector> cells; +extern std::unordered_map cell_map; +extern vector> cells; - extern std::unordered_map universe_map; - extern vector> universes; +extern std::unordered_map universe_map; +extern vector> universes; } // namespace model //============================================================================== //! A geometry primitive that fills all space and contains cells. //============================================================================== -class Universe -{ +class Universe { public: - - int32_t id_; //!< Unique ID - vector cells_; //!< Cells within this universe + int32_t id_; //!< Unique ID + vector cells_; //!< Cells within this universe //! \brief Write universe information to an HDF5 group. //! \param group_id An HDF5 group id. virtual void to_hdf5(hid_t group_id) const; - virtual bool find_cell(Particle &p) const; + virtual bool find_cell(Particle& p) const; BoundingBox bounding_box() const; @@ -117,12 +111,11 @@ public: //! \param on_surface The signed index of a surface that the coordinate is //! known to be on. This index takes precedence over surface sense //! calculations. - virtual bool - contains(Position r, Direction u, int32_t on_surface) const = 0; + virtual bool contains(Position r, Direction u, int32_t on_surface) const = 0; //! Find the oncoming boundary of this cell. - virtual std::pair - distance(Position r, Direction u, int32_t on_surface, Particle* p) const = 0; + virtual std::pair distance( + Position r, Direction u, int32_t on_surface, Particle* p) const = 0; //! Write all information needed to reconstruct the cell to an HDF5 group. //! \param group_id An HDF5 group id. @@ -157,7 +150,8 @@ public: //! \param[in] set_contained If this cell is not filled with a material, //! collect all contained cells with material fills and set their //! temperatures. - void set_temperature(double T, int32_t instance = -1, bool set_contained = false); + void set_temperature( + double T, int32_t instance = -1, bool set_contained = false); //! Set the rotation matrix of a cell instance //! \param[in] rot The rotation matrix of length 3 or 9 @@ -184,16 +178,16 @@ public: //---------------------------------------------------------------------------- // Data members - int32_t id_; //!< Unique ID - std::string name_; //!< User-defined name - Fill type_; //!< Material, universe, or lattice - int32_t universe_; //!< Universe # this cell is in - int32_t fill_; //!< Universe # filling this cell - int32_t n_instances_{0}; //!< Number of instances of this cell - GeometryType geom_type_; //!< Geometric representation type (CSG, DAGMC) + int32_t id_; //!< Unique ID + std::string name_; //!< User-defined name + Fill type_; //!< Material, universe, or lattice + int32_t universe_; //!< Universe # this cell is in + int32_t fill_; //!< Universe # filling this cell + int32_t n_instances_ {0}; //!< Number of instances of this cell + GeometryType geom_type_; //!< Geometric representation type (CSG, DAGMC) //! \brief Index corresponding to this cell in distribcell arrays - int distribcell_index_{C_NONE}; + int distribcell_index_ {C_NONE}; //! \brief Material(s) within this cell. //! @@ -210,7 +204,7 @@ public: vector region_; //! Reverse Polish notation for region expression vector rpn_; - bool simple_; //!< Does the region contain only intersections? + bool simple_; //!< Does the region contain only intersections? //! \brief Neighboring cells in the same universe. NeighborList neighbors_; @@ -229,24 +223,22 @@ public: }; struct CellInstanceItem { - int32_t index {-1}; //! Index into global cells array - int lattice_indx{-1}; //! Flat index value of the lattice cell + int32_t index {-1}; //! Index into global cells array + int lattice_indx {-1}; //! Flat index value of the lattice cell }; //============================================================================== -class CSGCell : public Cell -{ +class CSGCell : public Cell { public: CSGCell(); explicit CSGCell(pugi::xml_node cell_node); - bool - contains(Position r, Direction u, int32_t on_surface) const; + bool contains(Position r, Direction u, int32_t on_surface) const; - std::pair - distance(Position r, Direction u, int32_t on_surface, Particle* p) const; + std::pair distance( + Position r, Direction u, int32_t on_surface, Particle* p) const; void to_hdf5_inner(hid_t group_id) const override; @@ -285,8 +277,7 @@ protected: //! and spheres. //============================================================================== -class UniversePartitioner -{ +class UniversePartitioner { public: explicit UniversePartitioner(const Universe& univ); @@ -307,7 +298,6 @@ private: vector> partitions_; }; - //============================================================================== //! Define a containing (parent) cell //============================================================================== @@ -324,7 +314,9 @@ struct ParentCell { struct CellInstance { //! Check for equality bool operator==(const CellInstance& other) const - { return index_cell == other.index_cell && instance == other.instance; } + { + return index_cell == other.index_cell && instance == other.instance; + } gsl::index index_cell; gsl::index instance; @@ -333,7 +325,7 @@ struct CellInstance { struct CellInstanceHash { std::size_t operator()(const CellInstance& k) const { - return 4096*k.index_cell + k.instance; + return 4096 * k.index_cell + k.instance; } }; @@ -343,7 +335,6 @@ struct CellInstanceHash { void read_cells(pugi::xml_node node); - #ifdef DAGMC class DAGUniverse; #endif diff --git a/include/openmc/constants.h b/include/openmc/constants.h index e400c22bc..43acdbba5 100644 --- a/include/openmc/constants.h +++ b/include/openmc/constants.h @@ -79,16 +79,20 @@ constexpr double INFTY {std::numeric_limits::max()}; // (CODATA) 2018 recommendation (https://physics.nist.gov/cuu/Constants/). // Physical constants -constexpr double MASS_NEUTRON {1.00866491595}; // mass of a neutron in amu -constexpr double MASS_NEUTRON_EV {939.56542052e6}; // mass of a neutron in eV/c^2 -constexpr double MASS_PROTON {1.007276466621}; // mass of a proton in amu -constexpr double MASS_ELECTRON_EV {0.51099895000e6}; // electron mass energy equivalent in eV/c^2 -constexpr double FINE_STRUCTURE {137.035999084}; // inverse fine structure constant -constexpr double PLANCK_C {1.2398419839593942e4}; // Planck's constant times c in eV-Angstroms -constexpr double AMU {1.66053906660e-27}; // 1 amu in kg -constexpr double C_LIGHT {2.99792458e8}; // speed of light in m/s -constexpr double N_AVOGADRO {0.602214076}; // Avogadro's number in 10^24/mol -constexpr double K_BOLTZMANN {8.617333262e-5}; // Boltzmann constant in eV/K +constexpr double MASS_NEUTRON {1.00866491595}; // mass of a neutron in amu +constexpr double MASS_NEUTRON_EV { + 939.56542052e6}; // mass of a neutron in eV/c^2 +constexpr double MASS_PROTON {1.007276466621}; // mass of a proton in amu +constexpr double MASS_ELECTRON_EV { + 0.51099895000e6}; // electron mass energy equivalent in eV/c^2 +constexpr double FINE_STRUCTURE { + 137.035999084}; // inverse fine structure constant +constexpr double PLANCK_C { + 1.2398419839593942e4}; // Planck's constant times c in eV-Angstroms +constexpr double AMU {1.66053906660e-27}; // 1 amu in kg +constexpr double C_LIGHT {2.99792458e8}; // speed of light in m/s +constexpr double N_AVOGADRO {0.602214076}; // Avogadro's number in 10^24/mol +constexpr double K_BOLTZMANN {8.617333262e-5}; // Boltzmann constant in eV/K // Electron subshell labels constexpr array SUBSHELLS = {"K", "L1", "L2", "L3", "M1", "M2", @@ -99,16 +103,13 @@ constexpr array SUBSHELLS = {"K", "L1", "L2", "L3", "M1", "M2", // Void material and nuclide // TODO: refactor and remove constexpr int MATERIAL_VOID {-1}; -constexpr int NUCLIDE_NONE {-1}; +constexpr int NUCLIDE_NONE {-1}; // ============================================================================ // CROSS SECTION RELATED CONSTANTS // Temperature treatment method -enum class TemperatureMethod { - NEAREST, - INTERPOLATION -}; +enum class TemperatureMethod { NEAREST, INTERPOLATION }; // Reaction types enum ReactionType { @@ -117,105 +118,105 @@ enum ReactionType { ELASTIC = 2, N_NONELASTIC = 3, N_LEVEL = 4, - MISC = 5, - N_2ND = 11, - N_2N = 16, - N_3N = 17, + MISC = 5, + N_2ND = 11, + N_2N = 16, + N_3N = 17, N_FISSION = 18, - N_F = 19, - N_NF = 20, - N_2NF = 21, - N_NA = 22, - N_N3A = 23, - N_2NA = 24, - N_3NA = 25, - N_NP = 28, - N_N2A = 29, - N_2N2A = 30, - N_ND = 32, - N_NT = 33, - N_N3HE = 34, - N_ND2A = 35, - N_NT2A = 36, - N_4N = 37, - N_3NF = 38, - N_2NP = 41, - N_3NP = 42, - N_N2P = 44, - N_NPA = 45, - N_N1 = 51, - N_N40 = 90, - N_NC = 91, + N_F = 19, + N_NF = 20, + N_2NF = 21, + N_NA = 22, + N_N3A = 23, + N_2NA = 24, + N_3NA = 25, + N_NP = 28, + N_N2A = 29, + N_2N2A = 30, + N_ND = 32, + N_NT = 33, + N_N3HE = 34, + N_ND2A = 35, + N_NT2A = 36, + N_4N = 37, + N_3NF = 38, + N_2NP = 41, + N_3NP = 42, + N_N2P = 44, + N_NPA = 45, + N_N1 = 51, + N_N40 = 90, + N_NC = 91, N_DISAPPEAR = 101, N_GAMMA = 102, - N_P = 103, - N_D = 104, - N_T = 105, - N_3HE = 106, - N_A = 107, - N_2A = 108, - N_3A = 109, - N_2P = 111, - N_PA = 112, - N_T2A = 113, - N_D2A = 114, - N_PD = 115, - N_PT = 116, - N_DA = 117, - N_5N = 152, - N_6N = 153, - N_2NT = 154, - N_TA = 155, - N_4NP = 156, - N_3ND = 157, - N_NDA = 158, - N_2NPA = 159, - N_7N = 160, - N_8N = 161, - N_5NP = 162, - N_6NP = 163, - N_7NP = 164, - N_4NA = 165, - N_5NA = 166, - N_6NA = 167, - N_7NA = 168, - N_4ND = 169, - N_5ND = 170, - N_6ND = 171, - N_3NT = 172, - N_4NT = 173, - N_5NT = 174, - N_6NT = 175, + N_P = 103, + N_D = 104, + N_T = 105, + N_3HE = 106, + N_A = 107, + N_2A = 108, + N_3A = 109, + N_2P = 111, + N_PA = 112, + N_T2A = 113, + N_D2A = 114, + N_PD = 115, + N_PT = 116, + N_DA = 117, + N_5N = 152, + N_6N = 153, + N_2NT = 154, + N_TA = 155, + N_4NP = 156, + N_3ND = 157, + N_NDA = 158, + N_2NPA = 159, + N_7N = 160, + N_8N = 161, + N_5NP = 162, + N_6NP = 163, + N_7NP = 164, + N_4NA = 165, + N_5NA = 166, + N_6NA = 167, + N_7NA = 168, + N_4ND = 169, + N_5ND = 170, + N_6ND = 171, + N_3NT = 172, + N_4NT = 173, + N_5NT = 174, + N_6NT = 175, N_2N3HE = 176, N_3N3HE = 177, N_4N3HE = 178, - N_3N2P = 179, - N_3N2A = 180, - N_3NPA = 181, - N_DT = 182, - N_NPD = 183, - N_NPT = 184, - N_NDT = 185, + N_3N2P = 179, + N_3N2A = 180, + N_3NPA = 181, + N_DT = 182, + N_NPD = 183, + N_NPT = 184, + N_NDT = 185, N_NP3HE = 186, N_ND3HE = 187, N_NT3HE = 188, - N_NTA = 189, - N_2N2P = 190, - N_P3HE = 191, - N_D3HE = 192, - N_3HEA = 193, - N_4N2P = 194, - N_4N2A = 195, - N_4NPA = 196, - N_3P = 197, - N_N3P = 198, + N_NTA = 189, + N_2N2P = 190, + N_P3HE = 191, + N_D3HE = 192, + N_3HEA = 193, + N_4N2P = 194, + N_4N2A = 195, + N_4NPA = 196, + N_3P = 197, + N_N3P = 198, N_3N2PA = 199, - N_5N2P = 200, - N_XP = 203, - N_XD = 204, - N_XT = 205, - N_X3HE = 206, - N_XA = 207, + N_5N2P = 200, + N_XP = 203, + N_XD = 204, + N_XT = 205, + N_X3HE = 206, + N_XA = 207, HEATING = 301, DAMAGE_ENERGY = 444, COHERENT = 502, @@ -224,18 +225,18 @@ enum ReactionType { PAIR_PROD = 516, PAIR_PROD_NUC = 517, PHOTOELECTRIC = 522, - N_P0 = 600, - N_PC = 649, - N_D0 = 650, - N_DC = 699, - N_T0 = 700, - N_TC = 749, - N_3HE0 = 750, - N_3HEC = 799, - N_A0 = 800, - N_AC = 849, - N_2N0 = 875, - N_2NC = 891, + N_P0 = 600, + N_PC = 649, + N_D0 = 650, + N_DC = 699, + N_T0 = 700, + N_TC = 749, + N_3HE0 = 750, + N_3HEC = 799, + N_A0 = 800, + N_AC = 849, + N_2N0 = 875, + N_2NC = 891, HEATING_LOCAL = 901 }; @@ -255,9 +256,9 @@ constexpr int PARTIAL_FISSION_MAX {4}; // Resonance elastic scattering methods enum class ResScatMethod { - rvs, // Relative velocity sampling + rvs, // Relative velocity sampling dbrc, // Doppler broadening rejection correction - cxs // Constant cross section + cxs // Constant cross section }; enum class ElectronTreatment { @@ -296,31 +297,13 @@ enum class MgxsType { // ============================================================================ // TALLY-RELATED CONSTANTS -enum class TallyResult { - VALUE, - SUM, - SUM_SQ -}; +enum class TallyResult { VALUE, SUM, SUM_SQ }; -enum class TallyType { - VOLUME, - MESH_SURFACE, - SURFACE -}; +enum class TallyType { VOLUME, MESH_SURFACE, SURFACE }; -enum class TallyEstimator { - ANALOG, - TRACKLENGTH, - COLLISION -}; +enum class TallyEstimator { ANALOG, TRACKLENGTH, COLLISION }; -enum class TallyEvent { - SURFACE, - LATTICE, - KILL, - SCATTER, - ABSORB -}; +enum class TallyEvent { SURFACE, LATTICE, KILL, SCATTER, ABSORB }; // Tally score type -- if you change these, make sure you also update the // _SCORES dictionary in openmc/capi/tally.py @@ -329,40 +312,39 @@ enum class TallyEvent { // store one of these enum values usually also may be responsible for storing // MT numbers from the long enum above. enum TallyScore { - SCORE_FLUX = -1, // flux - SCORE_TOTAL = -2, // total reaction rate - SCORE_SCATTER = -3, // scattering rate - SCORE_NU_SCATTER = -4, // scattering production rate - SCORE_ABSORPTION = -5, // absorption rate - SCORE_FISSION = -6, // fission rate - SCORE_NU_FISSION = -7, // neutron production rate - SCORE_KAPPA_FISSION = -8, // fission energy production rate - SCORE_CURRENT = -9, // current - SCORE_EVENTS = -10, // number of events + SCORE_FLUX = -1, // flux + SCORE_TOTAL = -2, // total reaction rate + SCORE_SCATTER = -3, // scattering rate + SCORE_NU_SCATTER = -4, // scattering production rate + SCORE_ABSORPTION = -5, // absorption rate + SCORE_FISSION = -6, // fission rate + SCORE_NU_FISSION = -7, // neutron production rate + SCORE_KAPPA_FISSION = -8, // fission energy production rate + SCORE_CURRENT = -9, // current + SCORE_EVENTS = -10, // number of events SCORE_DELAYED_NU_FISSION = -11, // delayed neutron production rate - SCORE_PROMPT_NU_FISSION = -12, // prompt neutron production rate - SCORE_INVERSE_VELOCITY = -13, // flux-weighted inverse velocity - SCORE_FISS_Q_PROMPT = -14, // prompt fission Q-value - SCORE_FISS_Q_RECOV = -15, // recoverable fission Q-value - SCORE_DECAY_RATE = -16 // delayed neutron precursor decay rate + SCORE_PROMPT_NU_FISSION = -12, // prompt neutron production rate + SCORE_INVERSE_VELOCITY = -13, // flux-weighted inverse velocity + SCORE_FISS_Q_PROMPT = -14, // prompt fission Q-value + SCORE_FISS_Q_RECOV = -15, // recoverable fission Q-value + SCORE_DECAY_RATE = -16 // delayed neutron precursor decay rate }; // Global tally parameters constexpr int N_GLOBAL_TALLIES {4}; -enum class GlobalTally { - K_COLLISION, - K_ABSORPTION, - K_TRACKLENGTH, - LEAKAGE -}; +enum class GlobalTally { K_COLLISION, K_ABSORPTION, K_TRACKLENGTH, LEAKAGE }; // Miscellaneous constexpr int C_NONE {-1}; -constexpr int F90_NONE {0}; //TODO: replace usage of this with C_NONE +constexpr int F90_NONE {0}; // TODO: replace usage of this with C_NONE // Interpolation rules enum class Interpolation { - histogram = 1, lin_lin = 2, lin_log = 3, log_lin = 4, log_log = 5 + histogram = 1, + lin_lin = 2, + lin_log = 3, + log_lin = 4, + log_log = 5 }; enum class RunMode { @@ -383,11 +365,7 @@ constexpr int CMFD_NOACCEL {-1}; //============================================================================== // Geometry Constants -enum class GeometryType { - CSG, - DAG -}; - +enum class GeometryType { CSG, DAG }; } // namespace openmc diff --git a/include/openmc/container_util.h b/include/openmc/container_util.h index 1e65a18df..a40532343 100644 --- a/include/openmc/container_util.h +++ b/include/openmc/container_util.h @@ -2,7 +2,7 @@ #define OPENMC_CONTAINER_UTIL_H #include // for find -#include // for begin, end +#include // for begin, end namespace openmc { @@ -12,6 +12,6 @@ inline bool contains(const C& v, const T& x) return std::end(v) != std::find(std::begin(v), std::end(v), x); } -} +} // namespace openmc #endif // OPENMC_CONTAINER_UTIL_H diff --git a/include/openmc/cross_sections.h b/include/openmc/cross_sections.h index 8a78a4099..2b0473bec 100644 --- a/include/openmc/cross_sections.h +++ b/include/openmc/cross_sections.h @@ -3,8 +3,8 @@ #include "pugixml.hpp" -#include #include +#include #include "openmc/vector.h" @@ -18,22 +18,24 @@ class Library { public: // Types, enums enum class Type { - neutron = 1, photon = 3, thermal = 2, multigroup = 4, wmp = 5 + neutron = 1, + photon = 3, + thermal = 2, + multigroup = 4, + wmp = 5 }; // Constructors - Library() { }; + Library() {}; Library(pugi::xml_node node, const std::string& directory); // Comparison operator (for using in map) - bool operator<(const Library& other) { - return path_ < other.path_; - } + bool operator<(const Library& other) { return path_ < other.path_; } // Data members - Type type_; //!< Type of data library + Type type_; //!< Type of data library vector materials_; //!< Materials contained in library - std::string path_; //!< File path to library + std::string path_; //!< File path to library }; using LibraryKey = std::pair; @@ -60,11 +62,11 @@ extern vector libraries; //! libraries void read_cross_sections_xml(); - //! Load nuclide and thermal scattering data from HDF5 files // //! \param[in] nuc_temps Temperatures for each nuclide in [K] -//! \param[in] thermal_temps Temperatures for each thermal scattering table in [K] +//! \param[in] thermal_temps Temperatures for each thermal scattering table in +//! [K] void read_ce_cross_sections(const vector>& nuc_temps, const vector>& thermal_temps); diff --git a/include/openmc/dagmc.h b/include/openmc/dagmc.h index 6a71e6170..64bf4d209 100644 --- a/include/openmc/dagmc.h +++ b/include/openmc/dagmc.h @@ -17,7 +17,7 @@ namespace openmc { void read_dagmc_universes(pugi::xml_node node); void check_dagmc_root_univ(); -} +} // namespace openmc #ifdef DAGMC @@ -49,7 +49,7 @@ public: private: std::shared_ptr dagmc_ptr_; //!< Pointer to DagMC instance - int32_t dag_index_; //!< DagMC index of surface + int32_t dag_index_; //!< DagMC index of surface }; class DAGCell : public Cell { @@ -58,8 +58,8 @@ public: bool contains(Position r, Direction u, int32_t on_surface) const override; - std::pair - distance(Position r, Direction u, int32_t on_surface, Particle* p) const override; + std::pair distance( + Position r, Direction u, int32_t on_surface, Particle* p) const override; BoundingBox bounding_box() const override; @@ -71,24 +71,24 @@ public: private: std::shared_ptr dagmc_ptr_; //!< Pointer to DagMC instance - int32_t dag_index_; //!< DagMC index of cell + int32_t dag_index_; //!< DagMC index of cell }; class DAGUniverse : public Universe { public: - explicit DAGUniverse(pugi::xml_node node); //! Create a new DAGMC universe //! \param[in] filename Name of the DAGMC file - //! \param[in] auto_geom_ids Whether or not to automatically assign cell and surface IDs - //! \param[in] auto_mat_ids Whether or not to automatically assign material IDs - explicit DAGUniverse(const std::string& filename, - bool auto_geom_ids = false, - bool auto_mat_ids = false); + //! \param[in] auto_geom_ids Whether or not to automatically assign cell and + //! surface IDs \param[in] auto_mat_ids Whether or not to automatically assign + //! material IDs + explicit DAGUniverse(const std::string& filename, bool auto_geom_ids = false, + bool auto_mat_ids = false); - //! Initialize the DAGMC accel. data structures, indices, material assignments, etc. + //! Initialize the DAGMC accel. data structures, indices, material + //! assignments, etc. void initialize(); //! Reads UWUW materials and returns an ID map @@ -97,54 +97,67 @@ public: //! \return True if UWUW materials are present, False if not bool uses_uwuw() const; - //! Returns the index to the implicit complement's index in OpenMC for this DAGMC universe + //! Returns the index to the implicit complement's index in OpenMC for this + //! DAGMC universe int32_t implicit_complement_idx() const; //! Transform UWUW materials into an OpenMC-readable XML format - //! \return A string representing a materials.xml file of the UWUW materials in this universe + //! \return A string representing a materials.xml file of the UWUW materials + //! in this universe std::string get_uwuw_materials_xml() const; //! Writes the UWUW material file to XML (for debugging purposes) - void write_uwuw_materials_xml(const std::string& outfile = "uwuw_materials.xml") const; + void write_uwuw_materials_xml( + const std::string& outfile = "uwuw_materials.xml") const; //! Assign a material to a cell based //! \param[in] mat_string The DAGMC material assignment string //! \param[in] c The OpenMC cell to which the material is assigned - void legacy_assign_material(std::string mat_string, - std::unique_ptr& c) const; + void legacy_assign_material( + std::string mat_string, std::unique_ptr& c) const; - //! Generate a string representing the ranges of IDs present in the DAGMC model. - //! Contiguous chunks of IDs are represented as a range (i.e. 1-10). If there is - //! a single ID a chunk, it will be represented as a single number (i.e. 2, 4, 6, 8). - //! \param[in] dim Dimension of the entities - //! \return A string of the ID ranges for entities of dimension \p dim + //! Generate a string representing the ranges of IDs present in the DAGMC + //! model. Contiguous chunks of IDs are represented as a range (i.e. 1-10). If + //! there is a single ID a chunk, it will be represented as a single number + //! (i.e. 2, 4, 6, 8). \param[in] dim Dimension of the entities \return A + //! string of the ID ranges for entities of dimension \p dim std::string dagmc_ids_for_dim(int dim) const; - bool find_cell(Particle &p) const override; + bool find_cell(Particle& p) const override; void to_hdf5(hid_t universes_group) const override; // Data Members - std::shared_ptr dagmc_instance_; //!< DAGMC Instance for this universe - int32_t cell_idx_offset_; //!< An offset to the start of the cells in this universe in OpenMC's cell vector - int32_t surf_idx_offset_; //!< An offset to the start of the surfaces in this universe in OpenMC's surface vector + std::shared_ptr + dagmc_instance_; //!< DAGMC Instance for this universe + int32_t cell_idx_offset_; //!< An offset to the start of the cells in this + //!< universe in OpenMC's cell vector + int32_t surf_idx_offset_; //!< An offset to the start of the surfaces in this + //!< universe in OpenMC's surface vector // Accessors bool has_graveyard() const { return has_graveyard_; } private: - std::string filename_; //!< Name of the DAGMC file used to create this universe - std::shared_ptr uwuw_; //!< Pointer to the UWUW instance for this universe - bool adjust_geometry_ids_; //!< Indicates whether or not to automatically generate new cell and surface IDs for the universe - bool adjust_material_ids_; //!< Indicates whether or not to automatically generate new material IDs for the universe - bool has_graveyard_; //!< Indicates if the DAGMC geometry has a "graveyard" volume + std::string + filename_; //!< Name of the DAGMC file used to create this universe + std::shared_ptr + uwuw_; //!< Pointer to the UWUW instance for this universe + bool adjust_geometry_ids_; //!< Indicates whether or not to automatically + //!< generate new cell and surface IDs for the + //!< universe + bool adjust_material_ids_; //!< Indicates whether or not to automatically + //!< generate new material IDs for the universe + bool has_graveyard_; //!< Indicates if the DAGMC geometry has a "graveyard" + //!< volume }; //============================================================================== // Non-member functions //============================================================================== -int32_t next_cell(DAGUniverse* dag_univ, DAGCell* cur_cell, DAGSurface* surf_xed); +int32_t next_cell( + DAGUniverse* dag_univ, DAGCell* cur_cell, DAGSurface* surf_xed); } // namespace openmc diff --git a/include/openmc/distribution.h b/include/openmc/distribution.h index 888fab7d8..44fd985d2 100644 --- a/include/openmc/distribution.h +++ b/include/openmc/distribution.h @@ -57,7 +57,7 @@ private: class Uniform : public Distribution { public: explicit Uniform(pugi::xml_node node); - Uniform(double a, double b) : a_{a}, b_{b} {}; + Uniform(double a, double b) : a_ {a}, b_ {b} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -66,6 +66,7 @@ public: double a() const { return a_; } double b() const { return b_; } + private: double a_; //!< Lower bound of distribution double b_; //!< Upper bound of distribution @@ -78,7 +79,7 @@ private: class Maxwell : public Distribution { public: explicit Maxwell(pugi::xml_node node); - Maxwell(double theta) : theta_{theta} { }; + Maxwell(double theta) : theta_ {theta} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -86,6 +87,7 @@ public: double sample(uint64_t* seed) const; double theta() const { return theta_; } + private: double theta_; //!< Factor in exponential [eV] }; @@ -97,7 +99,7 @@ private: class Watt : public Distribution { public: explicit Watt(pugi::xml_node node); - Watt(double a, double b) : a_{a}, b_{b} { }; + Watt(double a, double b) : a_ {a}, b_ {b} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -106,19 +108,22 @@ public: double a() const { return a_; } double b() const { return b_; } + private: double a_; //!< Factor in exponential [eV] double b_; //!< Factor in square root [1/eV] }; //============================================================================== -//! Normal distributions with form 1/2*std_dev*sqrt(pi) exp (-(e-E0)/2*std_dev)^2 +//! Normal distributions with form 1/2*std_dev*sqrt(pi) exp +//! (-(e-E0)/2*std_dev)^2 //============================================================================== class Normal : public Distribution { public: explicit Normal(pugi::xml_node node); - Normal(double mean_value, double std_dev) : mean_value_{mean_value}, std_dev_{std_dev} { }; + Normal(double mean_value, double std_dev) + : mean_value_ {mean_value}, std_dev_ {std_dev} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -127,9 +132,10 @@ public: double mean_value() const { return mean_value_; } double std_dev() const { return std_dev_; } + private: - double mean_value_; //!< middle of distribution [eV] - double std_dev_; //!< standard deviation [eV] + double mean_value_; //!< middle of distribution [eV] + double std_dev_; //!< standard deviation [eV] }; //============================================================================== @@ -140,7 +146,8 @@ private: class Muir : public Distribution { public: explicit Muir(pugi::xml_node node); - Muir(double e0, double m_rat, double kt) : e0_{e0}, m_rat_{m_rat}, kt_{kt} { }; + Muir(double e0, double m_rat, double kt) + : e0_ {e0}, m_rat_ {m_rat}, kt_ {kt} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -150,6 +157,7 @@ public: double e0() const { return e0_; } double m_rat() const { return m_rat_; } double kt() const { return kt_; } + private: // example DT fusion m_rat = 5 (D = 2 + T = 3) // ion temp = 20000 eV @@ -167,7 +175,7 @@ class Tabular : public Distribution { public: explicit Tabular(pugi::xml_node node); Tabular(const double* x, const double* p, int n, Interpolation interp, - const double* c=nullptr); + const double* c = nullptr); //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer @@ -179,18 +187,19 @@ public: const vector& x() const { return x_; } const vector& p() const { return p_; } Interpolation interp() const { return interp_; } + private: - vector x_; //!< tabulated independent variable - vector p_; //!< tabulated probability density - vector c_; //!< cumulative distribution at tabulated values - Interpolation interp_; //!< interpolation rule + vector x_; //!< tabulated independent variable + vector p_; //!< tabulated probability density + vector c_; //!< cumulative distribution at tabulated values + Interpolation interp_; //!< interpolation rule //! Initialize tabulated probability density function //! \param x Array of values for independent variable //! \param p Array of tabulated probabilities //! \param n Number of tabulated values - void init(const double* x, const double* p, std::size_t n, - const double* c=nullptr); + void init( + const double* x, const double* p, std::size_t n, const double* c = nullptr); }; //============================================================================== @@ -200,7 +209,7 @@ private: class Equiprobable : public Distribution { public: explicit Equiprobable(pugi::xml_node node); - Equiprobable(const double* x, int n) : x_{x, x+n} { }; + Equiprobable(const double* x, int n) : x_ {x, x + n} {}; //! Sample a value from the distribution //! \param seed Pseudorandom number seed pointer diff --git a/include/openmc/distribution_energy.h b/include/openmc/distribution_energy.h index 9c7438f33..d8512aa45 100644 --- a/include/openmc/distribution_energy.h +++ b/include/openmc/distribution_energy.h @@ -4,8 +4,8 @@ #ifndef OPENMC_DISTRIBUTION_ENERGY_H #define OPENMC_DISTRIBUTION_ENERGY_H -#include "xtensor/xtensor.hpp" #include "hdf5.h" +#include "xtensor/xtensor.hpp" #include "openmc/constants.h" #include "openmc/endf.h" @@ -38,11 +38,12 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: int primary_flag_; //!< Indicator of whether the photon is a primary or //!< non-primary photon. - double energy_; //!< Photon energy or binding energy - double A_; //!< Atomic weight ratio of the target nuclide + double energy_; //!< Photon energy or binding energy + double A_; //!< Atomic weight ratio of the target nuclide }; //=============================================================================== @@ -58,8 +59,9 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: - double threshold_; //!< Energy threshold in lab, (A + 1)/A * |Q| + double threshold_; //!< Energy threshold in lab, (A + 1)/A * |Q| double mass_ratio_; //!< (A/(A+1))^2 }; @@ -78,17 +80,18 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: //! Outgoing energy for a single incoming energy struct CTTable { - Interpolation interpolation; //!< Interpolation law - int n_discrete; //!< Number of of discrete energies + Interpolation interpolation; //!< Interpolation law + int n_discrete; //!< Number of of discrete energies xt::xtensor e_out; //!< Outgoing energies in [eV] - xt::xtensor p; //!< Probability density - xt::xtensor c; //!< Cumulative distribution + xt::xtensor p; //!< Probability density + xt::xtensor c; //!< Cumulative distribution }; - int n_region_; //!< Number of inteprolation regions + int n_region_; //!< Number of inteprolation regions vector breakpoints_; //!< Breakpoints between regions vector interpolation_; //!< Interpolation laws vector energy_; //!< Incident energy in [eV] @@ -108,9 +111,10 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: Tabulated1D theta_; //!< Incoming energy dependent parameter - double u_; //!< Restriction energy + double u_; //!< Restriction energy }; //=============================================================================== @@ -127,9 +131,10 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: Tabulated1D theta_; //!< Incoming energy dependent parameter - double u_; //!< Restriction energy + double u_; //!< Restriction energy }; //=============================================================================== @@ -146,10 +151,11 @@ public: //! \param[inout] seed Pseudorandom number seed pointer //! \return Sampled energy in [eV] double sample(double E, uint64_t* seed) const; + private: Tabulated1D a_; //!< Energy-dependent 'a' parameter Tabulated1D b_; //!< Energy-dependent 'b' parameter - double u_; //!< Restriction energy + double u_; //!< Restriction energy }; } // namespace openmc diff --git a/include/openmc/distribution_multi.h b/include/openmc/distribution_multi.h index 793e8f719..991294f79 100644 --- a/include/openmc/distribution_multi.h +++ b/include/openmc/distribution_multi.h @@ -17,8 +17,8 @@ namespace openmc { class UnitSphereDistribution { public: - UnitSphereDistribution() { }; - explicit UnitSphereDistribution(Direction u) : u_ref_{u} { }; + UnitSphereDistribution() {}; + explicit UnitSphereDistribution(Direction u) : u_ref_ {u} {}; explicit UnitSphereDistribution(pugi::xml_node node); virtual ~UnitSphereDistribution() = default; @@ -27,7 +27,7 @@ public: //! \return Direction sampled virtual Direction sample(uint64_t* seed) const = 0; - Direction u_ref_ {0.0, 0.0, 1.0}; //!< reference direction + Direction u_ref_ {0.0, 0.0, 1.0}; //!< reference direction }; //============================================================================== @@ -61,7 +61,7 @@ Direction isotropic_direction(uint64_t* seed); class Isotropic : public UnitSphereDistribution { public: - Isotropic() { }; + Isotropic() {}; //! Sample a direction from the distribution //! \param seed Pseudorandom number seed pointer @@ -75,8 +75,9 @@ public: class Monodirectional : public UnitSphereDistribution { public: - Monodirectional(Direction u) : UnitSphereDistribution{u} { }; - explicit Monodirectional(pugi::xml_node node) : UnitSphereDistribution{node} { }; + Monodirectional(Direction u) : UnitSphereDistribution {u} {}; + explicit Monodirectional(pugi::xml_node node) + : UnitSphereDistribution {node} {}; //! Sample a direction from the distribution //! \param seed Pseudorandom number seed pointer diff --git a/include/openmc/distribution_spatial.h b/include/openmc/distribution_spatial.h index a56ff2dcf..9cceee184 100644 --- a/include/openmc/distribution_spatial.h +++ b/include/openmc/distribution_spatial.h @@ -37,6 +37,7 @@ public: Distribution* x() const { return x_.get(); } Distribution* y() const { return y_.get(); } Distribution* z() const { return z_.get(); } + private: UPtrDist x_; //!< Distribution of x coordinates UPtrDist y_; //!< Distribution of y coordinates @@ -55,19 +56,19 @@ public: //! \param seed Pseudorandom number seed pointer //! \return Sampled position Position sample(uint64_t* seed) const; - + Distribution* r() const { return r_.get(); } Distribution* phi() const { return phi_.get(); } Distribution* z() const { return z_.get(); } Position origin() const { return origin_; } + private: - UPtrDist r_; //!< Distribution of r coordinates - UPtrDist phi_; //!< Distribution of phi coordinates - UPtrDist z_; //!< Distribution of z coordinates + UPtrDist r_; //!< Distribution of r coordinates + UPtrDist phi_; //!< Distribution of phi coordinates + UPtrDist z_; //!< Distribution of z coordinates Position origin_; //!< Cartesian coordinates of the cylinder center }; - //============================================================================== //! Distribution of points specified by spherical coordinates r,theta,phi //============================================================================== @@ -84,11 +85,12 @@ public: Distribution* r() const { return r_.get(); } Distribution* theta() const { return theta_.get(); } Distribution* phi() const { return phi_.get(); } - Position origin () const { return origin_; } + Position origin() const { return origin_; } + private: - UPtrDist r_; //!< Distribution of r coordinates - UPtrDist theta_; //!< Distribution of theta coordinates - UPtrDist phi_; //!< Distribution of phi coordinates + UPtrDist r_; //!< Distribution of r coordinates + UPtrDist theta_; //!< Distribution of theta coordinates + UPtrDist phi_; //!< Distribution of phi coordinates Position origin_; //!< Cartesian coordinates of the sphere center }; @@ -98,7 +100,7 @@ private: class SpatialBox : public SpatialDistribution { public: - explicit SpatialBox(pugi::xml_node node, bool fission=false); + explicit SpatialBox(pugi::xml_node node, bool fission = false); //! Sample a position from the distribution //! \param seed Pseudorandom number seed pointer @@ -109,9 +111,10 @@ public: bool only_fissionable() const { return only_fissionable_; } Position lower_left() const { return lower_left_; } Position upper_right() const { return upper_right_; } + private: - Position lower_left_; //!< Lower-left coordinates of box - Position upper_right_; //!< Upper-right coordinates of box + Position lower_left_; //!< Lower-left coordinates of box + Position upper_right_; //!< Upper-right coordinates of box bool only_fissionable_ {false}; //!< Only accept sites in fissionable region? }; @@ -121,8 +124,8 @@ private: class SpatialPoint : public SpatialDistribution { public: - SpatialPoint() : r_{} { }; - SpatialPoint(Position r) : r_{r} { }; + SpatialPoint() : r_ {} {}; + SpatialPoint(Position r) : r_ {r} {}; explicit SpatialPoint(pugi::xml_node node); //! Sample a position from the distribution @@ -131,6 +134,7 @@ public: Position sample(uint64_t* seed) const; Position r() const { return r_; } + private: Position r_; //!< Single position at which sites are generated }; diff --git a/include/openmc/endf.h b/include/openmc/endf.h index 40e1cef83..7beb8e452 100644 --- a/include/openmc/endf.h +++ b/include/openmc/endf.h @@ -57,6 +57,7 @@ public: //! \param[in] x independent variable //! \return Polynomial evaluated at x double operator()(double x) const override; + private: vector coef_; //!< Polynomial coefficients }; @@ -86,9 +87,9 @@ private: std::size_t n_regions_ {0}; //!< number of interpolation regions vector nbt_; //!< values separating interpolation regions vector int_; //!< interpolation schemes - std::size_t n_pairs_; //!< number of (x,y) pairs - vector x_; //!< values of abscissa - vector y_; //!< values of ordinate + std::size_t n_pairs_; //!< number of (x,y) pairs + vector x_; //!< values of abscissa + vector y_; //!< values of ordinate }; //============================================================================== @@ -118,9 +119,11 @@ public: explicit IncoherentElasticXS(hid_t dset); double operator()(double E) const override; + private: double bound_xs_; //!< Characteristic bound xs in [b] - double debye_waller_; //!< Debye-Waller integral divided by atomic mass in [eV^-1] + double + debye_waller_; //!< Debye-Waller integral divided by atomic mass in [eV^-1] }; //! Read 1D function from HDF5 dataset diff --git a/include/openmc/error.h b/include/openmc/error.h index 053783446..d73795aee 100644 --- a/include/openmc/error.h +++ b/include/openmc/error.h @@ -2,8 +2,8 @@ #define OPENMC_ERROR_H #include -#include #include +#include #include @@ -18,50 +18,43 @@ namespace openmc { -inline void -set_errmsg(const char* message) +inline void set_errmsg(const char* message) { std::strcpy(openmc_err_msg, message); } -inline void -set_errmsg(const std::string& message) +inline void set_errmsg(const std::string& message) { std::strcpy(openmc_err_msg, message.c_str()); } -inline void -set_errmsg(const std::stringstream& message) +inline void set_errmsg(const std::stringstream& message) { std::strcpy(openmc_err_msg, message.str().c_str()); } -[[noreturn]] void fatal_error(const std::string& message, int err=-1); +[[noreturn]] void fatal_error(const std::string& message, int err = -1); -[[noreturn]] inline -void fatal_error(const std::stringstream& message) +[[noreturn]] inline void fatal_error(const std::stringstream& message) { fatal_error(message.str()); } -[[noreturn]] inline -void fatal_error(const char* message) +[[noreturn]] inline void fatal_error(const char* message) { - fatal_error(std::string{message, std::strlen(message)}); + fatal_error(std::string {message, std::strlen(message)}); } void warning(const std::string& message); -inline -void warning(const std::stringstream& message) +inline void warning(const std::stringstream& message) { warning(message.str()); } -void write_message(const std::string& message, int level=0); +void write_message(const std::string& message, int level = 0); -inline -void write_message(const std::stringstream& message, int level) +inline void write_message(const std::stringstream& message, int level) { write_message(message.str(), level); } diff --git a/include/openmc/event.h b/include/openmc/event.h index 981fa9b17..2d215a10e 100644 --- a/include/openmc/event.h +++ b/include/openmc/event.h @@ -7,7 +7,6 @@ #include "openmc/particle.h" #include "openmc/shared_array.h" - namespace openmc { //============================================================================== @@ -17,17 +16,17 @@ namespace openmc { // In the event-based model, instead of moving or sorting the particles // themselves based on which event they need, a queue is used to store the // index (and other useful info) for each event type. -// The EventQueueItem struct holds the relevant information about a particle needed -// for sorting the queue. For very high particle counts, a sorted queue has the -// potential to result in greatly improved cache efficiency. However, sorting -// will introduce some overhead due to the sorting process itself, and may not -// result in any benefits if not enough particles are present for them to achieve -// consistent locality improvements. -struct EventQueueItem{ - int64_t idx; //!< particle index in event-based particle buffer - ParticleType type; //!< particle type - int64_t material; //!< material that particle is in - double E; //!< particle energy +// The EventQueueItem struct holds the relevant information about a particle +// needed for sorting the queue. For very high particle counts, a sorted queue +// has the potential to result in greatly improved cache efficiency. However, +// sorting will introduce some overhead due to the sorting process itself, and +// may not result in any benefits if not enough particles are present for them +// to achieve consistent locality improvements. +struct EventQueueItem { + int64_t idx; //!< particle index in event-based particle buffer + ParticleType type; //!< particle type + int64_t material; //!< material that particle is in + double E; //!< particle energy // Constructors EventQueueItem() = default; @@ -35,16 +34,18 @@ struct EventQueueItem{ : idx(buffer_idx), type(p.type()), material(p.material()), E(p.E()) {} - // Compare by particle type, then by material type (4.5% fuel/7.0% fuel/cladding/etc), - // then by energy. - // TODO: Currently in OpenMC, the material ID corresponds not only to a general - // type, but also specific isotopic densities. Ideally we would - // like to be able to just sort by general material type, regardless of densities. - // A more general material type ID may be added in the future, in which case we - // can update the material field of this struct to contain the more general id. + // Compare by particle type, then by material type (4.5% fuel/7.0% + // fuel/cladding/etc), then by energy. + // TODO: Currently in OpenMC, the material ID corresponds not only to a + // general type, but also specific isotopic densities. Ideally we would like + // to be able to just sort by general material type, regardless of densities. + // A more general material type ID may be added in the future, in which case + // we can update the material field of this struct to contain the more general + // id. bool operator<(const EventQueueItem& rhs) const { - return std::tie(type, material, E) < std::tie(rhs.type, rhs.material, rhs.E); + return std::tie(type, material, E) < + std::tie(rhs.type, rhs.material, rhs.E); } }; diff --git a/include/openmc/finalize.h b/include/openmc/finalize.h index f99201abe..6d8cd9087 100644 --- a/include/openmc/finalize.h +++ b/include/openmc/finalize.h @@ -1,8 +1,6 @@ #ifndef OPENMC_FINALIZE_H #define OPENMC_FINALIZE_H -namespace openmc { - -} // namespace openmc +namespace openmc {} // namespace openmc #endif // OPENMC_FINALIZE_H diff --git a/include/openmc/geometry.h b/include/openmc/geometry.h index 617921f45..001e58c4c 100644 --- a/include/openmc/geometry.h +++ b/include/openmc/geometry.h @@ -19,7 +19,7 @@ class Particle; namespace model { -extern int root_universe; //!< Index of root universe +extern int root_universe; //!< Index of root universe extern "C" int n_coord_levels; //!< Number of CSG coordinate levels extern vector overlap_check_count; @@ -30,7 +30,8 @@ extern vector overlap_check_count; //! Check two distances by coincidence tolerance //============================================================================== -inline bool coincident(double d1, double d2) { +inline bool coincident(double d1, double d2) +{ return std::abs(d1 - d2) < FP_COINCIDENT; } @@ -38,15 +39,15 @@ inline bool coincident(double d1, double d2) { //! Check for overlapping cells at a particle's position. //============================================================================== -bool check_cell_overlap(Particle& p, bool error=true); +bool check_cell_overlap(Particle& p, bool error = true); //============================================================================== //! Get the cell instance for a particle at the specified universe level //! //! \param p A particle for which to compute the instance using //! its coordinates -//! \param level The level (zero indexed) of the geometry where the instance should be computed. -//! \return The instance of the cell at the specified level. +//! \param level The level (zero indexed) of the geometry where the instance +//! should be computed. \return The instance of the cell at the specified level. //============================================================================== int cell_instance_at_level(const Particle& p, int level); diff --git a/include/openmc/geometry_aux.h b/include/openmc/geometry_aux.h index 899326a53..b248d491a 100644 --- a/include/openmc/geometry_aux.h +++ b/include/openmc/geometry_aux.h @@ -14,8 +14,9 @@ namespace openmc { namespace model { - extern std::unordered_map> universe_cell_counts; - extern std::unordered_map universe_level_counts; +extern std::unordered_map> + universe_cell_counts; +extern std::unordered_map universe_level_counts; } // namespace model void read_geometry_xml(); @@ -69,7 +70,8 @@ int32_t find_root_universe(); //! filter. //============================================================================== -void prepare_distribcell(const std::vector* user_distribcells = nullptr); +void prepare_distribcell( + const std::vector* user_distribcells = nullptr); //============================================================================== //! Recursively search through the geometry and count cell instances. @@ -106,8 +108,8 @@ int count_universe_instances(int32_t search_univ, int32_t target_univ_id, //! desired instance of the target cell. //============================================================================== -std::string -distribcell_path(int32_t target_cell, int32_t map, int32_t target_offset); +std::string distribcell_path( + int32_t target_cell, int32_t map, int32_t target_offset); //============================================================================== //! Determine the maximum number of nested coordinate levels in the geometry. diff --git a/include/openmc/hdf5_interface.h b/include/openmc/hdf5_interface.h index ae91ce2ae..0fe55d170 100644 --- a/include/openmc/hdf5_interface.h +++ b/include/openmc/hdf5_interface.h @@ -5,8 +5,8 @@ #include #include #include // for strlen -#include #include +#include #include #include "hdf5.h" @@ -25,8 +25,7 @@ namespace openmc { // Low-level internal functions //============================================================================== -void read_attr(hid_t obj_id, const char* name, hid_t mem_type_id, - void* buffer); +void read_attr(hid_t obj_id, const char* name, hid_t mem_type_id, void* buffer); void write_attr(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, hid_t mem_type_id, const void* buffer); @@ -47,17 +46,18 @@ bool using_mpio_device(hid_t obj_id); hid_t create_group(hid_t parent_id, const std::string& name); inline hid_t create_group(hid_t parent_id, const std::stringstream& name) -{return create_group(parent_id, name.str());} +{ + return create_group(parent_id, name.str()); +} - -hid_t file_open(const std::string& filename, char mode, bool parallel=false); +hid_t file_open(const std::string& filename, char mode, bool parallel = false); hid_t open_group(hid_t group_id, const std::string& name); -void write_string(hid_t group_id, const char* name, const std::string& buffer, - bool indep); +void write_string( + hid_t group_id, const char* name, const std::string& buffer, bool indep); vector attribute_shape(hid_t obj_id, const char* name); vector dataset_names(hid_t group_id); -void ensure_exists(hid_t obj_id, const char* name, bool attribute=false); +void ensure_exists(hid_t obj_id, const char* name, bool attribute = false); vector group_names(hid_t group_id); vector object_shape(hid_t obj_id); std::string object_name(hid_t obj_id); @@ -67,56 +67,54 @@ std::string object_name(hid_t obj_id); //============================================================================== extern "C" { - bool attribute_exists(hid_t obj_id, const char* name); - size_t attribute_typesize(hid_t obj_id, const char* name); - hid_t create_group(hid_t parent_id, const char* name); - void close_dataset(hid_t dataset_id); - void close_group(hid_t group_id); - int dataset_ndims(hid_t dset); - size_t dataset_typesize(hid_t obj_id, const char* name); - hid_t file_open(const char* filename, char mode, bool parallel); - void file_close(hid_t file_id); - void get_name(hid_t obj_id, char* name); - int get_num_datasets(hid_t group_id); - int get_num_groups(hid_t group_id); - void get_datasets(hid_t group_id, char* name[]); - void get_groups(hid_t group_id, char* name[]); - void get_shape(hid_t obj_id, hsize_t* dims); - void get_shape_attr(hid_t obj_id, const char* name, hsize_t* dims); - bool object_exists(hid_t object_id, const char* name); - hid_t open_dataset(hid_t group_id, const char* name); - hid_t open_group(hid_t group_id, const char* name); - void read_attr_double(hid_t obj_id, const char* name, double* buffer); - void read_attr_int(hid_t obj_id, const char* name, int* buffer); - void read_attr_string(hid_t obj_id, const char* name, size_t slen, - char* buffer); - void read_complex(hid_t obj_id, const char* name, - std::complex* buffer, bool indep); - void read_double(hid_t obj_id, const char* name, double* buffer, bool indep); - void read_int(hid_t obj_id, const char* name, int* buffer, bool indep); - void read_llong(hid_t obj_id, const char* name, long long* buffer, - bool indep); - void read_string(hid_t obj_id, const char* name, size_t slen, char* buffer, - bool indep); +bool attribute_exists(hid_t obj_id, const char* name); +size_t attribute_typesize(hid_t obj_id, const char* name); +hid_t create_group(hid_t parent_id, const char* name); +void close_dataset(hid_t dataset_id); +void close_group(hid_t group_id); +int dataset_ndims(hid_t dset); +size_t dataset_typesize(hid_t obj_id, const char* name); +hid_t file_open(const char* filename, char mode, bool parallel); +void file_close(hid_t file_id); +void get_name(hid_t obj_id, char* name); +int get_num_datasets(hid_t group_id); +int get_num_groups(hid_t group_id); +void get_datasets(hid_t group_id, char* name[]); +void get_groups(hid_t group_id, char* name[]); +void get_shape(hid_t obj_id, hsize_t* dims); +void get_shape_attr(hid_t obj_id, const char* name, hsize_t* dims); +bool object_exists(hid_t object_id, const char* name); +hid_t open_dataset(hid_t group_id, const char* name); +hid_t open_group(hid_t group_id, const char* name); +void read_attr_double(hid_t obj_id, const char* name, double* buffer); +void read_attr_int(hid_t obj_id, const char* name, int* buffer); +void read_attr_string( + hid_t obj_id, const char* name, size_t slen, char* buffer); +void read_complex( + hid_t obj_id, const char* name, std::complex* buffer, bool indep); +void read_double(hid_t obj_id, const char* name, double* buffer, bool indep); +void read_int(hid_t obj_id, const char* name, int* buffer, bool indep); +void read_llong(hid_t obj_id, const char* name, long long* buffer, bool indep); +void read_string( + hid_t obj_id, const char* name, size_t slen, char* buffer, bool indep); - - void read_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, - double* results); - void write_attr_double(hid_t obj_id, int ndim, const hsize_t* dims, - const char* name, const double* buffer); - void write_attr_int(hid_t obj_id, int ndim, const hsize_t* dims, - const char* name, const int* buffer); - void write_attr_string(hid_t obj_id, const char* name, const char* buffer); - void write_double(hid_t group_id, int ndim, const hsize_t* dims, - const char* name, const double* buffer, bool indep); - void write_int(hid_t group_id, int ndim, const hsize_t* dims, - const char* name, const int* buffer, bool indep); - void write_llong(hid_t group_id, int ndim, const hsize_t* dims, - const char* name, const long long* buffer, bool indep); - void write_string(hid_t group_id, int ndim, const hsize_t* dims, size_t slen, - const char* name, char const* buffer, bool indep); - void write_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, - const double* results); +void read_tally_results( + hid_t group_id, hsize_t n_filter, hsize_t n_score, double* results); +void write_attr_double(hid_t obj_id, int ndim, const hsize_t* dims, + const char* name, const double* buffer); +void write_attr_int(hid_t obj_id, int ndim, const hsize_t* dims, + const char* name, const int* buffer); +void write_attr_string(hid_t obj_id, const char* name, const char* buffer); +void write_double(hid_t group_id, int ndim, const hsize_t* dims, + const char* name, const double* buffer, bool indep); +void write_int(hid_t group_id, int ndim, const hsize_t* dims, const char* name, + const int* buffer, bool indep); +void write_llong(hid_t group_id, int ndim, const hsize_t* dims, + const char* name, const long long* buffer, bool indep); +void write_string(hid_t group_id, int ndim, const hsize_t* dims, size_t slen, + const char* name, char const* buffer, bool indep); +void write_tally_results( + hid_t group_id, hsize_t n_filter, hsize_t n_score, const double* results); } // extern "C" //============================================================================== @@ -127,7 +125,9 @@ extern "C" { //============================================================================== template -struct H5TypeMap { static const hid_t type_id; }; +struct H5TypeMap { + static const hid_t type_id; +}; //============================================================================== // Templates/overloads for read_attribute @@ -185,8 +185,7 @@ void read_attribute(hid_t obj_id, const char* name, xt::xarray& arr) } // overload for std::string -inline void -read_attribute(hid_t obj_id, const char* name, std::string& str) +inline void read_attribute(hid_t obj_id, const char* name, std::string& str) { // Create buffer to read data into auto n = attribute_typesize(obj_id, name); @@ -194,7 +193,7 @@ read_attribute(hid_t obj_id, const char* name, std::string& str) // Read attribute and set string read_attr_string(obj_id, name, n, buffer); - str = std::string{buffer, n}; + str = std::string {buffer, n}; delete[] buffer; } @@ -207,7 +206,7 @@ inline void read_attribute( // Allocate a C char array to get strings auto n = attribute_typesize(obj_id, name); - char* buffer = new char[m*n]; + char* buffer = new char[m * n]; // Read char data in attribute read_attr_string(obj_id, name, n, buffer); @@ -216,10 +215,12 @@ inline void read_attribute( // Determine proper length of string -- strlen doesn't work because // buffer[i] might not have any null characters std::size_t k = 0; - for (; k < n; ++k) if (buffer[i*n + k] == '\0') break; + for (; k < n; ++k) + if (buffer[i * n + k] == '\0') + break; // Create string based on (char*, size_t) constructor - vec.emplace_back(&buffer[i*n], k); + vec.emplace_back(&buffer[i * n], k); } delete[] buffer; } @@ -232,17 +233,17 @@ inline void read_attribute( // this version of read_dataset for vectors, arrays, or other non-scalar types. // enable_if_t allows us to conditionally remove the function from overload // resolution when the type T doesn't meet a certain criterion. -template inline -std::enable_if_t>::value> -read_dataset(hid_t obj_id, const char* name, T& buffer, bool indep=false) +template +inline std::enable_if_t>::value> read_dataset( + hid_t obj_id, const char* name, T& buffer, bool indep = false) { - read_dataset_lowlevel(obj_id, name, H5TypeMap::type_id, H5S_ALL, indep, - &buffer); + read_dataset_lowlevel( + obj_id, name, H5TypeMap::type_id, H5S_ALL, indep, &buffer); } // overload for std::string -inline void -read_dataset(hid_t obj_id, const char* name, std::string& str, bool indep=false) +inline void read_dataset( + hid_t obj_id, const char* name, std::string& str, bool indep = false) { // Create buffer to read data into auto n = dataset_typesize(obj_id, name); @@ -250,7 +251,7 @@ read_dataset(hid_t obj_id, const char* name, std::string& str, bool indep=false) // Read attribute and set string read_string(obj_id, name, n, buffer, indep); - str = std::string{buffer, n}; + str = std::string {buffer, n}; } // array version @@ -258,8 +259,8 @@ template inline void read_dataset( hid_t dset, const char* name, array& buffer, bool indep = false) { - read_dataset_lowlevel(dset, name, H5TypeMap::type_id, H5S_ALL, indep, - buffer.data()); + read_dataset_lowlevel( + dset, name, H5TypeMap::type_id, H5S_ALL, indep, buffer.data()); } // vector version @@ -273,8 +274,8 @@ void read_dataset(hid_t dset, vector& vec, bool indep = false) vec.resize(shape[0]); // Read data into vector - read_dataset_lowlevel(dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, - vec.data()); + read_dataset_lowlevel( + dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, vec.data()); } template @@ -286,8 +287,8 @@ void read_dataset( close_dataset(dset); } -template -void read_dataset(hid_t dset, xt::xarray& arr, bool indep=false) +template +void read_dataset(hid_t dset, xt::xarray& arr, bool indep = false) { // Get shape of dataset vector shape = object_shape(dset); @@ -299,17 +300,17 @@ void read_dataset(hid_t dset, xt::xarray& arr, bool indep=false) arr.resize(shape); // Read data from attribute - read_dataset_lowlevel(dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, - arr.data()); + read_dataset_lowlevel( + dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, arr.data()); } template<> -void read_dataset(hid_t dset, xt::xarray>& arr, - bool indep); +void read_dataset( + hid_t dset, xt::xarray>& arr, bool indep); -template -void read_dataset(hid_t obj_id, const char* name, xt::xarray& arr, - bool indep=false) +template +void read_dataset( + hid_t obj_id, const char* name, xt::xarray& arr, bool indep = false) { // Open dataset and read array hid_t dset = open_dataset(obj_id, name); @@ -317,10 +318,9 @@ void read_dataset(hid_t obj_id, const char* name, xt::xarray& arr, close_dataset(dset); } - -template -void read_dataset(hid_t obj_id, const char* name, xt::xtensor& arr, - bool indep=false) +template +void read_dataset( + hid_t obj_id, const char* name, xt::xtensor& arr, bool indep = false) { // Open dataset and read array hid_t dset = open_dataset(obj_id, name); @@ -346,8 +346,8 @@ void read_dataset(hid_t obj_id, const char* name, xt::xtensor& arr, } // overload for Position -inline void -read_dataset(hid_t obj_id, const char* name, Position& r, bool indep=false) +inline void read_dataset( + hid_t obj_id, const char* name, Position& r, bool indep = false) { array x; read_dataset(obj_id, name, x, indep); @@ -356,9 +356,9 @@ read_dataset(hid_t obj_id, const char* name, Position& r, bool indep=false) r.z = x[2]; } -template -inline void read_dataset_as_shape(hid_t obj_id, const char* name, - xt::xtensor& arr, bool indep=false) +template +inline void read_dataset_as_shape( + hid_t obj_id, const char* name, xt::xtensor& arr, bool indep = false) { hid_t dset = open_dataset(obj_id, name); @@ -369,8 +369,8 @@ inline void read_dataset_as_shape(hid_t obj_id, const char* name, vector buffer(size); // Read data from attribute - read_dataset_lowlevel(dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, - buffer.data()); + read_dataset_lowlevel( + dset, nullptr, H5TypeMap::type_id, H5S_ALL, indep, buffer.data()); // Adapt into xarray arr = xt::adapt(buffer, arr.shape()); @@ -378,10 +378,9 @@ inline void read_dataset_as_shape(hid_t obj_id, const char* name, close_dataset(dset); } - -template +template inline void read_nd_vector(hid_t obj_id, const char* name, - xt::xtensor& result, bool must_have=false) + xt::xtensor& result, bool must_have = false) { if (object_exists(obj_id, name)) { read_dataset_as_shape(obj_id, name, result, true); @@ -394,20 +393,19 @@ inline void read_nd_vector(hid_t obj_id, const char* name, // Templates/overloads for write_attribute //============================================================================== -template inline void -write_attribute(hid_t obj_id, const char* name, T buffer) +template +inline void write_attribute(hid_t obj_id, const char* name, T buffer) { write_attr(obj_id, 0, nullptr, name, H5TypeMap::type_id, &buffer); } -inline void -write_attribute(hid_t obj_id, const char* name, const char* buffer) +inline void write_attribute(hid_t obj_id, const char* name, const char* buffer) { write_attr_string(obj_id, name, buffer); } -inline void -write_attribute(hid_t obj_id, const char* name, const std::string& buffer) +inline void write_attribute( + hid_t obj_id, const char* name, const std::string& buffer) { write_attr_string(obj_id, name, buffer.c_str()); } @@ -428,30 +426,26 @@ inline void write_attribute( write_attr(obj_id, 1, dims, name, H5TypeMap::type_id, buffer.data()); } -inline void -write_attribute(hid_t obj_id, const char* name, Position r) +inline void write_attribute(hid_t obj_id, const char* name, Position r) { array buffer {r.x, r.y, r.z}; write_attribute(obj_id, name, buffer); } - - //============================================================================== // Templates/overloads for write_dataset //============================================================================== // Template for scalars (ensured by SFINAE) -template inline -std::enable_if_t>::value> -write_dataset(hid_t obj_id, const char* name, T buffer) +template +inline std::enable_if_t>::value> write_dataset( + hid_t obj_id, const char* name, T buffer) { - write_dataset_lowlevel(obj_id, 0, nullptr, name, H5TypeMap::type_id, - H5S_ALL, false, &buffer); + write_dataset_lowlevel( + obj_id, 0, nullptr, name, H5TypeMap::type_id, H5S_ALL, false, &buffer); } -inline void -write_dataset(hid_t obj_id, const char* name, const char* buffer) +inline void write_dataset(hid_t obj_id, const char* name, const char* buffer) { write_string(obj_id, name, buffer, false); } @@ -461,8 +455,8 @@ inline void write_dataset( hid_t obj_id, const char* name, const array& buffer) { hsize_t dims[] {N}; - write_dataset_lowlevel(obj_id, 1, dims, name, H5TypeMap::type_id, - H5S_ALL, false, buffer.data()); + write_dataset_lowlevel(obj_id, 1, dims, name, H5TypeMap::type_id, H5S_ALL, + false, buffer.data()); } inline void write_dataset( @@ -478,10 +472,10 @@ inline void write_dataset( } // Copy data into contiguous buffer - char* temp = new char[n*m]; - std::fill(temp, temp + n*m, '\0'); + char* temp = new char[n * m]; + std::fill(temp, temp + n * m, '\0'); for (decltype(n) i = 0; i < n; ++i) { - std::copy(buffer[i].begin(), buffer[i].end(), temp + i*m); + std::copy(buffer[i].begin(), buffer[i].end(), temp + i * m); } // Write 2D data @@ -496,30 +490,29 @@ inline void write_dataset( hid_t obj_id, const char* name, const vector& buffer) { hsize_t dims[] {buffer.size()}; - write_dataset_lowlevel(obj_id, 1, dims, name, H5TypeMap::type_id, - H5S_ALL, false, buffer.data()); + write_dataset_lowlevel(obj_id, 1, dims, name, H5TypeMap::type_id, H5S_ALL, + false, buffer.data()); } // Template for xarray, xtensor, etc. -template inline void -write_dataset(hid_t obj_id, const char* name, const xt::xcontainer& arr) +template +inline void write_dataset( + hid_t obj_id, const char* name, const xt::xcontainer& arr) { using T = typename D::value_type; auto s = arr.shape(); vector dims {s.cbegin(), s.cend()}; write_dataset_lowlevel(obj_id, dims.size(), dims.data(), name, - H5TypeMap::type_id, H5S_ALL, false, arr.data()); + H5TypeMap::type_id, H5S_ALL, false, arr.data()); } -inline void -write_dataset(hid_t obj_id, const char* name, Position r) +inline void write_dataset(hid_t obj_id, const char* name, Position r) { array buffer {r.x, r.y, r.z}; write_dataset(obj_id, name, buffer); } -inline void -write_dataset(hid_t obj_id, const char* name, std::string buffer) +inline void write_dataset(hid_t obj_id, const char* name, std::string buffer) { write_string(obj_id, name, buffer.c_str(), false); } diff --git a/include/openmc/initialize.h b/include/openmc/initialize.h index eba616474..869be4441 100644 --- a/include/openmc/initialize.h +++ b/include/openmc/initialize.h @@ -13,6 +13,6 @@ void initialize_mpi(MPI_Comm intracomm); #endif void read_input_xml(); -} +} // namespace openmc #endif // OPENMC_INITIALIZE_H diff --git a/include/openmc/lattice.h b/include/openmc/lattice.h index e7db9016b..47627be26 100644 --- a/include/openmc/lattice.h +++ b/include/openmc/lattice.h @@ -20,11 +20,9 @@ namespace openmc { // Module constants //============================================================================== -constexpr int32_t NO_OUTER_UNIVERSE{-1}; +constexpr int32_t NO_OUTER_UNIVERSE {-1}; -enum class LatticeType { - rect, hex -}; +enum class LatticeType { rect, hex }; //============================================================================== // Global variables @@ -33,8 +31,8 @@ enum class LatticeType { class Lattice; namespace model { - extern std::unordered_map lattice_map; - extern vector> lattices; +extern std::unordered_map lattice_map; +extern vector> lattices; } // namespace model //============================================================================== @@ -45,15 +43,14 @@ namespace model { class LatticeIter; class ReverseLatticeIter; -class Lattice -{ +class Lattice { public: - int32_t id_; //!< Universe ID number - std::string name_; //!< User-defined name + int32_t id_; //!< Universe ID number + std::string name_; //!< User-defined name LatticeType type_; - vector universes_; //!< Universes filling each lattice tile - int32_t outer_ {NO_OUTER_UNIVERSE}; //!< Universe tiled outside the lattice - vector offsets_; //!< Distribcell offset table + vector universes_; //!< Universes filling each lattice tile + int32_t outer_ {NO_OUTER_UNIVERSE}; //!< Universe tiled outside the lattice + vector offsets_; //!< Distribcell offset table explicit Lattice(pugi::xml_node lat_node); @@ -72,7 +69,9 @@ public: //! Allocate offset table for distribcell. void allocate_offset_table(int n_maps) - {offsets_.resize(n_maps * universes_.size(), C_NONE);} + { + offsets_.resize(n_maps * universes_.size(), C_NONE); + } //! Populate the distribcell offset tables. int32_t fill_offset_table(int32_t offset, int32_t target_univ_id, int map, @@ -112,7 +111,9 @@ public: //! \return true if the given index fit within the lattice bounds. False //! otherwise. virtual bool is_valid_index(int indx) const - {return (indx >= 0) && (indx < universes_.size());} + { + return (indx >= 0) && (indx < universes_.size()); + } //! \brief Get the distribcell offset for a lattice tile. //! \param The map index for the target cell. @@ -138,7 +139,7 @@ public: void to_hdf5(hid_t group_id) const; protected: - bool is_3d_; //!< Has divisions along the z-axis? + bool is_3d_; //!< Has divisions along the z-axis? virtual void to_hdf5_inner(hid_t group_id) const = 0; }; @@ -147,26 +148,24 @@ protected: //! An iterator over lattice universes. //============================================================================== -class LatticeIter -{ +class LatticeIter { public: - int indx_; //!< An index to a Lattice universes or offsets array. + int indx_; //!< An index to a Lattice universes or offsets array. - LatticeIter(Lattice &lat, int indx) - : indx_(indx), lat_(lat) - {} + LatticeIter(Lattice& lat, int indx) : indx_(indx), lat_(lat) {} - bool operator==(const LatticeIter &rhs) {return (indx_ == rhs.indx_);} + bool operator==(const LatticeIter& rhs) { return (indx_ == rhs.indx_); } - bool operator!=(const LatticeIter &rhs) {return !(*this == rhs);} + bool operator!=(const LatticeIter& rhs) { return !(*this == rhs); } - int32_t& operator*() {return lat_.universes_[indx_];} + int32_t& operator*() { return lat_.universes_[indx_]; } LatticeIter& operator++() { while (indx_ < lat_.universes_.size()) { ++indx_; - if (lat_.is_valid_index(indx_)) return *this; + if (lat_.is_valid_index(indx_)) + return *this; } indx_ = lat_.universes_.size(); return *this; @@ -180,18 +179,16 @@ protected: //! A reverse iterator over lattice universes. //============================================================================== -class ReverseLatticeIter : public LatticeIter -{ +class ReverseLatticeIter : public LatticeIter { public: - ReverseLatticeIter(Lattice &lat, int indx) - : LatticeIter {lat, indx} - {} + ReverseLatticeIter(Lattice& lat, int indx) : LatticeIter {lat, indx} {} ReverseLatticeIter& operator++() { while (indx_ > -1) { --indx_; - if (lat_.is_valid_index(indx_)) return *this; + if (lat_.is_valid_index(indx_)) + return *this; } indx_ = -1; return *this; @@ -200,8 +197,7 @@ public: //============================================================================== -class RectLattice : public Lattice -{ +class RectLattice : public Lattice { public: explicit RectLattice(pugi::xml_node lat_node); @@ -225,15 +221,14 @@ public: void to_hdf5_inner(hid_t group_id) const; private: - array n_cells_; //!< Number of cells along each axis - Position lower_left_; //!< Global lower-left corner of the lattice - Position pitch_; //!< Lattice tile width along each axis + array n_cells_; //!< Number of cells along each axis + Position lower_left_; //!< Global lower-left corner of the lattice + Position pitch_; //!< Lattice tile width along each axis }; //============================================================================== -class HexLattice : public Lattice -{ +class HexLattice : public Lattice { public: explicit HexLattice(pugi::xml_node lat_node); @@ -264,8 +259,8 @@ public: private: enum class Orientation { - y, //!< Flat side of lattice parallel to y-axis - x //!< Flat side of lattice parallel to x-axis + y, //!< Flat side of lattice parallel to y-axis + x //!< Flat side of lattice parallel to x-axis }; //! Fill universes_ vector for 'y' orientation @@ -274,11 +269,11 @@ private: //! Fill universes_ vector for 'x' orientation void fill_lattice_x(const vector& univ_words); - int n_rings_; //!< Number of radial tile positions - int n_axial_; //!< Number of axial tile positions - Orientation orientation_; //!< Orientation of lattice - Position center_; //!< Global center of lattice - array pitch_; //!< Lattice tile width and height + int n_rings_; //!< Number of radial tile positions + int n_axial_; //!< Number of axial tile positions + Orientation orientation_; //!< Orientation of lattice + Position center_; //!< Global center of lattice + array pitch_; //!< Lattice tile width and height }; //============================================================================== diff --git a/include/openmc/material.h b/include/openmc/material.h index f0d810370..5fc52eba8 100644 --- a/include/openmc/material.h +++ b/include/openmc/material.h @@ -4,10 +4,10 @@ #include #include -#include -#include #include "pugixml.hpp" #include "xtensor/xtensor.hpp" +#include +#include #include "openmc/bremsstrahlung.h" #include "openmc/constants.h" @@ -34,15 +34,14 @@ extern vector> materials; //! A substance with constituent nuclides and thermal scattering data //============================================================================== -class Material -{ +class Material { public: //---------------------------------------------------------------------------- // Types struct ThermalTable { - int index_table; //!< Index of table in data::thermal_scatt + int index_table; //!< Index of table in data::thermal_scatt int index_nuclide; //!< Index in nuclide_ - double fraction; //!< How often to use table + double fraction; //!< How often to use table }; //---------------------------------------------------------------------------- @@ -116,11 +115,17 @@ public: //! Get nuclides in material //! \return Indices into the global nuclides vector - gsl::span nuclides() const { return {nuclide_.data(), nuclide_.size()}; } + gsl::span nuclides() const + { + return {nuclide_.data(), nuclide_.size()}; + } //! Get densities of each nuclide in material //! \return Densities in [atom/b-cm] - gsl::span densities() const { return {atom_density_.data(), atom_density_.size()}; } + gsl::span densities() const + { + return {atom_density_.data(), atom_density_.size()}; + } //! Get ID of material //! \return ID of material @@ -145,15 +150,16 @@ public: //---------------------------------------------------------------------------- // Data - int32_t id_ {C_NONE}; //!< Unique ID - std::string name_; //!< Name of material + int32_t id_ {C_NONE}; //!< Unique ID + std::string name_; //!< Name of material vector nuclide_; //!< Indices in nuclides vector vector element_; //!< Indices in elements vector xt::xtensor atom_density_; //!< Nuclide atom density in [atom/b-cm] - double density_; //!< Total atom density in [atom/b-cm] - double density_gpcc_; //!< Total atom density in [g/cm^3] - double volume_ {-1.0}; //!< Volume in [cm^3] - bool fissionable_ {false}; //!< Does this material contain fissionable nuclides + double density_; //!< Total atom density in [atom/b-cm] + double density_gpcc_; //!< Total atom density in [g/cm^3] + double volume_ {-1.0}; //!< Volume in [cm^3] + bool fissionable_ { + false}; //!< Does this material contain fissionable nuclides bool depletable_ {false}; //!< Is the material depletable? vector p0_; //!< Indicate which nuclides are to be treated with //!< iso-in-lab scattering diff --git a/include/openmc/math_functions.h b/include/openmc/math_functions.h index 0fd322556..c30ef7558 100644 --- a/include/openmc/math_functions.h +++ b/include/openmc/math_functions.h @@ -10,7 +10,6 @@ #include "openmc/position.h" - namespace openmc { //============================================================================== @@ -130,11 +129,11 @@ extern "C" void calc_zn_rad(int n, double rho, double zn_rad[]); //! \param seed A pointer to the pseudorandom seed //============================================================================== -extern "C" void rotate_angle_c(double uvw[3], double mu, const double* phi, - uint64_t* seed); +extern "C" void rotate_angle_c( + double uvw[3], double mu, const double* phi, uint64_t* seed); -Direction rotate_angle(Direction u, double mu, const double* phi, - uint64_t* seed); +Direction rotate_angle( + Direction u, double mu, const double* phi, uint64_t* seed); //============================================================================== //! Constructs a natural cubic spline. @@ -167,8 +166,8 @@ void spline(int n, const double x[], const double y[], double z[]); //! \return Interpolated value //============================================================================== -double spline_interpolate(int n, const double x[], const double y[], - const double z[], double xint); +double spline_interpolate( + int n, const double x[], const double y[], const double z[], double xint); //============================================================================== //! Evaluate the definite integral of the interpolating cubic spline between diff --git a/include/openmc/mesh.h b/include/openmc/mesh.h index 5eb56a379..d3ca900cf 100644 --- a/include/openmc/mesh.h +++ b/include/openmc/mesh.h @@ -16,10 +16,10 @@ #include "openmc/vector.h" #ifdef DAGMC -#include "moab/Core.hpp" #include "moab/AdaptiveKDTree.hpp" -#include "moab/Matrix3.hpp" +#include "moab/Core.hpp" #include "moab/GeomUtil.hpp" +#include "moab/Matrix3.hpp" #endif #ifdef LIBMESH @@ -56,11 +56,10 @@ namespace settings { // used when creating new libMesh::Mesh instances extern unique_ptr libmesh_init; extern const libMesh::Parallel::Communicator* libmesh_comm; -} +} // namespace settings #endif -class Mesh -{ +class Mesh { public: // Constructors and destructor Mesh() = default; @@ -76,11 +75,8 @@ public: //! \param[in] u Particle direction //! \param[out] bins Bins that were crossed //! \param[out] lengths Fraction of tracklength in each bin - virtual void bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const = 0; + virtual void bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const = 0; //! Determine which surface bins were crossed by a particle // @@ -88,11 +84,8 @@ public: //! \param[in] r1 Current position of the particle //! \param[in] u Particle direction //! \param[out] bins Surface bins that were crossed - virtual void - surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const = 0; + virtual void surface_bins_crossed( + Position r0, Position r1, const Direction& u, vector& bins) const = 0; //! Get bin at a given position in space // @@ -107,7 +100,7 @@ public: virtual int n_surface_bins() const = 0; //! Set the mesh ID - void set_id(int32_t id=-1); + void set_id(int32_t id = -1); //! Write mesh data to an HDF5 group // @@ -131,7 +124,7 @@ public: virtual std::string bin_label(int bin) const = 0; // Data members - int id_ {-1}; //!< User-specified ID + int id_ {-1}; //!< User-specified ID int n_dimension_; //!< Number of dimensions }; @@ -147,11 +140,8 @@ public: int n_surface_bins() const override; - void bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const override; + void bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const override; //! Count number of bank sites in each mesh bin / energy bin // @@ -210,7 +200,7 @@ public: std::string bin_label(int bin) const override; // Data members - xt::xtensor lower_left_; //!< Lower-left coordinates of mesh + xt::xtensor lower_left_; //!< Lower-left coordinates of mesh xt::xtensor upper_right_; //!< Upper-right coordinates of mesh xt::xtensor shape_; //!< Number of mesh elements in each dimension @@ -224,19 +214,15 @@ protected: //! Tessellation of n-dimensional Euclidean space by congruent squares or cubes //============================================================================== -class RegularMesh : public StructuredMesh -{ +class RegularMesh : public StructuredMesh { public: // Constructors RegularMesh() = default; RegularMesh(pugi::xml_node node); // Overridden methods - void - surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const override; + void surface_bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins) const override; int get_index_in_direction(double r, int i) const override; @@ -260,24 +246,19 @@ public: const SourceSite* bank, int64_t length, bool* outside) const; // Data members - double volume_frac_; //!< Volume fraction of each mesh element + double volume_frac_; //!< Volume fraction of each mesh element xt::xtensor width_; //!< Width of each mesh element }; - -class RectilinearMesh : public StructuredMesh -{ +class RectilinearMesh : public StructuredMesh { public: // Constructors RectilinearMesh() = default; RectilinearMesh(pugi::xml_node node); // Overridden methods - void - surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const override; + void surface_bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins) const override; int get_index_in_direction(double r, int i) const override; @@ -305,11 +286,8 @@ public: UnstructuredMesh(const std::string& filename); // Overridden Methods - void - surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const override; + void surface_bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins) const override; void to_hdf5(hid_t group) const override; @@ -349,7 +327,8 @@ public: virtual std::string library() const = 0; // Data members - bool output_ {true}; //!< Write tallies onto the unstructured mesh at the end of a run + bool output_ { + true}; //!< Write tallies onto the unstructured mesh at the end of a run std::string filename_; //!< Path to unstructured mesh file private: @@ -370,12 +349,8 @@ public: // Overridden Methods - void - bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const override; + void bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const override; int get_bin(Position r) const override; @@ -383,9 +358,8 @@ public: int n_surface_bins() const override; - std::pair, vector> - plot(Position plot_ll, - Position plot_ur) const override; + std::pair, vector> plot( + Position plot_ll, Position plot_ur) const override; std::string library() const override; @@ -396,9 +370,8 @@ public: void remove_scores() override; //! Set data for a score - void set_score_data(const std::string& score, - const vector& values, - const vector& std_dev) override; + void set_score_data(const std::string& score, const vector& values, + const vector& std_dev) override; //! Write the mesh with any current tally data void write(const std::string& base_filename) const override; @@ -408,7 +381,6 @@ public: double volume(int bin) const override; private: - void initialize() override; // Methods @@ -438,8 +410,9 @@ private: moab::EntityHandle get_tet(const Position& r) const; //! Return the containing tet given a position - moab::EntityHandle get_tet(const moab::CartVect& r) const { - return get_tet(Position(r[0], r[1], r[2])); + moab::EntityHandle get_tet(const moab::CartVect& r) const + { + return get_tet(Position(r[0], r[1], r[2])); }; //! Check for point containment within a tet; uses @@ -448,8 +421,7 @@ private: //! \param[in] r Position to check //! \param[in] MOAB terahedron to check //! \return True if r is inside, False if r is outside - bool point_in_tet(const moab::CartVect& r, - moab::EntityHandle tet) const; + bool point_in_tet(const moab::CartVect& r, moab::EntityHandle tet) const; //! Compute barycentric coordinate data for all tetrahedra //! in the mesh. @@ -500,12 +472,11 @@ private: // //! \param[in] score Name of the score //! \return The MOAB value and error tag handles, respectively - std::pair - get_score_tags(std::string score) const; + std::pair get_score_tags(std::string score) const; // Data members moab::Range ehs_; //!< Range of tetrahedra EntityHandle's in the mesh - moab::EntityHandle tetset_; //!< EntitySet containing all tetrahedra + moab::EntityHandle tetset_; //!< EntitySet containing all tetrahedra moab::EntityHandle kdtree_root_; //!< Root of the MOAB KDTree std::shared_ptr mbi_; //!< MOAB instance unique_ptr kdtree_; //!< MOAB KDTree instance @@ -524,11 +495,8 @@ public: LibMesh(const std::string& filename); // Overridden Methods - void bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const override; + void bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const override; int get_bin(Position r) const override; @@ -536,9 +504,8 @@ public: int n_surface_bins() const override; - std::pair, vector> - plot(Position plot_ll, - Position plot_ur) const override; + std::pair, vector> plot( + Position plot_ll, Position plot_ur) const override; std::string library() const override; @@ -546,9 +513,8 @@ public: void remove_scores() override; - void set_score_data(const std::string& var_name, - const vector& values, - const vector& std_dev) override; + void set_score_data(const std::string& var_name, const vector& values, + const vector& std_dev) override; void write(const std::string& base_filename) const override; @@ -557,7 +523,6 @@ public: double volume(int bin) const override; private: - void initialize() override; // Methods @@ -573,11 +538,15 @@ private: vector> pl_; //!< per-thread point locators unique_ptr - equation_systems_; //!< pointer to the equation systems of the mesh - std::string eq_system_name_; //!< name of the equation system holding OpenMC results - std::unordered_map variable_map_; //!< mapping of variable names (tally scores) to libMesh variable numbers + equation_systems_; //!< pointer to the equation systems of the mesh + std::string + eq_system_name_; //!< name of the equation system holding OpenMC results + std::unordered_map + variable_map_; //!< mapping of variable names (tally scores) to libMesh + //!< variable numbers libMesh::BoundingBox bbox_; //!< bounding box of the mesh - libMesh::dof_id_type first_element_id_; //!< id of the first element in the mesh + libMesh::dof_id_type + first_element_id_; //!< id of the first element in the mesh }; #endif diff --git a/include/openmc/message_passing.h b/include/openmc/message_passing.h index 82b27a779..b02d2938f 100644 --- a/include/openmc/message_passing.h +++ b/include/openmc/message_passing.h @@ -8,13 +8,13 @@ namespace openmc { namespace mpi { - extern int rank; - extern int n_procs; - extern bool master; +extern int rank; +extern int n_procs; +extern bool master; #ifdef OPENMC_MPI - extern MPI_Datatype source_site; - extern MPI_Comm intracomm; +extern MPI_Datatype source_site; +extern MPI_Comm intracomm; #endif } // namespace mpi diff --git a/include/openmc/mgxs.h b/include/openmc/mgxs.h index bfa1200e8..2da3c8363 100644 --- a/include/openmc/mgxs.h +++ b/include/openmc/mgxs.h @@ -22,8 +22,8 @@ namespace openmc { struct CacheData { double sqrtkT; // last temperature corresponding to t - int t; // temperature index - int a; // angle index + int t; // temperature index + int a; // angle index // last angle that corresponds to a double u; double v; @@ -35,156 +35,150 @@ struct CacheData { //============================================================================== class Mgxs { - private: +private: + xt::xtensor kTs; // temperature in eV (k * T) + AngleDistributionType + scatter_format; // flag for if this is legendre, histogram, or tabular + int num_groups; // number of energy groups + int num_delayed_groups; // number of delayed neutron groups + vector xs; // Cross section data + // MGXS Incoming Flux Angular grid information + bool is_isotropic; // used to skip search for angle indices if isotropic + int n_pol; + int n_azi; + vector polar; + vector azimuthal; - xt::xtensor kTs; // temperature in eV (k * T) - AngleDistributionType scatter_format; // flag for if this is legendre, histogram, or tabular - int num_groups; // number of energy groups - int num_delayed_groups; // number of delayed neutron groups - vector xs; // Cross section data - // MGXS Incoming Flux Angular grid information - bool is_isotropic; // used to skip search for angle indices if isotropic - int n_pol; - int n_azi; - vector polar; - vector azimuthal; + //! \brief Initializes the Mgxs object metadata + //! + //! @param in_name Name of the object. + //! @param in_awr atomic-weight ratio. + //! @param in_kTs temperatures (in units of eV) that data is available. + //! @param in_fissionable Is this item fissionable or not. + //! @param in_scatter_format Denotes whether Legendre, Tabular, or + //! Histogram scattering is used. + //! @param in_is_isotropic Is this an isotropic or angular with respect to + //! the incoming particle. + //! @param in_polar Polar angle grid. + //! @param in_azimuthal Azimuthal angle grid. + void init(const std::string& in_name, double in_awr, + const vector& in_kTs, bool in_fissionable, + AngleDistributionType in_scatter_format, bool in_is_isotropic, + const vector& in_polar, const vector& in_azimuthal); - //! \brief Initializes the Mgxs object metadata - //! - //! @param in_name Name of the object. - //! @param in_awr atomic-weight ratio. - //! @param in_kTs temperatures (in units of eV) that data is available. - //! @param in_fissionable Is this item fissionable or not. - //! @param in_scatter_format Denotes whether Legendre, Tabular, or - //! Histogram scattering is used. - //! @param in_is_isotropic Is this an isotropic or angular with respect to - //! the incoming particle. - //! @param in_polar Polar angle grid. - //! @param in_azimuthal Azimuthal angle grid. - void init(const std::string& in_name, double in_awr, - const vector& in_kTs, bool in_fissionable, - AngleDistributionType in_scatter_format, bool in_is_isotropic, - const vector& in_polar, const vector& in_azimuthal); + //! \brief Initializes the Mgxs object metadata from the HDF5 file + //! + //! @param xs_id HDF5 group id for the cross section data. + //! @param temperature Temperatures to read. + //! @param temps_to_read Resultant list of temperatures in the library + //! to read which correspond to the requested temperatures. + //! @param order_dim Resultant dimensionality of the scattering order. + void metadata_from_hdf5(hid_t xs_id, const vector& temperature, + vector& temps_to_read, int& order_dim); - //! \brief Initializes the Mgxs object metadata from the HDF5 file - //! - //! @param xs_id HDF5 group id for the cross section data. - //! @param temperature Temperatures to read. - //! @param temps_to_read Resultant list of temperatures in the library - //! to read which correspond to the requested temperatures. - //! @param order_dim Resultant dimensionality of the scattering order. - void metadata_from_hdf5(hid_t xs_id, const vector& temperature, - vector& temps_to_read, int& order_dim); + //! \brief Performs the actual act of combining the microscopic data for a + //! single temperature. + //! + //! @param micros Microscopic objects to combine. + //! @param scalars Scalars to multiply the microscopic data by. + //! @param micro_ts The temperature index of the microscopic objects that + //! corresponds to the temperature of interest. + //! @param this_t The temperature index of the macroscopic object. + void combine(const vector& micros, const vector& scalars, + const vector& micro_ts, int this_t); - //! \brief Performs the actual act of combining the microscopic data for a - //! single temperature. - //! - //! @param micros Microscopic objects to combine. - //! @param scalars Scalars to multiply the microscopic data by. - //! @param micro_ts The temperature index of the microscopic objects that - //! corresponds to the temperature of interest. - //! @param this_t The temperature index of the macroscopic object. - void combine(const vector& micros, const vector& scalars, - const vector& micro_ts, int this_t); + //! \brief Checks to see if this and that are able to be combined + //! + //! This comparison is used when building macroscopic cross sections + //! from microscopic cross sections. + //! @param that The other Mgxs to compare to this one. + //! @return True if they can be combined, False otherwise. + bool equiv(const Mgxs& that); - //! \brief Checks to see if this and that are able to be combined - //! - //! This comparison is used when building macroscopic cross sections - //! from microscopic cross sections. - //! @param that The other Mgxs to compare to this one. - //! @return True if they can be combined, False otherwise. - bool equiv(const Mgxs& that); +public: + std::string name; // name of dataset, e.g., UO2 + double awr; // atomic weight ratio + bool fissionable; // Is this fissionable + vector cache; // index and data cache - public: + Mgxs() = default; - std::string name; // name of dataset, e.g., UO2 - double awr; // atomic weight ratio - bool fissionable; // Is this fissionable - vector cache; // index and data cache + //! \brief Constructor that loads the Mgxs object from the HDF5 file + //! + //! @param xs_id HDF5 group id for the cross section data. + //! @param temperature Temperatures to read. + //! @param num_group number of energy groups + //! @param num_delay number of delayed groups + Mgxs(hid_t xs_id, const vector& temperature, int num_group, + int num_delay); - Mgxs() = default; + //! \brief Constructor that initializes and populates all data to build a + //! macroscopic cross section from microscopic cross sections. + //! + //! @param in_name Name of the object. + //! @param mat_kTs temperatures (in units of eV) that data is needed. + //! @param micros Microscopic objects to combine. + //! @param atom_densities Atom densities of those microscopic quantities. + //! @param num_group number of energy groups + //! @param num_delay number of delayed groups + Mgxs(const std::string& in_name, const vector& mat_kTs, + const vector& micros, const vector& atom_densities, + int num_group, int num_delay); - //! \brief Constructor that loads the Mgxs object from the HDF5 file - //! - //! @param xs_id HDF5 group id for the cross section data. - //! @param temperature Temperatures to read. - //! @param num_group number of energy groups - //! @param num_delay number of delayed groups - Mgxs(hid_t xs_id, const vector& temperature, int num_group, - int num_delay); + //! \brief Provides a cross section value given certain parameters + //! + //! @param xstype Type of cross section requested, according to the + //! enumerated constants. + //! @param gin Incoming energy group. + //! @param gout Outgoing energy group; use nullptr if irrelevant, or if a + //! sum is requested. + //! @param mu Cosine of the change-in-angle, for scattering quantities; + //! use nullptr if irrelevant. + //! @param dg delayed group index; use nullptr if irrelevant. + //! @return Requested cross section value. + double get_xs( + MgxsType xstype, int gin, const int* gout, const double* mu, const int* dg); - //! \brief Constructor that initializes and populates all data to build a - //! macroscopic cross section from microscopic cross sections. - //! - //! @param in_name Name of the object. - //! @param mat_kTs temperatures (in units of eV) that data is needed. - //! @param micros Microscopic objects to combine. - //! @param atom_densities Atom densities of those microscopic quantities. - //! @param num_group number of energy groups - //! @param num_delay number of delayed groups - Mgxs(const std::string& in_name, const vector& mat_kTs, - const vector& micros, const vector& atom_densities, - int num_group, int num_delay); + inline double get_xs(MgxsType xstype, int gin) + { + return get_xs(xstype, gin, nullptr, nullptr, nullptr); + } - //! \brief Provides a cross section value given certain parameters - //! - //! @param xstype Type of cross section requested, according to the - //! enumerated constants. - //! @param gin Incoming energy group. - //! @param gout Outgoing energy group; use nullptr if irrelevant, or if a - //! sum is requested. - //! @param mu Cosine of the change-in-angle, for scattering quantities; - //! use nullptr if irrelevant. - //! @param dg delayed group index; use nullptr if irrelevant. - //! @return Requested cross section value. - double - get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, - const int* dg); + //! \brief Samples the fission neutron energy and if prompt or delayed. + //! + //! @param gin Incoming energy group. + //! @param dg Sampled delayed group index. + //! @param gout Sampled outgoing energy group. + //! @param seed Pseudorandom seed pointer + void sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed); - inline double - get_xs(MgxsType xstype, int gin) - {return get_xs(xstype, gin, nullptr, nullptr, nullptr);} + //! \brief Samples the outgoing energy and angle from a scatter event. + //! + //! @param gin Incoming energy group. + //! @param gout Sampled outgoing energy group. + //! @param mu Sampled cosine of the change-in-angle. + //! @param wgt Weight of the particle to be adjusted. + //! @param seed Pseudorandom seed pointer. + void sample_scatter( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed); + //! \brief Calculates cross section quantities needed for tracking. + //! + //! @param p The particle whose attributes set which MGXS to get. + void calculate_xs(Particle& p); - //! \brief Samples the fission neutron energy and if prompt or delayed. - //! - //! @param gin Incoming energy group. - //! @param dg Sampled delayed group index. - //! @param gout Sampled outgoing energy group. - //! @param seed Pseudorandom seed pointer - void - sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed); + //! \brief Sets the temperature index in cache given a temperature + //! + //! @param sqrtkT Temperature of the material. + void set_temperature_index(double sqrtkT); - //! \brief Samples the outgoing energy and angle from a scatter event. - //! - //! @param gin Incoming energy group. - //! @param gout Sampled outgoing energy group. - //! @param mu Sampled cosine of the change-in-angle. - //! @param wgt Weight of the particle to be adjusted. - //! @param seed Pseudorandom seed pointer. - void - sample_scatter(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); + //! \brief Sets the angle index in cache given a direction + //! + //! @param u Incoming particle direction. + void set_angle_index(Direction u); - //! \brief Calculates cross section quantities needed for tracking. - //! - //! @param p The particle whose attributes set which MGXS to get. - void - calculate_xs(Particle& p); - - //! \brief Sets the temperature index in cache given a temperature - //! - //! @param sqrtkT Temperature of the material. - void - set_temperature_index(double sqrtkT); - - //! \brief Sets the angle index in cache given a direction - //! - //! @param u Incoming particle direction. - void - set_angle_index(Direction u); - - //! \brief Provide const access to list of XsData held by this - const vector& get_xsdata() const { return xs; } + //! \brief Provide const access to list of XsData held by this + const vector& get_xsdata() const { return xs; } }; } // namespace openmc diff --git a/include/openmc/mgxs_interface.h b/include/openmc/mgxs_interface.h index 57b5d9bf3..8bcdf6dc6 100644 --- a/include/openmc/mgxs_interface.h +++ b/include/openmc/mgxs_interface.h @@ -16,7 +16,6 @@ namespace openmc { class MgxsInterface { public: - MgxsInterface() = default; // Construct from path to cross sections file, as well as a list @@ -49,10 +48,10 @@ public: int num_energy_groups_; int num_delayed_groups_; - vector xs_names_; // available names in HDF5 file - vector xs_to_read_; // XS which appear in materials - vector> xs_temps_to_read_; // temperatures used - std::string cross_sections_path_; // path to MGXS h5 file + vector xs_names_; // available names in HDF5 file + vector xs_to_read_; // XS which appear in materials + vector> xs_temps_to_read_; // temperatures used + std::string cross_sections_path_; // path to MGXS h5 file vector nuclides_; vector macro_xs_; vector energy_bins_; @@ -62,7 +61,7 @@ public: }; namespace data { - extern MgxsInterface mg; +extern MgxsInterface mg; } // Puts available XS in MGXS file to globals so that when diff --git a/include/openmc/neighbor_list.h b/include/openmc/neighbor_list.h index f6142101d..f781424ff 100644 --- a/include/openmc/neighbor_list.h +++ b/include/openmc/neighbor_list.h @@ -18,8 +18,7 @@ namespace openmc { //! number of threads can safely read data without locks or reference counting. //============================================================================== -class NeighborList -{ +class NeighborList { public: using value_type = int32_t; using const_iterator = std::forward_list::const_iterator; @@ -43,7 +42,8 @@ public: if (!list_.empty()) { auto it1 = list_.cbegin(); auto it2 = ++list_.cbegin(); - while (it2 != list_.cend()) it1 = it2++; + while (it2 != list_.cend()) + it1 = it2++; list_.insert_after(it1, new_elem); } else { list_.push_front(new_elem); @@ -52,12 +52,9 @@ public: } } - const_iterator cbegin() const - {return list_.cbegin();} - - const_iterator cend() const - {return list_.cend();} + const_iterator cbegin() const { return list_.cbegin(); } + const_iterator cend() const { return list_.cend(); } private: std::forward_list list_; diff --git a/include/openmc/nuclide.h b/include/openmc/nuclide.h index 6067c53a0..f961e9808 100644 --- a/include/openmc/nuclide.h +++ b/include/openmc/nuclide.h @@ -48,7 +48,7 @@ public: void calculate_sab_xs(int i_sab, double sab_frac, Particle& p); // Methods - double nu(double E, EmissionMode mode, int group=0) const; + double nu(double E, EmissionMode mode, int group = 0) const; void calculate_elastic_xs(Particle& p) const; //! Determines the microscopic 0K elastic cross section at a trial relative @@ -66,15 +66,15 @@ public: //! \param[in] energy Energy group boundaries in [eV] //! \param[in] flux Flux in each energy group (not normalized per eV) //! \return Reaction rate - double collapse_rate(int MT, double temperature, gsl::span energy, - gsl::span flux) const; + double collapse_rate(int MT, double temperature, + gsl::span energy, gsl::span flux) const; // Data members std::string name_; //!< Name of nuclide, e.g. "U235" - int Z_; //!< Atomic number - int A_; //!< Mass number - int metastable_; //!< Metastable state - double awr_; //!< Atomic weight ratio + int Z_; //!< Atomic number + int A_; //!< Mass number + int metastable_; //!< Metastable state + double awr_; //!< Atomic weight ratio gsl::index index_; //!< Index in the nuclides array // Temperature dependent cross section data @@ -86,11 +86,11 @@ public: unique_ptr multipole_; // Fission data - bool fissionable_ {false}; //!< Whether nuclide is fissionable + bool fissionable_ {false}; //!< Whether nuclide is fissionable bool has_partial_fission_ {false}; //!< has partial fission reactions? vector fission_rx_; //!< Fission reactions - int n_precursor_ {0}; //!< Number of delayed neutron precursors - unique_ptr total_nu_; //!< Total neutron yield + int n_precursor_ {0}; //!< Number of delayed neutron precursors + unique_ptr total_nu_; //!< Total neutron yield unique_ptr fission_q_prompt_; //!< Prompt fission energy release unique_ptr fission_q_recov_; //!< Recoverable fission energy release @@ -115,7 +115,8 @@ public: vector index_inelastic_scatter_; private: - void create_derived(const Function1D* prompt_photons, const Function1D* delayed_photons); + void create_derived( + const Function1D* prompt_photons, const Function1D* delayed_photons); //! Determine temperature index and interpolation factor // diff --git a/include/openmc/openmp_interface.h b/include/openmc/openmp_interface.h index 4032ab1d4..dac03ac59 100644 --- a/include/openmc/openmp_interface.h +++ b/include/openmc/openmp_interface.h @@ -13,37 +13,36 @@ namespace openmc { //! This type meets the C++ "Lockable" requirements. //============================================================================== -class OpenMPMutex -{ +class OpenMPMutex { public: OpenMPMutex() { - #ifdef _OPENMP - omp_init_lock(&mutex_); - #endif +#ifdef _OPENMP + omp_init_lock(&mutex_); +#endif } ~OpenMPMutex() { - #ifdef _OPENMP - omp_destroy_lock(&mutex_); - #endif +#ifdef _OPENMP + omp_destroy_lock(&mutex_); +#endif } // Mutexes cannot be copied. We need to explicitly delete the copy // constructor and copy assignment operator to ensure the compiler doesn't // "help" us by implicitly trying to copy the underlying mutexes. OpenMPMutex(const OpenMPMutex&) = delete; - OpenMPMutex& operator= (const OpenMPMutex&) = delete; + OpenMPMutex& operator=(const OpenMPMutex&) = delete; //! Lock the mutex. // //! This function blocks execution until the lock succeeds. void lock() { - #ifdef _OPENMP - omp_set_lock(&mutex_); - #endif +#ifdef _OPENMP + omp_set_lock(&mutex_); +#endif } //! Try to lock the mutex and indicate success. @@ -52,25 +51,25 @@ public: //! the lock is unavailable. bool try_lock() noexcept { - #ifdef _OPENMP - return omp_test_lock(&mutex_); - #else - return true; - #endif +#ifdef _OPENMP + return omp_test_lock(&mutex_); +#else + return true; +#endif } //! Unlock the mutex. void unlock() noexcept { - #ifdef _OPENMP - omp_unset_lock(&mutex_); - #endif +#ifdef _OPENMP + omp_unset_lock(&mutex_); +#endif } private: - #ifdef _OPENMP - omp_lock_t mutex_; - #endif +#ifdef _OPENMP + omp_lock_t mutex_; +#endif }; } // namespace openmc diff --git a/include/openmc/particle.h b/include/openmc/particle.h index 0fda3d307..952c8c4e7 100644 --- a/include/openmc/particle.h +++ b/include/openmc/particle.h @@ -30,7 +30,6 @@ class Surface; class Particle : public ParticleData { public: - //========================================================================== // Constructors @@ -86,18 +85,22 @@ public: //! \param new_u The direction of the particle after translation/rotation. //! \param new_surface The signed index of the surface that the particle will //! reside on after translation/rotation. - void cross_periodic_bc(const Surface& surf, Position new_r, Direction new_u, - int new_surface); + void cross_periodic_bc( + const Surface& surf, Position new_r, Direction new_u, int new_surface); //! mark a particle as lost and create a particle restart file //! \param message A warning message to display void mark_as_lost(const char* message); void mark_as_lost(const std::string& message) - {mark_as_lost(message.c_str());} + { + mark_as_lost(message.c_str()); + } void mark_as_lost(const std::stringstream& message) - {mark_as_lost(message.str());} + { + mark_as_lost(message.str()); + } //! create a particle restart HDF5 file void write_restart() const; diff --git a/include/openmc/particle_data.h b/include/openmc/particle_data.h index f871e8032..67dabe3bf 100644 --- a/include/openmc/particle_data.h +++ b/include/openmc/particle_data.h @@ -207,18 +207,18 @@ private: // Cross section caches vector neutron_xs_; //!< Microscopic neutron cross sections vector photon_xs_; //!< Microscopic photon cross sections - MacroXS macro_xs_; //!< Macroscopic cross sections + MacroXS macro_xs_; //!< Macroscopic cross sections int64_t id_; //!< Unique ID ParticleType type_ {ParticleType::neutron}; //!< Particle type (n, p, e, etc.) - int n_coord_ {1}; //!< number of current coordinate levels - int cell_instance_; //!< offset for distributed properties - vector coord_; //!< coordinates for all levels + int n_coord_ {1}; //!< number of current coordinate levels + int cell_instance_; //!< offset for distributed properties + vector coord_; //!< coordinates for all levels // Particle coordinates before crossing a surface - int n_coord_last_ {1}; //!< number of current coordinates - vector cell_last_; //!< coordinates for all levels + int n_coord_last_ {1}; //!< number of current coordinates + vector cell_last_; //!< coordinates for all levels // Energy data double E_; //!< post-collision energy in eV diff --git a/include/openmc/photon.h b/include/openmc/photon.h index ca8f75474..bf64fa50c 100644 --- a/include/openmc/photon.h +++ b/include/openmc/photon.h @@ -6,9 +6,9 @@ #include "openmc/particle.h" #include "openmc/vector.h" +#include "xtensor/xtensor.hpp" #include #include -#include "xtensor/xtensor.hpp" #include #include @@ -23,9 +23,9 @@ namespace openmc { class ElectronSubshell { public: // Constructors - ElectronSubshell() { }; + ElectronSubshell() {}; - int index_subshell; //!< index in SUBSHELLS + int index_subshell; //!< index in SUBSHELLS int threshold; double n_electrons; double binding_energy; @@ -59,7 +59,7 @@ public: // Data members std::string name_; //!< Name of element, e.g. "Zr" - int Z_; //!< Atomic number + int Z_; //!< Atomic number gsl::index index_; //!< Index in global elements vector // Microscopic cross sections @@ -79,8 +79,9 @@ public: Tabulated1D coherent_anomalous_imag_; // Photoionization and atomic relaxation data - std::unordered_map shell_map_; //!< Given a shell designator, e.g. 3, this - //!< dictionary gives an index in shells_ + std::unordered_map + shell_map_; //!< Given a shell designator, e.g. 3, this + //!< dictionary gives an index in shells_ vector shells_; // Compton profile data @@ -99,8 +100,8 @@ public: xt::xtensor dcs_; private: - void compton_doppler(double alpha, double mu, double* E_out, int* i_shell, - uint64_t* seed) const; + void compton_doppler( + double alpha, double mu, double* E_out, int* i_shell, uint64_t* seed) const; }; //============================================================================== @@ -117,7 +118,8 @@ void free_memory_photon(); namespace data { -extern xt::xtensor compton_profile_pz; //! Compton profile momentum grid +extern xt::xtensor + compton_profile_pz; //! Compton profile momentum grid //! Photon interaction data for each element extern std::unordered_map element_map; diff --git a/include/openmc/physics.h b/include/openmc/physics.h index bf16083ef..b2e72e047 100644 --- a/include/openmc/physics.h +++ b/include/openmc/physics.h @@ -26,16 +26,17 @@ void sample_neutron_reaction(Particle& p); void sample_photon_reaction(Particle& p); //! Terminates the particle and either deposits all energy locally -//! (electron_treatment = ElectronTreatment::LED) or creates secondary bremsstrahlung -//! photons from electron deflections with charged particles (electron_treatment -//! = ElectronTreatment::TTB). +//! (electron_treatment = ElectronTreatment::LED) or creates secondary +//! bremsstrahlung photons from electron deflections with charged particles +//! (electron_treatment = ElectronTreatment::TTB). void sample_electron_reaction(Particle& p); //! Terminates the particle and either deposits all energy locally -//! (electron_treatment = ElectronTreatment::LED) or creates secondary bremsstrahlung -//! photons from electron deflections with charged particles (electron_treatment -//! = ElectronTreatment::TTB). Two annihilation photons of energy MASS_ELECTRON_EV (0.511 -//! MeV) are created and travel in opposite directions. +//! (electron_treatment = ElectronTreatment::LED) or creates secondary +//! bremsstrahlung photons from electron deflections with charged particles +//! (electron_treatment = ElectronTreatment::TTB). Two annihilation photons of +//! energy MASS_ELECTRON_EV (0.511 MeV) are created and travel in opposite +//! directions. void sample_positron_reaction(Particle& p); //! Sample a nuclide based on their total cross sections and densities within @@ -53,15 +54,15 @@ int sample_element(Particle& p); Reaction& sample_fission(int i_nuclide, Particle& p); -void sample_photon_product(int i_nuclide, Particle& p, int* i_rx, int* i_product); +void sample_photon_product( + int i_nuclide, Particle& p, int* i_rx, int* i_product); void absorption(Particle& p, int i_nuclide); void scatter(Particle& p, int i_nuclide); //! Treats the elastic scattering of a neutron with a target. -void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, - Particle& p); +void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p); void sab_scatter(int i_nuclide, int i_sab, Particle& p); @@ -76,8 +77,8 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, //! by most Monte Carlo codes, in which cross section is assumed to be constant //! in energy. Excellent documentation for this method can be found in //! FRA-TM-123. -Direction sample_cxs_target_velocity(double awr, double E, Direction u, double kT, - uint64_t* seed); +Direction sample_cxs_target_velocity( + double awr, double E, Direction u, double kT, uint64_t* seed); void sample_fission_neutron(int i_nuclide, const Reaction& rx, double E_in, SourceSite* site, uint64_t* seed); diff --git a/include/openmc/physics_mg.h b/include/openmc/physics_mg.h index 05184d959..4d9d1afc4 100644 --- a/include/openmc/physics_mg.h +++ b/include/openmc/physics_mg.h @@ -12,32 +12,27 @@ namespace openmc { //! \brief samples particle behavior after a collision event. //! \param p Particle to operate on -void -collision_mg(Particle& p); +void collision_mg(Particle& p); //! \brief samples a reaction type. //! //! Note that there is special logic when suvival biasing is turned on since //! fission and disappearance are treated implicitly. //! \param p Particle to operate on -void -sample_reaction(Particle& p); +void sample_reaction(Particle& p); //! \brief Samples the scattering event //! \param p Particle to operate on -void -scatter(Particle& p); +void scatter(Particle& p); //! \brief Determines the average total, prompt and delayed neutrons produced //! from fission and creates the appropriate bank sites. //! \param p Particle to operate on -void -create_fission_sites(Particle& p); +void create_fission_sites(Particle& p); //! \brief Handles an absorption event //! \param p Particle to operate on -void -absorption(Particle& p); +void absorption(Particle& p); } // namespace openmc #endif // OPENMC_PHYSICS_MG_H diff --git a/include/openmc/plot.h b/include/openmc/plot.h index 0e9ceea78..aa15277aa 100644 --- a/include/openmc/plot.h +++ b/include/openmc/plot.h @@ -1,21 +1,21 @@ #ifndef OPENMC_PLOT_H #define OPENMC_PLOT_H -#include #include +#include #include "pugixml.hpp" #include "xtensor/xarray.hpp" #include "hdf5.h" -#include "openmc/position.h" -#include "openmc/constants.h" #include "openmc/cell.h" +#include "openmc/constants.h" #include "openmc/error.h" #include "openmc/geometry.h" #include "openmc/particle.h" -#include "openmc/xml_interface.h" +#include "openmc/position.h" #include "openmc/random_lcg.h" +#include "openmc/xml_interface.h" namespace openmc { @@ -30,8 +30,9 @@ namespace model { extern std::unordered_map plot_map; //!< map of plot ids to index extern vector plots; //!< Plot instance container -extern uint64_t plotter_prn_seeds[N_STREAMS]; // Random number seeds used for plotter -extern int plotter_stream; // Stream index used by the plotter +extern uint64_t + plotter_prn_seeds[N_STREAMS]; // Random number seeds used for plotter +extern int plotter_stream; // Stream index used by the plotter } // namespace model @@ -40,10 +41,10 @@ extern int plotter_stream; // Stream index used by the plotter //=============================================================================== struct RGBColor { - //Constructors - RGBColor() : red(0), green(0), blue(0) { }; - RGBColor(const int v[3]) : red(v[0]), green(v[1]), blue(v[2]) { }; - RGBColor(int r, int g, int b) : red(r), green(g), blue(b) { }; + // Constructors + RGBColor() : red(0), green(0), blue(0) {}; + RGBColor(const int v[3]) : red(v[0]), green(v[1]), blue(v[2]) {}; + RGBColor(int r, int g, int b) : red(r), green(g), blue(b) {}; RGBColor(const vector& v) { @@ -55,7 +56,8 @@ struct RGBColor { blue = v[2]; } - bool operator ==(const RGBColor& other) { + bool operator==(const RGBColor& other) + { return red == other.red && green == other.green && blue == other.blue; } @@ -65,8 +67,7 @@ struct RGBColor { // some default colors const RGBColor WHITE {255, 255, 255}; -const RGBColor RED {255, 0, 0}; - +const RGBColor RED {255, 0, 0}; typedef xt::xtensor ImageData; @@ -94,48 +95,40 @@ struct PropertyData { xt::xtensor data_; //!< 2D array of temperature & density data }; -enum class PlotType { - slice = 1, - voxel = 2 -}; +enum class PlotType { slice = 1, voxel = 2 }; -enum class PlotBasis { - xy = 1, - xz = 2, - yz = 3 -}; +enum class PlotBasis { xy = 1, xz = 2, yz = 3 }; -enum class PlotColorBy { - cells = 0, - mats = 1 -}; +enum class PlotColorBy { cells = 0, mats = 1 }; //=============================================================================== // Plot class //=============================================================================== class PlotBase { public: - template T get_map() const; + template + T get_map() const; // Members public: - Position origin_; //!< Plot origin in geometry - Position width_; //!< Plot width in geometry - PlotBasis basis_; //!< Plot basis (XY/XZ/YZ) + Position origin_; //!< Plot origin in geometry + Position width_; //!< Plot width in geometry + PlotBasis basis_; //!< Plot basis (XY/XZ/YZ) array pixels_; //!< Plot size in pixels - bool color_overlaps_; //!< Show overlapping cells? - int level_; //!< Plot universe level + bool color_overlaps_; //!< Show overlapping cells? + int level_; //!< Plot universe level }; template -T PlotBase::get_map() const { +T PlotBase::get_map() const +{ size_t width = pixels_[0]; size_t height = pixels_[1]; // get pixel size - double in_pixel = (width_[0])/static_cast(width); - double out_pixel = (width_[1])/static_cast(height); + double in_pixel = (width_[0]) / static_cast(width); + double out_pixel = (width_[1]) / static_cast(height); // size data array T data(width, height); @@ -143,16 +136,16 @@ T PlotBase::get_map() const { // setup basis indices and initial position centered on pixel int in_i, out_i; Position xyz = origin_; - switch(basis_) { - case PlotBasis::xy : + switch (basis_) { + case PlotBasis::xy: in_i = 0; out_i = 1; break; - case PlotBasis::xz : + case PlotBasis::xz: in_i = 0; out_i = 2; break; - case PlotBasis::yz : + case PlotBasis::yz: in_i = 1; out_i = 2; break; @@ -167,25 +160,27 @@ T PlotBase::get_map() const { // arbitrary direction Direction dir = {0.7071, 0.7071, 0.0}; - #pragma omp parallel +#pragma omp parallel { Particle p; p.r() = xyz; p.u() = dir; p.coord(0).universe = model::root_universe; int level = level_; - int j{}; + int j {}; - #pragma omp for +#pragma omp for for (int y = 0; y < height; y++) { - p.r()[out_i] = xyz[out_i] - out_pixel * y; + p.r()[out_i] = xyz[out_i] - out_pixel * y; for (int x = 0; x < width; x++) { p.r()[in_i] = xyz[in_i] + in_pixel * x; p.n_coord() = 1; // local variables bool found_cell = exhaustive_find_cell(p); j = p.n_coord() - 1; - if (level >= 0) { j = level; } + if (level >= 0) { + j = level; + } if (found_cell) { data.set_value(y, x, p, j); } @@ -193,8 +188,8 @@ T PlotBase::get_map() const { data.set_overlap(y, x); } } // inner for - } // outer for - } // omp parallel + } // outer for + } // omp parallel return data; } @@ -221,18 +216,18 @@ private: void set_mask(pugi::xml_node plot_node); void set_overlap_color(pugi::xml_node plot_node); -// Members + // Members public: - int id_; //!< Plot ID - PlotType type_; //!< Plot type (Slice/Voxel) - PlotColorBy color_by_; //!< Plot coloring (cell/material) - int meshlines_width_; //!< Width of lines added to the plot + int id_; //!< Plot ID + PlotType type_; //!< Plot type (Slice/Voxel) + PlotColorBy color_by_; //!< Plot coloring (cell/material) + int meshlines_width_; //!< Width of lines added to the plot int index_meshlines_mesh_ {-1}; //!< Index of the mesh to draw on the plot - RGBColor meshlines_color_; //!< Color of meshlines on the plot - RGBColor not_found_ {WHITE}; //!< Plot background color - RGBColor overlap_color_ {RED}; //!< Plot overlap color - vector colors_; //!< Plot colors - std::string path_plot_; //!< Plot output filename + RGBColor meshlines_color_; //!< Color of meshlines on the plot + RGBColor not_found_ {WHITE}; //!< Plot background color + RGBColor overlap_color_ {RED}; //!< Plot overlap color + vector colors_; //!< Plot colors + std::string path_plot_; //!< Plot output filename }; //=============================================================================== @@ -255,16 +250,16 @@ void output_ppm(Plot const& pl, const ImageData& data); //! \param[out] dataspace pointer to voxel data //! \param[out] dataset pointer to voxesl data //! \param[out] pointer to memory space of voxel data -void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, - hid_t* dset, hid_t* memspace); +void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset, + hid_t* memspace); //! Write a section of the voxel data to hdf5 //! \param[in] voxel slice //! \param[out] dataspace pointer to voxel data //! \param[out] dataset pointer to voxesl data //! \param[out] pointer to data to write -void voxel_write_slice(int x, hid_t dspace, hid_t dset, - hid_t memspace, void* buf); +void voxel_write_slice( + int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf); //! Close voxel file entities //! \param[in] data space to close @@ -291,6 +286,5 @@ void create_voxel(Plot const& pl); //! \return RGBColor with random value RGBColor random_color(); - } // namespace openmc #endif // OPENMC_PLOT_H diff --git a/include/openmc/position.h b/include/openmc/position.h index ff258d0de..5ab0774f4 100644 --- a/include/openmc/position.h +++ b/include/openmc/position.h @@ -17,8 +17,8 @@ namespace openmc { struct Position { // Constructors Position() = default; - Position(double x_, double y_, double z_) : x{x_}, y{y_}, z{z_} { }; - Position(const double xyz[]) : x{xyz[0]}, y{xyz[1]}, z{xyz[2]} { }; + Position(double x_, double y_, double z_) : x {x_}, y {y_}, z {z_} {}; + Position(const double xyz[]) : x {xyz[0]}, y {xyz[1]}, z {xyz[2]} {}; Position(const vector& xyz) : x {xyz[0]}, y {xyz[1]}, z {xyz[2]} {}; Position(const array& xyz) : x {xyz[0]}, y {xyz[1]}, z {xyz[2]} {}; @@ -33,22 +33,30 @@ struct Position { Position& operator/=(double); Position operator-() const; - const double& operator[](int i) const { + const double& operator[](int i) const + { switch (i) { - case 0: return x; - case 1: return y; - case 2: return z; - default: - throw std::out_of_range{"Index in Position must be between 0 and 2."}; + case 0: + return x; + case 1: + return y; + case 2: + return z; + default: + throw std::out_of_range {"Index in Position must be between 0 and 2."}; } } - double& operator[](int i) { + double& operator[](int i) + { switch (i) { - case 0: return x; - case 1: return y; - case 2: return z; - default: - throw std::out_of_range{"Index in Position must be between 0 and 2."}; + case 0: + return x; + case 1: + return y; + case 2: + return z; + default: + throw std::out_of_range {"Index in Position must be between 0 and 2."}; } } @@ -69,12 +77,11 @@ struct Position { //! Dot product of two vectors //! \param[in] other Vector to take dot product with //! \result Resulting dot product - inline double dot(Position other) const { - return x*other.x + y*other.y + z*other.z; - } - inline double norm() const { - return std::sqrt(x*x + y*y + z*z); + inline double dot(Position other) const + { + return x * other.x + y * other.y + z * other.z; } + inline double norm() const { return std::sqrt(x * x + y * y + z * z); } //! Reflect a direction across a normal vector //! \param[in] other Vector to reflect across @@ -123,23 +130,60 @@ inline double& Position::get<2>() } // Binary operators -inline Position operator+(Position a, Position b) { return a += b; } -inline Position operator+(Position a, double b) { return a += b; } -inline Position operator+(double a, Position b) { return b += a; } +inline Position operator+(Position a, Position b) +{ + return a += b; +} +inline Position operator+(Position a, double b) +{ + return a += b; +} +inline Position operator+(double a, Position b) +{ + return b += a; +} -inline Position operator-(Position a, Position b) { return a -= b; } -inline Position operator-(Position a, double b) { return a -= b; } -inline Position operator-(double a, Position b) { return b -= a; } +inline Position operator-(Position a, Position b) +{ + return a -= b; +} +inline Position operator-(Position a, double b) +{ + return a -= b; +} +inline Position operator-(double a, Position b) +{ + return b -= a; +} -inline Position operator*(Position a, Position b) { return a *= b; } -inline Position operator*(Position a, double b) { return a *= b; } -inline Position operator*(double a, Position b) { return b *= a; } +inline Position operator*(Position a, Position b) +{ + return a *= b; +} +inline Position operator*(Position a, double b) +{ + return a *= b; +} +inline Position operator*(double a, Position b) +{ + return b *= a; +} -inline Position operator/(Position a, Position b) { return a /= b; } -inline Position operator/(Position a, double b) { return a /= b; } -inline Position operator/(double a, Position b) { return b /= a; } +inline Position operator/(Position a, Position b) +{ + return a /= b; +} +inline Position operator/(Position a, double b) +{ + return a /= b; +} +inline Position operator/(double a, Position b) +{ + return b /= a; +} -inline Position Position::reflect(Position n) const { +inline Position Position::reflect(Position n) const +{ const double projection = n.dot(*this); const double magnitude = n.dot(n); n *= (2.0 * projection / magnitude); @@ -147,10 +191,14 @@ inline Position Position::reflect(Position n) const { } inline bool operator==(Position a, Position b) -{return a.x == b.x && a.y == b.y && a.z == b.z;} +{ + return a.x == b.x && a.y == b.y && a.z == b.z; +} inline bool operator!=(Position a, Position b) -{return a.x != b.x || a.y != b.y || a.z != b.z;} +{ + return a.x != b.x || a.y != b.y || a.z != b.z; +} std::ostream& operator<<(std::ostream& os, Position a); diff --git a/include/openmc/progress_bar.h b/include/openmc/progress_bar.h index 18a3eea47..7708b9b03 100644 --- a/include/openmc/progress_bar.h +++ b/include/openmc/progress_bar.h @@ -5,18 +5,16 @@ class ProgressBar { -public: +public: // Constructor ProgressBar(); void set_value(double val); - + private: std::string bar; - char bar_old[72] = "???% | |"; - + char bar_old[72] = + "???% | |"; }; - #endif // OPENMC_PROGRESSBAR_H - diff --git a/include/openmc/random_dist.h b/include/openmc/random_dist.h index 844c0ce52..9bf55aa93 100644 --- a/include/openmc/random_dist.h +++ b/include/openmc/random_dist.h @@ -78,7 +78,8 @@ extern "C" double normal_variate(double mean, double std_dev, uint64_t* seed); //! \result The sampled outgoing energy //============================================================================== -extern "C" double muir_spectrum(double e0, double m_rat, double kt, uint64_t* seed); +extern "C" double muir_spectrum( + double e0, double m_rat, double kt, uint64_t* seed); } // namespace openmc diff --git a/include/openmc/random_lcg.h b/include/openmc/random_lcg.h index d73cc3ee2..4157b7cfe 100644 --- a/include/openmc/random_lcg.h +++ b/include/openmc/random_lcg.h @@ -3,19 +3,18 @@ #include - namespace openmc { //============================================================================== // Module constants. //============================================================================== -constexpr int N_STREAMS {4}; -constexpr int STREAM_TRACKING {0}; -constexpr int STREAM_SOURCE {1}; +constexpr int N_STREAMS {4}; +constexpr int STREAM_TRACKING {0}; +constexpr int STREAM_SOURCE {1}; constexpr int STREAM_URR_PTABLE {2}; -constexpr int STREAM_VOLUME {3}; -constexpr int64_t DEFAULT_SEED {1}; +constexpr int STREAM_VOLUME {3}; +constexpr int64_t DEFAULT_SEED {1}; //============================================================================== //! Generate a pseudo-random number using a linear congruential generator. diff --git a/include/openmc/reaction.h b/include/openmc/reaction.h index a597e6237..6b276db20 100644 --- a/include/openmc/reaction.h +++ b/include/openmc/reaction.h @@ -6,8 +6,8 @@ #include -#include #include "hdf5.h" +#include #include "openmc/reaction_product.h" #include "openmc/vector.h" @@ -43,10 +43,10 @@ public: vector value; }; - int mt_; //!< ENDF MT value - double q_value_; //!< Reaction Q value in [eV] - bool scatter_in_cm_; //!< scattering system in center-of-mass? - bool redundant_; //!< redundant reaction? + int mt_; //!< ENDF MT value + double q_value_; //!< Reaction Q value in [eV] + bool scatter_in_cm_; //!< scattering system in center-of-mass? + bool redundant_; //!< redundant reaction? vector xs_; //!< Cross section at each temperature vector products_; //!< Reaction products }; diff --git a/include/openmc/reaction_product.h b/include/openmc/reaction_product.h index 2c0a703dc..ce4fa8fc7 100644 --- a/include/openmc/reaction_product.h +++ b/include/openmc/reaction_product.h @@ -52,6 +52,6 @@ public: vector distribution_; //!< Secondary angle-energy distribution }; -} // namespace opemc +} // namespace openmc #endif // OPENMC_REACTION_PRODUCT_H diff --git a/include/openmc/scattdata.h b/include/openmc/scattdata.h index bc1700319..9f911d7db 100644 --- a/include/openmc/scattdata.h +++ b/include/openmc/scattdata.h @@ -21,151 +21,138 @@ class ScattDataTabular; //============================================================================== class ScattData { - public: - virtual ~ScattData() = default; - protected: - //! \brief Initializes the attributes of the base class. - void - base_init(int order, const xt::xtensor& in_gmin, - const xt::xtensor& in_gmax, const double_2dvec& in_energy, - const double_2dvec& in_mult); +public: + virtual ~ScattData() = default; - //! \brief Combines microscopic ScattDatas into a macroscopic one. - void base_combine(size_t max_order, size_t order_dim, - const vector& those_scatts, const vector& scalars, - xt::xtensor& in_gmin, xt::xtensor& in_gmax, - double_2dvec& sparse_mult, double_3dvec& sparse_scatter); +protected: + //! \brief Initializes the attributes of the base class. + void base_init(int order, const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_energy, + const double_2dvec& in_mult); - public: + //! \brief Combines microscopic ScattDatas into a macroscopic one. + void base_combine(size_t max_order, size_t order_dim, + const vector& those_scatts, const vector& scalars, + xt::xtensor& in_gmin, xt::xtensor& in_gmax, + double_2dvec& sparse_mult, double_3dvec& sparse_scatter); - double_2dvec energy; // Normalized p0 matrix for sampling Eout - double_2dvec mult; // nu-scatter multiplication (nu-scatt/scatt) - double_3dvec dist; // Angular distribution - xt::xtensor gmin; // minimum outgoing group - xt::xtensor gmax; // maximum outgoing group - xt::xtensor scattxs; // Isotropic Sigma_{s,g_{in}} +public: + double_2dvec energy; // Normalized p0 matrix for sampling Eout + double_2dvec mult; // nu-scatter multiplication (nu-scatt/scatt) + double_3dvec dist; // Angular distribution + xt::xtensor gmin; // minimum outgoing group + xt::xtensor gmax; // maximum outgoing group + xt::xtensor scattxs; // Isotropic Sigma_{s,g_{in}} - //! \brief Calculates the value of normalized f(mu). - //! - //! The value of f(mu) is normalized as in the integral of f(mu)dmu across - //! [-1,1] is 1. - //! - //! @param gin Incoming energy group of interest. - //! @param gout Outgoing energy group of interest. - //! @param mu Cosine of the change-in-angle of interest. - //! @return The value of f(mu). - virtual double - calc_f(int gin, int gout, double mu) = 0; + //! \brief Calculates the value of normalized f(mu). + //! + //! The value of f(mu) is normalized as in the integral of f(mu)dmu across + //! [-1,1] is 1. + //! + //! @param gin Incoming energy group of interest. + //! @param gout Outgoing energy group of interest. + //! @param mu Cosine of the change-in-angle of interest. + //! @return The value of f(mu). + virtual double calc_f(int gin, int gout, double mu) = 0; - //! \brief Samples the outgoing energy and angle from the ScattData info. - //! - //! @param gin Incoming energy group. - //! @param gout Sampled outgoing energy group. - //! @param mu Sampled cosine of the change-in-angle. - //! @param wgt Weight of the particle to be adjusted. - //! @param seed Pseudorandom number seed pointer - virtual void - sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed) = 0; + //! \brief Samples the outgoing energy and angle from the ScattData info. + //! + //! @param gin Incoming energy group. + //! @param gout Sampled outgoing energy group. + //! @param mu Sampled cosine of the change-in-angle. + //! @param wgt Weight of the particle to be adjusted. + //! @param seed Pseudorandom number seed pointer + virtual void sample( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed) = 0; - //! \brief Initializes the ScattData object from a given scatter and - //! multiplicity matrix. - //! - //! @param in_gmin List of minimum outgoing groups for every incoming group - //! @param in_gmax List of maximum outgoing groups for every incoming group - //! @param in_mult Input sparse multiplicity matrix - //! @param coeffs Input sparse scattering matrix - virtual void - init(const xt::xtensor& in_gmin, const xt::xtensor& in_gmax, - const double_2dvec& in_mult, const double_3dvec& coeffs) = 0; + //! \brief Initializes the ScattData object from a given scatter and + //! multiplicity matrix. + //! + //! @param in_gmin List of minimum outgoing groups for every incoming group + //! @param in_gmax List of maximum outgoing groups for every incoming group + //! @param in_mult Input sparse multiplicity matrix + //! @param coeffs Input sparse scattering matrix + virtual void init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs) = 0; - //! \brief Combines the microscopic data. - //! - //! @param those_scatts Microscopic objects to combine. - //! @param scalars Scalars to multiply the microscopic data by. - virtual void combine(const vector& those_scatts, - const vector& scalars) = 0; + //! \brief Combines the microscopic data. + //! + //! @param those_scatts Microscopic objects to combine. + //! @param scalars Scalars to multiply the microscopic data by. + virtual void combine( + const vector& those_scatts, const vector& scalars) = 0; - //! \brief Getter for the dimensionality of the scattering order. - //! - //! If Legendre this is the "n" in "Pn"; for Tabular, this is the number - //! of points, and for Histogram this is the number of bins. - //! - //! @return The order. - virtual size_t - get_order() = 0; + //! \brief Getter for the dimensionality of the scattering order. + //! + //! If Legendre this is the "n" in "Pn"; for Tabular, this is the number + //! of points, and for Histogram this is the number of bins. + //! + //! @return The order. + virtual size_t get_order() = 0; - //! \brief Builds a dense scattering matrix from the constituent parts - //! - //! @param max_order If Legendre this is the maximum value of "n" in "Pn" - //! requested; ignored otherwise. - //! @return The dense scattering matrix. - virtual xt::xtensor - get_matrix(size_t max_order) = 0; + //! \brief Builds a dense scattering matrix from the constituent parts + //! + //! @param max_order If Legendre this is the maximum value of "n" in "Pn" + //! requested; ignored otherwise. + //! @return The dense scattering matrix. + virtual xt::xtensor get_matrix(size_t max_order) = 0; - //! \brief Samples the outgoing energy from the ScattData info. - //! - //! @param gin Incoming energy group. - //! @param gout Sampled outgoing energy group. - //! @param i_gout Sampled outgoing energy group index. - //! @param seed Pseudorandom number seed pointer - void - sample_energy(int gin, int& gout, int& i_gout, uint64_t* seed); + //! \brief Samples the outgoing energy from the ScattData info. + //! + //! @param gin Incoming energy group. + //! @param gout Sampled outgoing energy group. + //! @param i_gout Sampled outgoing energy group index. + //! @param seed Pseudorandom number seed pointer + void sample_energy(int gin, int& gout, int& i_gout, uint64_t* seed); - //! \brief Provides a cross section value given certain parameters - //! - //! @param xstype Type of cross section requested, according to the - //! enumerated constants. - //! @param gin Incoming energy group. - //! @param gout Outgoing energy group; use nullptr if irrelevant, or if a - //! sum is requested. - //! @param mu Cosine of the change-in-angle, for scattering quantities; - //! use nullptr if irrelevant. - //! @return Requested cross section value. - double - get_xs(MgxsType xstype, int gin, const int* gout, const double* mu); + //! \brief Provides a cross section value given certain parameters + //! + //! @param xstype Type of cross section requested, according to the + //! enumerated constants. + //! @param gin Incoming energy group. + //! @param gout Outgoing energy group; use nullptr if irrelevant, or if a + //! sum is requested. + //! @param mu Cosine of the change-in-angle, for scattering quantities; + //! use nullptr if irrelevant. + //! @return Requested cross section value. + double get_xs(MgxsType xstype, int gin, const int* gout, const double* mu); }; //============================================================================== // ScattDataLegendre represents the angular distributions as Legendre kernels //============================================================================== -class ScattDataLegendre: public ScattData { +class ScattDataLegendre : public ScattData { - protected: +protected: + // Maximal value for rejection sampling from a rectangle + double_2dvec max_val; - // Maximal value for rejection sampling from a rectangle - double_2dvec max_val; + // Friend convert_legendre_to_tabular so it has access to protected + // parameters + friend void convert_legendre_to_tabular( + ScattDataLegendre& leg, ScattDataTabular& tab); - // Friend convert_legendre_to_tabular so it has access to protected - // parameters - friend void - convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab); +public: + void init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs); - public: + void combine( + const vector& those_scatts, const vector& scalars); - void - init(const xt::xtensor& in_gmin, const xt::xtensor& in_gmax, - const double_2dvec& in_mult, const double_3dvec& coeffs); + //! \brief Find the maximal value of the angular distribution to use as a + // bounding box with rejection sampling. + void update_max_val(); - void combine( - const vector& those_scatts, const vector& scalars); + double calc_f(int gin, int gout, double mu); - //! \brief Find the maximal value of the angular distribution to use as a - // bounding box with rejection sampling. - void - update_max_val(); + void sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - double - calc_f(int gin, int gout, double mu); + size_t get_order() { return dist[0][0].size() - 1; }; - void - sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - - size_t - get_order() {return dist[0][0].size() - 1;}; - - xt::xtensor - get_matrix(size_t max_order); + xt::xtensor get_matrix(size_t max_order); }; //============================================================================== @@ -173,34 +160,28 @@ class ScattDataLegendre: public ScattData { // would be if it came from a "mu" tally in OpenMC //============================================================================== -class ScattDataHistogram: public ScattData { +class ScattDataHistogram : public ScattData { - protected: +protected: + xt::xtensor mu; // Angle distribution mu bin boundaries + double dmu; // Quick storage of the mu spacing + double_3dvec fmu; // The angular distribution histogram - xt::xtensor mu; // Angle distribution mu bin boundaries - double dmu; // Quick storage of the mu spacing - double_3dvec fmu; // The angular distribution histogram +public: + void init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs); - public: + void combine( + const vector& those_scatts, const vector& scalars); - void - init(const xt::xtensor& in_gmin, const xt::xtensor& in_gmax, - const double_2dvec& in_mult, const double_3dvec& coeffs); + double calc_f(int gin, int gout, double mu); - void combine( - const vector& those_scatts, const vector& scalars); + void sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - double - calc_f(int gin, int gout, double mu); + size_t get_order() { return dist[0][0].size(); }; - void - sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - - size_t - get_order() {return dist[0][0].size();}; - - xt::xtensor - get_matrix(size_t max_order); + xt::xtensor get_matrix(size_t max_order); }; //============================================================================== @@ -208,39 +189,33 @@ class ScattDataHistogram: public ScattData { // f(mu) //============================================================================== -class ScattDataTabular: public ScattData { +class ScattDataTabular : public ScattData { - protected: +protected: + xt::xtensor mu; // Angle distribution mu grid points + double dmu; // Quick storage of the mu spacing + double_3dvec fmu; // The angular distribution function - xt::xtensor mu; // Angle distribution mu grid points - double dmu; // Quick storage of the mu spacing - double_3dvec fmu; // The angular distribution function + // Friend convert_legendre_to_tabular so it has access to protected + // parameters + friend void convert_legendre_to_tabular( + ScattDataLegendre& leg, ScattDataTabular& tab); - // Friend convert_legendre_to_tabular so it has access to protected - // parameters - friend void - convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab); +public: + void init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs); - public: + void combine( + const vector& those_scatts, const vector& scalars); - void - init(const xt::xtensor& in_gmin, const xt::xtensor& in_gmax, - const double_2dvec& in_mult, const double_3dvec& coeffs); + double calc_f(int gin, int gout, double mu); - void combine( - const vector& those_scatts, const vector& scalars); + void sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - double - calc_f(int gin, int gout, double mu); + size_t get_order() { return dist[0][0].size(); }; - void - sample(int gin, int& gout, double& mu, double& wgt, uint64_t* seed); - - size_t - get_order() {return dist[0][0].size();}; - - xt::xtensor - get_matrix(size_t max_order); + xt::xtensor get_matrix(size_t max_order); }; //============================================================================== @@ -253,9 +228,8 @@ class ScattDataTabular: public ScattData { //! @param leg The resultant ScattDataTabular object. //! @param n_mu The number of mu points to use when building the //! ScattDataTabular object. -void -convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab, - int n_mu); +void convert_legendre_to_tabular( + ScattDataLegendre& leg, ScattDataTabular& tab, int n_mu); } // namespace openmc #endif // OPENMC_SCATTDATA_H diff --git a/include/openmc/search.h b/include/openmc/search.h index 446e2916a..3a6f9789d 100644 --- a/include/openmc/search.h +++ b/include/openmc/search.h @@ -11,17 +11,18 @@ namespace openmc { //! Perform binary search template -typename std::iterator_traits::difference_type -lower_bound_index(It first, It last, const T& value) +typename std::iterator_traits::difference_type lower_bound_index( + It first, It last, const T& value) { - if (*first == value) return 0; + if (*first == value) + return 0; It index = std::lower_bound(first, last, value) - 1; return (index == last) ? -1 : index - first; } template -typename std::iterator_traits::difference_type -upper_bound_index(It first, It last, const T& value) +typename std::iterator_traits::difference_type upper_bound_index( + It first, It last, const T& value) { It index = std::upper_bound(first, last, value) - 1; return (index == last) ? -1 : index - first; diff --git a/include/openmc/secondary_correlated.h b/include/openmc/secondary_correlated.h index 46910c507..6905c38e3 100644 --- a/include/openmc/secondary_correlated.h +++ b/include/openmc/secondary_correlated.h @@ -23,11 +23,11 @@ class CorrelatedAngleEnergy : public AngleEnergy { public: //! Outgoing energy/angle at a single incoming energy struct CorrTable { - int n_discrete; //!< Number of discrete lines - Interpolation interpolation; //!< Interpolation law - xt::xtensor e_out; //!< Outgoing energies [eV] - xt::xtensor p; //!< Probability density - xt::xtensor c; //!< Cumulative distribution + int n_discrete; //!< Number of discrete lines + Interpolation interpolation; //!< Interpolation law + xt::xtensor e_out; //!< Outgoing energies [eV] + xt::xtensor p; //!< Probability density + xt::xtensor c; //!< Cumulative distribution vector> angle; //!< Angle distribution }; @@ -38,8 +38,8 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; // energy property vector& energy() { return energy_; } @@ -50,7 +50,7 @@ public: const vector& distribution() const { return distribution_; } private: - int n_region_; //!< Number of interpolation regions + int n_region_; //!< Number of interpolation regions vector breakpoints_; //!< Breakpoints between regions vector interpolation_; //!< Interpolation laws vector energy_; //!< Energies [eV] at which distributions diff --git a/include/openmc/secondary_kalbach.h b/include/openmc/secondary_kalbach.h index ea9b8199a..83806d352 100644 --- a/include/openmc/secondary_kalbach.h +++ b/include/openmc/secondary_kalbach.h @@ -29,21 +29,22 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: //! Outgoing energy/angle at a single incoming energy struct KMTable { - int n_discrete; //!< Number of discrete lines - Interpolation interpolation; //!< Interpolation law + int n_discrete; //!< Number of discrete lines + Interpolation interpolation; //!< Interpolation law xt::xtensor e_out; //!< Outgoing energies [eV] - xt::xtensor p; //!< Probability density - xt::xtensor c; //!< Cumulative distribution - xt::xtensor r; //!< Pre-compound fraction - xt::xtensor a; //!< Parameterized function + xt::xtensor p; //!< Probability density + xt::xtensor c; //!< Cumulative distribution + xt::xtensor r; //!< Pre-compound fraction + xt::xtensor a; //!< Parameterized function }; - int n_region_; //!< Number of interpolation regions + int n_region_; //!< Number of interpolation regions vector breakpoints_; //!< Breakpoints between regions vector interpolation_; //!< Interpolation laws vector energy_; //!< Energies [eV] at which distributions diff --git a/include/openmc/secondary_nbody.h b/include/openmc/secondary_nbody.h index a0f6787ad..efb4fd75b 100644 --- a/include/openmc/secondary_nbody.h +++ b/include/openmc/secondary_nbody.h @@ -25,13 +25,14 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: - int n_bodies_; //!< Number of particles distributed + int n_bodies_; //!< Number of particles distributed double mass_ratio_; //!< Total mass of particles [neutron mass] - double A_; //!< Atomic weight ratio - double Q_; //!< Reaction Q-value [eV] + double A_; //!< Atomic weight ratio + double Q_; //!< Reaction Q-value [eV] }; } // namespace openmc diff --git a/include/openmc/secondary_thermal.h b/include/openmc/secondary_thermal.h index 9848c37fe..84ed68f51 100644 --- a/include/openmc/secondary_thermal.h +++ b/include/openmc/secondary_thermal.h @@ -9,8 +9,8 @@ #include "openmc/secondary_correlated.h" #include "openmc/vector.h" -#include #include "xtensor/xtensor.hpp" +#include namespace openmc { @@ -25,14 +25,14 @@ public: //! \param[in] xs Coherent elastic scattering cross section explicit CoherentElasticAE(const CoherentElasticXS& xs); - //! Sample distribution for an angle and energy //! \param[in] E_in Incoming energy in [eV] //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: const CoherentElasticXS& xs_; //!< Coherent elastic scattering cross section }; @@ -53,8 +53,9 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom number seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: double debye_waller_; }; @@ -77,8 +78,9 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom number seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: const vector& energy_; //!< Energies at which cosines are tabulated xt::xtensor mu_out_; //!< Cosines for each incident energy @@ -102,12 +104,15 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom number seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: - const vector& energy_; //!< Incident energies - xt::xtensor energy_out_; //!< Outgoing energies for each incident energy - xt::xtensor mu_out_; //!< Outgoing cosines for each incident/outgoing energy + const vector& energy_; //!< Incident energies + xt::xtensor + energy_out_; //!< Outgoing energies for each incident energy + xt::xtensor + mu_out_; //!< Outgoing cosines for each incident/outgoing energy bool skewed_; //!< Whether outgoing energy distribution is skewed }; @@ -127,12 +132,13 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom number seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; + private: //! Secondary energy/angle distribution struct DistEnergySab { - std::size_t n_e_out; //!< Number of outgoing energies + std::size_t n_e_out; //!< Number of outgoing energies xt::xtensor e_out; //!< Outgoing energies xt::xtensor e_out_pdf; //!< Probability density function xt::xtensor e_out_cdf; //!< Cumulative distribution function @@ -144,7 +150,6 @@ private: //!< each incident energy }; - } // namespace openmc #endif // OPENMC_SECONDARY_THERMAL_H diff --git a/include/openmc/secondary_uncorrelated.h b/include/openmc/secondary_uncorrelated.h index 58527047d..3afa3d9ce 100644 --- a/include/openmc/secondary_uncorrelated.h +++ b/include/openmc/secondary_uncorrelated.h @@ -29,13 +29,14 @@ public: //! \param[out] E_out Outgoing energy in [eV] //! \param[out] mu Outgoing cosine with respect to current direction //! \param[inout] seed Pseudorandom seed pointer - void sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const override; + void sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const override; // Accessors AngleDistribution& angle() { return angle_; } + private: - AngleDistribution angle_; //!< Angle distribution + AngleDistribution angle_; //!< Angle distribution unique_ptr energy_; //!< Energy distribution }; diff --git a/include/openmc/settings.h b/include/openmc/settings.h index cc3887f8f..2d0261960 100644 --- a/include/openmc/settings.h +++ b/include/openmc/settings.h @@ -22,89 +22,100 @@ namespace openmc { namespace settings { - // Boolean flags -extern bool assume_separate; //!< assume tallies are spatially separate? -extern bool check_overlaps; //!< check overlaps in geometry? -extern bool confidence_intervals; //!< use confidence intervals for results? -extern bool create_fission_neutrons; //!< create fission neutrons (fixed source)? -extern "C" bool cmfd_run; //!< is a CMFD run? -extern bool delayed_photon_scaling; //!< Scale fission photon yield to include delayed -extern "C" bool entropy_on; //!< calculate Shannon entropy? -extern bool event_based; //!< use event-based mode (instead of history-based) -extern bool legendre_to_tabular; //!< convert Legendre distributions to tabular? -extern bool material_cell_offsets; //!< create material cells offsets? -extern "C" bool output_summary; //!< write summary.h5? -extern bool output_tallies; //!< write tallies.out? -extern bool particle_restart_run; //!< particle restart run? -extern "C" bool photon_transport; //!< photon transport turned on? -extern "C" bool reduce_tallies; //!< reduce tallies at end of batch? -extern bool res_scat_on; //!< use resonance upscattering method? -extern "C" bool restart_run; //!< restart run? -extern "C" bool run_CE; //!< run with continuous-energy data? -extern bool source_latest; //!< write latest source at each batch? -extern bool source_separate; //!< write source to separate file? -extern bool source_write; //!< write source in HDF5 files? -extern bool surf_source_write; //!< write surface source file? -extern bool surf_source_read; //!< read surface source file? -extern bool survival_biasing; //!< use survival biasing? -extern bool temperature_multipole; //!< use multipole data? -extern "C" bool trigger_on; //!< tally triggers enabled? -extern bool trigger_predict; //!< predict batches for triggers? -extern bool ufs_on; //!< uniform fission site method on? -extern bool urr_ptables_on; //!< use unresolved resonance prob. tables? -extern bool write_all_tracks; //!< write track files for every particle? -extern bool write_initial_source; //!< write out initial source file? +extern bool assume_separate; //!< assume tallies are spatially separate? +extern bool check_overlaps; //!< check overlaps in geometry? +extern bool confidence_intervals; //!< use confidence intervals for results? +extern bool + create_fission_neutrons; //!< create fission neutrons (fixed source)? +extern "C" bool cmfd_run; //!< is a CMFD run? +extern bool + delayed_photon_scaling; //!< Scale fission photon yield to include delayed +extern "C" bool entropy_on; //!< calculate Shannon entropy? +extern bool event_based; //!< use event-based mode (instead of history-based) +extern bool legendre_to_tabular; //!< convert Legendre distributions to tabular? +extern bool material_cell_offsets; //!< create material cells offsets? +extern "C" bool output_summary; //!< write summary.h5? +extern bool output_tallies; //!< write tallies.out? +extern bool particle_restart_run; //!< particle restart run? +extern "C" bool photon_transport; //!< photon transport turned on? +extern "C" bool reduce_tallies; //!< reduce tallies at end of batch? +extern bool res_scat_on; //!< use resonance upscattering method? +extern "C" bool restart_run; //!< restart run? +extern "C" bool run_CE; //!< run with continuous-energy data? +extern bool source_latest; //!< write latest source at each batch? +extern bool source_separate; //!< write source to separate file? +extern bool source_write; //!< write source in HDF5 files? +extern bool surf_source_write; //!< write surface source file? +extern bool surf_source_read; //!< read surface source file? +extern bool survival_biasing; //!< use survival biasing? +extern bool temperature_multipole; //!< use multipole data? +extern "C" bool trigger_on; //!< tally triggers enabled? +extern bool trigger_predict; //!< predict batches for triggers? +extern bool ufs_on; //!< uniform fission site method on? +extern bool urr_ptables_on; //!< use unresolved resonance prob. tables? +extern bool write_all_tracks; //!< write track files for every particle? +extern bool write_initial_source; //!< write out initial source file? // Paths to various files -extern std::string path_cross_sections; //!< path to cross_sections.xml -extern std::string path_input; //!< directory where main .xml files resides -extern std::string path_output; //!< directory where output files are written +extern std::string path_cross_sections; //!< path to cross_sections.xml +extern std::string path_input; //!< directory where main .xml files resides +extern std::string path_output; //!< directory where output files are written extern std::string path_particle_restart; //!< path to a particle restart file extern std::string path_sourcepoint; //!< path to a source file extern "C" std::string path_statepoint; //!< path to a statepoint file -extern "C" int32_t n_inactive; //!< number of inactive batches -extern "C" int32_t max_lost_particles; //!< maximum number of lost particles -extern double rel_max_lost_particles; //!< maximum number of lost particles, relative to the total number of particles -extern "C" int32_t gen_per_batch; //!< number of generations per batch -extern "C" int64_t n_particles; //!< number of particles per generation +extern "C" int32_t n_inactive; //!< number of inactive batches +extern "C" int32_t max_lost_particles; //!< maximum number of lost particles +extern double + rel_max_lost_particles; //!< maximum number of lost particles, relative to the + //!< total number of particles +extern "C" int32_t gen_per_batch; //!< number of generations per batch +extern "C" int64_t n_particles; //!< number of particles per generation +extern int64_t + max_particles_in_flight; //!< Max num. event-based particles in flight -extern int64_t max_particles_in_flight; //!< Max num. event-based particles in flight - -extern ElectronTreatment electron_treatment; //!< how to treat secondary electrons +extern ElectronTreatment + electron_treatment; //!< how to treat secondary electrons extern array energy_cutoff; //!< Energy cutoff in [eV] for each particle type -extern int legendre_to_tabular_points; //!< number of points to convert Legendres -extern int max_order; //!< Maximum Legendre order for multigroup data -extern int n_log_bins; //!< number of bins for logarithmic energy grid -extern int n_batches; //!< number of (inactive+active) batches -extern int n_max_batches; //!< Maximum number of batches +extern int + legendre_to_tabular_points; //!< number of points to convert Legendres +extern int max_order; //!< Maximum Legendre order for multigroup data +extern int n_log_bins; //!< number of bins for logarithmic energy grid +extern int n_batches; //!< number of (inactive+active) batches +extern int n_max_batches; //!< Maximum number of batches extern ResScatMethod res_scat_method; //!< resonance upscattering method -extern double res_scat_energy_min; //!< Min energy in [eV] for res. upscattering -extern double res_scat_energy_max; //!< Max energy in [eV] for res. upscattering +extern double res_scat_energy_min; //!< Min energy in [eV] for res. upscattering +extern double res_scat_energy_max; //!< Max energy in [eV] for res. upscattering extern vector - res_scat_nuclides; //!< Nuclides using res. upscattering treatment -extern RunMode run_mode; //!< Run mode (eigenvalue, fixed src, etc.) -extern std::unordered_set sourcepoint_batch; //!< Batches when source should be written -extern std::unordered_set statepoint_batch; //!< Batches when state should be written -extern std::unordered_set source_write_surf_id; //!< Surface ids where sources will be written -extern int64_t max_surface_particles; //!< maximum number of particles to be banked on surfaces per process -extern TemperatureMethod temperature_method; //!< method for choosing temperatures -extern double temperature_tolerance; //!< Tolerance in [K] on choosing temperatures -extern double temperature_default; //!< Default T in [K] + res_scat_nuclides; //!< Nuclides using res. upscattering treatment +extern RunMode run_mode; //!< Run mode (eigenvalue, fixed src, etc.) +extern std::unordered_set + sourcepoint_batch; //!< Batches when source should be written +extern std::unordered_set + statepoint_batch; //!< Batches when state should be written +extern std::unordered_set + source_write_surf_id; //!< Surface ids where sources will be written +extern int64_t max_surface_particles; //!< maximum number of particles to be + //!< banked on surfaces per process +extern TemperatureMethod + temperature_method; //!< method for choosing temperatures +extern double + temperature_tolerance; //!< Tolerance in [K] on choosing temperatures +extern double temperature_default; //!< Default T in [K] extern array - temperature_range; //!< Min/max T in [K] over which to load xs -extern int trace_batch; //!< Batch to trace particle on -extern int trace_gen; //!< Generation to trace particle on -extern int64_t trace_particle; //!< Particle ID to enable trace on + temperature_range; //!< Min/max T in [K] over which to load xs +extern int trace_batch; //!< Batch to trace particle on +extern int trace_gen; //!< Generation to trace particle on +extern int64_t trace_particle; //!< Particle ID to enable trace on extern vector> - track_identifiers; //!< Particle numbers for writing tracks -extern int trigger_batch_interval; //!< Batch interval for triggers -extern "C" int verbosity; //!< How verbose to make output -extern double weight_cutoff; //!< Weight cutoff for Russian roulette -extern double weight_survive; //!< Survival weight after Russian roulette + track_identifiers; //!< Particle numbers for writing tracks +extern int trigger_batch_interval; //!< Batch interval for triggers +extern "C" int verbosity; //!< How verbose to make output +extern double weight_cutoff; //!< Weight cutoff for Russian roulette +extern double weight_survive; //!< Survival weight after Russian roulette } // namespace settings //============================================================================== diff --git a/include/openmc/shared_array.h b/include/openmc/shared_array.h index 588b8812b..6fee29b82 100644 --- a/include/openmc/shared_array.h +++ b/include/openmc/shared_array.h @@ -20,10 +20,10 @@ namespace openmc { // call the thread_safe_append() function concurrently and store data to the // object at the index returned from thread_safe_append() safely, but no other // operations are protected. -template -class SharedArray { +template +class SharedArray { -public: +public: //========================================================================== // Constructors @@ -45,7 +45,7 @@ public: //! Return a reference to the element at specified location i. No bounds //! checking is performed. - T& operator[](int64_t i) {return data_[i];} + T& operator[](int64_t i) { return data_[i]; } const T& operator[](int64_t i) const { return data_[i]; } //! Allocate space in the container for the specified number of elements. @@ -58,7 +58,7 @@ public: capacity_ = capacity; } - //! Increase the size of the container by one and append value to the + //! Increase the size of the container by one and append value to the //! array. Returns an index to the element of the array written to. Also //! tests to enforce that the append operation does not read off the end //! of the array. In the event that this does happen, set the size to be @@ -72,12 +72,12 @@ public: { // Atomically capture the index we want to write to int64_t idx; - #pragma omp atomic capture seq_cst +#pragma omp atomic capture seq_cst idx = size_++; // Check that we haven't written off the end of the array if (idx >= capacity_) { - #pragma omp atomic write seq_cst +#pragma omp atomic write seq_cst size_ = capacity_; return -1; } @@ -98,32 +98,31 @@ public: } //! Return the number of elements in the container - int64_t size() {return size_;} + int64_t size() { return size_; } //! Resize the container to contain a specified number of elements. This is - //! useful in cases where the container is written to in a non-thread safe manner, - //! where the internal size of the array needs to be manually updated. + //! useful in cases where the container is written to in a non-thread safe + //! manner, where the internal size of the array needs to be manually updated. // //! \param size The new size of the container - void resize(int64_t size) {size_ = size;} + void resize(int64_t size) { size_ = size; } //! Return the number of elements that the container has currently allocated //! space for. - int64_t capacity() {return capacity_;} + int64_t capacity() { return capacity_; } //! Return pointer to the underlying array serving as element storage. - T* data() {return data_.get();} - const T* data() const {return data_.get();} + T* data() { return data_.get(); } + const T* data() const { return data_.get(); } -private: +private: //========================================================================== // Data members unique_ptr data_; //!< An RAII handle to the elements - int64_t size_ {0}; //!< The current number of elements + int64_t size_ {0}; //!< The current number of elements int64_t capacity_ {0}; //!< The total space allocated for elements - -}; +}; } // namespace openmc diff --git a/include/openmc/simulation.h b/include/openmc/simulation.h index e7f8eb758..dd8bb7cdf 100644 --- a/include/openmc/simulation.h +++ b/include/openmc/simulation.h @@ -22,22 +22,24 @@ constexpr int STATUS_EXIT_ON_TRIGGER {2}; namespace simulation { -extern "C" int current_batch; //!< current batch -extern "C" int current_gen; //!< current fission generation -extern "C" bool initialized; //!< has simulation been initialized? -extern "C" double keff; //!< average k over batches -extern "C" double keff_std; //!< standard deviation of average k -extern "C" double k_col_abs; //!< sum over batches of k_collision * k_absorption -extern "C" double k_col_tra; //!< sum over batches of k_collision * k_tracklength -extern "C" double k_abs_tra; //!< sum over batches of k_absorption * k_tracklength -extern double log_spacing; //!< lethargy spacing for energy grid searches -extern "C" int n_lost_particles; //!< cumulative number of lost particles +extern "C" int current_batch; //!< current batch +extern "C" int current_gen; //!< current fission generation +extern "C" bool initialized; //!< has simulation been initialized? +extern "C" double keff; //!< average k over batches +extern "C" double keff_std; //!< standard deviation of average k +extern "C" double k_col_abs; //!< sum over batches of k_collision * k_absorption +extern "C" double + k_col_tra; //!< sum over batches of k_collision * k_tracklength +extern "C" double + k_abs_tra; //!< sum over batches of k_absorption * k_tracklength +extern double log_spacing; //!< lethargy spacing for energy grid searches +extern "C" int n_lost_particles; //!< cumulative number of lost particles extern "C" bool need_depletion_rx; //!< need to calculate depletion rx? -extern "C" int restart_batch; //!< batch at which a restart job resumed -extern "C" bool satisfy_triggers; //!< have tally triggers been satisfied? -extern "C" int total_gen; //!< total number of generations simulated -extern double total_weight; //!< Total source weight in a batch -extern int64_t work_per_rank; //!< number of particles per MPI rank +extern "C" int restart_batch; //!< batch at which a restart job resumed +extern "C" bool satisfy_triggers; //!< have tally triggers been satisfied? +extern "C" int total_gen; //!< total number of generations simulated +extern double total_weight; //!< Total source weight in a batch +extern int64_t work_per_rank; //!< number of particles per MPI rank extern const RegularMesh* entropy_mesh; extern const RegularMesh* ufs_mesh; diff --git a/include/openmc/source.h b/include/openmc/source.h index 5cbccf272..cc644577e 100644 --- a/include/openmc/source.h +++ b/include/openmc/source.h @@ -67,10 +67,10 @@ public: private: ParticleType particle_ {ParticleType::neutron}; //!< Type of particle emitted - double strength_ {1.0}; //!< Source strength - UPtrSpace space_; //!< Spatial distribution - UPtrAngle angle_; //!< Angular distribution - UPtrDist energy_; //!< Energy distribution + double strength_ {1.0}; //!< Source strength + UPtrSpace space_; //!< Spatial distribution + UPtrAngle angle_; //!< Angular distribution + UPtrDist energy_; //!< Energy distribution }; //============================================================================== @@ -106,6 +106,7 @@ public: } double strength() const override { return custom_source_->strength(); } + private: void* shared_library_; //!< library from dlopen unique_ptr custom_source_; diff --git a/include/openmc/summary.h b/include/openmc/summary.h index ff2ab71a8..10e445aed 100644 --- a/include/openmc/summary.h +++ b/include/openmc/summary.h @@ -11,6 +11,6 @@ void write_nuclides(hid_t file); void write_geometry(hid_t file); void write_materials(hid_t file); -} +} // namespace openmc #endif // OPENMC_SUMMARY_H diff --git a/include/openmc/surface.h b/include/openmc/surface.h index b3f2bdfad..325c313aa 100644 --- a/include/openmc/surface.h +++ b/include/openmc/surface.h @@ -1,7 +1,7 @@ #ifndef OPENMC_SURFACE_H #define OPENMC_SURFACE_H -#include // For numeric_limits +#include // For numeric_limits #include #include @@ -24,16 +24,15 @@ namespace openmc { class Surface; namespace model { - extern std::unordered_map surface_map; - extern vector> surfaces; +extern std::unordered_map surface_map; +extern vector> surfaces; } // namespace model //============================================================================== //! Coordinates for an axis-aligned cuboid that bounds a geometric object. //============================================================================== -struct BoundingBox -{ +struct BoundingBox { double xmin = -INFTY; double xmax = INFTY; double ymin = -INFTY; @@ -41,19 +40,21 @@ struct BoundingBox double zmin = -INFTY; double zmax = INFTY; - - inline BoundingBox operator &(const BoundingBox& other) { + inline BoundingBox operator&(const BoundingBox& other) + { BoundingBox result = *this; return result &= other; } - inline BoundingBox operator |(const BoundingBox& other) { + inline BoundingBox operator|(const BoundingBox& other) + { BoundingBox result = *this; return result |= other; } // intersect operator - inline BoundingBox& operator &=(const BoundingBox& other) { + inline BoundingBox& operator&=(const BoundingBox& other) + { xmin = std::max(xmin, other.xmin); xmax = std::min(xmax, other.xmax); ymin = std::max(ymin, other.ymin); @@ -64,7 +65,8 @@ struct BoundingBox } // union operator - inline BoundingBox& operator |=(const BoundingBox& other) { + inline BoundingBox& operator|=(const BoundingBox& other) + { xmin = std::min(xmin, other.xmin); xmax = std::max(xmax, other.xmax); ymin = std::min(ymin, other.ymin); @@ -73,22 +75,19 @@ struct BoundingBox zmax = std::max(zmax, other.zmax); return *this; } - }; //============================================================================== //! A geometry primitive used to define regions of 3D space. //============================================================================== -class Surface -{ +class Surface { public: - - int id_; //!< Unique ID - std::string name_; //!< User-defined name + int id_; //!< Unique ID + std::string name_; //!< User-defined name std::shared_ptr bc_ {nullptr}; //!< Boundary condition - GeometryType geom_type_; //!< Geometry type indicator (CSG or DAGMC) - bool surf_source_ {false}; //!< Activate source banking for the surface? + GeometryType geom_type_; //!< Geometry type indicator (CSG or DAGMC) + bool surf_source_ {false}; //!< Activate source banking for the surface? explicit Surface(pugi::xml_node surf_node); Surface(); @@ -110,8 +109,8 @@ public: //! \return Outgoing direction of the ray virtual Direction reflect(Position r, Direction u, Particle* p) const; - virtual Direction diffuse_reflect(Position r, Direction u, - uint64_t* seed) const; + virtual Direction diffuse_reflect( + Position r, Direction u, uint64_t* seed) const; //! Evaluate the equation describing the surface. //! @@ -143,8 +142,7 @@ protected: virtual void to_hdf5_inner(hid_t group_id) const = 0; }; -class CSGSurface : public Surface -{ +class CSGSurface : public Surface { public: explicit CSGSurface(pugi::xml_node surf_node); CSGSurface(); @@ -159,8 +157,7 @@ protected: //! The plane is described by the equation \f$x - x_0 = 0\f$ //============================================================================== -class SurfaceXPlane : public CSGSurface -{ +class SurfaceXPlane : public CSGSurface { public: explicit SurfaceXPlane(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -178,8 +175,7 @@ public: //! The plane is described by the equation \f$y - y_0 = 0\f$ //============================================================================== -class SurfaceYPlane : public CSGSurface -{ +class SurfaceYPlane : public CSGSurface { public: explicit SurfaceYPlane(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -197,8 +193,7 @@ public: //! The plane is described by the equation \f$z - z_0 = 0\f$ //============================================================================== -class SurfaceZPlane : public CSGSurface -{ +class SurfaceZPlane : public CSGSurface { public: explicit SurfaceZPlane(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -216,8 +211,7 @@ public: //! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ //============================================================================== -class SurfacePlane : public CSGSurface -{ +class SurfacePlane : public CSGSurface { public: explicit SurfacePlane(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -235,8 +229,7 @@ public: //! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceXCylinder : public CSGSurface -{ +class SurfaceXCylinder : public CSGSurface { public: explicit SurfaceXCylinder(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -255,8 +248,7 @@ public: //! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceYCylinder : public CSGSurface -{ +class SurfaceYCylinder : public CSGSurface { public: explicit SurfaceYCylinder(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -275,8 +267,7 @@ public: //! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceZCylinder : public CSGSurface -{ +class SurfaceZCylinder : public CSGSurface { public: explicit SurfaceZCylinder(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -295,8 +286,7 @@ public: //! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceSphere : public CSGSurface -{ +class SurfaceSphere : public CSGSurface { public: explicit SurfaceSphere(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -315,8 +305,7 @@ public: //! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ //============================================================================== -class SurfaceXCone : public CSGSurface -{ +class SurfaceXCone : public CSGSurface { public: explicit SurfaceXCone(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -334,8 +323,7 @@ public: //! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ //============================================================================== -class SurfaceYCone : public CSGSurface -{ +class SurfaceYCone : public CSGSurface { public: explicit SurfaceYCone(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -353,8 +341,7 @@ public: //! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ //============================================================================== -class SurfaceZCone : public CSGSurface -{ +class SurfaceZCone : public CSGSurface { public: explicit SurfaceZCone(pugi::xml_node surf_node); double evaluate(Position r) const; @@ -368,11 +355,11 @@ public: //============================================================================== //! A general surface described by a quadratic equation. // -//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ +//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = +//! 0\f$ //============================================================================== -class SurfaceQuadric : public CSGSurface -{ +class SurfaceQuadric : public CSGSurface { public: explicit SurfaceQuadric(pugi::xml_node surf_node); double evaluate(Position r) const; diff --git a/include/openmc/tallies/derivative.h b/include/openmc/tallies/derivative.h index d3a7b8b20..38362e85f 100644 --- a/include/openmc/tallies/derivative.h +++ b/include/openmc/tallies/derivative.h @@ -15,18 +15,14 @@ namespace openmc { // Different independent variables -enum class DerivativeVariable { - DENSITY, - NUCLIDE_DENSITY, - TEMPERATURE -}; +enum class DerivativeVariable { DENSITY, NUCLIDE_DENSITY, TEMPERATURE }; struct TallyDerivative { - DerivativeVariable variable; //!< Independent variable (like temperature) - int id; //!< User-defined identifier - int diff_material; //!< Material this derivative is applied to - int diff_nuclide; //!< Nuclide this material is applied to + DerivativeVariable variable; //!< Independent variable (like temperature) + int id; //!< User-defined identifier + int diff_material; //!< Material this derivative is applied to + int diff_nuclide; //!< Nuclide this material is applied to TallyDerivative() {} explicit TallyDerivative(pugi::xml_node node); @@ -41,8 +37,7 @@ void read_tally_derivatives(pugi::xml_node node); //! Scale the given score by its logarithmic derivative -void -apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, +void apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, double atom_density, int score_bin, double& score); //! Adjust diff tally flux derivatives for a particle scattering event. diff --git a/include/openmc/tallies/filter.h b/include/openmc/tallies/filter.h index 9620632a3..b0145f0e1 100644 --- a/include/openmc/tallies/filter.h +++ b/include/openmc/tallies/filter.h @@ -21,8 +21,7 @@ namespace openmc { //! Modifies tally score events. //============================================================================== -class Filter -{ +class Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors, factory functions @@ -67,12 +66,11 @@ public: //! \param[in] estimator Tally estimator being used //! \param[out] match will contain the matching bins and corresponding //! weights; note that there may be zero matching bins - virtual void - get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const = 0; + virtual void get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const = 0; //! Writes data describing this filter to an HDF5 statepoint group. - virtual void - to_statepoint(hid_t filter_group) const + virtual void to_statepoint(hid_t filter_group) const { write_dataset(filter_group, "type", type()); write_dataset(filter_group, "n_bins", n_bins_); @@ -107,6 +105,7 @@ public: protected: int n_bins_; + private: int32_t id_ {C_NONE}; gsl::index index_; @@ -117,10 +116,10 @@ private: //============================================================================== namespace model { - extern "C" int32_t n_filters; - extern std::unordered_map filter_map; - extern vector> tally_filters; -} +extern "C" int32_t n_filters; +extern std::unordered_map filter_map; +extern vector> tally_filters; +} // namespace model //============================================================================== // Non-member functions diff --git a/include/openmc/tallies/filter_azimuthal.h b/include/openmc/tallies/filter_azimuthal.h index d1c468233..4cda9163f 100644 --- a/include/openmc/tallies/filter_azimuthal.h +++ b/include/openmc/tallies/filter_azimuthal.h @@ -14,8 +14,7 @@ namespace openmc { //! Bins the incident neutron azimuthal angle (relative to the global xy-plane). //============================================================================== -class AzimuthalFilter : public Filter -{ +class AzimuthalFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -25,12 +24,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "azimuthal";} + std::string type() const override { return "azimuthal"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_cell.h b/include/openmc/tallies/filter_cell.h index e4180148f..6e2463f24 100644 --- a/include/openmc/tallies/filter_cell.h +++ b/include/openmc/tallies/filter_cell.h @@ -15,8 +15,7 @@ namespace openmc { //! Specifies which geometric cells tally events reside in. //============================================================================== -class CellFilter : public Filter -{ +class CellFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "cell";} + std::string type() const override { return "cell"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_cell_instance.h b/include/openmc/tallies/filter_cell_instance.h index 387f7e591..d74850df7 100644 --- a/include/openmc/tallies/filter_cell_instance.h +++ b/include/openmc/tallies/filter_cell_instance.h @@ -28,12 +28,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "cellinstance";} + std::string type() const override { return "cellinstance"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_cellborn.h b/include/openmc/tallies/filter_cellborn.h index e1e1225dd..282854020 100644 --- a/include/openmc/tallies/filter_cellborn.h +++ b/include/openmc/tallies/filter_cellborn.h @@ -11,16 +11,15 @@ namespace openmc { //! Specifies which cell the particle was born in. //============================================================================== -class CellbornFilter : public CellFilter -{ +class CellbornFilter : public CellFilter { public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "cellborn";} + std::string type() const override { return "cellborn"; } - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; std::string text_label(int bin) const override; }; diff --git a/include/openmc/tallies/filter_cellfrom.h b/include/openmc/tallies/filter_cellfrom.h index cf11937bd..47abd0353 100644 --- a/include/openmc/tallies/filter_cellfrom.h +++ b/include/openmc/tallies/filter_cellfrom.h @@ -11,16 +11,15 @@ namespace openmc { //! Specifies which geometric cells particles exit when crossing a surface. //============================================================================== -class CellFromFilter : public CellFilter -{ +class CellFromFilter : public CellFilter { public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "cellfrom";} + std::string type() const override { return "cellfrom"; } - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; std::string text_label(int bin) const override; }; diff --git a/include/openmc/tallies/filter_collision.h b/include/openmc/tallies/filter_collision.h index 1b23bd440..46c64c553 100644 --- a/include/openmc/tallies/filter_collision.h +++ b/include/openmc/tallies/filter_collision.h @@ -1,8 +1,8 @@ #ifndef OPENMC_TALLIES_FILTER_COLLISIONS_H #define OPENMC_TALLIES_FILTER_COLLISIONS_H -#include #include +#include #include "openmc/tallies/filter.h" #include "openmc/vector.h" @@ -27,7 +27,7 @@ public: void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, + void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; @@ -46,8 +46,7 @@ protected: vector bins_; - std::unordered_map map_; - + std::unordered_map map_; }; } // namespace openmc diff --git a/include/openmc/tallies/filter_delayedgroup.h b/include/openmc/tallies/filter_delayedgroup.h index 63987e339..868807f05 100644 --- a/include/openmc/tallies/filter_delayedgroup.h +++ b/include/openmc/tallies/filter_delayedgroup.h @@ -15,8 +15,7 @@ namespace openmc { //! iterated over in the scoring subroutines. //============================================================================== -class DelayedGroupFilter : public Filter -{ +class DelayedGroupFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "delayedgroup";} + std::string type() const override { return "delayedgroup"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_distribcell.h b/include/openmc/tallies/filter_distribcell.h index 68cb694e7..d72ae022f 100644 --- a/include/openmc/tallies/filter_distribcell.h +++ b/include/openmc/tallies/filter_distribcell.h @@ -11,8 +11,7 @@ namespace openmc { //! Specifies which distributed geometric cells tally events reside in. //============================================================================== -class DistribcellFilter : public Filter -{ +class DistribcellFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -22,12 +21,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "distribcell";} + std::string type() const override { return "distribcell"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_energy.h b/include/openmc/tallies/filter_energy.h index 2db0231e2..c820f28fb 100644 --- a/include/openmc/tallies/filter_energy.h +++ b/include/openmc/tallies/filter_energy.h @@ -12,8 +12,7 @@ namespace openmc { //! Bins the incident neutron energy. //============================================================================== -class EnergyFilter : public Filter -{ +class EnergyFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -23,12 +22,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "energy";} + std::string type() const override { return "energy"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; @@ -59,16 +58,15 @@ protected: //! tallies manually iterate over the filter bins. //============================================================================== -class EnergyoutFilter : public EnergyFilter -{ +class EnergyoutFilter : public EnergyFilter { public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "energyout";} + std::string type() const override { return "energyout"; } - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; std::string text_label(int bin) const override; }; diff --git a/include/openmc/tallies/filter_energyfunc.h b/include/openmc/tallies/filter_energyfunc.h index 5c131ba69..c066dfa17 100644 --- a/include/openmc/tallies/filter_energyfunc.h +++ b/include/openmc/tallies/filter_energyfunc.h @@ -11,29 +11,24 @@ namespace openmc { //! described by a piecewise linear-linear interpolation. //============================================================================== -class EnergyFunctionFilter : public Filter -{ +class EnergyFunctionFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors - EnergyFunctionFilter() - : Filter {} - { - n_bins_ = 1; - } + EnergyFunctionFilter() : Filter {} { n_bins_ = 1; } ~EnergyFunctionFilter() = default; //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "energyfunction";} + std::string type() const override { return "energyfunction"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_legendre.h b/include/openmc/tallies/filter_legendre.h index 5a489b946..b1fac37c8 100644 --- a/include/openmc/tallies/filter_legendre.h +++ b/include/openmc/tallies/filter_legendre.h @@ -11,8 +11,7 @@ namespace openmc { //! Gives Legendre moments of the change in scattering angle //============================================================================== -class LegendreFilter : public Filter -{ +class LegendreFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -22,12 +21,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "legendre";} + std::string type() const override { return "legendre"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_match.h b/include/openmc/tallies/filter_match.h index b07656f17..613a729f5 100644 --- a/include/openmc/tallies/filter_match.h +++ b/include/openmc/tallies/filter_match.h @@ -1,15 +1,13 @@ #ifndef OPENMC_TALLIES_FILTERMATCH_H #define OPENMC_TALLIES_FILTERMATCH_H - namespace openmc { //============================================================================== //! Stores bins and weights for filtered tally events. //============================================================================== -class FilterMatch -{ +class FilterMatch { public: vector bins_; vector weights_; diff --git a/include/openmc/tallies/filter_material.h b/include/openmc/tallies/filter_material.h index 65bfce04e..8a67c1a75 100644 --- a/include/openmc/tallies/filter_material.h +++ b/include/openmc/tallies/filter_material.h @@ -15,8 +15,7 @@ namespace openmc { //! Specifies which material tally events reside in. //============================================================================== -class MaterialFilter : public Filter -{ +class MaterialFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "material";} + std::string type() const override { return "material"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_mesh.h b/include/openmc/tallies/filter_mesh.h index 8a712f4cb..ef055b1a2 100644 --- a/include/openmc/tallies/filter_mesh.h +++ b/include/openmc/tallies/filter_mesh.h @@ -3,8 +3,8 @@ #include -#include "openmc/tallies/filter.h" #include "openmc/position.h" +#include "openmc/tallies/filter.h" namespace openmc { @@ -14,8 +14,7 @@ namespace openmc { //! correspond to the fraction of the track length that lies in that bin. //============================================================================== -class MeshFilter : public Filter -{ +class MeshFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -25,12 +24,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "mesh";} + std::string type() const override { return "mesh"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; @@ -39,7 +38,7 @@ public: //---------------------------------------------------------------------------- // Accessors - virtual int32_t mesh() const {return mesh_;} + virtual int32_t mesh() const { return mesh_; } virtual void set_mesh(int32_t mesh); @@ -47,10 +46,9 @@ public: virtual void set_translation(const double translation[3]); - virtual const Position& translation() const {return translation_;} - - virtual bool translated() const {return translated_;} + virtual const Position& translation() const { return translation_; } + virtual bool translated() const { return translated_; } protected: //---------------------------------------------------------------------------- diff --git a/include/openmc/tallies/filter_meshsurface.h b/include/openmc/tallies/filter_meshsurface.h index baaf1e53c..28f4e265f 100644 --- a/include/openmc/tallies/filter_meshsurface.h +++ b/include/openmc/tallies/filter_meshsurface.h @@ -5,16 +5,15 @@ namespace openmc { -class MeshSurfaceFilter : public MeshFilter -{ +class MeshSurfaceFilter : public MeshFilter { public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "meshsurface";} + std::string type() const override { return "meshsurface"; } - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; std::string text_label(int bin) const override; @@ -24,18 +23,18 @@ public: void set_mesh(int32_t mesh) override; enum class MeshDir { - OUT_LEFT, // x min - IN_LEFT, // x min + OUT_LEFT, // x min + IN_LEFT, // x min OUT_RIGHT, // x max - IN_RIGHT, // x max - OUT_BACK, // y min - IN_BACK, // y min + IN_RIGHT, // x max + OUT_BACK, // y min + IN_BACK, // y min OUT_FRONT, // y max - IN_FRONT, // y max - OUT_BOTTOM, // z min - IN_BOTTOM, // z min - OUT_TOP, // z max - IN_TOP // z max + IN_FRONT, // y max + OUT_BOTTOM, // z min + IN_BOTTOM, // z min + OUT_TOP, // z max + IN_TOP // z max }; }; diff --git a/include/openmc/tallies/filter_mu.h b/include/openmc/tallies/filter_mu.h index cad5bad1f..de934d156 100644 --- a/include/openmc/tallies/filter_mu.h +++ b/include/openmc/tallies/filter_mu.h @@ -13,8 +13,7 @@ namespace openmc { //! reactions. //============================================================================== -class MuFilter : public Filter -{ +class MuFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -24,12 +23,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "mu";} + std::string type() const override { return "mu"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_particle.h b/include/openmc/tallies/filter_particle.h index da022b81e..cd4c5d413 100644 --- a/include/openmc/tallies/filter_particle.h +++ b/include/openmc/tallies/filter_particle.h @@ -11,8 +11,7 @@ namespace openmc { //! Bins by type of particle (e.g. neutron, photon). //============================================================================== -class ParticleFilter : public Filter -{ +class ParticleFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -22,12 +21,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "particle";} + std::string type() const override { return "particle"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_polar.h b/include/openmc/tallies/filter_polar.h index ecfbc6f9c..23c00e619 100644 --- a/include/openmc/tallies/filter_polar.h +++ b/include/openmc/tallies/filter_polar.h @@ -14,8 +14,7 @@ namespace openmc { //! Bins the incident neutron polar angle (relative to the global z-axis). //============================================================================== -class PolarFilter : public Filter -{ +class PolarFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -25,12 +24,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "polar";} + std::string type() const override { return "polar"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_sph_harm.h b/include/openmc/tallies/filter_sph_harm.h index 91c81bdae..498590d3c 100644 --- a/include/openmc/tallies/filter_sph_harm.h +++ b/include/openmc/tallies/filter_sph_harm.h @@ -9,16 +9,13 @@ namespace openmc { -enum class SphericalHarmonicsCosine { - scatter, particle -}; +enum class SphericalHarmonicsCosine { scatter, particle }; //============================================================================== //! Gives spherical harmonics expansion moments of a tally score //============================================================================== -class SphericalHarmonicsFilter : public Filter -{ +class SphericalHarmonicsFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -28,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "sphericalharmonics";} + std::string type() const override { return "sphericalharmonics"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_sptl_legendre.h b/include/openmc/tallies/filter_sptl_legendre.h index 581142f78..d6ac24668 100644 --- a/include/openmc/tallies/filter_sptl_legendre.h +++ b/include/openmc/tallies/filter_sptl_legendre.h @@ -7,16 +7,13 @@ namespace openmc { -enum class LegendreAxis { - x, y, z -}; +enum class LegendreAxis { x, y, z }; //============================================================================== //! Gives Legendre moments of the particle's normalized position along an axis //============================================================================== -class SpatialLegendreFilter : public Filter -{ +class SpatialLegendreFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +23,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "spatiallegendre";} + std::string type() const override { return "spatiallegendre"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_surface.h b/include/openmc/tallies/filter_surface.h index 28b510534..368fd09d0 100644 --- a/include/openmc/tallies/filter_surface.h +++ b/include/openmc/tallies/filter_surface.h @@ -15,8 +15,7 @@ namespace openmc { //! Specifies which surface particles are crossing //============================================================================== -class SurfaceFilter : public Filter -{ +class SurfaceFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "surface";} + std::string type() const override { return "surface"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_universe.h b/include/openmc/tallies/filter_universe.h index dfdbb8cf9..afe583b2d 100644 --- a/include/openmc/tallies/filter_universe.h +++ b/include/openmc/tallies/filter_universe.h @@ -15,8 +15,7 @@ namespace openmc { //! Specifies which geometric universes tally events reside in. //============================================================================== -class UniverseFilter : public Filter -{ +class UniverseFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -26,12 +25,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "universe";} + std::string type() const override { return "universe"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; diff --git a/include/openmc/tallies/filter_zernike.h b/include/openmc/tallies/filter_zernike.h index a1248eac1..72c47e654 100644 --- a/include/openmc/tallies/filter_zernike.h +++ b/include/openmc/tallies/filter_zernike.h @@ -11,8 +11,7 @@ namespace openmc { //! Gives Zernike polynomial moments of a particle's position //============================================================================== -class ZernikeFilter : public Filter -{ +class ZernikeFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors @@ -22,12 +21,12 @@ public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "zernike";} + std::string type() const override { return "zernike"; } void from_xml(pugi::xml_node node) override; - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; @@ -68,16 +67,15 @@ protected: //! Gives even order radial Zernike polynomial moments of a particle's position //============================================================================== -class ZernikeRadialFilter : public ZernikeFilter -{ +class ZernikeRadialFilter : public ZernikeFilter { public: //---------------------------------------------------------------------------- // Methods - std::string type() const override {return "zernikeradial";} + std::string type() const override { return "zernikeradial"; } - void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) - const override; + void get_all_bins(const Particle& p, TallyEstimator estimator, + FilterMatch& match) const override; std::string text_label(int bin) const override; diff --git a/include/openmc/tallies/tally.h b/include/openmc/tallies/tally.h index 25208f6fb..39e0b0af2 100644 --- a/include/openmc/tallies/tally.h +++ b/include/openmc/tallies/tally.h @@ -7,10 +7,10 @@ #include "openmc/tallies/trigger.h" #include "openmc/vector.h" -#include #include "pugixml.hpp" #include "xtensor/xfixed.hpp" #include "xtensor/xtensor.hpp" +#include #include #include @@ -49,18 +49,18 @@ public: const vector& filters() const { return filters_; } - int32_t filters(int i) const {return filters_[i];} + int32_t filters(int i) const { return filters_[i]; } void set_filters(gsl::span filters); //! Given already-set filters, set the stride lengths void set_strides(); - int32_t strides(int i) const {return strides_[i];} + int32_t strides(int i) const { return strides_[i]; } - int32_t n_filter_bins() const {return n_filter_bins_;} + int32_t n_filter_bins() const { return n_filter_bins_; } - bool writable() const { return writable_;} + bool writable() const { return writable_; } //---------------------------------------------------------------------------- // Other methods. @@ -148,23 +148,24 @@ private: //============================================================================== namespace model { - extern std::unordered_map tally_map; - extern vector> tallies; - extern vector active_tallies; - extern vector active_analog_tallies; - extern vector active_tracklength_tallies; - extern vector active_collision_tallies; - extern vector active_meshsurf_tallies; - extern vector active_surface_tallies; -} +extern std::unordered_map tally_map; +extern vector> tallies; +extern vector active_tallies; +extern vector active_analog_tallies; +extern vector active_tracklength_tallies; +extern vector active_collision_tallies; +extern vector active_meshsurf_tallies; +extern vector active_surface_tallies; +} // namespace model namespace simulation { - //! Global tallies (such as k-effective estimators) - extern xt::xtensor_fixed> global_tallies; +//! Global tallies (such as k-effective estimators) +extern xt::xtensor_fixed> + global_tallies; - //! Number of realizations for global tallies - extern "C" int32_t n_realizations; -} +//! Number of realizations for global tallies +extern "C" int32_t n_realizations; +} // namespace simulation extern double global_tally_absorption; extern double global_tally_collision; @@ -187,8 +188,9 @@ void setup_active_tallies(); // Alias for the type returned by xt::adapt(...). N is the dimension of the // multidimensional array -template -using adaptor_type = xt::xtensor_adaptor, N>; +template +using adaptor_type = + xt::xtensor_adaptor, N>; #ifdef OPENMC_MPI //! Collect all tally results onto master process diff --git a/include/openmc/tallies/tally_scoring.h b/include/openmc/tallies/tally_scoring.h index 4510f725f..85d0fc58f 100644 --- a/include/openmc/tallies/tally_scoring.h +++ b/include/openmc/tallies/tally_scoring.h @@ -18,10 +18,8 @@ namespace openmc { //! bins that are valid for the current tally event. //============================================================================== -class FilterBinIter -{ +class FilterBinIter { public: - //! Construct an iterator over bins that match a given particle's state. FilterBinIter(const Tally& tally, Particle& p); @@ -32,10 +30,14 @@ public: const Tally& tally, bool end, vector* particle_filter_matches); bool operator==(const FilterBinIter& other) const - {return index_ == other.index_;} + { + return index_ == other.index_; + } bool operator!=(const FilterBinIter& other) const - {return !(*this == other);} + { + return !(*this == other); + } FilterBinIter& operator++(); diff --git a/include/openmc/tallies/trigger.h b/include/openmc/tallies/trigger.h index a11759114..9fe159b9d 100644 --- a/include/openmc/tallies/trigger.h +++ b/include/openmc/tallies/trigger.h @@ -12,21 +12,23 @@ namespace openmc { //============================================================================== enum class TriggerMetric { - variance, relative_error, standard_deviation, not_active + variance, + relative_error, + standard_deviation, + not_active }; //! Stops the simulation early if a desired tally uncertainty is reached. struct Trigger { - TriggerMetric metric; //!< The type of uncertainty (e.g. std dev) measured - double threshold; //!< Uncertainty value below which trigger is satisfied - int score_index; //!< Index of the relevant score in the tally's arrays + TriggerMetric metric; //!< The type of uncertainty (e.g. std dev) measured + double threshold; //!< Uncertainty value below which trigger is satisfied + int score_index; //!< Index of the relevant score in the tally's arrays }; //! Stops the simulation early if a desired k-effective uncertainty is reached. -struct KTrigger -{ +struct KTrigger { TriggerMetric metric {TriggerMetric::not_active}; double threshold {0.}; }; @@ -35,9 +37,9 @@ struct KTrigger // Global variable declarations //============================================================================== -//TODO: consider a different namespace +// TODO: consider a different namespace namespace settings { - extern KTrigger keff_trigger; +extern KTrigger keff_trigger; } //============================================================================== diff --git a/include/openmc/thermal.h b/include/openmc/thermal.h index d2db789e2..de0767d0a 100644 --- a/include/openmc/thermal.h +++ b/include/openmc/thermal.h @@ -25,7 +25,7 @@ class ThermalScattering; namespace data { extern std::unordered_map thermal_scatt_map; extern vector> thermal_scatt; -} +} // namespace data //============================================================================== //! Secondary angle-energy data for thermal neutron scattering at a single @@ -50,12 +50,13 @@ public: //! \param[out] E_out Outgoing neutron energy in [eV] //! \param[out] mu Outgoing scattering angle cosine //! \param[inout] seed Pseudorandom seed pointer - void sample(const NuclideMicroXS& micro_xs, double E_in, - double* E_out, double* mu, uint64_t* seed); + void sample(const NuclideMicroXS& micro_xs, double E_in, double* E_out, + double* mu, uint64_t* seed); + private: struct Reaction { // Default constructor - Reaction() { } + Reaction() {} // Data members unique_ptr xs; //!< Cross section @@ -83,13 +84,13 @@ public: //! Determine inelastic/elastic cross section at given energy //! //! \param[in] E incoming energy in [eV] - //! \param[in] sqrtkT square-root of temperature multipled by Boltzmann's constant - //! \param[out] i_temp corresponding temperature index - //! \param[out] elastic Thermal elastic scattering cross section - //! \param[out] inelastic Thermal inelastic scattering cross section - //! \param[inout] seed Pseudorandom seed pointer + //! \param[in] sqrtkT square-root of temperature multipled by Boltzmann's + //! constant \param[out] i_temp corresponding temperature index \param[out] + //! elastic Thermal elastic scattering cross section \param[out] inelastic + //! Thermal inelastic scattering cross section \param[inout] seed Pseudorandom + //! seed pointer void calculate_xs(double E, double sqrtkT, int* i_temp, double* elastic, - double* inelastic, uint64_t* seed) const; + double* inelastic, uint64_t* seed) const; //! Determine whether table applies to a particular nuclide //! @@ -98,13 +99,13 @@ public: bool has_nuclide(const char* name) const; // Sample an outgoing energy and angle - void sample(const NuclideMicroXS& micro_xs, double E_in, - double* E_out, double* mu); + void sample( + const NuclideMicroXS& micro_xs, double E_in, double* E_out, double* mu); - std::string name_; //!< name of table, e.g. "c_H_in_H2O" - double awr_; //!< weight of nucleus in neutron masses - double energy_max_; //!< maximum energy for thermal scattering in [eV] - vector kTs_; //!< temperatures in [eV] (k*T) + std::string name_; //!< name of table, e.g. "c_H_in_H2O" + double awr_; //!< weight of nucleus in neutron masses + double energy_max_; //!< maximum energy for thermal scattering in [eV] + vector kTs_; //!< temperatures in [eV] (k*T) vector nuclides_; //!< Valid nuclides //! cross sections and distributions at each temperature diff --git a/include/openmc/timer.h b/include/openmc/timer.h index 3acf483d6..62b97883f 100644 --- a/include/openmc/timer.h +++ b/include/openmc/timer.h @@ -58,9 +58,9 @@ public: void reset(); private: - bool running_ {false}; //!< is timer running? + bool running_ {false}; //!< is timer running? std::chrono::time_point start_; //!< starting point for clock - double elapsed_ {0.0}; //!< elapsed time in [s] + double elapsed_ {0.0}; //!< elapsed time in [s] }; //============================================================================== diff --git a/include/openmc/urr.h b/include/openmc/urr.h index 676425442..5e3d467a0 100644 --- a/include/openmc/urr.h +++ b/include/openmc/urr.h @@ -14,7 +14,7 @@ namespace openmc { //! UrrData contains probability tables for the unresolved resonance range. //============================================================================== -class UrrData{ +class UrrData { public: Interpolation interp_; //!< interpolation type int inelastic_flag_; //!< inelastic competition flag diff --git a/include/openmc/volume_calc.h b/include/openmc/volume_calc.h index 2071411f8..33cc7343a 100644 --- a/include/openmc/volume_calc.h +++ b/include/openmc/volume_calc.h @@ -9,8 +9,8 @@ #include "pugixml.hpp" #include "xtensor/xtensor.hpp" -#include #include +#include namespace openmc { @@ -28,14 +28,15 @@ public: vector atoms; //!< Number of atoms for each nuclide vector uncertainty; //!< Uncertainty on number of atoms int iterations; //!< Number of iterations needed to obtain the results - }; // Results for a single domain + }; // Results for a single domain // Constructors VolumeCalculation(pugi::xml_node node); // Methods - //! \brief Stochastically determine the volume of a set of domains along with the + //! \brief Stochastically determine the volume of a set of domains along with + //! the //! average number densities of nuclides within the domain // //! \return Vector of results for each user-specified domain @@ -49,20 +50,17 @@ public: const std::string& filename, const vector& results) const; // Tally filter and map types - enum class TallyDomain { - UNIVERSE, - MATERIAL, - CELL - }; + enum class TallyDomain { UNIVERSE, MATERIAL, CELL }; // Data members TallyDomain domain_type_; //!< Type of domain (cell, material, etc.) - size_t n_samples_; //!< Number of samples to use + size_t n_samples_; //!< Number of samples to use double threshold_ {-1.0}; //!< Error threshold for domain volumes - TriggerMetric trigger_type_ {TriggerMetric::not_active}; //!< Trigger metric for the volume calculation - Position lower_left_; //!< Lower-left position of bounding box - Position upper_right_; //!< Upper-right position of bounding box - vector domain_ids_; //!< IDs of domains to find volumes of + TriggerMetric trigger_type_ { + TriggerMetric::not_active}; //!< Trigger metric for the volume calculation + Position lower_left_; //!< Lower-left position of bounding box + Position upper_right_; //!< Upper-right position of bounding box + vector domain_ids_; //!< IDs of domains to find volumes of private: //! \brief Check whether a material has already been hit for a given domain. diff --git a/include/openmc/wmp.h b/include/openmc/wmp.h index 5b3104afc..6a4abd867 100644 --- a/include/openmc/wmp.h +++ b/include/openmc/wmp.h @@ -39,8 +39,8 @@ class WindowedMultipole { public: // Types struct WindowInfo { - int index_start; // Index of starting pole - int index_end; // Index of ending pole + int index_start; // Index of starting pole + int index_end; // Index of ending pole bool broaden_poly; // Whether to broaden polynomial curvefit }; @@ -54,7 +54,8 @@ public: //! //! \param E Incident neutron energy in [eV] //! \param sqrtkT Square root of temperature times Boltzmann constant - //! \return Tuple of elastic scattering, absorption, and fission cross sections in [b] + //! \return Tuple of elastic scattering, absorption, and fission cross + //! sections in [b] std::tuple evaluate(double E, double sqrtkT) const; //! \brief Evaluates the windowed multipole equations for the derivative of @@ -65,18 +66,20 @@ public: //! \param sqrtkT Square root of temperature times Boltzmann constant //! \return Tuple of derivatives of elastic scattering, absorption, and //! fission cross sections in [b/K] - std::tuple evaluate_deriv(double E, double sqrtkT) const; + std::tuple evaluate_deriv( + double E, double sqrtkT) const; // Data members - std::string name_; //!< Name of nuclide - double E_min_; //!< Minimum energy in [eV] - double E_max_; //!< Maximum energy in [eV] - double sqrt_awr_; //!< Square root of atomic weight ratio - double inv_spacing_; //!< 1 / spacing in sqrt(E) space - int fit_order_; //!< Order of the fit - bool fissionable_; //!< Is the nuclide fissionable? - vector window_info_; // Information about a window - xt::xtensor curvefit_; // Curve fit coefficients (window, poly order, reaction) + std::string name_; //!< Name of nuclide + double E_min_; //!< Minimum energy in [eV] + double E_max_; //!< Maximum energy in [eV] + double sqrt_awr_; //!< Square root of atomic weight ratio + double inv_spacing_; //!< 1 / spacing in sqrt(E) space + int fit_order_; //!< Order of the fit + bool fissionable_; //!< Is the nuclide fissionable? + vector window_info_; // Information about a window + xt::xtensor + curvefit_; // Curve fit coefficients (window, poly order, reaction) xt::xtensor, 2> data_; //!< Poles and residues // Constant data @@ -99,7 +102,6 @@ void check_wmp_version(hid_t file); //! \param[in] i_nuclide Index in global nuclides array void read_multipole_data(int i_nuclide); - //============================================================================== //! Doppler broadens the windowed multipole curvefit. //! @@ -111,7 +113,8 @@ void read_multipole_data(int i_nuclide); //! \param factors The output leading coefficient //============================================================================== -extern "C" void broaden_wmp_polynomials(double E, double dopp, int n, double factors[]); +extern "C" void broaden_wmp_polynomials( + double E, double dopp, int n, double factors[]); } // namespace openmc diff --git a/include/openmc/xml_interface.h b/include/openmc/xml_interface.h index ddd92ad7e..d96bb6cc2 100644 --- a/include/openmc/xml_interface.h +++ b/include/openmc/xml_interface.h @@ -6,21 +6,20 @@ #include #include "pugixml.hpp" -#include "xtensor/xarray.hpp" #include "xtensor/xadapt.hpp" +#include "xtensor/xarray.hpp" #include "openmc/vector.h" namespace openmc { -inline bool -check_for_node(pugi::xml_node node, const char *name) +inline bool check_for_node(pugi::xml_node node, const char* name) { return node.attribute(name) || node.child(name); } std::string get_node_value(pugi::xml_node node, const char* name, - bool lowercase=false, bool strip=false); + bool lowercase = false, bool strip = false); bool get_node_value_bool(pugi::xml_node node, const char* name); @@ -41,9 +40,9 @@ vector get_node_array( return values; } -template -xt::xarray get_node_xarray(pugi::xml_node node, const char* name, - bool lowercase=false) +template +xt::xarray get_node_xarray( + pugi::xml_node node, const char* name, bool lowercase = false) { vector v = get_node_array(node, name, lowercase); vector shape = {v.size()}; diff --git a/include/openmc/xsdata.h b/include/openmc/xsdata.h index cf6d8058b..feafde68d 100644 --- a/include/openmc/xsdata.h +++ b/include/openmc/xsdata.h @@ -28,127 +28,117 @@ enum class AngleDistributionType { class XsData { - private: +private: + //! \brief Reads scattering data from the HDF5 file + void scatter_from_hdf5(hid_t xsdata_grp, size_t n_ang, + AngleDistributionType scatter_format, + AngleDistributionType final_scatter_format, int order_data); - //! \brief Reads scattering data from the HDF5 file - void - scatter_from_hdf5(hid_t xsdata_grp, size_t n_ang, AngleDistributionType scatter_format, - AngleDistributionType final_scatter_format, int order_data); + //! \brief Reads fission data from the HDF5 file + void fission_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic); - //! \brief Reads fission data from the HDF5 file - void - fission_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic); + //! \brief Reads fission data formatted as chi and nu-fission vectors from + // the HDF5 file when beta is provided. + void fission_vector_beta_from_hdf5( + hid_t xsdata_grp, size_t n_ang, bool is_isotropic); - //! \brief Reads fission data formatted as chi and nu-fission vectors from - // the HDF5 file when beta is provided. - void - fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic); + //! \brief Reads fission data formatted as chi and nu-fission vectors from + // the HDF5 file when beta is not provided. + void fission_vector_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang); - //! \brief Reads fission data formatted as chi and nu-fission vectors from - // the HDF5 file when beta is not provided. - void - fission_vector_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang); + //! \brief Reads fission data formatted as chi and nu-fission vectors from + // the HDF5 file when no delayed data is provided. + void fission_vector_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang); - //! \brief Reads fission data formatted as chi and nu-fission vectors from - // the HDF5 file when no delayed data is provided. - void - fission_vector_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang); + //! \brief Reads fission data formatted as a nu-fission matrix from + // the HDF5 file when beta is provided. + void fission_matrix_beta_from_hdf5( + hid_t xsdata_grp, size_t n_ang, bool is_isotropic); - //! \brief Reads fission data formatted as a nu-fission matrix from - // the HDF5 file when beta is provided. - void - fission_matrix_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic); + //! \brief Reads fission data formatted as a nu-fission matrix from + // the HDF5 file when beta is not provided. + void fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang); - //! \brief Reads fission data formatted as a nu-fission matrix from - // the HDF5 file when beta is not provided. - void - fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang); + //! \brief Reads fission data formatted as a nu-fission matrix from + // the HDF5 file when no delayed data is provided. + void fission_matrix_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang); - //! \brief Reads fission data formatted as a nu-fission matrix from - // the HDF5 file when no delayed data is provided. - void - fission_matrix_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang); + //! Number of energy and delayed neutron groups + size_t n_g_, n_dg_; - //! Number of energy and delayed neutron groups - size_t n_g_, n_dg_; +public: + // The following quantities have the following dimensions: + // [angle][incoming group] + xt::xtensor total; + xt::xtensor absorption; + xt::xtensor nu_fission; + xt::xtensor prompt_nu_fission; + xt::xtensor kappa_fission; + xt::xtensor fission; + xt::xtensor inverse_velocity; - public: + // decay_rate has the following dimensions: + // [angle][delayed group] + xt::xtensor decay_rate; + // delayed_nu_fission has the following dimensions: + // [angle][delayed group][incoming group] + xt::xtensor delayed_nu_fission; + // chi_prompt has the following dimensions: + // [angle][incoming group][outgoing group] + xt::xtensor chi_prompt; + // chi_delayed has the following dimensions: + // [angle][incoming group][outgoing group][delayed group] + xt::xtensor chi_delayed; + // scatter has the following dimensions: [angle] + vector> scatter; - // The following quantities have the following dimensions: - // [angle][incoming group] - xt::xtensor total; - xt::xtensor absorption; - xt::xtensor nu_fission; - xt::xtensor prompt_nu_fission; - xt::xtensor kappa_fission; - xt::xtensor fission; - xt::xtensor inverse_velocity; + XsData() = default; - // decay_rate has the following dimensions: - // [angle][delayed group] - xt::xtensor decay_rate; - // delayed_nu_fission has the following dimensions: - // [angle][delayed group][incoming group] - xt::xtensor delayed_nu_fission; - // chi_prompt has the following dimensions: - // [angle][incoming group][outgoing group] - xt::xtensor chi_prompt; - // chi_delayed has the following dimensions: - // [angle][incoming group][outgoing group][delayed group] - xt::xtensor chi_delayed; - // scatter has the following dimensions: [angle] - vector> scatter; + //! \brief Constructs the XsData object metadata. + //! + //! @param num_groups Number of energy groups. + //! @param num_delayed_groups Number of delayed groups. + //! @param fissionable Is this a fissionable data set or not. + //! @param scatter_format The scattering representation of the file. + //! @param n_pol Number of polar angles. + //! @param n_azi Number of azimuthal angles. + //! @param n_groups Number of energy groups. + //! @param n_d_groups Number of delayed neutron groups. + XsData(bool fissionable, AngleDistributionType scatter_format, int n_pol, + int n_azi, size_t n_groups, size_t n_d_groups); - XsData() = default; + //! \brief Loads the XsData object from the HDF5 file + //! + //! @param xs_id HDF5 group id for the cross section data. + //! @param fissionable Is this a fissionable data set or not. + //! @param scatter_format The scattering representation of the file. + //! @param final_scatter_format The scattering representation after reading; + //! this is different from scatter_format if converting a Legendre to + //! a tabular representation. + //! @param order_data The dimensionality of the scattering data in the file. + //! @param is_isotropic Is this an isotropic or angular with respect to + //! the incoming particle. + //! @param n_pol Number of polar angles. + //! @param n_azi Number of azimuthal angles. + void from_hdf5(hid_t xsdata_grp, bool fissionable, + AngleDistributionType scatter_format, + AngleDistributionType final_scatter_format, int order_data, + bool is_isotropic, int n_pol, int n_azi); - //! \brief Constructs the XsData object metadata. - //! - //! @param num_groups Number of energy groups. - //! @param num_delayed_groups Number of delayed groups. - //! @param fissionable Is this a fissionable data set or not. - //! @param scatter_format The scattering representation of the file. - //! @param n_pol Number of polar angles. - //! @param n_azi Number of azimuthal angles. - //! @param n_groups Number of energy groups. - //! @param n_d_groups Number of delayed neutron groups. - XsData(bool fissionable, AngleDistributionType scatter_format, int n_pol, - int n_azi, size_t n_groups, size_t n_d_groups); + //! \brief Combines the microscopic data to a macroscopic object. + //! + //! @param micros Microscopic objects to combine. + //! @param scalars Scalars to multiply the microscopic data by. + void combine(const vector& those_xs, const vector& scalars); - //! \brief Loads the XsData object from the HDF5 file - //! - //! @param xs_id HDF5 group id for the cross section data. - //! @param fissionable Is this a fissionable data set or not. - //! @param scatter_format The scattering representation of the file. - //! @param final_scatter_format The scattering representation after reading; - //! this is different from scatter_format if converting a Legendre to - //! a tabular representation. - //! @param order_data The dimensionality of the scattering data in the file. - //! @param is_isotropic Is this an isotropic or angular with respect to - //! the incoming particle. - //! @param n_pol Number of polar angles. - //! @param n_azi Number of azimuthal angles. - void - from_hdf5(hid_t xsdata_grp, bool fissionable, AngleDistributionType scatter_format, - AngleDistributionType final_scatter_format, int order_data, bool is_isotropic, int n_pol, - int n_azi); - - //! \brief Combines the microscopic data to a macroscopic object. - //! - //! @param micros Microscopic objects to combine. - //! @param scalars Scalars to multiply the microscopic data by. - void combine( - const vector& those_xs, const vector& scalars); - - //! \brief Checks to see if this and that are able to be combined - //! - //! This comparison is used when building macroscopic cross sections - //! from microscopic cross sections. - //! @param that The other XsData to compare to this one. - //! @return True if they can be combined. - bool - equiv(const XsData& that); + //! \brief Checks to see if this and that are able to be combined + //! + //! This comparison is used when building macroscopic cross sections + //! from microscopic cross sections. + //! @param that The other XsData to compare to this one. + //! @return True if they can be combined. + bool equiv(const XsData& that); }; - -} //namespace openmc +} // namespace openmc #endif // OPENMC_XSDATA_H diff --git a/src/bank.cpp b/src/bank.cpp index f587197aa..8d00d5440 100644 --- a/src/bank.cpp +++ b/src/bank.cpp @@ -7,7 +7,6 @@ #include - namespace openmc { //============================================================================== @@ -20,10 +19,11 @@ vector source_bank; SharedArray surf_source_bank; -// The fission bank is allocated as a SharedArray, rather than a vector, as it will -// be shared by all threads in the simulation. It will be allocated to a fixed -// maximum capacity in the init_fission_bank() function. Then, Elements will be -// added to it by using SharedArray's special thread_safe_append() function. +// The fission bank is allocated as a SharedArray, rather than a vector, as it +// will be shared by all threads in the simulation. It will be allocated to a +// fixed maximum capacity in the init_fission_bank() function. Then, Elements +// will be added to it by using SharedArray's special thread_safe_append() +// function. SharedArray fission_bank; // Each entry in this vector corresponds to the number of progeny produced @@ -69,7 +69,7 @@ void sort_fission_bank() int64_t tmp = simulation::progeny_per_particle[0]; simulation::progeny_per_particle[0] = 0; for (int64_t i = 1; i < simulation::progeny_per_particle.size(); i++) { - int64_t value = simulation::progeny_per_particle[i-1] + tmp; + int64_t value = simulation::progeny_per_particle[i - 1] + tmp; tmp = simulation::progeny_per_particle[i]; simulation::progeny_per_particle[i] = value; } @@ -84,7 +84,8 @@ void sort_fission_bank() vector sorted_bank_holder; // If there is not enough space, allocate a temporary vector and point to it - if (simulation::fission_bank.size() > simulation::fission_bank.capacity() / 2) { + if (simulation::fission_bank.size() > + simulation::fission_bank.capacity() / 2) { sorted_bank_holder.resize(simulation::fission_bank.size()); sorted_bank = sorted_bank_holder.data(); } else { // otherwise, point sorted_bank to unused portion of the fission bank @@ -98,14 +99,14 @@ void sort_fission_bank() int64_t idx = simulation::progeny_per_particle[offset] + site.progeny_id; if (idx >= simulation::fission_bank.size()) { fatal_error("Mismatch detected between sum of all particle progeny and " - "shared fission bank size."); + "shared fission bank size."); } sorted_bank[idx] = site; } // Copy sorted bank into the fission bank std::copy(sorted_bank, sorted_bank + simulation::fission_bank.size(), - simulation::fission_bank.data()); + simulation::fission_bank.data()); } //============================================================================== @@ -141,7 +142,7 @@ extern "C" int openmc_fission_bank(void** ptr, int64_t* n) return OPENMC_E_ALLOCATE; } else { *ptr = simulation::fission_bank.data(); - *n = simulation::fission_bank.size(); + *n = simulation::fission_bank.size(); return 0; } } diff --git a/src/boundary_condition.cpp b/src/boundary_condition.cpp index 884b06f81..5b842399e 100644 --- a/src/boundary_condition.cpp +++ b/src/boundary_condition.cpp @@ -14,8 +14,7 @@ namespace openmc { // VacuumBC implementation //============================================================================== -void -VacuumBC::handle_particle(Particle& p, const Surface& surf) const +void VacuumBC::handle_particle(Particle& p, const Surface& surf) const { p.cross_vacuum_bc(surf); } @@ -24,8 +23,7 @@ VacuumBC::handle_particle(Particle& p, const Surface& surf) const // ReflectiveBC implementation //============================================================================== -void -ReflectiveBC::handle_particle(Particle& p, const Surface& surf) const +void ReflectiveBC::handle_particle(Particle& p, const Surface& surf) const { Direction u = surf.reflect(p.r(), p.u(), &p); u /= u.norm(); @@ -37,8 +35,7 @@ ReflectiveBC::handle_particle(Particle& p, const Surface& surf) const // WhiteBC implementation //============================================================================== -void -WhiteBC::handle_particle(Particle& p, const Surface& surf) const +void WhiteBC::handle_particle(Particle& p, const Surface& surf) const { Direction u = surf.diffuse_reflect(p.r(), p.u(), p.current_seed()); u /= u.norm(); @@ -62,7 +59,8 @@ TranslationalPeriodicBC::TranslationalPeriodicBC(int i_surf, int j_surf) } else if (const auto* ptr = dynamic_cast(&surf1)) { } else if (const auto* ptr = dynamic_cast(&surf1)) { } else { - throw std::invalid_argument(fmt::format("Surface {} is an invalid type for " + throw std::invalid_argument(fmt::format( + "Surface {} is an invalid type for " "translational periodic BCs. Only planes are supported for these BCs.", surf1.id_)); } @@ -73,7 +71,8 @@ TranslationalPeriodicBC::TranslationalPeriodicBC(int i_surf, int j_surf) } else if (const auto* ptr = dynamic_cast(&surf2)) { } else if (const auto* ptr = dynamic_cast(&surf2)) { } else { - throw std::invalid_argument(fmt::format("Surface {} is an invalid type for " + throw std::invalid_argument(fmt::format( + "Surface {} is an invalid type for " "translational periodic BCs. Only planes are supported for these BCs.", surf2.id_)); } @@ -109,8 +108,8 @@ TranslationalPeriodicBC::TranslationalPeriodicBC(int i_surf, int j_surf) translation_ = u * (d2 - d1); } -void -TranslationalPeriodicBC::handle_particle(Particle& p, const Surface& surf) const +void TranslationalPeriodicBC::handle_particle( + Particle& p, const Surface& surf) const { // TODO: off-by-one on surface indices throughout this function. int i_particle_surf = std::abs(p.surface()) - 1; @@ -126,7 +125,8 @@ TranslationalPeriodicBC::handle_particle(Particle& p, const Surface& surf) const new_r = p.r() - translation_; new_surface = p.surface() > 0 ? i_surf_ + 1 : -(i_surf_ + 1); } else { - throw std::runtime_error("Called BoundaryCondition::handle_particle after " + throw std::runtime_error( + "Called BoundaryCondition::handle_particle after " "hitting a surface, but that surface is not recognized by the BC."); } @@ -153,9 +153,11 @@ RotationalPeriodicBC::RotationalPeriodicBC(int i_surf, int j_surf) } else if (const auto* ptr = dynamic_cast(&surf1)) { surf1_is_xyplane = false; } else { - throw std::invalid_argument(fmt::format("Surface {} is an invalid type for " + throw std::invalid_argument(fmt::format( + "Surface {} is an invalid type for " "rotational periodic BCs. Only x-planes, y-planes, or general planes " - "(that are perpendicular to z) are supported for these BCs.", surf1.id_)); + "(that are perpendicular to z) are supported for these BCs.", + surf1.id_)); } // Check the type of the second surface @@ -167,9 +169,11 @@ RotationalPeriodicBC::RotationalPeriodicBC(int i_surf, int j_surf) } else if (const auto* ptr = dynamic_cast(&surf2)) { surf2_is_xyplane = false; } else { - throw std::invalid_argument(fmt::format("Surface {} is an invalid type for " + throw std::invalid_argument(fmt::format( + "Surface {} is an invalid type for " "rotational periodic BCs. Only x-planes, y-planes, or general planes " - "(that are perpendicular to z) are supported for these BCs.", surf2.id_)); + "(that are perpendicular to z) are supported for these BCs.", + surf2.id_)); } // Compute the surface normal vectors and make sure they are perpendicular @@ -177,26 +181,34 @@ RotationalPeriodicBC::RotationalPeriodicBC(int i_surf, int j_surf) Direction norm1 = surf1.normal({0, 0, 0}); Direction norm2 = surf2.normal({0, 0, 0}); if (std::abs(norm1.z) > FP_PRECISION) { - throw std::invalid_argument(fmt::format("Rotational periodic BCs are only " + throw std::invalid_argument(fmt::format( + "Rotational periodic BCs are only " "supported for rotations about the z-axis, but surface {} is not " - "perpendicular to the z-axis.", surf1.id_)); + "perpendicular to the z-axis.", + surf1.id_)); } if (std::abs(norm2.z) > FP_PRECISION) { - throw std::invalid_argument(fmt::format("Rotational periodic BCs are only " + throw std::invalid_argument(fmt::format( + "Rotational periodic BCs are only " "supported for rotations about the z-axis, but surface {} is not " - "perpendicular to the z-axis.", surf2.id_)); + "perpendicular to the z-axis.", + surf2.id_)); } // Make sure both surfaces intersect the origin if (std::abs(surf1.evaluate({0, 0, 0})) > FP_COINCIDENT) { - throw std::invalid_argument(fmt::format("Rotational periodic BCs are only " + throw std::invalid_argument(fmt::format( + "Rotational periodic BCs are only " "supported for rotations about the origin, but surface {} does not " - "intersect the origin.", surf1.id_)); + "intersect the origin.", + surf1.id_)); } if (std::abs(surf2.evaluate({0, 0, 0})) > FP_COINCIDENT) { - throw std::invalid_argument(fmt::format("Rotational periodic BCs are only " + throw std::invalid_argument(fmt::format( + "Rotational periodic BCs are only " "supported for rotations about the origin, but surface {} does not " - "intersect the origin.", surf2.id_)); + "intersect the origin.", + surf2.id_)); } // Compute the BC rotation angle. Here it is assumed that both surface @@ -212,14 +224,15 @@ RotationalPeriodicBC::RotationalPeriodicBC(int i_surf, int j_surf) // Warn the user if the angle does not evenly divide a circle double rem = std::abs(std::remainder((2 * PI / angle_), 1.0)); if (rem > FP_REL_PRECISION && rem < 1 - FP_REL_PRECISION) { - warning(fmt::format("Rotational periodic BC specified with a rotation " + warning(fmt::format( + "Rotational periodic BC specified with a rotation " "angle of {} degrees which does not evenly divide 360 degrees.", angle_ * 180 / PI)); } } -void -RotationalPeriodicBC::handle_particle(Particle& p, const Surface& surf) const +void RotationalPeriodicBC::handle_particle( + Particle& p, const Surface& surf) const { // TODO: off-by-one on surface indices throughout this function. int i_particle_surf = std::abs(p.surface()) - 1; @@ -236,7 +249,8 @@ RotationalPeriodicBC::handle_particle(Particle& p, const Surface& surf) const theta = -angle_; new_surface = p.surface() > 0 ? -(i_surf_ + 1) : i_surf_ + 1; } else { - throw std::runtime_error("Called BoundaryCondition::handle_particle after " + throw std::runtime_error( + "Called BoundaryCondition::handle_particle after " "hitting a surface, but that surface is not recognized by the BC."); } @@ -246,13 +260,9 @@ RotationalPeriodicBC::handle_particle(Particle& p, const Surface& surf) const double cos_theta = std::cos(theta); double sin_theta = std::sin(theta); Position new_r = { - cos_theta*r.x - sin_theta*r.y, - sin_theta*r.x + cos_theta*r.y, - r.z}; + cos_theta * r.x - sin_theta * r.y, sin_theta * r.x + cos_theta * r.y, r.z}; Direction new_u = { - cos_theta*u.x - sin_theta*u.y, - sin_theta*u.x + cos_theta*u.y, - u.z}; + cos_theta * u.x - sin_theta * u.y, sin_theta * u.x + cos_theta * u.y, u.z}; // Pass the new location, direction, and surface to the particle. p.cross_periodic_bc(surf, new_r, new_u, new_surface); diff --git a/src/bremsstrahlung.cpp b/src/bremsstrahlung.cpp index 099e0ca0c..d22d6392a 100644 --- a/src/bremsstrahlung.cpp +++ b/src/bremsstrahlung.cpp @@ -47,30 +47,32 @@ void thick_target_bremsstrahlung(Particle& p, double* E_lost) auto n_e = data::ttb_e_grid.size(); // Find the lower bounding index of the incident electron energy - size_t j = lower_bound_index(data::ttb_e_grid.cbegin(), - data::ttb_e_grid.cend(), e); - if (j == n_e - 1) --j; + size_t j = + lower_bound_index(data::ttb_e_grid.cbegin(), data::ttb_e_grid.cend(), e); + if (j == n_e - 1) + --j; // Get the interpolation bounds double e_l = data::ttb_e_grid(j); - double e_r = data::ttb_e_grid(j+1); + double e_r = data::ttb_e_grid(j + 1); double y_l = mat->yield(j); - double y_r = mat->yield(j+1); + double y_r = mat->yield(j + 1); // Calculate the interpolation weight w_j+1 of the bremsstrahlung energy PDF // interpolated in log energy, which can be interpreted as the probability // of index j+1 - double f = (e - e_l)/(e_r - e_l); + double f = (e - e_l) / (e_r - e_l); // Get the photon number yield for the given energy using linear // interpolation on a log-log scale - double y = std::exp(y_l + (y_r - y_l)*f); + double y = std::exp(y_l + (y_r - y_l) * f); // Sample number of secondary bremsstrahlung photons int n = y + prn(p.current_seed()); *E_lost = 0.0; - if (n == 0) return; + if (n == 0) + return; // Sample index of the tabulated PDF in the energy grid, j or j+1 double c_max; @@ -83,8 +85,8 @@ void thick_target_bremsstrahlung(Particle& p, double* E_lost) double p_l = mat->pdf(i_e, i_e - 1); double p_r = mat->pdf(i_e, i_e); double c_l = mat->cdf(i_e, i_e - 1); - double a = std::log(p_r/p_l)/(e_r - e_l) + 1.0; - c_max = c_l + std::exp(e_l)*p_l/a*(std::exp(a*(e - e_l)) - 1.0); + double a = std::log(p_r / p_l) / (e_r - e_l) + 1.0; + c_max = c_l + std::exp(e_l) * p_l / a * (std::exp(a * (e - e_l)) - 1.0); } else { i_e = j; @@ -96,7 +98,7 @@ void thick_target_bremsstrahlung(Particle& p, double* E_lost) for (int i = 0; i < n; ++i) { // Generate a random number r and determine the index i for which // cdf(i) <= r*cdf,max <= cdf(i+1) - double c = prn(p.current_seed())*c_max; + double c = prn(p.current_seed()) * c_max; int i_w = lower_bound_index(&mat->cdf(i_e, 0), &mat->cdf(i_e, 0) + i_e, c); // Sample the photon energy @@ -105,8 +107,9 @@ void thick_target_bremsstrahlung(Particle& p, double* E_lost) double p_l = mat->pdf(i_e, i_w); double p_r = mat->pdf(i_e, i_w + 1); double c_l = mat->cdf(i_e, i_w); - double a = std::log(p_r/p_l)/(w_r - w_l) + 1.0; - double w = std::exp(w_l)*std::pow(a*(c - c_l)/(std::exp(w_l)*p_l) + 1.0, 1.0/a); + double a = std::log(p_r / p_l) / (w_r - w_l) + 1.0; + double w = std::exp(w_l) * + std::pow(a * (c - c_l) / (std::exp(w_l) * p_l) + 1.0, 1.0 / a); if (w > settings::energy_cutoff[photon]) { // Create secondary photon diff --git a/src/cell.cpp b/src/cell.cpp index 97f64e3a1..a88e38541 100644 --- a/src/cell.cpp +++ b/src/cell.cpp @@ -31,11 +31,11 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map cell_map; - vector> cells; +std::unordered_map cell_map; +vector> cells; - std::unordered_map universe_map; - vector> universes; +std::unordered_map universe_map; +vector> universes; } // namespace model //============================================================================== @@ -54,7 +54,7 @@ vector tokenize(const std::string region_spec) } // Parse all halfspaces and operators except for intersection (whitespace). - for (int i = 0; i < region_spec.size(); ) { + for (int i = 0; i < region_spec.size();) { if (region_spec[i] == '(') { tokens.push_back(OP_LEFT_PAREN); i++; @@ -71,34 +71,37 @@ vector tokenize(const std::string region_spec) tokens.push_back(OP_COMPLEMENT); i++; - } else if (region_spec[i] == '-' || region_spec[i] == '+' - || std::isdigit(region_spec[i])) { + } else if (region_spec[i] == '-' || region_spec[i] == '+' || + std::isdigit(region_spec[i])) { // This is the start of a halfspace specification. Iterate j until we // find the end, then push-back everything between i and j. int j = i + 1; - while (j < region_spec.size() && std::isdigit(region_spec[j])) {j++;} - tokens.push_back(std::stoi(region_spec.substr(i, j-i))); + while (j < region_spec.size() && std::isdigit(region_spec[j])) { + j++; + } + tokens.push_back(std::stoi(region_spec.substr(i, j - i))); i = j; } else if (std::isspace(region_spec[i])) { i++; } else { - auto err_msg = fmt::format( - "Region specification contains invalid character, \"{}\"", region_spec[i]); + auto err_msg = + fmt::format("Region specification contains invalid character, \"{}\"", + region_spec[i]); fatal_error(err_msg); } } // Add in intersection operators where a missing operator is needed. int i = 0; - while (i < tokens.size()-1) { + while (i < tokens.size() - 1) { bool left_compat {(tokens[i] < OP_UNION) || (tokens[i] == OP_RIGHT_PAREN)}; - bool right_compat {(tokens[i+1] < OP_UNION) - || (tokens[i+1] == OP_LEFT_PAREN) - || (tokens[i+1] == OP_COMPLEMENT)}; + bool right_compat {(tokens[i + 1] < OP_UNION) || + (tokens[i + 1] == OP_LEFT_PAREN) || + (tokens[i + 1] == OP_COMPLEMENT)}; if (left_compat && right_compat) { - tokens.insert(tokens.begin()+i+1, OP_INTERSECTION); + tokens.insert(tokens.begin() + i + 1, OP_INTERSECTION); } i++; } @@ -126,9 +129,8 @@ vector generate_rpn(int32_t cell_id, vector infix) while (stack.size() > 0) { int32_t op = stack.back(); - if (op < OP_RIGHT_PAREN && - ((token == OP_COMPLEMENT && token < op) || - (token != OP_COMPLEMENT && token <= op))) { + if (op < OP_RIGHT_PAREN && ((token == OP_COMPLEMENT && token < op) || + (token != OP_COMPLEMENT && token <= op))) { // While there is an operator, op, on top of the stack, if the token // is left-associative and its precedence is less than or equal to // that of op or if the token is right-associative and its precedence @@ -156,7 +158,8 @@ vector generate_rpn(int32_t cell_id, vector infix) // means there are mismatched parentheses. if (it == stack.rend()) { fatal_error(fmt::format( - "Mismatched parentheses in region specification for cell {}", cell_id)); + "Mismatched parentheses in region specification for cell {}", + cell_id)); } rpn.push_back(stack.back()); stack.pop_back(); @@ -187,8 +190,7 @@ vector generate_rpn(int32_t cell_id, vector infix) // Universe implementation //============================================================================== -void -Universe::to_hdf5(hid_t universes_group) const +void Universe::to_hdf5(hid_t universes_group) const { // Create a group for this universe. auto group = create_group(universes_group, fmt::format("universe {}", id_)); @@ -199,39 +201,39 @@ Universe::to_hdf5(hid_t universes_group) const // Write the contained cells. if (cells_.size() > 0) { vector cell_ids; - for (auto i_cell : cells_) cell_ids.push_back(model::cells[i_cell]->id_); + for (auto i_cell : cells_) + cell_ids.push_back(model::cells[i_cell]->id_); write_dataset(group, "cells", cell_ids); } close_group(group); } -bool -Universe::find_cell(Particle& p) const { +bool Universe::find_cell(Particle& p) const +{ const auto& cells { - !partitioner_ - ? cells_ - : partitioner_->get_cells(p.r_local(), p.u_local()) - }; + !partitioner_ ? cells_ : partitioner_->get_cells(p.r_local(), p.u_local())}; for (auto it = cells.begin(); it != cells.end(); it++) { int32_t i_cell = *it; - int32_t i_univ = p.coord(p.n_coord()-1).universe; - if (model::cells[i_cell]->universe_ != i_univ) continue; + int32_t i_univ = p.coord(p.n_coord() - 1).universe; + if (model::cells[i_cell]->universe_ != i_univ) + continue; // Check if this cell contains the particle; Position r {p.r_local()}; Direction u {p.u_local()}; auto surf = p.surface(); if (model::cells[i_cell]->contains(r, u, surf)) { - p.coord(p.n_coord()-1).cell = i_cell; + p.coord(p.n_coord() - 1).cell = i_cell; return true; } } return false; } -BoundingBox Universe::bounding_box() const { +BoundingBox Universe::bounding_box() const +{ BoundingBox bbox = {INFTY, -INFTY, INFTY, -INFTY, INFTY, -INFTY}; if (cells_.size() == 0) { return {}; @@ -248,8 +250,8 @@ BoundingBox Universe::bounding_box() const { // Cell implementation //============================================================================== -void -Cell::set_rotation(const vector& rot) { +void Cell::set_rotation(const vector& rot) +{ if (fill_ == C_NONE) { fatal_error(fmt::format("Cannot apply a rotation to cell {}" " because it is not filled with another universe", @@ -290,40 +292,37 @@ Cell::set_rotation(const vector& rot) { } } -double -Cell::temperature(int32_t instance) const +double Cell::temperature(int32_t instance) const { if (sqrtkT_.size() < 1) { - throw std::runtime_error{"Cell temperature has not yet been set."}; + throw std::runtime_error {"Cell temperature has not yet been set."}; } if (instance >= 0) { - double sqrtkT = sqrtkT_.size() == 1 ? - sqrtkT_.at(0) : - sqrtkT_.at(instance); + double sqrtkT = sqrtkT_.size() == 1 ? sqrtkT_.at(0) : sqrtkT_.at(instance); return sqrtkT * sqrtkT / K_BOLTZMANN; } else { return sqrtkT_[0] * sqrtkT_[0] / K_BOLTZMANN; } } -void -Cell::set_temperature(double T, int32_t instance, bool set_contained) +void Cell::set_temperature(double T, int32_t instance, bool set_contained) { if (settings::temperature_method == TemperatureMethod::INTERPOLATION) { if (T < data::temperature_min) { - throw std::runtime_error{"Temperature is below minimum temperature at " - "which data is available."}; + throw std::runtime_error {"Temperature is below minimum temperature at " + "which data is available."}; } else if (T > data::temperature_max) { - throw std::runtime_error{"Temperature is above maximum temperature at " - "which data is available."}; + throw std::runtime_error {"Temperature is above maximum temperature at " + "which data is available."}; } } if (type_ == Fill::MATERIAL) { if (instance >= 0) { // If temperature vector is not big enough, resize it first - if (sqrtkT_.size() != n_instances_) sqrtkT_.resize(n_instances_, sqrtkT_[0]); + if (sqrtkT_.size() != n_instances_) + sqrtkT_.resize(n_instances_, sqrtkT_[0]); // Set temperature for the corresponding instance sqrtkT_.at(instance) = std::sqrt(K_BOLTZMANN * T); @@ -335,15 +334,17 @@ Cell::set_temperature(double T, int32_t instance, bool set_contained) } } else { if (!set_contained) { - throw std::runtime_error{fmt::format("Attempted to set the temperature of cell {} " - "which is not filled by a material.", id_)}; + throw std::runtime_error { + fmt::format("Attempted to set the temperature of cell {} " + "which is not filled by a material.", + id_)}; } auto contained_cells = this->get_contained_cells(); for (const auto& entry : contained_cells) { auto& cell = model::cells[entry.first]; Expects(cell->type_ == Fill::MATERIAL); - auto& instances = entry.second; + auto& instances = entry.second; for (auto instance : instances) { cell->set_temperature(T, instance); } @@ -377,7 +378,8 @@ void Cell::import_properties_hdf5(hid_t group) auto n_temps = temps.size(); if (n_temps > 1 && n_temps != n_instances_) { throw std::runtime_error(fmt::format( - "Number of temperatures for cell {} doesn't match number of instances", id_)); + "Number of temperatures for cell {} doesn't match number of instances", + id_)); } // Modify temperatures for the cell @@ -390,9 +392,8 @@ void Cell::import_properties_hdf5(hid_t group) close_group(cell_group); } - -void -Cell::to_hdf5(hid_t cell_group) const { +void Cell::to_hdf5(hid_t cell_group) const +{ // Create a group for this cell. auto group = create_group(cell_group, fmt::format("cell {}", id_)); @@ -455,7 +456,8 @@ Cell::to_hdf5(hid_t cell_group) const { //============================================================================== // default constructor -CSGCell::CSGCell() { +CSGCell::CSGCell() +{ geom_type_ = GeometryType::CSG; } @@ -483,19 +485,21 @@ CSGCell::CSGCell(pugi::xml_node cell_node) bool fill_present = check_for_node(cell_node, "fill"); bool material_present = check_for_node(cell_node, "material"); if (!(fill_present || material_present)) { - fatal_error(fmt::format( - "Neither material nor fill was specified for cell {}", id_)); + fatal_error( + fmt::format("Neither material nor fill was specified for cell {}", id_)); } if (fill_present && material_present) { fatal_error(fmt::format("Cell {} has both a material and a fill specified; " - "only one can be specified per cell", id_)); + "only one can be specified per cell", + id_)); } if (fill_present) { fill_ = std::stoi(get_node_value(cell_node, "fill")); if (fill_ == universe_) { fatal_error(fmt::format("Cell {} is filled with the same universe that" - "it is contained in.", id_)); + "it is contained in.", + id_)); } } else { fill_ = C_NONE; @@ -517,8 +521,8 @@ CSGCell::CSGCell(pugi::xml_node cell_node) } } } else { - fatal_error(fmt::format("An empty material element was specified for cell {}", - id_)); + fatal_error(fmt::format( + "An empty material element was specified for cell {}", id_)); } } @@ -531,7 +535,8 @@ CSGCell::CSGCell(pugi::xml_node cell_node) if (material_.size() == 0) { fatal_error(fmt::format( "Cell {} was specified with a temperature but no material. Temperature" - "specification is only valid for cells filled with a material.", id_)); + "specification is only valid for cells filled with a material.", + id_)); } // Make sure all temperatures are non-negative. @@ -563,8 +568,9 @@ CSGCell::CSGCell(pugi::xml_node cell_node) if (r < OP_UNION) { const auto& it {model::surface_map.find(abs(r))}; if (it == model::surface_map.end()) { - throw std::runtime_error{"Invalid surface ID " + std::to_string(abs(r)) - + " specified in region for cell " + std::to_string(id_) + "."}; + throw std::runtime_error { + "Invalid surface ID " + std::to_string(abs(r)) + + " specified in region for cell " + std::to_string(id_) + "."}; } r = (r > 0) ? it->second + 1 : -(it->second + 1); } @@ -601,13 +607,14 @@ CSGCell::CSGCell(pugi::xml_node cell_node) if (check_for_node(cell_node, "translation")) { if (fill_ == C_NONE) { fatal_error(fmt::format("Cannot apply a translation to cell {}" - " because it is not filled with another universe", id_)); + " because it is not filled with another universe", + id_)); } auto xyz {get_node_array(cell_node, "translation")}; if (xyz.size() != 3) { - fatal_error(fmt::format( - "Non-3D translation vector applied to cell {}", id_)); + fatal_error( + fmt::format("Non-3D translation vector applied to cell {}", id_)); } translation_ = xyz; } @@ -621,8 +628,7 @@ CSGCell::CSGCell(pugi::xml_node cell_node) //============================================================================== -bool -CSGCell::contains(Position r, Direction u, int32_t on_surface) const +bool CSGCell::contains(Position r, Direction u, int32_t on_surface) const { if (simple_) { return contains_simple(r, u, on_surface); @@ -633,24 +639,25 @@ CSGCell::contains(Position r, Direction u, int32_t on_surface) const //============================================================================== -std::pair -CSGCell::distance(Position r, Direction u, int32_t on_surface, Particle* p) const +std::pair CSGCell::distance( + Position r, Direction u, int32_t on_surface, Particle* p) const { double min_dist {INFTY}; int32_t i_surf {std::numeric_limits::max()}; for (int32_t token : rpn_) { // Ignore this token if it corresponds to an operator rather than a region. - if (token >= OP_UNION) continue; + if (token >= OP_UNION) + continue; // Calculate the distance to this surface. // Note the off-by-one indexing bool coincident {std::abs(token) == std::abs(on_surface)}; - double d {model::surfaces[abs(token)-1]->distance(r, u, coincident)}; + double d {model::surfaces[abs(token) - 1]->distance(r, u, coincident)}; // Check if this distance is the new minimum. if (d < min_dist) { - if (min_dist - d >= FP_PRECISION*min_dist) { + if (min_dist - d >= FP_PRECISION * min_dist) { min_dist = d; i_surf = -token; } @@ -662,8 +669,7 @@ CSGCell::distance(Position r, Direction u, int32_t on_surface, Particle* p) cons //============================================================================== -void -CSGCell::to_hdf5_inner(hid_t group_id) const +void CSGCell::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "geom_type", "csg", false); @@ -683,19 +689,19 @@ CSGCell::to_hdf5_inner(hid_t group_id) const region_spec << " |"; } else { // Note the off-by-one indexing - auto surf_id = model::surfaces[abs(token)-1]->id_; + auto surf_id = model::surfaces[abs(token) - 1]->id_; region_spec << " " << ((token > 0) ? surf_id : -surf_id); } } write_string(group_id, "region", region_spec.str(), false); } - } -BoundingBox CSGCell::bounding_box_simple() const { +BoundingBox CSGCell::bounding_box_simple() const +{ BoundingBox bbox; for (int32_t token : rpn_) { - bbox &= model::surfaces[abs(token)-1]->bounding_box(token > 0); + bbox &= model::surfaces[abs(token) - 1]->bounding_box(token > 0); } return bbox; } @@ -704,9 +710,13 @@ void CSGCell::apply_demorgan( vector::iterator start, vector::iterator stop) { while (start < stop) { - if (*start < OP_UNION) { *start *= -1; } - else if (*start == OP_UNION) { *start = OP_INTERSECTION; } - else if (*start == OP_INTERSECTION) { *start = OP_UNION; } + if (*start < OP_UNION) { + *start *= -1; + } else if (*start == OP_UNION) { + *start = OP_INTERSECTION; + } else if (*start == OP_INTERSECTION) { + *start = OP_UNION; + } start++; } } @@ -725,7 +735,7 @@ vector::iterator CSGCell::find_left_parenthesis( // decrement parenthesis level if there are two adjacent surfaces if (one < OP_UNION && two < OP_UNION) { parenthesis_level--; - // increment if there are two adjacent operators + // increment if there are two adjacent operators } else if (one >= OP_UNION && two >= OP_UNION) { parenthesis_level++; } @@ -787,14 +797,14 @@ BoundingBox CSGCell::bounding_box_complex(vector rpn) return stack.front(); } -BoundingBox CSGCell::bounding_box() const { +BoundingBox CSGCell::bounding_box() const +{ return simple_ ? bounding_box_simple() : bounding_box_complex(rpn_); } //============================================================================== -bool -CSGCell::contains_simple(Position r, Direction u, int32_t on_surface) const +bool CSGCell::contains_simple(Position r, Direction u, int32_t on_surface) const { for (int32_t token : rpn_) { // Assume that no tokens are operators. Evaluate the sense of particle with @@ -806,8 +816,10 @@ CSGCell::contains_simple(Position r, Direction u, int32_t on_surface) const return false; } else { // Note the off-by-one indexing - bool sense = model::surfaces[abs(token)-1]->sense(r, u); - if (sense != (token > 0)) {return false;} + bool sense = model::surfaces[abs(token) - 1]->sense(r, u); + if (sense != (token > 0)) { + return false; + } } } return true; @@ -815,8 +827,8 @@ CSGCell::contains_simple(Position r, Direction u, int32_t on_surface) const //============================================================================== -bool -CSGCell::contains_complex(Position r, Direction u, int32_t on_surface) const +bool CSGCell::contains_complex( + Position r, Direction u, int32_t on_surface) const { // Make a stack of booleans. We don't know how big it needs to be, but we do // know that rpn.size() is an upper-bound. @@ -828,11 +840,11 @@ CSGCell::contains_complex(Position r, Direction u, int32_t on_surface) const // the last two items on the stack. If the token is a unary operator // (complement), apply it to the last item on the stack. if (token == OP_UNION) { - stack[i_stack-1] = stack[i_stack-1] || stack[i_stack]; - i_stack --; + stack[i_stack - 1] = stack[i_stack - 1] || stack[i_stack]; + i_stack--; } else if (token == OP_INTERSECTION) { - stack[i_stack-1] = stack[i_stack-1] && stack[i_stack]; - i_stack --; + stack[i_stack - 1] = stack[i_stack - 1] && stack[i_stack]; + i_stack--; } else if (token == OP_COMPLEMENT) { stack[i_stack] = !stack[i_stack]; } else { @@ -840,14 +852,14 @@ CSGCell::contains_complex(Position r, Direction u, int32_t on_surface) const // respect to the surface and see if the token matches the sense. If the // particle's surface attribute is set and matches the token, that // overrides the determination based on sense(). - i_stack ++; + i_stack++; if (token == on_surface) { stack[i_stack] = true; } else if (-token == on_surface) { stack[i_stack] = false; } else { // Note the off-by-one indexing - bool sense = model::surfaces[abs(token)-1]->sense(r, u); + bool sense = model::surfaces[abs(token) - 1]->sense(r, u); stack[i_stack] = (sense == (token > 0)); } } @@ -908,7 +920,8 @@ UniversePartitioner::UniversePartitioner(const Universe& univ) // It is difficult to determine the bounds of a complex cell, so add complex // cells to all partitions. if (!model::cells[i_cell]->simple_) { - for (auto& p : partitions_) p.push_back(i_cell); + for (auto& p : partitions_) + p.push_back(i_cell); continue; } @@ -933,7 +946,8 @@ UniversePartitioner::UniversePartitioner(const Universe& univ) // If there are no bounding z-planes, add this cell to all partitions. if (lower_token == 0) { - for (auto& p : partitions_) p.push_back(i_cell); + for (auto& p : partitions_) + p.push_back(i_cell); continue; } @@ -989,7 +1003,7 @@ const vector& UniversePartitioner::get_cells( left = middle + 1; middle = right_leaf; } else { - return partitions_[middle+1]; + return partitions_[middle + 1]; } } else { @@ -998,7 +1012,7 @@ const vector& UniversePartitioner::get_cells( // side of this surface. int left_leaf = left + (middle - left) / 2; if (left_leaf != middle) { - right = middle-1; + right = middle - 1; middle = left_leaf; } else { return partitions_[middle]; @@ -1015,7 +1029,9 @@ void read_cells(pugi::xml_node node) { // Count the number of cells. int n_cells = 0; - for (pugi::xml_node cell_node: node.children("cell")) {n_cells++;} + for (pugi::xml_node cell_node : node.children("cell")) { + n_cells++; + } // Loop over XML cell elements and populate the array. model::cells.reserve(n_cells); @@ -1030,7 +1046,8 @@ void read_cells(pugi::xml_node node) if (search == model::cell_map.end()) { model::cell_map[id] = i; } else { - fatal_error(fmt::format("Two or more cells use the same unique ID: {}", id)); + fatal_error( + fmt::format("Two or more cells use the same unique ID: {}", id)); } } @@ -1065,8 +1082,8 @@ void read_cells(pugi::xml_node node) // C-API functions //============================================================================== -extern "C" int -openmc_cell_get_fill(int32_t index, int* type, int32_t** indices, int32_t* n) +extern "C" int openmc_cell_get_fill( + int32_t index, int* type, int32_t** indices, int32_t* n) { if (index >= 0 && index < model::cells.size()) { Cell& c {*model::cells[index]}; @@ -1085,9 +1102,8 @@ openmc_cell_get_fill(int32_t index, int* type, int32_t** indices, int32_t* n) return 0; } -extern "C" int -openmc_cell_set_fill(int32_t index, int type, int32_t n, - const int32_t* indices) +extern "C" int openmc_cell_set_fill( + int32_t index, int type, int32_t n, const int32_t* indices) { Fill filltype = static_cast(type); if (index >= 0 && index < model::cells.size()) { @@ -1119,8 +1135,8 @@ openmc_cell_set_fill(int32_t index, int type, int32_t n, return 0; } -extern "C" int -openmc_cell_set_temperature(int32_t index, double T, const int32_t* instance, bool set_contained) +extern "C" int openmc_cell_set_temperature( + int32_t index, double T, const int32_t* instance, bool set_contained) { if (index < 0 || index >= model::cells.size()) { strcpy(openmc_err_msg, "Index in cells array is out of bounds."); @@ -1137,8 +1153,8 @@ openmc_cell_set_temperature(int32_t index, double T, const int32_t* instance, bo return 0; } -extern "C" int -openmc_cell_get_temperature(int32_t index, const int32_t* instance, double* T) +extern "C" int openmc_cell_get_temperature( + int32_t index, const int32_t* instance, double* T) { if (index < 0 || index >= model::cells.size()) { strcpy(openmc_err_msg, "Index in cells array is out of bounds."); @@ -1156,8 +1172,9 @@ openmc_cell_get_temperature(int32_t index, const int32_t* instance, double* T) } //! Get the bounding box of a cell -extern "C" int -openmc_cell_bounding_box(const int32_t index, double* llc, double* urc) { +extern "C" int openmc_cell_bounding_box( + const int32_t index, double* llc, double* urc) +{ BoundingBox bbox; @@ -1178,8 +1195,8 @@ openmc_cell_bounding_box(const int32_t index, double* llc, double* urc) { } //! Get the name of a cell -extern "C" int -openmc_cell_get_name(int32_t index, const char** name) { +extern "C" int openmc_cell_get_name(int32_t index, const char** name) +{ if (index < 0 || index >= model::cells.size()) { set_errmsg("Index in cells array is out of bounds."); return OPENMC_E_OUT_OF_BOUNDS; @@ -1191,8 +1208,8 @@ openmc_cell_get_name(int32_t index, const char** name) { } //! Set the name of a cell -extern "C" int -openmc_cell_set_name(int32_t index, const char* name) { +extern "C" int openmc_cell_set_name(int32_t index, const char* name) +{ if (index < 0 || index >= model::cells.size()) { set_errmsg("Index in cells array is out of bounds."); return OPENMC_E_OUT_OF_BOUNDS; @@ -1232,24 +1249,25 @@ void Cell::get_contained_cells_inner( instance += cell->offset_[distribcell_index_]; } else if (cell->type_ == Fill::LATTICE) { auto& lattice = model::lattices[cell->fill_]; - instance += lattice->offset(this->distribcell_index_, parent_cell.lattice_index); + instance += lattice->offset( + this->distribcell_index_, parent_cell.lattice_index); } } } // add entry to contained cells contained_cells[model::cell_map[id_]].push_back(instance); - // filled with universe, add the containing cell to the parent cells - // and recurse + // filled with universe, add the containing cell to the parent cells + // and recurse } else if (type_ == Fill::UNIVERSE) { parent_cells.push_back({model::cell_map[id_], -1}); auto& univ = model::universes[fill_]; - for(auto cell_index : univ->cells_) { + for (auto cell_index : univ->cells_) { auto& cell = model::cells[cell_index]; cell->get_contained_cells_inner(contained_cells, parent_cells); } parent_cells.pop_back(); - // filled with a lattice, visit each universe in the lattice - // with a recursive call to collect the cell instances + // filled with a lattice, visit each universe in the lattice + // with a recursive call to collect the cell instances } else if (type_ == Fill::LATTICE) { auto& lattice = model::lattices[fill_]; for (auto i = lattice->begin(); i != lattice->end(); ++i) { @@ -1265,8 +1283,7 @@ void Cell::get_contained_cells_inner( } //! Return the index in the cells array of a cell with a given ID -extern "C" int -openmc_get_cell_index(int32_t id, int32_t* index) +extern "C" int openmc_get_cell_index(int32_t id, int32_t* index) { auto it = model::cell_map.find(id); if (it != model::cell_map.end()) { @@ -1279,8 +1296,7 @@ openmc_get_cell_index(int32_t id, int32_t* index) } //! Return the ID of a cell -extern "C" int -openmc_cell_get_id(int32_t index, int32_t* id) +extern "C" int openmc_cell_get_id(int32_t index, int32_t* id) { if (index >= 0 && index < model::cells.size()) { *id = model::cells[index]->id_; @@ -1292,8 +1308,7 @@ openmc_cell_get_id(int32_t index, int32_t* id) } //! Set the ID of a cell -extern "C" int -openmc_cell_set_id(int32_t index, int32_t id) +extern "C" int openmc_cell_set_id(int32_t index, int32_t id) { if (index >= 0 && index < model::cells.size()) { model::cells[index]->id_ = id; @@ -1327,7 +1342,7 @@ extern "C" int openmc_cell_set_translation(int32_t index, const double xyz[]) if (model::cells[index]->fill_ == C_NONE) { set_errmsg(fmt::format("Cannot apply a translation to cell {}" " because it is not filled with another universe", - index)); + index)); return OPENMC_E_GEOMETRY; } model::cells[index]->translation_ = Position(xyz); @@ -1353,8 +1368,8 @@ extern "C" int openmc_cell_get_rotation(int32_t index, double rot[], size_t* n) } //! Set the flattened rotation matrix of a cell -extern "C" int openmc_cell_set_rotation(int32_t index, const double rot[], - size_t rot_len) +extern "C" int openmc_cell_set_rotation( + int32_t index, const double rot[], size_t rot_len) { if (index >= 0 && index < model::cells.size()) { if (model::cells[index]->fill_ == C_NONE) { @@ -1373,8 +1388,8 @@ extern "C" int openmc_cell_set_rotation(int32_t index, const double rot[], } //! Get the number of instances of the requested cell -extern "C" int -openmc_cell_get_num_instances(int32_t index, int32_t* num_instances) +extern "C" int openmc_cell_get_num_instances( + int32_t index, int32_t* num_instances) { if (index < 0 || index >= model::cells.size()) { set_errmsg("Index in cells array is out of bounds."); @@ -1385,17 +1400,22 @@ openmc_cell_get_num_instances(int32_t index, int32_t* num_instances) } //! Extend the cells array by n elements -extern "C" int -openmc_extend_cells(int32_t n, int32_t* index_start, int32_t* index_end) +extern "C" int openmc_extend_cells( + int32_t n, int32_t* index_start, int32_t* index_end) { - if (index_start) *index_start = model::cells.size(); - if (index_end) *index_end = model::cells.size() + n - 1; + if (index_start) + *index_start = model::cells.size(); + if (index_end) + *index_end = model::cells.size() + n - 1; for (int32_t i = 0; i < n; i++) { model::cells.push_back(make_unique()); } return 0; } -extern "C" int cells_size() { return model::cells.size(); } +extern "C" int cells_size() +{ + return model::cells.size(); +} } // namespace openmc diff --git a/src/cmfd_solver.cpp b/src/cmfd_solver.cpp index 4efc515ad..943042f67 100644 --- a/src/cmfd_solver.cpp +++ b/src/cmfd_solver.cpp @@ -66,7 +66,7 @@ int get_cmfd_energy_bin(const double E) } else { // Iterate through energy grid to find matching bin for (int g = 0; g < cmfd::ng; g++) { - if (E >= cmfd::egrid[g] && E < cmfd::egrid[g+1]) { + if (E >= cmfd::egrid[g] && E < cmfd::egrid[g + 1]) { return g; } } @@ -79,7 +79,8 @@ int get_cmfd_energy_bin(const double E) // COUNT_BANK_SITES bins fission sites according to CMFD mesh and energy //============================================================================== -xt::xtensor count_bank_sites(xt::xtensor& bins, bool* outside) +xt::xtensor count_bank_sites( + xt::xtensor& bins, bool* outside) { // Determine shape of array for counts std::size_t cnt_size = cmfd::nx * cmfd::ny * cmfd::nz * cmfd::ng; @@ -106,22 +107,22 @@ xt::xtensor count_bank_sites(xt::xtensor& bins, bool* outside int energy_bin = get_cmfd_energy_bin(site.E); // add to appropriate bin - cnt(mesh_bin*cmfd::ng+energy_bin) += site.wgt; + cnt(mesh_bin * cmfd::ng + energy_bin) += site.wgt; // store bin index which is used again when updating weights - bins[i] = mesh_bin*cmfd::ng+energy_bin; + bins[i] = mesh_bin * cmfd::ng + energy_bin; } // Create copy of count data. Since ownership will be acquired by xtensor, // std::allocator must be used to avoid Valgrind mismatched free() / delete // warnings. int total = cnt.size(); - double* cnt_reduced = std::allocator{}.allocate(total); + double* cnt_reduced = std::allocator {}.allocate(total); #ifdef OPENMC_MPI // collect values from all processors - MPI_Reduce(cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, - mpi::intracomm); + MPI_Reduce( + cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm); // Check if there were sites outside the mesh for any processor MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm); @@ -142,8 +143,8 @@ xt::xtensor count_bank_sites(xt::xtensor& bins, bool* outside // OPENMC_CMFD_REWEIGHT performs reweighting of particles in source bank //============================================================================== -extern "C" -void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) +extern "C" void openmc_cmfd_reweight( + const bool feedback, const double* cmfd_src) { // Get size of source bank and cmfd_src auto bank_size = simulation::source_bank.size(); @@ -152,8 +153,8 @@ void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) // count bank sites for CMFD mesh, store bins in bank_bins for reweighting xt::xtensor bank_bins({bank_size}, 0); bool sites_outside; - xt::xtensor sourcecounts = count_bank_sites(bank_bins, - &sites_outside); + xt::xtensor sourcecounts = + count_bank_sites(bank_bins, &sites_outside); // Compute CMFD weightfactors xt::xtensor weightfactors = xt::xtensor({src_size}, 1.); @@ -162,7 +163,7 @@ void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) fatal_error("Source sites outside of the CMFD mesh"); } - double norm = xt::sum(sourcecounts)()/cmfd::norm; + double norm = xt::sum(sourcecounts)() / cmfd::norm; for (int i = 0; i < src_size; i++) { if (sourcecounts[i] > 0 && cmfd_src[i] > 0) { weightfactors[i] = cmfd_src[i] * norm / sourcecounts[i]; @@ -170,7 +171,8 @@ void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) } } - if (!feedback) return; + if (!feedback) + return; #ifdef OPENMC_MPI // Send weightfactors to all processors @@ -188,9 +190,8 @@ void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src) // OPENMC_INITIALIZE_MESH_EGRID sets the mesh and energy grid for CMFD reweight //============================================================================== -extern "C" -void openmc_initialize_mesh_egrid(const int meshtally_id, const int* cmfd_indices, - const double norm) +extern "C" void openmc_initialize_mesh_egrid( + const int meshtally_id, const int* cmfd_indices, const double norm) { // Make sure all CMFD memory is freed free_memory_cmfd(); @@ -242,9 +243,9 @@ void openmc_initialize_mesh_egrid(const int meshtally_id, const int* cmfd_indice void matrix_to_indices(int irow, int& g, int& i, int& j, int& k) { g = irow % cmfd::ng; - i = cmfd::indexmap(irow/cmfd::ng, 0); - j = cmfd::indexmap(irow/cmfd::ng, 1); - k = cmfd::indexmap(irow/cmfd::ng, 2); + i = cmfd::indexmap(irow / cmfd::ng, 0); + j = cmfd::indexmap(irow / cmfd::ng, 1); + k = cmfd::indexmap(irow / cmfd::ng, 2); } //============================================================================== @@ -254,7 +255,7 @@ void matrix_to_indices(int irow, int& g, int& i, int& j, int& k) int get_diagonal_index(int row) { - for (int j = cmfd::indptr[row]; j < cmfd::indptr[row+1]; j++) { + for (int j = cmfd::indptr[row]; j < cmfd::indptr[row + 1]; j++) { if (cmfd::indices[j] == row) return j; } @@ -272,7 +273,7 @@ void set_indexmap(const int* coremap) for (int z = 0; z < cmfd::nz; z++) { for (int y = 0; y < cmfd::ny; y++) { for (int x = 0; x < cmfd::nx; x++) { - int idx = (z*cmfd::ny*cmfd::nx) + (y*cmfd::nx) + x; + int idx = (z * cmfd::ny * cmfd::nx) + (y * cmfd::nx) + x; if (coremap[idx] != CMFD_NOACCEL) { int counter = coremap[idx]; cmfd::indexmap(counter, 0) = x; @@ -288,8 +289,8 @@ void set_indexmap(const int* coremap) // CMFD_LINSOLVER_1G solves a one group CMFD linear system //============================================================================== -int cmfd_linsolver_1g(const double* A_data, const double* b, double* x, - double tol) +int cmfd_linsolver_1g( + const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; @@ -304,14 +305,15 @@ int cmfd_linsolver_1g(const double* A_data, const double* b, double* x, // Perform red/black Gauss-Seidel iterations for (int irb = 0; irb < 2; irb++) { - // Loop around matrix rows - #pragma omp parallel for reduction (+:err) if(cmfd::use_all_threads) +// Loop around matrix rows +#pragma omp parallel for reduction(+ : err) if (cmfd::use_all_threads) for (int irow = 0; irow < cmfd::dim; irow++) { int g, i, j, k; matrix_to_indices(irow, g, i, j, k); // Filter out black cells - if ((i+j+k) % 2 != irb) continue; + if ((i + j + k) % 2 != irb) + continue; // Get index of diagonal for current row int didx = get_diagonal_index(irow); @@ -341,7 +343,7 @@ int cmfd_linsolver_1g(const double* A_data, const double* b, double* x, return igs; // Calculate new overrelaxation parameter - w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); + w = 1.0 / (1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met @@ -355,8 +357,8 @@ int cmfd_linsolver_1g(const double* A_data, const double* b, double* x, // CMFD_LINSOLVER_2G solves a two group CMFD linear system //============================================================================== -int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, - double tol) +int cmfd_linsolver_2g( + const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; @@ -371,38 +373,41 @@ int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, // Perform red/black Gauss-Seidel iterations for (int irb = 0; irb < 2; irb++) { - // Loop around matrix rows - #pragma omp parallel for reduction (+:err) if(cmfd::use_all_threads) - for (int irow = 0; irow < cmfd::dim; irow+=2) { +// Loop around matrix rows +#pragma omp parallel for reduction(+ : err) if (cmfd::use_all_threads) + for (int irow = 0; irow < cmfd::dim; irow += 2) { int g, i, j, k; matrix_to_indices(irow, g, i, j, k); // Filter out black cells - if ((i+j+k) % 2 != irb) continue; + if ((i + j + k) % 2 != irb) + continue; // Get index of diagonals for current row and next row int d1idx = get_diagonal_index(irow); - int d2idx = get_diagonal_index(irow+1); + int d2idx = get_diagonal_index(irow + 1); // Get block diagonal - double m11 = A_data[d1idx]; // group 1 diagonal - double m12 = A_data[d1idx + 1]; // group 1 right of diagonal (sorted by col) - double m21 = A_data[d2idx - 1]; // group 2 left of diagonal (sorted by col) - double m22 = A_data[d2idx]; // group 2 diagonal + double m11 = A_data[d1idx]; // group 1 diagonal + double m12 = + A_data[d1idx + 1]; // group 1 right of diagonal (sorted by col) + double m21 = + A_data[d2idx - 1]; // group 2 left of diagonal (sorted by col) + double m22 = A_data[d2idx]; // group 2 diagonal // Analytically invert the diagonal - double dm = m11*m22 - m12*m21; - double d11 = m22/dm; - double d12 = -m12/dm; - double d21 = -m21/dm; - double d22 = m11/dm; + double dm = m11 * m22 - m12 * m21; + double d11 = m22 / dm; + double d12 = -m12 / dm; + double d21 = -m21 / dm; + double d22 = m11 / dm; // Perform temporary sums, first do left of diag, then right of diag double tmp1 = 0.0; double tmp2 = 0.0; for (int icol = cmfd::indptr[irow]; icol < d1idx; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; - for (int icol = cmfd::indptr[irow+1]; icol < d2idx-1; icol++) + for (int icol = cmfd::indptr[irow + 1]; icol < d2idx - 1; icol++) tmp2 += A_data[icol] * x[cmfd::indices[icol]]; for (int icol = d1idx + 2; icol < cmfd::indptr[irow + 1]; icol++) tmp1 += A_data[icol] * x[cmfd::indices[icol]]; @@ -414,8 +419,8 @@ int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, tmp2 = b[irow + 1] - tmp2; // Solve for new x - double x1 = d11*tmp1 + d12*tmp2; - double x2 = d21*tmp1 + d22*tmp2; + double x1 = d11 * tmp1 + d12 * tmp2; + double x2 = d21 * tmp1 + d22 * tmp2; // Perform overrelaxation x[irow] = (1.0 - w) * x[irow] + w * x1; @@ -433,7 +438,7 @@ int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, return igs; // Calculate new overrelaxation parameter - w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); + w = 1.0 / (1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met @@ -447,8 +452,8 @@ int cmfd_linsolver_2g(const double* A_data, const double* b, double* x, // CMFD_LINSOLVER_NG solves a general CMFD linear system //============================================================================== -int cmfd_linsolver_ng(const double* A_data, const double* b, double* x, - double tol) +int cmfd_linsolver_ng( + const double* A_data, const double* b, double* x, double tol) { // Set overrelaxation parameter double w = 1.0; @@ -489,7 +494,7 @@ int cmfd_linsolver_ng(const double* A_data, const double* b, double* x, return igs; // Calculate new overrelaxation parameter - w = 1.0/(1.0 - 0.25 * cmfd::spectral * w); + w = 1.0 / (1.0 - 0.25 * cmfd::spectral * w); } // Throw error, as max iterations met @@ -504,11 +509,9 @@ int cmfd_linsolver_ng(const double* A_data, const double* b, double* x, // linear solver //============================================================================== -extern "C" -void openmc_initialize_linsolver(const int* indptr, int len_indptr, - const int* indices, int n_elements, int dim, - double spectral, const int* map, - bool use_all_threads) +extern "C" void openmc_initialize_linsolver(const int* indptr, int len_indptr, + const int* indices, int n_elements, int dim, double spectral, const int* map, + bool use_all_threads) { // Store elements of indptr for (int i = 0; i < len_indptr; i++) @@ -538,9 +541,8 @@ void openmc_initialize_linsolver(const int* indptr, int len_indptr, // equations //============================================================================== -extern "C" -int openmc_run_linsolver(const double* A_data, const double* b, double* x, - double tol) +extern "C" int openmc_run_linsolver( + const double* A_data, const double* b, double* x, double tol) { switch (cmfd::ng) { case 1: diff --git a/src/cross_sections.cpp b/src/cross_sections.cpp index 8124bd794..9156bdc90 100644 --- a/src/cross_sections.cpp +++ b/src/cross_sections.cpp @@ -4,8 +4,8 @@ #include "openmc/constants.h" #include "openmc/container_util.h" #include "openmc/error.h" -#include "openmc/geometry_aux.h" #include "openmc/file_utils.h" +#include "openmc/geometry_aux.h" #include "openmc/hdf5_interface.h" #include "openmc/material.h" #include "openmc/message_passing.h" @@ -15,10 +15,10 @@ #include "openmc/settings.h" #include "openmc/simulation.h" #include "openmc/string_utils.h" -#include "openmc/timer.h" #include "openmc/thermal.h" -#include "openmc/xml_interface.h" +#include "openmc/timer.h" #include "openmc/wmp.h" +#include "openmc/xml_interface.h" #include "pugixml.hpp" @@ -35,7 +35,7 @@ namespace data { std::map library_map; vector libraries; -} +} // namespace data //============================================================================== // Library methods @@ -111,7 +111,8 @@ void read_cross_sections_xml() if (settings::run_CE) { char* envvar = std::getenv("OPENMC_CROSS_SECTIONS"); if (!envvar) { - fatal_error("No cross_sections.xml file was specified in " + fatal_error( + "No cross_sections.xml file was specified in " "materials.xml or in the OPENMC_CROSS_SECTIONS" " environment variable. OpenMC needs such a file to identify " "where to find data libraries. Please consult the" @@ -122,12 +123,13 @@ void read_cross_sections_xml() } else { char* envvar = std::getenv("OPENMC_MG_CROSS_SECTIONS"); if (!envvar) { - fatal_error("No mgxs.h5 file was specified in " - "materials.xml or in the OPENMC_MG_CROSS_SECTIONS environment " - "variable. OpenMC needs such a file to identify where to " - "find MG cross section libraries. Please consult the user's " - "guide at https://docs.openmc.org for information on " - "how to set up MG cross section libraries."); + fatal_error( + "No mgxs.h5 file was specified in " + "materials.xml or in the OPENMC_MG_CROSS_SECTIONS environment " + "variable. OpenMC needs such a file to identify where to " + "find MG cross section libraries. Please consult the user's " + "guide at https://docs.openmc.org for information on " + "how to set up MG cross section libraries."); } settings::path_cross_sections = envvar; } @@ -157,8 +159,8 @@ void read_cross_sections_xml() for (const auto& name : settings::res_scat_nuclides) { LibraryKey key {Library::Type::neutron, name}; if (data::library_map.find(key) == data::library_map.end()) { - fatal_error("Could not find resonant scatterer " + - name + " in cross_sections.xml file!"); + fatal_error("Could not find resonant scatterer " + name + + " in cross_sections.xml file!"); } } } @@ -188,11 +190,13 @@ void read_ce_cross_sections(const vector>& nuc_temps, std::string& name = nuclide_names[i_nuc]; // If we've already read this nuclide, skip it - if (already_read.find(name) != already_read.end()) continue; + if (already_read.find(name) != already_read.end()) + continue; const auto& temps = nuc_temps[i_nuc]; int err = openmc_load_nuclide(name.c_str(), temps.data(), temps.size()); - if (err < 0) throw std::runtime_error{openmc_err_msg}; + if (err < 0) + throw std::runtime_error {openmc_err_msg}; already_read.insert(name); } @@ -232,14 +236,17 @@ void read_ce_cross_sections(const vector>& nuc_temps, mat->finalize(); } // materials - if (settings::photon_transport && settings::electron_treatment == ElectronTreatment::TTB) { + if (settings::photon_transport && + settings::electron_treatment == ElectronTreatment::TTB) { // Take logarithm of energies since they are log-log interpolated data::ttb_e_grid = xt::log(data::ttb_e_grid); } // Show minimum/maximum temperature - write_message(4, "Minimum neutron data temperature: {} K", data::temperature_min); - write_message(4, "Maximum neutron data temperature: {} K", data::temperature_max); + write_message( + 4, "Minimum neutron data temperature: {} K", data::temperature_min); + write_message( + 4, "Maximum neutron data temperature: {} K", data::temperature_max); // If the user wants multipole, make sure we found a multipole library. if (settings::temperature_multipole) { @@ -252,8 +259,8 @@ void read_ce_cross_sections(const vector>& nuc_temps, } if (mpi::master && !mp_found) { warning("Windowed multipole functionality is turned on, but no multipole " - "libraries were found. Make sure that windowed multipole data is " - "present in your cross_sections.xml file."); + "libraries were found. Make sure that windowed multipole data is " + "present in your cross_sections.xml file."); } } } @@ -264,8 +271,7 @@ void read_ce_cross_sections_xml() const auto& filename = settings::path_cross_sections; if (!file_exists(filename)) { // Could not find cross_sections.xml file - fatal_error("Cross sections XML file '" + filename + - "' does not exist."); + fatal_error("Cross sections XML file '" + filename + "' does not exist."); } write_message("Reading cross sections XML file...", 5); @@ -301,11 +307,13 @@ void read_ce_cross_sections_xml() // Make sure file was not empty if (data::libraries.empty()) { - fatal_error("No cross section libraries present in cross_sections.xml file."); + fatal_error( + "No cross section libraries present in cross_sections.xml file."); } } -void finalize_cross_sections(){ +void finalize_cross_sections() +{ if (settings::run_mode != RunMode::PLOTTING) { simulation::time_read_xs.start(); if (settings::run_CE) { @@ -326,7 +334,8 @@ void finalize_cross_sections(){ } } -void library_clear() { +void library_clear() +{ data::libraries.clear(); data::library_map.clear(); } diff --git a/src/dagmc.cpp b/src/dagmc.cpp index 630f665fa..a6ff0e3b8 100644 --- a/src/dagmc.cpp +++ b/src/dagmc.cpp @@ -8,19 +8,19 @@ #include "openmc/geometry_aux.h" #include "openmc/hdf5_interface.h" #include "openmc/material.h" -#include "openmc/string_utils.h" #include "openmc/settings.h" +#include "openmc/string_utils.h" #ifdef DAGMC -#include "uwuw.hpp" #include "dagmcmetadata.hpp" +#include "uwuw.hpp" #endif #include -#include -#include #include #include +#include +#include namespace openmc { @@ -30,7 +30,7 @@ const bool DAGMC_ENABLED = true; const bool DAGMC_ENABLED = false; #endif -} +} // namespace openmc #ifdef DAGMC @@ -40,7 +40,8 @@ namespace openmc { // DAGMC Universe implementation //============================================================================== -DAGUniverse::DAGUniverse(pugi::xml_node node) { +DAGUniverse::DAGUniverse(pugi::xml_node node) +{ if (check_for_node(node, "id")) { id_ = std::stoi(get_node_value(node, "id")); } else { @@ -66,14 +67,16 @@ DAGUniverse::DAGUniverse(pugi::xml_node node) { initialize(); } -DAGUniverse::DAGUniverse(const std::string& filename, - bool auto_geom_ids, - bool auto_mat_ids) -: filename_(filename), adjust_geometry_ids_(auto_geom_ids), adjust_material_ids_(auto_mat_ids) { +DAGUniverse::DAGUniverse( + const std::string& filename, bool auto_geom_ids, bool auto_mat_ids) + : filename_(filename), adjust_geometry_ids_(auto_geom_ids), + adjust_material_ids_(auto_mat_ids) +{ // determine the next universe id int32_t next_univ_id = 0; for (const auto& u : model::universes) { - if (u->id_ > next_univ_id) next_univ_id = u->id_; + if (u->id_ > next_univ_id) + next_univ_id = u->id_; } next_univ_id++; @@ -83,14 +86,15 @@ DAGUniverse::DAGUniverse(const std::string& filename, initialize(); } -void -DAGUniverse::initialize() { +void DAGUniverse::initialize() +{ geom_type() = GeometryType::DAG; // determine the next cell id int32_t next_cell_id = 0; for (const auto& c : model::cells) { - if (c->id_ > next_cell_id) next_cell_id = c->id_; + if (c->id_ > next_cell_id) + next_cell_id = c->id_; } cell_idx_offset_ = model::cells.size(); next_cell_id++; @@ -98,7 +102,8 @@ DAGUniverse::initialize() { // determine the next surface id int32_t next_surf_id = 0; for (const auto& s : model::surfaces) { - if (s->id_ > next_surf_id) next_surf_id = s->id_; + if (s->id_ > next_surf_id) + next_surf_id = s->id_; } surf_idx_offset_ = model::surfaces.size(); next_surf_id++; @@ -151,17 +156,20 @@ DAGUniverse::initialize() { // set cell ids using global IDs auto c = std::make_unique(dagmc_instance_, i + 1); - c->id_ = adjust_geometry_ids_ ? next_cell_id++ : dagmc_instance_->id_by_index(3, c->dag_index()); + c->id_ = adjust_geometry_ids_ + ? next_cell_id++ + : dagmc_instance_->id_by_index(3, c->dag_index()); c->universe_ = this->id_; c->fill_ = C_NONE; // no fill, single universe - auto in_map = model::cell_map.find(c->id_); + auto in_map = model::cell_map.find(c->id_); if (in_map == model::cell_map.end()) { model::cell_map[c->id_] = model::cells.size(); } else { warning(fmt::format("DAGMC Cell IDs: {}", dagmc_ids_for_dim(3))); fatal_error(fmt::format("Cell ID {} exists in both DAGMC Universe {} " - "and the CSG geometry.", c->id_, this->id_)); + "and the CSG geometry.", + c->id_, this->id_)); } // --- Materials --- @@ -188,11 +196,14 @@ DAGUniverse::initialize() { std::string uwuw_mat = DMD.volume_material_property_data_eh[vol_handle]; if (uwuw_->material_library.count(uwuw_mat) != 0) { // Note: material numbers are set by UWUW - int mat_number = uwuw_->material_library.get_material(uwuw_mat).metadata["mat_number"].asInt(); + int mat_number = uwuw_->material_library.get_material(uwuw_mat) + .metadata["mat_number"] + .asInt(); c->material_.push_back(mat_number); } else { fatal_error(fmt::format("Material with value '{}' not found in the " - "UWUW material library", mat_str)); + "UWUW material library", + mat_str)); } } else { legacy_assign_material(mat_str, c); @@ -218,7 +229,8 @@ DAGUniverse::initialize() { } else if (mat->temperature() > 0.0) { c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * mat->temperature())); } else { - c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * settings::temperature_default)); + c->sqrtkT_.push_back( + std::sqrt(K_BOLTZMANN * settings::temperature_default)); } model::cells.emplace_back(std::move(c)); @@ -236,31 +248,36 @@ DAGUniverse::initialize() { // initialize surface objects int n_surfaces = dagmc_instance_->num_entities(2); for (int i = 0; i < n_surfaces; i++) { - moab::EntityHandle surf_handle = dagmc_instance_->entity_by_index(2, i+1); + moab::EntityHandle surf_handle = dagmc_instance_->entity_by_index(2, i + 1); // set cell ids using global IDs - auto s = std::make_unique(dagmc_instance_, i+1); - s->id_ = adjust_geometry_ids_ ? next_surf_id++ : dagmc_instance_->id_by_index(2, i+1); + auto s = std::make_unique(dagmc_instance_, i + 1); + s->id_ = adjust_geometry_ids_ ? next_surf_id++ + : dagmc_instance_->id_by_index(2, i + 1); // set BCs std::string bc_value = DMD.get_surface_property("boundary", surf_handle); to_lower(bc_value); - if (bc_value.empty() || bc_value == "transmit" || bc_value == "transmission") { + if (bc_value.empty() || bc_value == "transmit" || + bc_value == "transmission") { // set to transmission by default (nullptr) } else if (bc_value == "vacuum") { s->bc_ = std::make_shared(); - } else if (bc_value == "reflective" || bc_value == "reflect" || bc_value == "reflecting") { + } else if (bc_value == "reflective" || bc_value == "reflect" || + bc_value == "reflecting") { s->bc_ = std::make_shared(); } else if (bc_value == "periodic") { fatal_error("Periodic boundary condition not supported in DAGMC."); } else { fatal_error(fmt::format("Unknown boundary condition \"{}\" specified " - "on surface {}", bc_value, s->id_)); + "on surface {}", + bc_value, s->id_)); } // graveyard check moab::Range parent_vols; - rval = dagmc_instance_->moab_instance()->get_parent_meshsets(surf_handle, parent_vols); + rval = dagmc_instance_->moab_instance()->get_parent_meshsets( + surf_handle, parent_vols); MB_CHK_ERR_CONT(rval); // if this surface belongs to the graveyard @@ -277,15 +294,15 @@ DAGUniverse::initialize() { } else { warning(fmt::format("DAGMC Surface IDs: {}", dagmc_ids_for_dim(2))); fatal_error(fmt::format("Surface ID {} exists in both Universe {} " - "and the CSG geometry.", s->id_, this->id_)); + "and the CSG geometry.", + s->id_, this->id_)); } model::surfaces.emplace_back(std::move(s)); } // end surface loop } -std::string -DAGUniverse::dagmc_ids_for_dim(int dim) const +std::string DAGUniverse::dagmc_ids_for_dim(int dim) const { // generate a vector of ids std::vector id_vec; @@ -313,14 +330,17 @@ DAGUniverse::dagmc_ids_for_dim(int dim) const if (id_vec[i + 1] > stop_id + 1) { if (start_id != stop_id) { - // there are several IDs in a row, print condensed version (i.e. 1-10, 12-20) + // there are several IDs in a row, print condensed version (i.e. 1-10, + // 12-20) out << start_id << "-" << stop_id; } else { // only one ID in this contiguous block (i.e. 3, 5, 7, 9) out << start_id; } // insert a comma as long as we aren't in the last ID set - if (i < n_ents - 1) { out << ", "; } + if (i < n_ents - 1) { + out << ", "; + } // if we are at the end of a set, set the start ID to the first value // in the next set. @@ -333,17 +353,18 @@ DAGUniverse::dagmc_ids_for_dim(int dim) const return out.str(); } -int32_t -DAGUniverse::implicit_complement_idx() const { +int32_t DAGUniverse::implicit_complement_idx() const +{ moab::EntityHandle ic; - moab::ErrorCode rval = dagmc_instance_->geom_tool()->get_implicit_complement(ic); + moab::ErrorCode rval = + dagmc_instance_->geom_tool()->get_implicit_complement(ic); MB_CHK_SET_ERR_CONT(rval, "Failed to get implicit complement"); // off-by-one: DAGMC indices start at one return cell_idx_offset_ + dagmc_instance_->index_by_handle(ic) - 1; } -bool -DAGUniverse::find_cell(Particle &p) const { +bool DAGUniverse::find_cell(Particle& p) const +{ // if the particle isn't in any of the other DagMC // cells, place it in the implicit complement bool found = Universe::find_cell(p); @@ -354,8 +375,8 @@ DAGUniverse::find_cell(Particle &p) const { return found; } -void -DAGUniverse::to_hdf5(hid_t universes_group) const { +void DAGUniverse::to_hdf5(hid_t universes_group) const +{ // Create a group for this universe. auto group = create_group(universes_group, fmt::format("universe {}", id_)); @@ -364,20 +385,20 @@ DAGUniverse::to_hdf5(hid_t universes_group) const { // Write other properties of the DAGMC Universe write_string(group, "filename", filename_, false); - write_attribute(group, "auto_geom_ids", static_cast(adjust_geometry_ids_)); - write_attribute(group, "auto_mat_ids", static_cast(adjust_material_ids_)); + write_attribute( + group, "auto_geom_ids", static_cast(adjust_geometry_ids_)); + write_attribute( + group, "auto_mat_ids", static_cast(adjust_material_ids_)); close_group(group); } -bool -DAGUniverse::uses_uwuw() const +bool DAGUniverse::uses_uwuw() const { return !uwuw_->material_library.empty(); } -std::string -DAGUniverse::get_uwuw_materials_xml() const +std::string DAGUniverse::get_uwuw_materials_xml() const { if (!uses_uwuw()) { throw std::runtime_error("This DAGMC Universe does not use UWUW materials"); @@ -389,18 +410,20 @@ DAGUniverse::get_uwuw_materials_xml() const ss << "\n"; const auto& mat_lib = uwuw_->material_library; // write materials - for (auto mat : mat_lib) { ss << mat.second->openmc("atom"); } + for (auto mat : mat_lib) { + ss << mat.second->openmc("atom"); + } // write footer ss << ""; return ss.str(); } -void -DAGUniverse::write_uwuw_materials_xml(const std::string& outfile) const +void DAGUniverse::write_uwuw_materials_xml(const std::string& outfile) const { if (!uses_uwuw()) { - throw std::runtime_error("This DAGMC universe does not use UWUW materials."); + throw std::runtime_error( + "This DAGMC universe does not use UWUW materials."); } std::string xml_str = get_uwuw_materials_xml(); @@ -410,9 +433,8 @@ DAGUniverse::write_uwuw_materials_xml(const std::string& outfile) const mats_xml.close(); } -void -DAGUniverse::legacy_assign_material(std::string mat_string, - std::unique_ptr& c) const +void DAGUniverse::legacy_assign_material( + std::string mat_string, std::unique_ptr& c) const { bool mat_found_by_name = false; // attempt to find a material with a matching name @@ -425,10 +447,11 @@ DAGUniverse::legacy_assign_material(std::string mat_string, if (!mat_found_by_name) { mat_found_by_name = true; c->material_.push_back(m->id_); - // report error if more than one material is found + // report error if more than one material is found } else { fatal_error(fmt::format( - "More than one material found with name '{}'. Please ensure materials " + "More than one material found with name '{}'. Please ensure " + "materials " "have unique names if using this property to assign materials.", mat_string)); } @@ -459,8 +482,8 @@ DAGUniverse::legacy_assign_material(std::string mat_string, } } -void -DAGUniverse::read_uwuw_materials() { +void DAGUniverse::read_uwuw_materials() +{ int32_t next_material_id = 0; for (const auto& m : model::materials) { @@ -470,7 +493,8 @@ DAGUniverse::read_uwuw_materials() { uwuw_ = std::make_shared(filename_.c_str()); const auto& mat_lib = uwuw_->material_library; - if (mat_lib.size() == 0) return; + if (mat_lib.size() == 0) + return; // if we're using automatic IDs, update the UWUW material metadata if (adjust_material_ids_) { @@ -482,7 +506,9 @@ DAGUniverse::read_uwuw_materials() { std::stringstream ss; ss << "\n"; ss << "\n"; - for (auto mat : mat_lib) { ss << mat.second->openmc("atom"); } + for (auto mat : mat_lib) { + ss << mat.second->openmc("atom"); + } ss << ""; std::string mat_xml_string = ss.str(); @@ -503,24 +529,31 @@ DAGUniverse::read_uwuw_materials() { //============================================================================== DAGCell::DAGCell(std::shared_ptr dag_ptr, int32_t dag_idx) - : Cell{}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx) { + : Cell {}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx) +{ geom_type_ = GeometryType::DAG; simple_ = true; }; -std::pair -DAGCell::distance(Position r, Direction u, int32_t on_surface, Particle* p) const +std::pair DAGCell::distance( + Position r, Direction u, int32_t on_surface, Particle* p) const { Expects(p); // if we've changed direction or we're not on a surface, // reset the history and update last direction - if (u != p->last_dir()) { p->last_dir() = u; p->history().reset(); } - if (on_surface == 0) { p->history().reset(); } + if (u != p->last_dir()) { + p->last_dir() = u; + p->history().reset(); + } + if (on_surface == 0) { + p->history().reset(); + } const auto& univ = model::universes[p->coord(p->n_coord() - 1).universe]; DAGUniverse* dag_univ = static_cast(univ.get()); - if (!dag_univ) fatal_error("DAGMC call made for particle in a non-DAGMC universe"); + if (!dag_univ) + fatal_error("DAGMC call made for particle in a non-DAGMC universe"); moab::ErrorCode rval; moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_); @@ -532,21 +565,23 @@ DAGCell::distance(Position r, Direction u, int32_t on_surface, Particle* p) cons MB_CHK_ERR_CONT(rval); int surf_idx; if (hit_surf != 0) { - surf_idx = dag_univ->surf_idx_offset_ + dagmc_ptr_->index_by_handle(hit_surf); + surf_idx = + dag_univ->surf_idx_offset_ + dagmc_ptr_->index_by_handle(hit_surf); } else { // indicate that particle is lost surf_idx = -1; dist = INFINITY; - if (!dagmc_ptr_->is_implicit_complement(vol) || model::universe_map[dag_univ->id_] == model::root_universe) { - p->mark_as_lost(fmt::format("No intersection found with DAGMC cell {}", id_)); + if (!dagmc_ptr_->is_implicit_complement(vol) || + model::universe_map[dag_univ->id_] == model::root_universe) { + p->mark_as_lost( + fmt::format("No intersection found with DAGMC cell {}", id_)); } } return {dist, surf_idx}; } -bool -DAGCell::contains(Position r, Direction u, int32_t on_surface) const +bool DAGCell::contains(Position r, Direction u, int32_t on_surface) const { moab::ErrorCode rval; moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_); @@ -559,14 +594,12 @@ DAGCell::contains(Position r, Direction u, int32_t on_surface) const return result; } -void -DAGCell::to_hdf5_inner(hid_t group_id) const { +void DAGCell::to_hdf5_inner(hid_t group_id) const +{ write_string(group_id, "geom_type", "dagmc", false); - } -BoundingBox -DAGCell::bounding_box() const +BoundingBox DAGCell::bounding_box() const { moab::ErrorCode rval; moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_); @@ -581,19 +614,17 @@ DAGCell::bounding_box() const //============================================================================== DAGSurface::DAGSurface(std::shared_ptr dag_ptr, int32_t dag_idx) -: Surface{}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx) + : Surface {}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx) { geom_type_ = GeometryType::DAG; } // empty constructor -double -DAGSurface::evaluate(Position r) const +double DAGSurface::evaluate(Position r) const { return 0.0; } -double -DAGSurface::distance(Position r, Direction u, bool coincident) const +double DAGSurface::distance(Position r, Direction u, bool coincident) const { moab::ErrorCode rval; moab::EntityHandle surf = dagmc_ptr_->entity_by_index(2, dag_index_); @@ -603,12 +634,12 @@ DAGSurface::distance(Position r, Direction u, bool coincident) const double dir[3] = {u.x, u.y, u.z}; rval = dagmc_ptr_->ray_fire(surf, pnt, dir, hit_surf, dist, NULL, 0, 0); MB_CHK_ERR_CONT(rval); - if (dist < 0.0) dist = INFTY; + if (dist < 0.0) + dist = INFTY; return dist; } -Direction -DAGSurface::normal(Position r) const +Direction DAGSurface::normal(Position r) const { moab::ErrorCode rval; moab::EntityHandle surf = dagmc_ptr_->entity_by_index(2, dag_index_); @@ -619,8 +650,7 @@ DAGSurface::normal(Position r) const return dir; } -Direction -DAGSurface::reflect(Position r, Direction u, Particle* p) const +Direction DAGSurface::reflect(Position r, Direction u, Particle* p) const { Expects(p); p->history().reset_to_last_intersection(); @@ -638,27 +668,32 @@ DAGSurface::reflect(Position r, Direction u, Particle* p) const // Non-member functions //============================================================================== -void read_dagmc_universes(pugi::xml_node node) { +void read_dagmc_universes(pugi::xml_node node) +{ for (pugi::xml_node dag_node : node.children("dagmc_universe")) { model::universes.push_back(std::make_unique(dag_node)); - model::universe_map[model::universes.back()->id_] = model::universes.size() - 1; + model::universe_map[model::universes.back()->id_] = + model::universes.size() - 1; } } -void check_dagmc_root_univ() { +void check_dagmc_root_univ() +{ const auto& ru = model::universes[model::root_universe]; if (ru->geom_type() == GeometryType::DAG) { // if the root universe contains DAGMC geometry, warn the user // if it does not contain a graveyard volume auto dag_univ = dynamic_cast(ru.get()); if (dag_univ && !dag_univ->has_graveyard()) { - warning("No graveyard volume found in the DagMC model. " - "This may result in lost particles and rapid simulation failure."); + warning( + "No graveyard volume found in the DagMC model. " + "This may result in lost particles and rapid simulation failure."); } } } -int32_t next_cell(DAGUniverse* dag_univ, DAGCell* cur_cell, DAGSurface* surf_xed) +int32_t next_cell( + DAGUniverse* dag_univ, DAGCell* cur_cell, DAGSurface* surf_xed) { moab::EntityHandle surf = surf_xed->dagmc_ptr()->entity_by_index(2, surf_xed->dag_index()); @@ -668,10 +703,10 @@ int32_t next_cell(DAGUniverse* dag_univ, DAGCell* cur_cell, DAGSurface* surf_xed moab::EntityHandle new_vol; cur_cell->dagmc_ptr()->next_vol(surf, vol, new_vol); - return cur_cell->dagmc_ptr()->index_by_handle(new_vol) + dag_univ->cell_idx_offset_; + return cur_cell->dagmc_ptr()->index_by_handle(new_vol) + + dag_univ->cell_idx_offset_; } - } // namespace openmc #else diff --git a/src/distribution.cpp b/src/distribution.cpp index 68318c992..4713110ab 100644 --- a/src/distribution.cpp +++ b/src/distribution.cpp @@ -24,14 +24,14 @@ Discrete::Discrete(pugi::xml_node node) auto params = get_node_array(node, "parameters"); std::size_t n = params.size(); - std::copy(params.begin(), params.begin() + n/2, std::back_inserter(x_)); - std::copy(params.begin() + n/2, params.end(), std::back_inserter(p_)); + std::copy(params.begin(), params.begin() + n / 2, std::back_inserter(x_)); + std::copy(params.begin() + n / 2, params.end(), std::back_inserter(p_)); normalize(); } Discrete::Discrete(const double* x, const double* p, int n) - : x_{x, x+n}, p_{p, p+n} + : x_ {x, x + n}, p_ {p, p + n} { normalize(); } @@ -44,9 +44,10 @@ double Discrete::sample(uint64_t* seed) const double c = 0.0; for (int i = 0; i < n; ++i) { c += p_[i]; - if (xi < c) return x_[i]; + if (xi < c) + return x_[i]; } - throw std::runtime_error{"Error when sampling probability mass function."}; + throw std::runtime_error {"Error when sampling probability mass function."}; } else { return x_[0]; } @@ -79,7 +80,7 @@ Uniform::Uniform(pugi::xml_node node) double Uniform::sample(uint64_t* seed) const { - return a_ + prn(seed)*(b_ - a_); + return a_ + prn(seed) * (b_ - a_); } //============================================================================== @@ -121,7 +122,7 @@ double Watt::sample(uint64_t* seed) const //============================================================================== Normal::Normal(pugi::xml_node node) { - auto params = get_node_array(node,"parameters"); + auto params = get_node_array(node, "parameters"); if (params.size() != 2) { openmc::fatal_error("Normal energy distribution must have two " "parameters specified."); @@ -141,7 +142,7 @@ double Normal::sample(uint64_t* seed) const //============================================================================== Muir::Muir(pugi::xml_node node) { - auto params = get_node_array(node,"parameters"); + auto params = get_node_array(node, "parameters"); if (params.size() != 3) { openmc::fatal_error("Muir energy distribution must have three " "parameters specified."); @@ -170,7 +171,8 @@ Tabular::Tabular(pugi::xml_node node) } else if (temp == "linear-linear") { interp_ = Interpolation::lin_lin; } else { - openmc::fatal_error("Unknown interpolation type for distribution: " + temp); + openmc::fatal_error( + "Unknown interpolation type for distribution: " + temp); } } else { interp_ = Interpolation::histogram; @@ -184,13 +186,15 @@ Tabular::Tabular(pugi::xml_node node) init(x, p, n); } -Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp, const double* c) - : interp_{interp} +Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp, + const double* c) + : interp_ {interp} { init(x, p, n, c); } -void Tabular::init(const double* x, const double* p, std::size_t n, const double* c) +void Tabular::init( + const double* x, const double* p, std::size_t n, const double* c) { // Copy x/p arrays into vectors std::copy(x, x + n, std::back_inserter(x_)); @@ -211,17 +215,17 @@ void Tabular::init(const double* x, const double* p, std::size_t n, const double c_[0] = 0.0; for (int i = 1; i < n; ++i) { if (interp_ == Interpolation::histogram) { - c_[i] = c_[i-1] + p_[i-1]*(x_[i] - x_[i-1]); + c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]); } else if (interp_ == Interpolation::lin_lin) { - c_[i] = c_[i-1] + 0.5*(p_[i-1] + p_[i]) * (x_[i] - x_[i-1]); + c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]); } } } // Normalize density and distribution functions for (int i = 0; i < n; ++i) { - p_[i] = p_[i]/c_[n-1]; - c_[i] = c_[i]/c_[n-1]; + p_[i] = p_[i] / c_[n - 1]; + c_[i] = c_[i] / c_[n - 1]; } } @@ -235,8 +239,9 @@ double Tabular::sample(uint64_t* seed) const int i; std::size_t n = c_.size(); for (i = 0; i < n - 1; ++i) { - if (c <= c_[i+1]) break; - c_i = c_[i+1]; + if (c <= c_[i + 1]) + break; + c_i = c_[i + 1]; } // Determine bounding PDF values @@ -246,7 +251,7 @@ double Tabular::sample(uint64_t* seed) const if (interp_ == Interpolation::histogram) { // Histogram interpolation if (p_i > 0.0) { - return x_i + (c - c_i)/p_i; + return x_i + (c - c_i) / p_i; } else { return x_i; } @@ -255,11 +260,13 @@ double Tabular::sample(uint64_t* seed) const double x_i1 = x_[i + 1]; double p_i1 = p_[i + 1]; - double m = (p_i1 - p_i)/(x_i1 - x_i); + double m = (p_i1 - p_i) / (x_i1 - x_i); if (m == 0.0) { - return x_i + (c - c_i)/p_i; + return x_i + (c - c_i) / p_i; } else { - return x_i + (std::sqrt(std::max(0.0, p_i*p_i + 2*m*(c - c_i))) - p_i)/m; + return x_i + + (std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) / + m; } } } @@ -273,11 +280,11 @@ double Equiprobable::sample(uint64_t* seed) const std::size_t n = x_.size(); double r = prn(seed); - int i = std::floor((n - 1)*r); + int i = std::floor((n - 1) * r); double xl = x_[i]; - double xr = x_[i+i]; - return xl + ((n - 1)*r - i) * (xr - xl); + double xr = x_[i + i]; + return xl + ((n - 1) * r - i) * (xr - xl); } //============================================================================== @@ -295,19 +302,19 @@ UPtrDist distribution_from_xml(pugi::xml_node node) // Allocate extension of Distribution UPtrDist dist; if (type == "uniform") { - dist = UPtrDist{new Uniform(node)}; + dist = UPtrDist {new Uniform(node)}; } else if (type == "maxwell") { - dist = UPtrDist{new Maxwell(node)}; + dist = UPtrDist {new Maxwell(node)}; } else if (type == "watt") { - dist = UPtrDist{new Watt(node)}; + dist = UPtrDist {new Watt(node)}; } else if (type == "normal") { - dist = UPtrDist{new Normal(node)}; + dist = UPtrDist {new Normal(node)}; } else if (type == "muir") { - dist = UPtrDist{new Muir(node)}; + dist = UPtrDist {new Muir(node)}; } else if (type == "discrete") { - dist = UPtrDist{new Discrete(node)}; + dist = UPtrDist {new Discrete(node)}; } else if (type == "tabular") { - dist = UPtrDist{new Tabular(node)}; + dist = UPtrDist {new Tabular(node)}; } else { openmc::fatal_error("Invalid distribution type: " + type); } diff --git a/src/distribution_angle.cpp b/src/distribution_angle.cpp index 13e8c480f..5e92b794a 100644 --- a/src/distribution_angle.cpp +++ b/src/distribution_angle.cpp @@ -1,6 +1,6 @@ #include "openmc/distribution_angle.h" -#include // for abs, copysign +#include // for abs, copysign #include "xtensor/xarray.hpp" #include "xtensor/xview.hpp" @@ -38,15 +38,15 @@ AngleDistribution::AngleDistribution(hid_t group) int j = offsets[i]; int n; if (i < n_energy - 1) { - n = offsets[i+1] - j; + n = offsets[i + 1] - j; } else { n = temp.shape()[1] - j; } // Create and initialize tabular distribution - auto xs = xt::view(temp, 0, xt::range(j, j+n)); - auto ps = xt::view(temp, 1, xt::range(j, j+n)); - auto cs = xt::view(temp, 2, xt::range(j, j+n)); + auto xs = xt::view(temp, 0, xt::range(j, j + n)); + auto ps = xt::view(temp, 1, xt::range(j, j + n)); + auto cs = xt::view(temp, 2, xt::range(j, j + n)); vector x {xs.begin(), xs.end()}; vector p {ps.begin(), ps.end()}; vector c {cs.begin(), cs.end()}; @@ -55,8 +55,8 @@ AngleDistribution::AngleDistribution(hid_t group) // CDF values that were passed through to the HDF5 library. At a later // time, we can remove the CDF values from the HDF5 library and // reconstruct them using the PDF - Tabular* mudist = new Tabular{x.data(), p.data(), n, int2interp(interp[i]), - c.data()}; + Tabular* mudist = + new Tabular {x.data(), p.data(), n, int2interp(interp[i]), c.data()}; distribution_.emplace_back(mudist); } @@ -79,17 +79,19 @@ double AngleDistribution::sample(double E, uint64_t* seed) const r = 1.0; } else { i = lower_bound_index(energy_.begin(), energy_.end(), E); - r = (E - energy_[i])/(energy_[i+1] - energy_[i]); + r = (E - energy_[i]) / (energy_[i + 1] - energy_[i]); } // Sample between the ith and (i+1)th bin - if (r > prn(seed)) ++i; + if (r > prn(seed)) + ++i; // Sample i-th distribution double mu = distribution_[i]->sample(seed); // Make sure mu is in range [-1,1] and return - if (std::abs(mu) > 1.0) mu = std::copysign(1.0, mu); + if (std::abs(mu) > 1.0) + mu = std::copysign(1.0, mu); return mu; } diff --git a/src/distribution_energy.cpp b/src/distribution_energy.cpp index 1fd95d401..409ae5d9f 100644 --- a/src/distribution_energy.cpp +++ b/src/distribution_energy.cpp @@ -29,7 +29,7 @@ DiscretePhoton::DiscretePhoton(hid_t group) double DiscretePhoton::sample(double E, uint64_t* seed) const { if (primary_flag_ == 2) { - return energy_ + A_/(A_+ 1)*E; + return energy_ + A_ / (A_ + 1) * E; } else { return energy_; } @@ -47,7 +47,7 @@ LevelInelastic::LevelInelastic(hid_t group) double LevelInelastic::sample(double E, uint64_t* seed) const { - return mass_ratio_*(E - threshold_); + return mass_ratio_ * (E - threshold_); } //============================================================================== @@ -94,7 +94,7 @@ ContinuousTabular::ContinuousTabular(hid_t group) int j = offsets[i]; int n; if (i < n_energy - 1) { - n = offsets[i+1] - j; + n = offsets[i + 1] - j; } else { n = eout.shape()[1] - j; } @@ -105,35 +105,35 @@ ContinuousTabular::ContinuousTabular(hid_t group) d.n_discrete = n_discrete[i]; // Copy data - d.e_out = xt::view(eout, 0, xt::range(j, j+n)); - d.p = xt::view(eout, 1, xt::range(j, j+n)); + d.e_out = xt::view(eout, 0, xt::range(j, j + n)); + d.p = xt::view(eout, 1, xt::range(j, j + n)); // To get answers that match ACE data, for now we still use the tabulated // CDF values that were passed through to the HDF5 library. At a later // time, we can remove the CDF values from the HDF5 library and // reconstruct them using the PDF if (true) { - d.c = xt::view(eout, 2, xt::range(j, j+n)); + d.c = xt::view(eout, 2, xt::range(j, j + n)); } else { // Calculate cumulative distribution function -- discrete portion for (int k = 0; k < d.n_discrete; ++k) { if (k == 0) { d.c[k] = d.p[k]; } else { - d.c[k] = d.c[k-1] + d.p[k]; + d.c[k] = d.c[k - 1] + d.p[k]; } } // Continuous portion for (int k = d.n_discrete; k < n; ++k) { if (k == d.n_discrete) { - d.c[k] = d.c[k-1] + d.p[k]; + d.c[k] = d.c[k - 1] + d.p[k]; } else { if (d.interpolation == Interpolation::histogram) { - d.c[k] = d.c[k-1] + d.p[k-1]*(d.e_out[k] - d.e_out[k-1]); + d.c[k] = d.c[k - 1] + d.p[k - 1] * (d.e_out[k] - d.e_out[k - 1]); } else if (d.interpolation == Interpolation::lin_lin) { - d.c[k] = d.c[k-1] + 0.5*(d.p[k-1] + d.p[k]) * - (d.e_out[k] - d.e_out[k-1]); + d.c[k] = d.c[k - 1] + 0.5 * (d.p[k - 1] + d.p[k]) * + (d.e_out[k] - d.e_out[k - 1]); } } } @@ -170,7 +170,7 @@ double ContinuousTabular::sample(double E, uint64_t* seed) const r = 1.0; } else { i = lower_bound_index(energy_.begin(), energy_.end(), E); - r = (E - energy_[i]) / (energy_[i+1] - energy_[i]); + r = (E - energy_[i]) / (energy_[i + 1] - energy_[i]); } // Sample between the ith and [i+1]th bin @@ -187,10 +187,10 @@ double ContinuousTabular::sample(double E, uint64_t* seed) const double E_i_1 = distribution_[i].e_out[n_discrete]; double E_i_K = distribution_[i].e_out[n_energy_out - 1]; - n_energy_out = distribution_[i+1].e_out.size(); - n_discrete = distribution_[i+1].n_discrete; - double E_i1_1 = distribution_[i+1].e_out[n_discrete]; - double E_i1_K = distribution_[i+1].e_out[n_energy_out - 1]; + n_energy_out = distribution_[i + 1].e_out.size(); + n_discrete = distribution_[i + 1].n_discrete; + double E_i1_1 = distribution_[i + 1].e_out[n_discrete]; + double E_i1_K = distribution_[i + 1].e_out[n_energy_out - 1]; double E_1 = E_i_1 + r * (E_i1_1 - E_i_1); double E_K = E_i_K + r * (E_i1_K - E_i_K); @@ -217,8 +217,9 @@ double ContinuousTabular::sample(double E, uint64_t* seed) const double c_k1; for (int j = n_discrete; j < end; ++j) { k = j; - c_k1 = distribution_[l].c[k+1]; - if (r1 < c_k1) break; + c_k1 = distribution_[l].c[k + 1]; + if (r1 < c_k1) + break; k = j + 1; c_k = c_k1; } @@ -229,39 +230,41 @@ double ContinuousTabular::sample(double E, uint64_t* seed) const if (distribution_[l].interpolation == Interpolation::histogram) { // Histogram interpolation if (p_l_k > 0.0 && k >= n_discrete) { - E_out = E_l_k + (r1 - c_k)/p_l_k; + E_out = E_l_k + (r1 - c_k) / p_l_k; } } else if (distribution_[l].interpolation == Interpolation::lin_lin) { // Linear-linear interpolation - double E_l_k1 = distribution_[l].e_out[k+1]; - double p_l_k1 = distribution_[l].p[k+1]; + double E_l_k1 = distribution_[l].e_out[k + 1]; + double p_l_k1 = distribution_[l].p[k + 1]; if (E_l_k != E_l_k1) { - double frac = (p_l_k1 - p_l_k)/(E_l_k1 - E_l_k); + double frac = (p_l_k1 - p_l_k) / (E_l_k1 - E_l_k); if (frac == 0.0) { - E_out = E_l_k + (r1 - c_k)/p_l_k; + E_out = E_l_k + (r1 - c_k) / p_l_k; } else { - E_out = E_l_k + (std::sqrt(std::max(0.0, p_l_k*p_l_k + - 2.0*frac*(r1 - c_k))) - p_l_k)/frac; + E_out = + E_l_k + + (std::sqrt(std::max(0.0, p_l_k * p_l_k + 2.0 * frac * (r1 - c_k))) - + p_l_k) / + frac; } } } else { - throw std::runtime_error{"Unexpected interpolation for continuous energy " - "distribution."}; + throw std::runtime_error {"Unexpected interpolation for continuous energy " + "distribution."}; } // Now interpolate between incident energy bins i and i + 1 if (!histogram_interp && n_energy_out > 1 && k >= n_discrete) { if (l == i) { - return E_1 + (E_out - E_i_1)*(E_K - E_1)/(E_i_K - E_i_1); + return E_1 + (E_out - E_i_1) * (E_K - E_1) / (E_i_K - E_i_1); } else { - return E_1 + (E_out - E_i1_1)*(E_K - E_1)/(E_i1_K - E_i1_1); + return E_1 + (E_out - E_i1_1) * (E_K - E_1) / (E_i1_K - E_i1_1); } } else { return E_out; } - } //============================================================================== @@ -272,7 +275,7 @@ MaxwellEnergy::MaxwellEnergy(hid_t group) { read_attribute(group, "u", u_); hid_t dset = open_dataset(group, "theta"); - theta_ = Tabulated1D{dset}; + theta_ = Tabulated1D {dset}; close_dataset(dset); } @@ -286,7 +289,8 @@ double MaxwellEnergy::sample(double E, uint64_t* seed) const double E_out = maxwell_spectrum(theta, seed); // Accept energy based on restriction energy - if (E_out <= E - u_) return E_out; + if (E_out <= E - u_) + return E_out; } } @@ -298,7 +302,7 @@ Evaporation::Evaporation(hid_t group) { read_attribute(group, "u", u_); hid_t dset = open_dataset(group, "theta"); - theta_ = Tabulated1D{dset}; + theta_ = Tabulated1D {dset}; close_dataset(dset); } @@ -307,15 +311,16 @@ double Evaporation::sample(double E, uint64_t* seed) const // Get temperature corresponding to incoming energy double theta = theta_(E); - double y = (E - u_)/theta; + double y = (E - u_) / theta; double v = 1.0 - std::exp(-y); // Sample outgoing energy based on evaporation spectrum probability // density function double x; while (true) { - x = -std::log((1.0 - v*prn(seed))*(1.0 - v*prn(seed))); - if (x <= y) break; + x = -std::log((1.0 - v * prn(seed)) * (1.0 - v * prn(seed))); + if (x <= y) + break; } return x * theta; @@ -332,10 +337,10 @@ WattEnergy::WattEnergy(hid_t group) // Read tabulated functions hid_t dset = open_dataset(group, "a"); - a_ = Tabulated1D{dset}; + a_ = Tabulated1D {dset}; close_dataset(dset); dset = open_dataset(group, "b"); - b_ = Tabulated1D{dset}; + b_ = Tabulated1D {dset}; close_dataset(dset); } @@ -350,8 +355,9 @@ double WattEnergy::sample(double E, uint64_t* seed) const double E_out = watt_spectrum(a, b, seed); // Accept energy based on restriction energy - if (E_out <= E - u_) return E_out; + if (E_out <= E - u_) + return E_out; } } -} +} // namespace openmc diff --git a/src/distribution_multi.cpp b/src/distribution_multi.cpp index cdf73aee1..0735f0994 100644 --- a/src/distribution_multi.cpp +++ b/src/distribution_multi.cpp @@ -28,29 +28,29 @@ UnitSphereDistribution::UnitSphereDistribution(pugi::xml_node node) } } - //============================================================================== // PolarAzimuthal implementation //============================================================================== -PolarAzimuthal::PolarAzimuthal(Direction u, UPtrDist mu, UPtrDist phi) : - UnitSphereDistribution{u}, mu_{std::move(mu)}, phi_{std::move(phi)} { } +PolarAzimuthal::PolarAzimuthal(Direction u, UPtrDist mu, UPtrDist phi) + : UnitSphereDistribution {u}, mu_ {std::move(mu)}, phi_ {std::move(phi)} +{} PolarAzimuthal::PolarAzimuthal(pugi::xml_node node) - : UnitSphereDistribution{node} + : UnitSphereDistribution {node} { if (check_for_node(node, "mu")) { pugi::xml_node node_dist = node.child("mu"); mu_ = distribution_from_xml(node_dist); } else { - mu_ = UPtrDist{new Uniform(-1., 1.)}; + mu_ = UPtrDist {new Uniform(-1., 1.)}; } if (check_for_node(node, "phi")) { pugi::xml_node node_dist = node.child("phi"); phi_ = distribution_from_xml(node_dist); } else { - phi_ = UPtrDist{new Uniform(0.0, 2.0*PI)}; + phi_ = UPtrDist {new Uniform(0.0, 2.0 * PI)}; } } @@ -58,7 +58,8 @@ Direction PolarAzimuthal::sample(uint64_t* seed) const { // Sample cosine of polar angle double mu = mu_->sample(seed); - if (mu == 1.0) return u_ref_; + if (mu == 1.0) + return u_ref_; // Sample azimuthal angle double phi = phi_->sample(seed); @@ -72,10 +73,10 @@ Direction PolarAzimuthal::sample(uint64_t* seed) const Direction isotropic_direction(uint64_t* seed) { - double phi = uniform_distribution(0., 2.0*PI, seed); + double phi = uniform_distribution(0., 2.0 * PI, seed); double mu = uniform_distribution(-1., 1., seed); - return {mu, std::sqrt(1.0 - mu*mu) * std::cos(phi), - std::sqrt(1.0 - mu*mu) * std::sin(phi)}; + return {mu, std::sqrt(1.0 - mu * mu) * std::cos(phi), + std::sqrt(1.0 - mu * mu) * std::sin(phi)}; } Direction Isotropic::sample(uint64_t* seed) const diff --git a/src/distribution_spatial.cpp b/src/distribution_spatial.cpp index 356383eb7..66430ddff 100644 --- a/src/distribution_spatial.cpp +++ b/src/distribution_spatial.cpp @@ -20,7 +20,7 @@ CartesianIndependent::CartesianIndependent(pugi::xml_node node) // If no distribution was specified, default to a single point at x=0 double x[] {0.0}; double p[] {1.0}; - x_ = UPtrDist{new Discrete{x, p, 1}}; + x_ = UPtrDist {new Discrete {x, p, 1}}; } // Read distribution for y coordinate @@ -31,7 +31,7 @@ CartesianIndependent::CartesianIndependent(pugi::xml_node node) // If no distribution was specified, default to a single point at y=0 double x[] {0.0}; double p[] {1.0}; - y_ = UPtrDist{new Discrete{x, p, 1}}; + y_ = UPtrDist {new Discrete {x, p, 1}}; } // Read distribution for z coordinate @@ -42,7 +42,7 @@ CartesianIndependent::CartesianIndependent(pugi::xml_node node) // If no distribution was specified, default to a single point at z=0 double x[] {0.0}; double p[] {1.0}; - z_ = UPtrDist{new Discrete{x, p, 1}}; + z_ = UPtrDist {new Discrete {x, p, 1}}; } } @@ -96,21 +96,21 @@ CylindricalIndependent::CylindricalIndependent(pugi::xml_node node) if (origin.size() == 3) { origin_ = origin; } else { - fatal_error("Origin for cylindrical source distribution must be length 3"); + fatal_error( + "Origin for cylindrical source distribution must be length 3"); } } else { // If no coordinates were specified, default to (0, 0, 0) origin_ = {0.0, 0.0, 0.0}; } - } Position CylindricalIndependent::sample(uint64_t* seed) const { double r = r_->sample(seed); double phi = phi_->sample(seed); - double x = r*cos(phi) + origin_.x; - double y = r*sin(phi) + origin_.y; + double x = r * cos(phi) + origin_.x; + double y = r * sin(phi) + origin_.y; double z = z_->sample(seed) + origin_.z; return {x, y, z}; } @@ -166,7 +166,6 @@ SphericalIndependent::SphericalIndependent(pugi::xml_node node) // If no coordinates were specified, default to (0, 0, 0) origin_ = {0.0, 0.0, 0.0}; } - } Position SphericalIndependent::sample(uint64_t* seed) const @@ -174,9 +173,9 @@ Position SphericalIndependent::sample(uint64_t* seed) const double r = r_->sample(seed); double theta = theta_->sample(seed); double phi = phi_->sample(seed); - double x = r*sin(theta)*cos(phi) + origin_.x; - double y = r*sin(theta)*sin(phi) + origin_.y; - double z = r*cos(theta) + origin_.z; + double x = r * sin(theta) * cos(phi) + origin_.x; + double y = r * sin(theta) * sin(phi) + origin_.y; + double z = r * cos(theta) + origin_.z; return {x, y, z}; } @@ -185,7 +184,7 @@ Position SphericalIndependent::sample(uint64_t* seed) const //============================================================================== SpatialBox::SpatialBox(pugi::xml_node node, bool fission) - : only_fissionable_{fission} + : only_fissionable_ {fission} { // Read lower-right/upper-left coordinates auto params = get_node_array(node, "parameters"); @@ -193,14 +192,14 @@ SpatialBox::SpatialBox(pugi::xml_node node, bool fission) openmc::fatal_error("Box/fission spatial source must have six " "parameters specified."); - lower_left_ = Position{params[0], params[1], params[2]}; - upper_right_ = Position{params[3], params[4], params[5]}; + lower_left_ = Position {params[0], params[1], params[2]}; + upper_right_ = Position {params[3], params[4], params[5]}; } Position SpatialBox::sample(uint64_t* seed) const { Position xi {prn(seed), prn(seed), prn(seed)}; - return lower_left_ + xi*(upper_right_ - lower_left_); + return lower_left_ + xi * (upper_right_ - lower_left_); } //============================================================================== @@ -216,7 +215,7 @@ SpatialPoint::SpatialPoint(pugi::xml_node node) "parameters specified."); // Set position - r_ = Position{params.data()}; + r_ = Position {params.data()}; } Position SpatialPoint::sample(uint64_t* seed) const diff --git a/src/eigenvalue.cpp b/src/eigenvalue.cpp index 1e0d7d972..b35281f4a 100644 --- a/src/eigenvalue.cpp +++ b/src/eigenvalue.cpp @@ -22,10 +22,10 @@ #include "openmc/timer.h" #include // for min -#include // for sqrt, abs, pow -#include // for back_inserter +#include // for sqrt, abs, pow +#include // for back_inserter +#include //for infinity #include -#include //for infinity namespace openmc { @@ -51,7 +51,9 @@ void calculate_generation_keff() const auto& gt = simulation::global_tallies; // Get keff for this generation by subtracting off the starting value - simulation::keff_generation = gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) - simulation::keff_generation; + simulation::keff_generation = + gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) - + simulation::keff_generation; double keff_reduced; #ifdef OPENMC_MPI @@ -89,16 +91,17 @@ void synchronize_bank() // While we would expect the value of start on rank 0 to be 0, the MPI // standard says that the receive buffer on rank 0 is undefined and not // significant - if (mpi::rank == 0) start = 0; + if (mpi::rank == 0) + start = 0; int64_t finish = start + simulation::fission_bank.size(); int64_t total = finish; MPI_Bcast(&total, 1, MPI_INT64_T, mpi::n_procs - 1, mpi::intracomm); #else - int64_t start = 0; + int64_t start = 0; int64_t finish = simulation::fission_bank.size(); - int64_t total = finish; + int64_t total = finish; #endif // If there are not that many particles per generation, it's possible that no @@ -107,7 +110,8 @@ void synchronize_bank() // runs enough particles to avoid this in the first place. if (simulation::fission_bank.size() == 0) { - fatal_error("No fission sites banked on MPI rank " + std::to_string(mpi::rank)); + fatal_error( + "No fission sites banked on MPI rank " + std::to_string(mpi::rank)); } // Make sure all processors start at the same point for random sampling. Then @@ -139,7 +143,7 @@ void synchronize_bank() int64_t index_temp = 0; vector temp_sites(3 * simulation::work_per_rank); - for (int64_t i = 0; i < simulation::fission_bank.size(); i++ ) { + for (int64_t i = 0; i < simulation::fission_bank.size(); i++) { const auto& site = simulation::fission_bank[i]; // If there are less than n_particles particles banked, automatically add @@ -174,8 +178,8 @@ void synchronize_bank() // Allocate space for bank_position if this hasn't been done yet int64_t bank_position[mpi::n_procs]; - MPI_Allgather(&start, 1, MPI_INT64_T, bank_position, 1, - MPI_INT64_T, mpi::intracomm); + MPI_Allgather( + &start, 1, MPI_INT64_T, bank_position, 1, MPI_INT64_T, mpi::intracomm); #else start = 0; finish = index_temp; @@ -219,19 +223,21 @@ void synchronize_bank() if (start < settings::n_particles) { // Determine the index of the processor which has the first part of the // source_bank for the local processor - int neighbor = upper_bound_index(simulation::work_index.begin(), - simulation::work_index.end(), start); + int neighbor = upper_bound_index( + simulation::work_index.begin(), simulation::work_index.end(), start); while (start < finish) { // Determine the number of sites to send - int64_t n = std::min(simulation::work_index[neighbor + 1], finish) - start; + int64_t n = + std::min(simulation::work_index[neighbor + 1], finish) - start; // Initiate an asynchronous send of source sites to the neighboring // process if (neighbor != mpi::rank) { requests.emplace_back(); - MPI_Isend(&temp_sites[index_local], static_cast(n), mpi::source_site, - neighbor, mpi::rank, mpi::intracomm, &requests.back()); + MPI_Isend(&temp_sites[index_local], static_cast(n), + mpi::source_site, neighbor, mpi::rank, mpi::intracomm, + &requests.back()); } // Increment all indices @@ -242,7 +248,8 @@ void synchronize_bank() // Check for sites out of bounds -- this only happens in the rare // circumstance that a processor close to the end has so many sites that // it would exceed the bank on the last processor - if (neighbor > mpi::n_procs - 1) break; + if (neighbor > mpi::n_procs - 1) + break; } } @@ -259,7 +266,8 @@ void synchronize_bank() if (start >= bank_position[mpi::n_procs - 1]) { neighbor = mpi::n_procs - 1; } else { - neighbor = upper_bound_index(bank_position, bank_position + mpi::n_procs, start); + neighbor = + upper_bound_index(bank_position, bank_position + mpi::n_procs, start); } while (start < simulation::work_index[mpi::rank + 1]) { @@ -268,7 +276,9 @@ void synchronize_bank() if (neighbor == mpi::n_procs - 1) { n = simulation::work_index[mpi::rank + 1] - start; } else { - n = std::min(bank_position[neighbor + 1], simulation::work_index[mpi::rank + 1]) - start; + n = std::min(bank_position[neighbor + 1], + simulation::work_index[mpi::rank + 1]) - + start; } if (neighbor != mpi::rank) { @@ -276,8 +286,8 @@ void synchronize_bank() // asynchronous receive for the source sites requests.emplace_back(); - MPI_Irecv(&simulation::source_bank[index_local], static_cast(n), mpi::source_site, - neighbor, neighbor, mpi::intracomm, &requests.back()); + MPI_Irecv(&simulation::source_bank[index_local], static_cast(n), + mpi::source_site, neighbor, neighbor, mpi::intracomm, &requests.back()); } else { // If the source sites are on this procesor, we can simply copy them @@ -316,7 +326,8 @@ void calculate_average_keff() int i = overall_generation() - 1; int n; if (simulation::current_batch > settings::n_inactive) { - n = settings::gen_per_batch*simulation::n_realizations + simulation::current_gen; + n = settings::gen_per_batch * simulation::n_realizations + + simulation::current_gen; } else { n = 0; } @@ -338,14 +349,16 @@ void calculate_average_keff() if (settings::confidence_intervals) { // Calculate t-value for confidence intervals double alpha = 1.0 - CONFIDENCE_LEVEL; - t_value = t_percentile(1.0 - alpha/2.0, n - 1); + t_value = t_percentile(1.0 - alpha / 2.0, n - 1); } else { t_value = 1.0; } // Standard deviation of the sample mean of k - simulation::keff_std = t_value * std::sqrt((simulation::k_sum[1]/n - - std::pow(simulation::keff, 2)) / (n - 1)); + simulation::keff_std = + t_value * + std::sqrt( + (simulation::k_sum[1] / n - std::pow(simulation::keff, 2)) / (n - 1)); } } } @@ -360,7 +373,7 @@ int openmc_get_keff(double* k_combined) if (simulation::n_realizations <= 3) { k_combined[0] = simulation::keff; k_combined[1] = simulation::keff_std; - if (simulation::n_realizations <=1) { + if (simulation::n_realizations <= 1) { k_combined[1] = std::numeric_limits::infinity(); } return 0; @@ -377,9 +390,15 @@ int openmc_get_keff(double* k_combined) kv[0] = gt(GlobalTally::K_COLLISION, TallyResult::SUM) / n; kv[1] = gt(GlobalTally::K_ABSORPTION, TallyResult::SUM) / n; kv[2] = gt(GlobalTally::K_TRACKLENGTH, TallyResult::SUM) / n; - cov(0, 0) = (gt(GlobalTally::K_COLLISION, TallyResult::SUM_SQ) - n*kv[0]*kv[0]) / (n - 1); - cov(1, 1) = (gt(GlobalTally::K_ABSORPTION, TallyResult::SUM_SQ) - n*kv[1]*kv[1]) / (n - 1); - cov(2, 2) = (gt(GlobalTally::K_TRACKLENGTH, TallyResult::SUM_SQ) - n*kv[2]*kv[2]) / (n - 1); + cov(0, 0) = + (gt(GlobalTally::K_COLLISION, TallyResult::SUM_SQ) - n * kv[0] * kv[0]) / + (n - 1); + cov(1, 1) = + (gt(GlobalTally::K_ABSORPTION, TallyResult::SUM_SQ) - n * kv[1] * kv[1]) / + (n - 1); + cov(2, 2) = + (gt(GlobalTally::K_TRACKLENGTH, TallyResult::SUM_SQ) - n * kv[2] * kv[2]) / + (n - 1); // Calculate covariances based on sums with Bessel's correction cov(0, 1) = (simulation::k_col_abs - n * kv[0] * kv[1]) / (n - 1); @@ -455,7 +474,7 @@ int openmc_get_keff(double* k_combined) // Calculate weighting double f = cov(j, j) * (cov(k, k) - cov(i, k)) - cov(k, k) * cov(i, j) + - cov(j, k) * (cov(i, j) + cov(i, k) - cov(j, k)); + cov(j, k) * (cov(i, j) + cov(i, k) - cov(j, k)); // Add to S sums for variance of combined estimate S[0] += f * cov(0, l); @@ -471,15 +490,15 @@ int openmc_get_keff(double* k_combined) for (auto& S_i : S) { S_i *= (n - 1); } - S[0] *= (n - 1)*(n - 1); + S[0] *= (n - 1) * (n - 1); // Calculate combined estimate of k-effective k_combined[0] /= g; // Calculate standard deviation of combined estimate - g *= (n - 1)*(n - 1); - k_combined[1] = std::sqrt(S[0] / (g*n*(n - 3)) * - (1 + n*((S[1] - 2*S[2]) / g))); + g *= (n - 1) * (n - 1); + k_combined[1] = + std::sqrt(S[0] / (g * n * (n - 3)) * (1 + n * ((S[1] - 2 * S[2]) / g))); } else { // Use only two estimators @@ -489,16 +508,15 @@ int openmc_get_keff(double* k_combined) // Store the commonly used term double f = kv[i] - kv[j]; - double g = cov(i, i) + cov(j, j) - 2.0*cov(i, j); + double g = cov(i, i) + cov(j, j) - 2.0 * cov(i, j); // Calculate combined estimate of k-effective k_combined[0] = kv[i] - (cov(i, i) - cov(i, j)) / g * f; // Calculate standard deviation of combined estimate - k_combined[1] = (cov(i, i)*cov(j, j) - cov(i, j)*cov(i, j)) * - (g + n*f*f) / (n*(n - 2)*g*g); + k_combined[1] = (cov(i, i) * cov(j, j) - cov(i, j) * cov(i, j)) * + (g + n * f * f) / (n * (n - 2) * g * g); k_combined[1] = std::sqrt(k_combined[1]); - } return 0; } @@ -507,13 +525,14 @@ void shannon_entropy() { // Get source weight in each mesh bin bool sites_outside; - xt::xtensor p = simulation::entropy_mesh->count_sites( - simulation::fission_bank.data(), simulation::fission_bank.size(), - &sites_outside); + xt::xtensor p = + simulation::entropy_mesh->count_sites(simulation::fission_bank.data(), + simulation::fission_bank.size(), &sites_outside); // display warning message if there were sites outside entropy box if (sites_outside) { - if (mpi::master) warning("Fission source site(s) outside of entropy box."); + if (mpi::master) + warning("Fission source site(s) outside of entropy box."); } if (mpi::master) { @@ -524,7 +543,7 @@ void shannon_entropy() double H = 0.0; for (auto p_i : p) { if (p_i > 0.0) { - H -= p_i * std::log(p_i)/std::log(2.0); + H -= p_i * std::log(p_i) / std::log(2.0); } } @@ -547,8 +566,9 @@ void ufs_count_sites() } else { // count number of source sites in each ufs mesh cell bool sites_outside; - simulation::source_frac = simulation::ufs_mesh->count_sites( - simulation::source_bank.data(), simulation::source_bank.size(), &sites_outside); + simulation::source_frac = + simulation::ufs_mesh->count_sites(simulation::source_bank.data(), + simulation::source_bank.size(), &sites_outside); // Check for sites outside of the mesh if (mpi::master && sites_outside) { @@ -558,7 +578,8 @@ void ufs_count_sites() #ifdef OPENMC_MPI // Send source fraction to all processors int n_bins = xt::prod(simulation::ufs_mesh->shape_)(); - MPI_Bcast(simulation::source_frac.data(), n_bins, MPI_DOUBLE, 0, mpi::intracomm); + MPI_Bcast( + simulation::source_frac.data(), n_bins, MPI_DOUBLE, 0, mpi::intracomm); #endif // Normalize to total weight to get fraction of source in each cell @@ -583,8 +604,8 @@ double ufs_get_weight(const Particle& p) } if (simulation::source_frac(mesh_bin) != 0.0) { - return simulation::ufs_mesh->volume_frac_ - / simulation::source_frac(mesh_bin); + return simulation::ufs_mesh->volume_frac_ / + simulation::source_frac(mesh_bin); } else { return 1.0; } @@ -609,7 +630,7 @@ void write_eigenvalue_hdf5(hid_t group) void read_eigenvalue_hdf5(hid_t group) { read_dataset(group, "generations_per_batch", settings::gen_per_batch); - int n = simulation::restart_batch*settings::gen_per_batch; + int n = simulation::restart_batch * settings::gen_per_batch; simulation::k_generation.resize(n); read_dataset(group, "k_generation", simulation::k_generation); if (settings::entropy_on) { diff --git a/src/endf.cpp b/src/endf.cpp index eb7e00e28..b42c8641d 100644 --- a/src/endf.cpp +++ b/src/endf.cpp @@ -26,24 +26,35 @@ Interpolation int2interp(int i) // should be accounted for in the distribution classes somehow. switch (i) { - case 1: case 11: case 21: + case 1: + case 11: + case 21: return Interpolation::histogram; - case 2: case 12: case 22: + case 2: + case 12: + case 22: return Interpolation::lin_lin; - case 3: case 13: case 23: + case 3: + case 13: + case 23: return Interpolation::lin_log; - case 4: case 14: case 24: + case 4: + case 14: + case 24: return Interpolation::log_lin; - case 5: case 15: case 25: + case 5: + case 15: + case 25: return Interpolation::log_log; default: - throw std::runtime_error{"Invalid interpolation code."}; + throw std::runtime_error {"Invalid interpolation code."}; } } bool is_fission(int mt) { - return mt == N_FISSION || mt == N_F || mt == N_NF || mt == N_2NF || mt == N_3NF; + return mt == N_FISSION || mt == N_F || mt == N_NF || mt == N_2NF || + mt == N_3NF; } bool is_disappearance(int mt) @@ -52,8 +63,8 @@ bool is_disappearance(int mt) return true; } else if (mt >= N_P0 && mt <= N_AC) { return true; - } else if (mt == N_TA || mt == N_DT || mt == N_P3HE || mt == N_D3HE - || mt == N_3HEA || mt == N_3P) { + } else if (mt == N_TA || mt == N_DT || mt == N_P3HE || mt == N_D3HE || + mt == N_3HEA || mt == N_3P) { return true; } else { return false; @@ -92,8 +103,8 @@ unique_ptr read_function(hid_t group, const char* name) } else if (func_type == "IncoherentElastic") { func = make_unique(dset); } else { - throw std::runtime_error{"Unknown function type " + func_type + - " for dataset " + object_name(dset)}; + throw std::runtime_error {"Unknown function type " + func_type + + " for dataset " + object_name(dset)}; } close_dataset(dset); return func; @@ -115,7 +126,7 @@ double Polynomial::operator()(double x) const // ordered in increasing powers of x. double y = 0.0; for (auto c = coef_.crbegin(); c != coef_.crend(); ++c) { - y = y*x + *c; + y = y * x + *c; } return y; } @@ -130,7 +141,8 @@ Tabulated1D::Tabulated1D(hid_t dset) n_regions_ = nbt_.size(); // Change 1-indexing to 0-indexing - for (auto& b : nbt_) --b; + for (auto& b : nbt_) + --b; vector int_temp; read_attribute(dset, "interpolation", int_temp); @@ -179,7 +191,8 @@ double Tabulated1D::operator()(double x) const } // handle special case of histogram interpolation - if (interp == Interpolation::histogram) return y_[i]; + if (interp == Interpolation::histogram) + return y_[i]; // determine bounding values double x0 = x_[i]; @@ -191,19 +204,19 @@ double Tabulated1D::operator()(double x) const double r; switch (interp) { case Interpolation::lin_lin: - r = (x - x0)/(x1 - x0); - return y0 + r*(y1 - y0); + r = (x - x0) / (x1 - x0); + return y0 + r * (y1 - y0); case Interpolation::lin_log: - r = log(x/x0)/log(x1/x0); - return y0 + r*(y1 - y0); + r = log(x / x0) / log(x1 / x0); + return y0 + r * (y1 - y0); case Interpolation::log_lin: - r = (x - x0)/(x1 - x0); - return y0*exp(r*log(y1/y0)); + r = (x - x0) / (x1 - x0); + return y0 * exp(r * log(y1 / y0)); case Interpolation::log_log: - r = log(x/x0)/log(x1/x0); - return y0*exp(r*log(y1/y0)); + r = log(x / x0) / log(x1 / x0); + return y0 * exp(r * log(y1 / y0)); default: - throw std::runtime_error{"Invalid interpolation scheme."}; + throw std::runtime_error {"Invalid interpolation scheme."}; } } @@ -233,7 +246,8 @@ double CoherentElasticXS::operator()(double E) const // section will be zero return 0.0; } else { - auto i_grid = lower_bound_index(bragg_edges_.begin(), bragg_edges_.end(), E); + auto i_grid = + lower_bound_index(bragg_edges_.begin(), bragg_edges_.end(), E); return factors_[i_grid] / E; } } @@ -254,7 +268,7 @@ double IncoherentElasticXS::operator()(double E) const { // Determine cross section using ENDF-102, Eq. (7.5) double W = debye_waller_; - return bound_xs_ / 2.0 * ((1 - std::exp(-4.0*E*W))/(2.0*E*W)); + return bound_xs_ / 2.0 * ((1 - std::exp(-4.0 * E * W)) / (2.0 * E * W)); } } // namespace openmc diff --git a/src/error.cpp b/src/error.cpp index d44e8766e..566950a97 100644 --- a/src/error.cpp +++ b/src/error.cpp @@ -3,7 +3,8 @@ #include "openmc/message_passing.h" #include "openmc/settings.h" -#if defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) +#if defined(__unix__) || defined(__unix) || \ + (defined(__APPLE__) && defined(__MACH__)) #include // for isatty #endif @@ -98,7 +99,8 @@ void warning(const std::string& message) void write_message(const std::string& message, int level) { // Only allow master to print to screen - if (!mpi::master) return; + if (!mpi::master) + return; if (level <= settings::verbosity) { std::cout << " "; diff --git a/src/event.cpp b/src/event.cpp index 895b1d62e..1db5c99d7 100644 --- a/src/event.cpp +++ b/src/event.cpp @@ -61,7 +61,7 @@ void dispatch_xs_event(int64_t buffer_idx) void process_init_events(int64_t n_particles, int64_t source_offset) { simulation::time_event_init.start(); - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < n_particles; i++) { initialize_history(simulation::particles[i], source_offset + i + 1); dispatch_xs_event(i); @@ -79,11 +79,13 @@ void process_calculate_xs_events(SharedArray& queue) // to C++17, std::sort is a serial only operation, which in this case // makes it too slow to be practical for most test problems. // - // std::sort(std::execution::par_unseq, queue.data(), queue.data() + queue.size()); + // std::sort(std::execution::par_unseq, queue.data(), queue.data() + + // queue.size()); - int64_t offset = simulation::advance_particle_queue.size();; + int64_t offset = simulation::advance_particle_queue.size(); + ; - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < queue.size(); i++) { Particle* p = &simulation::particles[queue[i].idx]; p->event_calculate_xs(); @@ -105,7 +107,7 @@ void process_advance_particle_events() { simulation::time_event_advance_particle.start(); - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < simulation::advance_particle_queue.size(); i++) { int64_t buffer_idx = simulation::advance_particle_queue[i].idx; Particle& p = simulation::particles[buffer_idx]; @@ -126,7 +128,7 @@ void process_surface_crossing_events() { simulation::time_event_surface_crossing.start(); - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < simulation::surface_crossing_queue.size(); i++) { int64_t buffer_idx = simulation::surface_crossing_queue[i].idx; Particle& p = simulation::particles[buffer_idx]; @@ -145,7 +147,7 @@ void process_collision_events() { simulation::time_event_collision.start(); - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < simulation::collision_queue.size(); i++) { int64_t buffer_idx = simulation::collision_queue[i].idx; Particle& p = simulation::particles[buffer_idx]; @@ -163,7 +165,7 @@ void process_collision_events() void process_death_events(int64_t n_particles) { simulation::time_event_death.start(); - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i = 0; i < n_particles; i++) { Particle& p = simulation::particles[i]; p.event_death(); diff --git a/src/finalize.cpp b/src/finalize.cpp index 6d207bd7a..b1e09a37e 100644 --- a/src/finalize.cpp +++ b/src/finalize.cpp @@ -20,9 +20,9 @@ #include "openmc/simulation.h" #include "openmc/source.h" #include "openmc/surface.h" +#include "openmc/tallies/tally.h" #include "openmc/thermal.h" #include "openmc/timer.h" -#include "openmc/tallies/tally.h" #include "openmc/volume_calc.h" #include "xtensor/xview.hpp" @@ -53,7 +53,7 @@ void free_memory() } } -} +} // namespace openmc using namespace openmc; @@ -139,7 +139,8 @@ int openmc_finalize() // Free all MPI types #ifdef OPENMC_MPI - if (mpi::source_site != MPI_DATATYPE_NULL) MPI_Type_free(&mpi::source_site); + if (mpi::source_site != MPI_DATATYPE_NULL) + MPI_Type_free(&mpi::source_site); #endif return 0; diff --git a/src/geometry.cpp b/src/geometry.cpp index 8f5bda38f..acce3fc78 100644 --- a/src/geometry.cpp +++ b/src/geometry.cpp @@ -13,14 +13,12 @@ #include "openmc/string_utils.h" #include "openmc/surface.h" - namespace openmc { //============================================================================== // Global variables //============================================================================== - namespace model { int root_universe {-1}; @@ -65,17 +63,21 @@ bool check_cell_overlap(Particle& p, bool error) //============================================================================== -int cell_instance_at_level(const Particle& p, int level) { +int cell_instance_at_level(const Particle& p, int level) +{ // throw error if the requested level is too deep for the geometry if (level > model::n_coord_levels) { - fatal_error(fmt::format("Cell instance at level {} requested, but only {} levels exist in the geometry.", level, p.n_coord())); + fatal_error(fmt::format("Cell instance at level {} requested, but only {} " + "levels exist in the geometry.", + level, p.n_coord())); } // determine the cell instance Cell& c {*model::cells[p.coord(level).cell]}; // quick exit if this cell doesn't have distribcell instances - if (c.distribcell_index_ == C_NONE) return C_NONE; + if (c.distribcell_index_ == C_NONE) + return C_NONE; // compute the cell's instance int instance = 0; @@ -96,8 +98,7 @@ int cell_instance_at_level(const Particle& p, int level) { //============================================================================== -bool -find_cell_inner(Particle& p, const NeighborList* neighbor_list) +bool find_cell_inner(Particle& p, const NeighborList* neighbor_list) { // Find which cell of this universe the particle is in. Use the neighbor list // to shorten the search if one was provided. @@ -109,7 +110,8 @@ find_cell_inner(Particle& p, const NeighborList* neighbor_list) // Make sure the search cell is in the same universe. int i_universe = p.coord(p.n_coord() - 1).universe; - if (model::cells[i_cell]->universe_ != i_universe) continue; + if (model::cells[i_cell]->universe_ != i_universe) + continue; // Check if this cell contains the particle. Position r {p.r_local()}; @@ -132,7 +134,7 @@ find_cell_inner(Particle& p, const NeighborList* neighbor_list) } // Check successively lower coordinate levels until finding material fill - for (;;++p.n_coord()) { + for (;; ++p.n_coord()) { // If we did not attempt to use neighbor lists, i_cell is still C_NONE. In // that case, we should now do an exhaustive search to find the right value // of i_cell. @@ -147,7 +149,9 @@ find_cell_inner(Particle& p, const NeighborList* neighbor_list) found = univ->find_cell(p); } - if (!found) { return found; } + if (!found) { + return found; + } i_cell = p.coord(p.n_coord() - 1).cell; // Announce the cell that the particle is entering. @@ -299,16 +303,17 @@ bool exhaustive_find_cell(Particle& p) //============================================================================== -void -cross_lattice(Particle& p, const BoundaryInfo& boundary) +void cross_lattice(Particle& p, const BoundaryInfo& boundary) { auto& coord {p.coord(p.n_coord() - 1)}; auto& lat {*model::lattices[coord.lattice]}; if (settings::verbosity >= 10 || p.trace()) { - write_message(fmt::format( - " Crossing lattice {}. Current position ({},{},{}). r={}", - lat.id_, coord.lattice_i[0], coord.lattice_i[1], coord.lattice_i[2], p.r()), 1); + write_message( + fmt::format(" Crossing lattice {}. Current position ({},{},{}). r={}", + lat.id_, coord.lattice_i[0], coord.lattice_i[1], coord.lattice_i[2], + p.r()), + 1); } // Set the lattice indices. @@ -380,23 +385,23 @@ BoundaryInfo distance_to_boundary(Particle& p) // Find the distance to the next lattice tile crossing. if (coord.lattice != C_NONE) { auto& lat {*model::lattices[coord.lattice]}; - //TODO: refactor so both lattice use the same position argument (which - //also means the lat.type attribute can be removed) + // TODO: refactor so both lattice use the same position argument (which + // also means the lat.type attribute can be removed) std::pair> lattice_distance; switch (lat.type_) { - case LatticeType::rect: - lattice_distance = lat.distance(r, u, coord.lattice_i); - break; - case LatticeType::hex: - auto& cell_above {model::cells[p.coord(i - 1).cell]}; - Position r_hex {p.coord(i - 1).r}; - r_hex -= cell_above->translation_; - if (coord.rotated) { - r_hex = r_hex.rotate(cell_above->rotation_); - } - r_hex.z = coord.r.z; - lattice_distance = lat.distance(r_hex, u, coord.lattice_i); - break; + case LatticeType::rect: + lattice_distance = lat.distance(r, u, coord.lattice_i); + break; + case LatticeType::hex: + auto& cell_above {model::cells[p.coord(i - 1).cell]}; + Position r_hex {p.coord(i - 1).r}; + r_hex -= cell_above->translation_; + if (coord.rotated) { + r_hex = r_hex.rotate(cell_above->rotation_); + } + r_hex.z = coord.r.z; + lattice_distance = lat.distance(r_hex, u, coord.lattice_i); + break; } d_lat = lattice_distance.first; level_lat_trans = lattice_distance.second; @@ -412,7 +417,7 @@ BoundaryInfo distance_to_boundary(Particle& p) // is selected. This logic must consider floating point precision. double& d = info.distance; if (d_surf < d_lat - FP_COINCIDENT) { - if (d == INFINITY || (d - d_surf)/d >= FP_REL_PRECISION) { + if (d == INFINITY || (d - d_surf) / d >= FP_REL_PRECISION) { d = d_surf; // If the cell is not simple, it is possible that both the negative and @@ -423,7 +428,7 @@ BoundaryInfo distance_to_boundary(Particle& p) info.surface_index = level_surf_cross; } else { Position r_hit = r + d_surf * u; - Surface& surf {*model::surfaces[std::abs(level_surf_cross)-1]}; + Surface& surf {*model::surfaces[std::abs(level_surf_cross) - 1]}; Direction norm = surf.normal(r_hit); if (u.dot(norm) > 0) { info.surface_index = std::abs(level_surf_cross); @@ -438,7 +443,7 @@ BoundaryInfo distance_to_boundary(Particle& p) info.coord_level = i + 1; } } else { - if (d == INFINITY || (d - d_lat)/d >= FP_REL_PRECISION) { + if (d == INFINITY || (d - d_lat) / d >= FP_REL_PRECISION) { d = d_lat; info.surface_index = 0; info.lattice_translation = level_lat_trans; @@ -453,12 +458,12 @@ BoundaryInfo distance_to_boundary(Particle& p) // C API //============================================================================== -extern "C" int -openmc_find_cell(const double* xyz, int32_t* index, int32_t* instance) +extern "C" int openmc_find_cell( + const double* xyz, int32_t* index, int32_t* instance) { Particle p; - p.r() = Position{xyz}; + p.r() = Position {xyz}; p.u() = {0.0, 0.0, 1.0}; if (!exhaustive_find_cell(p)) { @@ -471,7 +476,8 @@ openmc_find_cell(const double* xyz, int32_t* index, int32_t* instance) return 0; } -extern "C" int openmc_global_bounding_box(double* llc, double* urc) { +extern "C" int openmc_global_bounding_box(double* llc, double* urc) +{ auto bbox = model::universes.at(model::root_universe)->bounding_box(); // set lower left corner values diff --git a/src/geometry_aux.cpp b/src/geometry_aux.cpp index 857803421..842822d05 100644 --- a/src/geometry_aux.cpp +++ b/src/geometry_aux.cpp @@ -1,6 +1,6 @@ #include "openmc/geometry_aux.h" -#include // for std::max +#include // for std::max #include #include @@ -22,17 +22,17 @@ #include "openmc/tallies/filter_cell_instance.h" #include "openmc/tallies/filter_distribcell.h" - namespace openmc { namespace model { - std::unordered_map> universe_cell_counts; - std::unordered_map universe_level_counts; +std::unordered_map> + universe_cell_counts; +std::unordered_map universe_level_counts; } // namespace model - // adds the cell counts of universe b to universe a -void update_universe_cell_count(int32_t a, int32_t b) { +void update_universe_cell_count(int32_t a, int32_t b) +{ auto& universe_a_counts = model::universe_cell_counts[a]; const auto& universe_b_counts = model::universe_cell_counts[b]; for (const auto& it : universe_b_counts) { @@ -77,7 +77,7 @@ void read_geometry_xml() } if (settings::run_mode != RunMode::PLOTTING && !boundary_exists) { - fatal_error("No boundary conditions were applied to any surfaces!"); + fatal_error("No boundary conditions were applied to any surfaces!"); } // Allocate universes, universe cell arrays, and assign base universe @@ -89,8 +89,7 @@ void read_geometry_xml() //============================================================================== -void -adjust_indices() +void adjust_indices() { // Adjust material/fill idices. for (auto& c : model::cells) { @@ -106,7 +105,8 @@ adjust_indices() c->fill_ = search_lat->second; } else { fatal_error(fmt::format("Specified fill {} on cell {} is neither a " - "universe nor a lattice.", id, c->id_)); + "universe nor a lattice.", + id, c->id_)); } } else { c->type_ = Fill::MATERIAL; @@ -114,9 +114,9 @@ adjust_indices() if (mat_id != MATERIAL_VOID) { auto search = model::material_map.find(mat_id); if (search == model::material_map.end()) { - fatal_error(fmt::format( - "Could not find material {} specified on cell {}", - mat_id, c->id_)); + fatal_error( + fmt::format("Could not find material {} specified on cell {}", + mat_id, c->id_)); } // Change from ID to index mat_id = search->second; @@ -145,8 +145,7 @@ adjust_indices() //============================================================================== //! Partition some universes with many z-planes for faster find_cell searches. -void -partition_universes() +void partition_universes() { // Iterate over universes with more than 10 cells. (Fewer than 10 is likely // not worth partitioning.) @@ -156,7 +155,8 @@ partition_universes() std::unordered_set surf_inds; for (auto i_cell : univ->cells_) { for (auto token : model::cells[i_cell]->rpn_) { - if (token < OP_UNION) surf_inds.insert(std::abs(token) - 1); + if (token < OP_UNION) + surf_inds.insert(std::abs(token) - 1); } } @@ -178,13 +178,14 @@ partition_universes() //============================================================================== -void -assign_temperatures() +void assign_temperatures() { for (auto& c : model::cells) { // Ignore non-material cells and cells with defined temperature. - if (c->material_.size() == 0) continue; - if (c->sqrtkT_.size() > 0) continue; + if (c->material_.size() == 0) + continue; + if (c->sqrtkT_.size() > 0) + continue; c->sqrtkT_.reserve(c->material_.size()); for (auto i_mat : c->material_) { @@ -206,24 +207,26 @@ void get_temperatures( { for (const auto& cell : model::cells) { // Skip non-material cells. - if (cell->fill_ != C_NONE) continue; + if (cell->fill_ != C_NONE) + continue; for (int j = 0; j < cell->material_.size(); ++j) { // Skip void materials int i_material = cell->material_[j]; - if (i_material == MATERIAL_VOID) continue; + if (i_material == MATERIAL_VOID) + continue; // Get temperature(s) of cell (rounding to nearest integer) vector cell_temps; if (cell->sqrtkT_.size() == 1) { double sqrtkT = cell->sqrtkT_[0]; - cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); + cell_temps.push_back(sqrtkT * sqrtkT / K_BOLTZMANN); } else if (cell->sqrtkT_.size() == cell->material_.size()) { double sqrtkT = cell->sqrtkT_[j]; - cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); + cell_temps.push_back(sqrtkT * sqrtkT / K_BOLTZMANN); } else { for (double sqrtkT : cell->sqrtkT_) - cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); + cell_temps.push_back(sqrtkT * sqrtkT / K_BOLTZMANN); } const auto& mat {model::materials[i_material]}; @@ -267,8 +270,7 @@ void finalize_geometry() //============================================================================== -int32_t -find_root_universe() +int32_t find_root_universe() { // Find all the universes listed as a cell fill. std::unordered_set fill_univ_ids; @@ -302,16 +304,16 @@ find_root_universe() } } } - if (!root_found) fatal_error("Could not find a root universe. Make sure " - "there are no circular dependencies in the geometry."); + if (!root_found) + fatal_error("Could not find a root universe. Make sure " + "there are no circular dependencies in the geometry."); return root_univ; } //============================================================================== -void -prepare_distribcell(const std::vector* user_distribcells) +void prepare_distribcell(const std::vector* user_distribcells) { write_message("Preparing distributed cell instances...", 5); @@ -338,7 +340,8 @@ prepare_distribcell(const std::vector* user_distribcells) // By default, add material cells to the list of distributed cells if (settings::material_cell_offsets) { for (gsl::index i = 0; i < model::cells.size(); ++i) { - if (model::cells[i]->type_ == Fill::MATERIAL) distribcells.insert(i); + if (model::cells[i]->type_ == Fill::MATERIAL) + distribcells.insert(i); } } @@ -352,8 +355,8 @@ prepare_distribcell(const std::vector* user_distribcells) fatal_error(fmt::format( "Cell {} was specified with {} materials but has {} distributed " "instances. The number of materials must equal one or the number " - "of instances.", c.id_, c.material_.size(), c.n_instances_ - )); + "of instances.", + c.id_, c.material_.size(), c.n_instances_)); } } @@ -362,8 +365,8 @@ prepare_distribcell(const std::vector* user_distribcells) fatal_error(fmt::format( "Cell {} was specified with {} temperatures but has {} distributed " "instances. The number of temperatures must equal one or the number " - "of instances.", c.id_, c.sqrtkT_.size(), c.n_instances_ - )); + "of instances.", + c.id_, c.sqrtkT_.size(), c.n_instances_)); } } } @@ -392,8 +395,8 @@ prepare_distribcell(const std::vector* user_distribcells) lat->allocate_offset_table(n_maps); } - // Fill the cell and lattice offset tables. - #pragma omp parallel for +// Fill the cell and lattice offset tables. +#pragma omp parallel for for (int map = 0; map < target_univ_ids.size(); map++) { auto target_univ_id = target_univ_ids[map]; std::unordered_map univ_count_memo; @@ -405,13 +408,13 @@ prepare_distribcell(const std::vector* user_distribcells) if (c.type_ == Fill::UNIVERSE) { c.offset_[map] = offset; int32_t search_univ = c.fill_; - offset += count_universe_instances(search_univ, target_univ_id, - univ_count_memo); + offset += count_universe_instances( + search_univ, target_univ_id, univ_count_memo); } else if (c.type_ == Fill::LATTICE) { Lattice& lat = *model::lattices[c.fill_]; - offset = lat.fill_offset_table(offset, target_univ_id, map, - univ_count_memo); + offset = + lat.fill_offset_table(offset, target_univ_id, map, univ_count_memo); } } } @@ -420,8 +423,7 @@ prepare_distribcell(const std::vector* user_distribcells) //============================================================================== -void -count_cell_instances(int32_t univ_indx) +void count_cell_instances(int32_t univ_indx) { const auto univ_counts = model::universe_cell_counts.find(univ_indx); if (univ_counts != model::universe_cell_counts.end()) { @@ -452,8 +454,7 @@ count_cell_instances(int32_t univ_indx) //============================================================================== -int -count_universe_instances(int32_t search_univ, int32_t target_univ_id, +int count_universe_instances(int32_t search_univ, int32_t target_univ_id, std::unordered_map& univ_count_memo) { // If this is the target, it can't contain itself. @@ -473,15 +474,15 @@ count_universe_instances(int32_t search_univ, int32_t target_univ_id, if (c.type_ == Fill::UNIVERSE) { int32_t next_univ = c.fill_; - count += count_universe_instances(next_univ, target_univ_id, - univ_count_memo); + count += + count_universe_instances(next_univ, target_univ_id, univ_count_memo); } else if (c.type_ == Fill::LATTICE) { Lattice& lat = *model::lattices[c.fill_]; for (auto it = lat.begin(); it != lat.end(); ++it) { int32_t next_univ = *it; - count += count_universe_instances(next_univ, target_univ_id, - univ_count_memo); + count += + count_universe_instances(next_univ, target_univ_id, univ_count_memo); } } } @@ -494,9 +495,8 @@ count_universe_instances(int32_t search_univ, int32_t target_univ_id, //============================================================================== -std::string -distribcell_path_inner(int32_t target_cell, int32_t map, int32_t target_offset, - const Universe& search_univ, int32_t offset) +std::string distribcell_path_inner(int32_t target_cell, int32_t map, + int32_t target_offset, const Universe& search_univ, int32_t offset) { std::stringstream path; @@ -527,13 +527,14 @@ distribcell_path_inner(int32_t target_cell, int32_t map, int32_t target_offset, temp_offset = offset + c.offset_[map]; } else { Lattice& lat = *model::lattices[c.fill_]; - int32_t indx = lat.universes_.size()*map + lat.begin().indx_; + int32_t indx = lat.universes_.size() * map + lat.begin().indx_; temp_offset = offset + lat.offsets_[indx]; } // The desired cell is the first cell that gives an offset smaller or // equal to the target offset. - if (temp_offset <= target_offset) break; + if (temp_offset <= target_offset) + break; } } @@ -544,30 +545,30 @@ distribcell_path_inner(int32_t target_cell, int32_t map, int32_t target_offset, if (c.type_ == Fill::UNIVERSE) { // Recurse into the fill cell. offset += c.offset_[map]; - path << distribcell_path_inner(target_cell, map, target_offset, - *model::universes[c.fill_], offset); + path << distribcell_path_inner( + target_cell, map, target_offset, *model::universes[c.fill_], offset); return path.str(); } else { // Recurse into the lattice cell. Lattice& lat = *model::lattices[c.fill_]; path << "l" << lat.id_; for (ReverseLatticeIter it = lat.rbegin(); it != lat.rend(); ++it) { - int32_t indx = lat.universes_.size()*map + it.indx_; + int32_t indx = lat.universes_.size() * map + it.indx_; int32_t temp_offset = offset + lat.offsets_[indx]; if (temp_offset <= target_offset) { offset = temp_offset; path << "(" << lat.index_to_string(it.indx_) << ")->"; - path << distribcell_path_inner(target_cell, map, target_offset, - *model::universes[*it], offset); + path << distribcell_path_inner( + target_cell, map, target_offset, *model::universes[*it], offset); return path.str(); } } - throw std::runtime_error{"Error determining distribcell path."}; + throw std::runtime_error {"Error determining distribcell path."}; } } -std::string -distribcell_path(int32_t target_cell, int32_t map, int32_t target_offset) +std::string distribcell_path( + int32_t target_cell, int32_t map, int32_t target_offset) { auto& root_univ = *model::universes[model::root_universe]; return distribcell_path_inner(target_cell, map, target_offset, root_univ, 0); @@ -575,8 +576,7 @@ distribcell_path(int32_t target_cell, int32_t map, int32_t target_offset) //============================================================================== -int -maximum_levels(int32_t univ) +int maximum_levels(int32_t univ) { const auto level_count = model::universe_level_counts.find(univ); @@ -607,8 +607,7 @@ maximum_levels(int32_t univ) //============================================================================== -void -free_memory_geometry() +void free_memory_geometry() { model::cells.clear(); model::cell_map.clear(); diff --git a/src/hdf5_interface.cpp b/src/hdf5_interface.cpp index 522c9c262..48510d191 100644 --- a/src/hdf5_interface.cpp +++ b/src/hdf5_interface.cpp @@ -4,8 +4,8 @@ #include #include -#include "xtensor/xtensor.hpp" #include "xtensor/xarray.hpp" +#include "xtensor/xtensor.hpp" #include #include "hdf5.h" @@ -19,16 +19,13 @@ namespace openmc { -bool -attribute_exists(hid_t obj_id, const char* name) +bool attribute_exists(hid_t obj_id, const char* name) { htri_t out = H5Aexists_by_name(obj_id, ".", name, H5P_DEFAULT); return out > 0; } - -size_t -attribute_typesize(hid_t obj_id, const char* name) +size_t attribute_typesize(hid_t obj_id, const char* name) { hid_t attr = H5Aopen(obj_id, name, H5P_DEFAULT); hid_t filetype = H5Aget_type(attr); @@ -38,9 +35,7 @@ attribute_typesize(hid_t obj_id, const char* name) return n; } - -void -get_shape(hid_t obj_id, hsize_t* dims) +void get_shape(hid_t obj_id, hsize_t* dims) { auto type = H5Iget_type(obj_id); hid_t dspace; @@ -49,7 +44,7 @@ get_shape(hid_t obj_id, hsize_t* dims) } else if (type == H5I_ATTR) { dspace = H5Aget_space(obj_id); } else { - throw std::runtime_error{ + throw std::runtime_error { "Expected dataset or attribute in call to get_shape."}; } H5Sget_simple_extent_dims(dspace, dims, nullptr); @@ -74,7 +69,7 @@ vector object_shape(hid_t obj_id) } else if (type == H5I_ATTR) { dspace = H5Aget_space(obj_id); } else { - throw std::runtime_error{ + throw std::runtime_error { "Expected dataset or attribute in call to object_shape."}; } int n = H5Sget_simple_extent_ndims(dspace); @@ -88,8 +83,7 @@ vector object_shape(hid_t obj_id) return shape; } -void -get_shape_attr(hid_t obj_id, const char* name, hsize_t* dims) +void get_shape_attr(hid_t obj_id, const char* name, hsize_t* dims) { hid_t attr = H5Aopen(obj_id, name, H5P_DEFAULT); hid_t dspace = H5Aget_space(attr); @@ -98,9 +92,7 @@ get_shape_attr(hid_t obj_id, const char* name, hsize_t* dims) H5Aclose(attr); } - -hid_t -create_group(hid_t parent_id, char const *name) +hid_t create_group(hid_t parent_id, char const* name) { hid_t out = H5Gcreate(parent_id, name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if (out < 0) { @@ -109,30 +101,24 @@ create_group(hid_t parent_id, char const *name) return out; } - -hid_t -create_group(hid_t parent_id, const std::string &name) +hid_t create_group(hid_t parent_id, const std::string& name) { return create_group(parent_id, name.c_str()); } - -void -close_dataset(hid_t dataset_id) +void close_dataset(hid_t dataset_id) { - if (H5Dclose(dataset_id) < 0) fatal_error("Failed to close dataset"); + if (H5Dclose(dataset_id) < 0) + fatal_error("Failed to close dataset"); } - -void -close_group(hid_t group_id) +void close_group(hid_t group_id) { - if (H5Gclose(group_id) < 0) fatal_error("Failed to close group"); + if (H5Gclose(group_id) < 0) + fatal_error("Failed to close group"); } - -int -dataset_ndims(hid_t dset) +int dataset_ndims(hid_t dset) { hid_t dspace = H5Dget_space(dset); int ndims = H5Sget_simple_extent_ndims(dspace); @@ -140,9 +126,7 @@ dataset_ndims(hid_t dset) return ndims; } - -size_t -dataset_typesize(hid_t obj_id, const char* name) +size_t dataset_typesize(hid_t obj_id, const char* name) { hid_t dset = open_dataset(obj_id, name); hid_t filetype = H5Dget_type(dset); @@ -152,9 +136,7 @@ dataset_typesize(hid_t obj_id, const char* name) return n; } - -void -ensure_exists(hid_t obj_id, const char* name, bool attribute) +void ensure_exists(hid_t obj_id, const char* name, bool attribute) { if (attribute) { if (!attribute_exists(obj_id, name)) { @@ -163,31 +145,29 @@ ensure_exists(hid_t obj_id, const char* name, bool attribute) } } else { if (!object_exists(obj_id, name)) { - fatal_error(fmt::format("Object \"{}\" does not exist in object {}", - name, object_name(obj_id))); + fatal_error(fmt::format("Object \"{}\" does not exist in object {}", name, + object_name(obj_id))); } } } - -hid_t -file_open(const char* filename, char mode, bool parallel) +hid_t file_open(const char* filename, char mode, bool parallel) { bool create; unsigned int flags; switch (mode) { - case 'r': - case 'a': - create = false; - flags = (mode == 'r' ? H5F_ACC_RDONLY : H5F_ACC_RDWR); - break; - case 'w': - case 'x': - create = true; - flags = (mode == 'x' ? H5F_ACC_EXCL : H5F_ACC_TRUNC); - break; - default: - fatal_error(fmt::format("Invalid file mode: ", mode)); + case 'r': + case 'a': + create = false; + flags = (mode == 'r' ? H5F_ACC_RDONLY : H5F_ACC_RDWR); + break; + case 'w': + case 'x': + create = true; + flags = (mode == 'x' ? H5F_ACC_EXCL : H5F_ACC_TRUNC); + break; + default: + fatal_error(fmt::format("Invalid file mode: ", mode)); } hid_t plist = H5P_DEFAULT; @@ -213,14 +193,14 @@ file_open(const char* filename, char mode, bool parallel) #ifdef PHDF5 // Close the property list - if (parallel) H5Pclose(plist); + if (parallel) + H5Pclose(plist); #endif return file_id; } -hid_t -file_open(const std::string& filename, char mode, bool parallel) +hid_t file_open(const std::string& filename, char mode, bool parallel) { return file_open(filename.c_str(), mode, parallel); } @@ -235,15 +215,12 @@ void file_close(hid_t file_id) H5Fclose(file_id); } - -void -get_name(hid_t obj_id, char* name) +void get_name(hid_t obj_id, char* name) { size_t size = 1 + H5Iget_name(obj_id, nullptr, 0); H5Iget_name(obj_id, name, size); } - int get_num_datasets(hid_t group_id) { // Determine number of links in the group @@ -255,15 +232,15 @@ int get_num_datasets(hid_t group_id) int ndatasets = 0; for (hsize_t i = 0; i < info.nlinks; ++i) { // Determine type of object (and skip non-group) - H5Oget_info_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, - H5P_DEFAULT); - if (oinfo.type == H5O_TYPE_DATASET) ndatasets += 1; + H5Oget_info_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, H5P_DEFAULT); + if (oinfo.type == H5O_TYPE_DATASET) + ndatasets += 1; } return ndatasets; } - int get_num_groups(hid_t group_id) { // Determine number of links in the group @@ -275,17 +252,16 @@ int get_num_groups(hid_t group_id) int ngroups = 0; for (hsize_t i = 0; i < info.nlinks; ++i) { // Determine type of object (and skip non-group) - H5Oget_info_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, - H5P_DEFAULT); - if (oinfo.type == H5O_TYPE_GROUP) ngroups += 1; + H5Oget_info_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, H5P_DEFAULT); + if (oinfo.type == H5O_TYPE_GROUP) + ngroups += 1; } return ngroups; } - -void -get_datasets(hid_t group_id, char* name[]) +void get_datasets(hid_t group_id, char* name[]) { // Determine number of links in the group H5G_info_t info; @@ -297,24 +273,23 @@ get_datasets(hid_t group_id, char* name[]) size_t size; for (hsize_t i = 0; i < info.nlinks; ++i) { // Determine type of object (and skip non-group) - H5Oget_info_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, - H5P_DEFAULT); - if (oinfo.type != H5O_TYPE_DATASET) continue; + H5Oget_info_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, H5P_DEFAULT); + if (oinfo.type != H5O_TYPE_DATASET) + continue; // Get size of name - size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, - i, nullptr, 0, H5P_DEFAULT); + size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, + nullptr, 0, H5P_DEFAULT); // Read name H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, - name[count], size, H5P_DEFAULT); + name[count], size, H5P_DEFAULT); count += 1; } } - -void -get_groups(hid_t group_id, char* name[]) +void get_groups(hid_t group_id, char* name[]) { // Determine number of links in the group H5G_info_t info; @@ -326,17 +301,18 @@ get_groups(hid_t group_id, char* name[]) size_t size; for (hsize_t i = 0; i < info.nlinks; ++i) { // Determine type of object (and skip non-group) - H5Oget_info_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, - H5P_DEFAULT); - if (oinfo.type != H5O_TYPE_GROUP) continue; + H5Oget_info_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, H5P_DEFAULT); + if (oinfo.type != H5O_TYPE_GROUP) + continue; // Get size of name - size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, - i, nullptr, 0, H5P_DEFAULT); + size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, + nullptr, 0, H5P_DEFAULT); // Read name H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, - name[count], size, H5P_DEFAULT); + name[count], size, H5P_DEFAULT); count += 1; } } @@ -353,18 +329,19 @@ vector member_names(hid_t group_id, H5O_type_t type) vector names; for (hsize_t i = 0; i < info.nlinks; ++i) { // Determine type of object (and skip non-group) - H5Oget_info_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, - H5P_DEFAULT); - if (oinfo.type != type) continue; + H5Oget_info_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, &oinfo, H5P_DEFAULT); + if (oinfo.type != type) + continue; // Get size of name - size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, - i, nullptr, 0, H5P_DEFAULT); + size = 1 + H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, + nullptr, 0, H5P_DEFAULT); // Read name char* buffer = new char[size]; - H5Lget_name_by_idx(group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, - buffer, size, H5P_DEFAULT); + H5Lget_name_by_idx( + group_id, ".", H5_INDEX_NAME, H5_ITER_INC, i, buffer, size, H5P_DEFAULT); names.emplace_back(&buffer[0]); delete[] buffer; } @@ -381,8 +358,7 @@ vector dataset_names(hid_t group_id) return member_names(group_id, H5O_TYPE_DATASET); } -bool -object_exists(hid_t object_id, const char* name) +bool object_exists(hid_t object_id, const char* name) { htri_t out = H5LTpath_valid(object_id, name, true); if (out < 0) { @@ -391,9 +367,7 @@ object_exists(hid_t object_id, const char* name) return (out > 0); } - -std::string -object_name(hid_t obj_id) +std::string object_name(hid_t obj_id) { // Determine size and create buffer size_t size = 1 + H5Iget_name(obj_id, nullptr, 0); @@ -406,47 +380,36 @@ object_name(hid_t obj_id) return str; } - -hid_t -open_dataset(hid_t group_id, const char* name) +hid_t open_dataset(hid_t group_id, const char* name) { ensure_exists(group_id, name); return H5Dopen(group_id, name, H5P_DEFAULT); } - -hid_t -open_group(hid_t group_id, const char* name) +hid_t open_group(hid_t group_id, const char* name) { ensure_exists(group_id, name); return H5Gopen(group_id, name, H5P_DEFAULT); } -void -read_attr(hid_t obj_id, const char* name, hid_t mem_type_id, void* buffer) +void read_attr(hid_t obj_id, const char* name, hid_t mem_type_id, void* buffer) { hid_t attr = H5Aopen(obj_id, name, H5P_DEFAULT); H5Aread(attr, mem_type_id, buffer); H5Aclose(attr); } - -void -read_attr_double(hid_t obj_id, const char* name, double* buffer) +void read_attr_double(hid_t obj_id, const char* name, double* buffer) { read_attr(obj_id, name, H5T_NATIVE_DOUBLE, buffer); } - -void -read_attr_int(hid_t obj_id, const char* name, int* buffer) +void read_attr_int(hid_t obj_id, const char* name, int* buffer) { read_attr(obj_id, name, H5T_NATIVE_INT, buffer); } - -void -read_attr_string(hid_t obj_id, const char* name, size_t slen, char* buffer) +void read_attr_string(hid_t obj_id, const char* name, size_t slen, char* buffer) { // Create datatype for a string hid_t datatype = H5Tcopy(H5T_C_S1); @@ -461,13 +424,12 @@ read_attr_string(hid_t obj_id, const char* name, size_t slen, char* buffer) H5Tclose(datatype); } - -void -read_dataset_lowlevel(hid_t obj_id, const char* name, hid_t mem_type_id, - hid_t mem_space_id, bool indep, void* buffer) +void read_dataset_lowlevel(hid_t obj_id, const char* name, hid_t mem_type_id, + hid_t mem_space_id, bool indep, void* buffer) { hid_t dset = obj_id; - if (name) dset = open_dataset(obj_id, name); + if (name) + dset = open_dataset(obj_id, name); if (using_mpio_device(dset)) { #ifdef PHDF5 @@ -486,7 +448,8 @@ read_dataset_lowlevel(hid_t obj_id, const char* name, hid_t mem_type_id, H5Dread(dset, mem_type_id, mem_space_id, H5S_ALL, H5P_DEFAULT, buffer); } - if (name) H5Dclose(dset); + if (name) + H5Dclose(dset); } template<> @@ -508,32 +471,24 @@ void read_dataset(hid_t dset, xt::xarray>& arr, bool indep) arr = xt::adapt(buffer, shape); } - -void -read_double(hid_t obj_id, const char* name, double* buffer, bool indep) +void read_double(hid_t obj_id, const char* name, double* buffer, bool indep) { - read_dataset_lowlevel(obj_id, name, H5T_NATIVE_DOUBLE, H5S_ALL, indep, - buffer); + read_dataset_lowlevel( + obj_id, name, H5T_NATIVE_DOUBLE, H5S_ALL, indep, buffer); } - -void -read_int(hid_t obj_id, const char* name, int* buffer, bool indep) +void read_int(hid_t obj_id, const char* name, int* buffer, bool indep) { read_dataset_lowlevel(obj_id, name, H5T_NATIVE_INT, H5S_ALL, indep, buffer); } - -void -read_llong(hid_t obj_id, const char* name, long long* buffer, bool indep) +void read_llong(hid_t obj_id, const char* name, long long* buffer, bool indep) { read_dataset_lowlevel(obj_id, name, H5T_NATIVE_LLONG, H5S_ALL, indep, buffer); } - -void -read_string(hid_t obj_id, const char* name, size_t slen, char* buffer, - bool indep) +void read_string( + hid_t obj_id, const char* name, size_t slen, char* buffer, bool indep) { // Create datatype for a string hid_t datatype = H5Tcopy(H5T_C_S1); @@ -548,10 +503,8 @@ read_string(hid_t obj_id, const char* name, size_t slen, char* buffer, H5Tclose(datatype); } - -void -read_complex(hid_t obj_id, const char* name, std::complex* buffer, - bool indep) +void read_complex( + hid_t obj_id, const char* name, std::complex* buffer, bool indep) { // Create compound datatype for complex numbers struct complex_t { @@ -570,10 +523,8 @@ read_complex(hid_t obj_id, const char* name, std::complex* buffer, H5Tclose(complex_id); } - -void -read_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, - double* results) +void read_tally_results( + hid_t group_id, hsize_t n_filter, hsize_t n_score, double* results) { // Create dataspace for hyperslab in memory constexpr int ndim = 3; @@ -584,17 +535,15 @@ read_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, H5Sselect_hyperslab(memspace, H5S_SELECT_SET, start, nullptr, count, nullptr); // Read the dataset - read_dataset_lowlevel(group_id, "results", H5T_NATIVE_DOUBLE, memspace, - false, results); + read_dataset_lowlevel( + group_id, "results", H5T_NATIVE_DOUBLE, memspace, false, results); // Free resources H5Sclose(memspace); } - -void -write_attr(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, - hid_t mem_type_id, const void* buffer) +void write_attr(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, + hid_t mem_type_id, const void* buffer) { // If array is given, create a simple dataspace. Otherwise, create a scalar // datascape. @@ -606,8 +555,8 @@ write_attr(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, } // Create attribute and Write data - hid_t attr = H5Acreate(obj_id, name, mem_type_id, dspace, - H5P_DEFAULT, H5P_DEFAULT); + hid_t attr = + H5Acreate(obj_id, name, mem_type_id, dspace, H5P_DEFAULT, H5P_DEFAULT); H5Awrite(attr, mem_type_id, buffer); // Free resources @@ -615,25 +564,19 @@ write_attr(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, H5Sclose(dspace); } - -void -write_attr_double(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, - const double* buffer) +void write_attr_double(hid_t obj_id, int ndim, const hsize_t* dims, + const char* name, const double* buffer) { write_attr(obj_id, ndim, dims, name, H5T_NATIVE_DOUBLE, buffer); } - -void -write_attr_int(hid_t obj_id, int ndim, const hsize_t* dims, const char* name, - const int* buffer) +void write_attr_int(hid_t obj_id, int ndim, const hsize_t* dims, + const char* name, const int* buffer) { write_attr(obj_id, ndim, dims, name, H5T_NATIVE_INT, buffer); } - -void -write_attr_string(hid_t obj_id, const char* name, const char* buffer) +void write_attr_string(hid_t obj_id, const char* name, const char* buffer) { size_t n = strlen(buffer); if (n > 0) { @@ -648,9 +591,7 @@ write_attr_string(hid_t obj_id, const char* name, const char* buffer) } } - -void -write_dataset_lowlevel(hid_t group_id, int ndim, const hsize_t* dims, +void write_dataset_lowlevel(hid_t group_id, int ndim, const hsize_t* dims, const char* name, hid_t mem_type_id, hid_t mem_space_id, bool indep, const void* buffer) { @@ -663,8 +604,8 @@ write_dataset_lowlevel(hid_t group_id, int ndim, const hsize_t* dims, dspace = H5Screate(H5S_SCALAR); } - hid_t dset = H5Dcreate(group_id, name, mem_type_id, dspace, - H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + hid_t dset = H5Dcreate( + group_id, name, mem_type_id, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if (using_mpio_device(group_id)) { #ifdef PHDF5 @@ -688,64 +629,52 @@ write_dataset_lowlevel(hid_t group_id, int ndim, const hsize_t* dims, H5Sclose(dspace); } - -void -write_double(hid_t group_id, int ndim, const hsize_t* dims, const char* name, - const double* buffer, bool indep) +void write_double(hid_t group_id, int ndim, const hsize_t* dims, + const char* name, const double* buffer, bool indep) { - write_dataset_lowlevel(group_id, ndim, dims, name, H5T_NATIVE_DOUBLE, H5S_ALL, - indep, buffer); + write_dataset_lowlevel( + group_id, ndim, dims, name, H5T_NATIVE_DOUBLE, H5S_ALL, indep, buffer); } - -void -write_int(hid_t group_id, int ndim, const hsize_t* dims, const char* name, - const int* buffer, bool indep) +void write_int(hid_t group_id, int ndim, const hsize_t* dims, const char* name, + const int* buffer, bool indep) { - write_dataset_lowlevel(group_id, ndim, dims, name, H5T_NATIVE_INT, H5S_ALL, - indep, buffer); + write_dataset_lowlevel( + group_id, ndim, dims, name, H5T_NATIVE_INT, H5S_ALL, indep, buffer); } - -void -write_llong(hid_t group_id, int ndim, const hsize_t* dims, const char* name, - const long long* buffer, bool indep) +void write_llong(hid_t group_id, int ndim, const hsize_t* dims, + const char* name, const long long* buffer, bool indep) { - write_dataset_lowlevel(group_id, ndim, dims, name, H5T_NATIVE_LLONG, H5S_ALL, - indep, buffer); + write_dataset_lowlevel( + group_id, ndim, dims, name, H5T_NATIVE_LLONG, H5S_ALL, indep, buffer); } - -void -write_string(hid_t group_id, int ndim, const hsize_t* dims, size_t slen, - const char* name, const char* buffer, bool indep) +void write_string(hid_t group_id, int ndim, const hsize_t* dims, size_t slen, + const char* name, const char* buffer, bool indep) { if (slen > 0) { // Set up appropriate datatype for a fixed-length string hid_t datatype = H5Tcopy(H5T_C_S1); H5Tset_size(datatype, slen); - write_dataset_lowlevel(group_id, ndim, dims, name, datatype, H5S_ALL, indep, - buffer); + write_dataset_lowlevel( + group_id, ndim, dims, name, datatype, H5S_ALL, indep, buffer); // Free resources H5Tclose(datatype); } } - -void -write_string(hid_t group_id, const char* name, const std::string& buffer, - bool indep) +void write_string( + hid_t group_id, const char* name, const std::string& buffer, bool indep) { - write_string(group_id, 0, nullptr, buffer.length(), name, buffer.c_str(), - indep); + write_string( + group_id, 0, nullptr, buffer.length(), name, buffer.c_str(), indep); } - -void -write_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, - const double* results) +void write_tally_results( + hid_t group_id, hsize_t n_filter, hsize_t n_score, const double* results) { // Set dimensions of sum/sum_sq hyperslab to store constexpr int ndim = 3; @@ -759,15 +688,13 @@ write_tally_results(hid_t group_id, hsize_t n_filter, hsize_t n_score, // Create and write dataset write_dataset_lowlevel(group_id, ndim, count, "results", H5T_NATIVE_DOUBLE, - memspace, false, results); + memspace, false, results); // Free resources H5Sclose(memspace); } - -bool -using_mpio_device(hid_t obj_id) +bool using_mpio_device(hid_t obj_id) { // Determine file that this object is part of hid_t file_id = H5Iget_file_id(obj_id); @@ -800,7 +727,7 @@ template<> const hid_t H5TypeMap::type_id = H5T_NATIVE_INT64; template<> const hid_t H5TypeMap::type_id = H5T_NATIVE_DOUBLE; -template <> +template<> const hid_t H5TypeMap::type_id = H5T_NATIVE_CHAR; } // namespace openmc diff --git a/src/initialize.cpp b/src/initialize.cpp index d67d6b3b3..e53767691 100644 --- a/src/initialize.cpp +++ b/src/initialize.cpp @@ -37,7 +37,6 @@ #include "libmesh/libmesh.h" #endif - int openmc_init(int argc, char* argv[], const void* intracomm) { using namespace openmc; @@ -46,7 +45,7 @@ int openmc_init(int argc, char* argv[], const void* intracomm) // Check if intracomm was passed MPI_Comm comm; if (intracomm) { - comm = *static_cast(intracomm); + comm = *static_cast(intracomm); } else { comm = MPI_COMM_WORLD; } @@ -57,7 +56,8 @@ int openmc_init(int argc, char* argv[], const void* intracomm) // Parse command-line arguments int err = parse_command_line(argc, argv); - if (err) return err; + if (err) + return err; #ifdef LIBMESH @@ -67,23 +67,24 @@ int openmc_init(int argc, char* argv[], const void* intracomm) int n_threads = 1; #endif -// initialize libMesh if it hasn't been initialized already -// (if initialized externally, the libmesh_init object needs to be provided also) -if (!settings::libmesh_init && !libMesh::initialized()) { + // initialize libMesh if it hasn't been initialized already + // (if initialized externally, the libmesh_init object needs to be provided + // also) + if (!settings::libmesh_init && !libMesh::initialized()) { #ifdef OPENMC_MPI - // pass command line args, empty MPI communicator, and number of threads. - // Because libMesh was not initialized, we assume that OpenMC is the primary - // application and that its main MPI comm should be used. - settings::libmesh_init = - make_unique(argc, argv, comm, n_threads); + // pass command line args, empty MPI communicator, and number of threads. + // Because libMesh was not initialized, we assume that OpenMC is the primary + // application and that its main MPI comm should be used. + settings::libmesh_init = + make_unique(argc, argv, comm, n_threads); #else - // pass command line args, empty MPI communicator, and number of threads - settings::libmesh_init = - make_unique(argc, argv, 0, n_threads); + // pass command line args, empty MPI communicator, and number of threads + settings::libmesh_init = + make_unique(argc, argv, 0, n_threads); #endif - settings::libmesh_comm = &(settings::libmesh_init->comm()); -} + settings::libmesh_comm = &(settings::libmesh_init->comm()); + } #endif @@ -107,7 +108,8 @@ if (!settings::libmesh_init && !libMesh::initialized()) { read_input_xml(); // Check for particle restart run - if (settings::particle_restart_run) settings::run_mode = RunMode::PARTICLE; + if (settings::particle_restart_run) + settings::run_mode = RunMode::PARTICLE; // Stop initialization timer simulation::time_initialize.stop(); @@ -126,7 +128,8 @@ void initialize_mpi(MPI_Comm intracomm) // Initialize MPI int flag; MPI_Initialized(&flag); - if (!flag) MPI_Init(nullptr, nullptr); + if (!flag) + MPI_Init(nullptr, nullptr); // Determine number of processes and rank for each MPI_Comm_size(intracomm, &mpi::n_procs); @@ -150,18 +153,17 @@ void initialize_mpi(MPI_Comm intracomm) } int blocks[] {3, 3, 1, 1, 1, 1, 1, 1, 1}; - MPI_Datatype types[] {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_INT, MPI_INT, MPI_INT, MPI_LONG, MPI_LONG}; + MPI_Datatype types[] {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_INT, + MPI_INT, MPI_INT, MPI_LONG, MPI_LONG}; MPI_Type_create_struct(9, blocks, disp, types, &mpi::source_site); MPI_Type_commit(&mpi::source_site); } #endif // OPENMC_MPI - -int -parse_command_line(int argc, char* argv[]) +int parse_command_line(int argc, char* argv[]) { int last_flag = 0; - for (int i=1; i < argc; ++i) { + for (int i = 1; i < argc; ++i) { std::string arg {argv[i]}; if (arg[0] == '-') { if (arg == "-p" || arg == "--plot") { @@ -192,7 +194,8 @@ parse_command_line(int argc, char* argv[]) settings::path_particle_restart = argv[i]; settings::particle_restart_run = true; } else { - auto msg = fmt::format("Unrecognized file after restart flag: {}.", filetype); + auto msg = + fmt::format("Unrecognized file after restart flag: {}.", filetype); strcpy(openmc_err_msg, msg.c_str()); return OPENMC_E_INVALID_ARGUMENT; } @@ -200,20 +203,21 @@ parse_command_line(int argc, char* argv[]) // If its a restart run check for additional source file if (settings::restart_run && i + 1 < argc) { // Check if it has extension we can read - if (ends_with(argv[i+1], ".h5")) { + if (ends_with(argv[i + 1], ".h5")) { // Check file type is a source file - file_id = file_open(argv[i+1], 'r', true); + file_id = file_open(argv[i + 1], 'r', true); read_attribute(file_id, "filetype", filetype); file_close(file_id); if (filetype != "source") { - std::string msg {"Second file after restart flag must be a source file"}; + std::string msg { + "Second file after restart flag must be a source file"}; strcpy(openmc_err_msg, msg.c_str()); return OPENMC_E_INVALID_ARGUMENT; } // It is a source file - settings::path_sourcepoint = argv[i+1]; + settings::path_sourcepoint = argv[i + 1]; i += 1; } else { @@ -227,7 +231,7 @@ parse_command_line(int argc, char* argv[]) } } else if (arg == "-g" || arg == "--geometry-debug") { - settings::check_overlaps = true; + settings::check_overlaps = true; } else if (arg == "-c" || arg == "--volume") { settings::run_mode = RunMode::VOLUME; } else if (arg == "-s" || arg == "--threads") { @@ -304,18 +308,19 @@ void read_input_xml() if (settings::run_mode == RunMode::PLOTTING) { // Read plots.xml if it exists read_plots_xml(); - if (mpi::master && settings::verbosity >= 5) print_plot(); + if (mpi::master && settings::verbosity >= 5) + print_plot(); } else { // Write summary information - if (mpi::master && settings::output_summary) write_summary(); + if (mpi::master && settings::output_summary) + write_summary(); // Warn if overlap checking is on if (mpi::master && settings::check_overlaps) { warning("Cell overlap checking is ON."); } } - } } // namespace openmc diff --git a/src/lattice.cpp b/src/lattice.cpp index ee102eb3b..c69a235be 100644 --- a/src/lattice.cpp +++ b/src/lattice.cpp @@ -21,9 +21,9 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map lattice_map; - vector> lattices; -} +std::unordered_map lattice_map; +vector> lattices; +} // namespace model //============================================================================== // Lattice implementation @@ -49,21 +49,28 @@ Lattice::Lattice(pugi::xml_node lat_node) //============================================================================== LatticeIter Lattice::begin() -{return LatticeIter(*this, 0);} +{ + return LatticeIter(*this, 0); +} LatticeIter Lattice::end() -{return LatticeIter(*this, universes_.size());} +{ + return LatticeIter(*this, universes_.size()); +} ReverseLatticeIter Lattice::rbegin() -{return ReverseLatticeIter(*this, universes_.size()-1);} +{ + return ReverseLatticeIter(*this, universes_.size() - 1); +} ReverseLatticeIter Lattice::rend() -{return ReverseLatticeIter(*this, -1);} +{ + return ReverseLatticeIter(*this, -1); +} //============================================================================== -void -Lattice::adjust_indices() +void Lattice::adjust_indices() { // Adjust the indices for the universes array. for (LatticeIter it = begin(); it != end(); ++it) { @@ -91,9 +98,8 @@ Lattice::adjust_indices() //============================================================================== -int32_t -Lattice::fill_offset_table(int32_t offset, int32_t target_univ_id, int map, - std::unordered_map& univ_count_memo) +int32_t Lattice::fill_offset_table(int32_t offset, int32_t target_univ_id, + int map, std::unordered_map& univ_count_memo) { for (LatticeIter it = begin(); it != end(); ++it) { offsets_[map * universes_.size() + it.indx_] = offset; @@ -104,8 +110,7 @@ Lattice::fill_offset_table(int32_t offset, int32_t target_univ_id, int map, //============================================================================== -void -Lattice::to_hdf5(hid_t lattices_group) const +void Lattice::to_hdf5(hid_t lattices_group) const { // Make a group for the lattice. std::string group_name {"lattice "}; @@ -134,8 +139,7 @@ Lattice::to_hdf5(hid_t lattices_group) const // RectLattice implementation //============================================================================== -RectLattice::RectLattice(pugi::xml_node lat_node) - : Lattice {lat_node} +RectLattice::RectLattice(pugi::xml_node lat_node) : Lattice {lat_node} { type_ = LatticeType::rect; @@ -165,7 +169,9 @@ RectLattice::RectLattice(pugi::xml_node lat_node) } lower_left_[0] = stod(ll_words[0]); lower_left_[1] = stod(ll_words[1]); - if (is_3d_) {lower_left_[2] = stod(ll_words[2]);} + if (is_3d_) { + lower_left_[2] = stod(ll_words[2]); + } // Read the lattice pitches. std::string pitch_str {get_node_value(lat_node, "pitch")}; @@ -176,7 +182,9 @@ RectLattice::RectLattice(pugi::xml_node lat_node) } pitch_[0] = stod(pitch_words[0]); pitch_[1] = stod(pitch_words[1]); - if (is_3d_) {pitch_[2] = stod(pitch_words[2]);} + if (is_3d_) { + pitch_[2] = stod(pitch_words[2]); + } // Read the universes and make sure the correct number was specified. std::string univ_str {get_node_value(lat_node, "universes")}; @@ -216,9 +224,9 @@ int32_t const& RectLattice::operator[](array const& i_xyz) bool RectLattice::are_valid_indices(array const& i_xyz) const { - return ( (i_xyz[0] >= 0) && (i_xyz[0] < n_cells_[0]) - && (i_xyz[1] >= 0) && (i_xyz[1] < n_cells_[1]) - && (i_xyz[2] >= 0) && (i_xyz[2] < n_cells_[2])); + return ((i_xyz[0] >= 0) && (i_xyz[0] < n_cells_[0]) && (i_xyz[1] >= 0) && + (i_xyz[1] < n_cells_[1]) && (i_xyz[2] >= 0) && + (i_xyz[2] < n_cells_[2])); } //============================================================================== @@ -320,10 +328,10 @@ void RectLattice::get_indices( Position RectLattice::get_local_position( Position r, const array& i_xyz) const { - r.x -= (lower_left_.x + (i_xyz[0] + 0.5)*pitch_.x); - r.y -= (lower_left_.y + (i_xyz[1] + 0.5)*pitch_.y); + r.x -= (lower_left_.x + (i_xyz[0] + 0.5) * pitch_.x); + r.y -= (lower_left_.y + (i_xyz[1] + 0.5) * pitch_.y); if (is_3d_) { - r.z -= (lower_left_.z + (i_xyz[2] + 0.5)*pitch_.z); + r.z -= (lower_left_.z + (i_xyz[2] + 0.5) * pitch_.z); } return r; } @@ -339,16 +347,14 @@ int32_t& RectLattice::offset(int map, array const& i_xyz) //============================================================================== -int32_t -RectLattice::offset(int map, int indx) const +int32_t RectLattice::offset(int map, int indx) const { return offsets_[n_cells_[0] * n_cells_[1] * n_cells_[2] * map + indx]; } //============================================================================== -std::string -RectLattice::index_to_string(int indx) const +std::string RectLattice::index_to_string(int indx) const { int iz {indx / (n_cells_[0] * n_cells_[1])}; int iy {(indx - n_cells_[0] * n_cells_[1] * iz) / n_cells_[0]}; @@ -365,8 +371,7 @@ RectLattice::index_to_string(int indx) const //============================================================================== -void -RectLattice::to_hdf5_inner(hid_t lat_group) const +void RectLattice::to_hdf5_inner(hid_t lat_group) const { // Write basic lattice information. write_string(lat_group, "type", "rectangular", false); @@ -394,8 +399,8 @@ RectLattice::to_hdf5_inner(hid_t lat_group) const for (int m = 0; m < nz; m++) { for (int k = 0; k < ny; k++) { for (int j = 0; j < nx; j++) { - int indx1 = nx*ny*m + nx*k + j; - int indx2 = nx*ny*m + nx*(ny-k-1) + j; + int indx1 = nx * ny * m + nx * k + j; + int indx2 = nx * ny * m + nx * (ny - k - 1) + j; out[indx2] = model::universes[universes_[indx1]]->id_; } } @@ -411,8 +416,8 @@ RectLattice::to_hdf5_inner(hid_t lat_group) const for (int k = 0; k < ny; k++) { for (int j = 0; j < nx; j++) { - int indx1 = nx*k + j; - int indx2 = nx*(ny-k-1) + j; + int indx1 = nx * k + j; + int indx2 = nx * (ny - k - 1) + j; out[indx2] = model::universes[universes_[indx1]]->id_; } } @@ -426,8 +431,7 @@ RectLattice::to_hdf5_inner(hid_t lat_group) const // HexLattice implementation //============================================================================== -HexLattice::HexLattice(pugi::xml_node lat_node) - : Lattice {lat_node} +HexLattice::HexLattice(pugi::xml_node lat_node) : Lattice {lat_node} { type_ = LatticeType::hex; @@ -449,8 +453,8 @@ HexLattice::HexLattice(pugi::xml_node lat_node) } else if (orientation == "x") { orientation_ = Orientation::x; } else { - fatal_error("Unrecognized orientation '" + orientation - + "' for lattice " + std::to_string(id_)); + fatal_error("Unrecognized orientation '" + orientation + + "' for lattice " + std::to_string(id_)); } } else { orientation_ = Orientation::y; @@ -468,7 +472,9 @@ HexLattice::HexLattice(pugi::xml_node lat_node) } center_[0] = stod(center_words[0]); center_[1] = stod(center_words[1]); - if (is_3d_) {center_[2] = stod(center_words[2]);} + if (is_3d_) { + center_[2] = stod(center_words[2]); + } // Read the lattice pitches. std::string pitch_str {get_node_value(lat_node, "pitch")}; @@ -481,17 +487,19 @@ HexLattice::HexLattice(pugi::xml_node lat_node) "specified by 1 number."); } pitch_[0] = stod(pitch_words[0]); - if (is_3d_) {pitch_[1] = stod(pitch_words[1]);} + if (is_3d_) { + pitch_[1] = stod(pitch_words[1]); + } // Read the universes and make sure the correct number was specified. - int n_univ = (3*n_rings_*n_rings_ - 3*n_rings_ + 1) * n_axial_; + int n_univ = (3 * n_rings_ * n_rings_ - 3 * n_rings_ + 1) * n_axial_; std::string univ_str {get_node_value(lat_node, "universes")}; vector univ_words {split(univ_str)}; if (univ_words.size() != n_univ) { fatal_error(fmt::format( "Expected {} universes for a hexagonal lattice with {} rings and {} " - "axial levels but {} were specified.", n_univ, n_rings_, n_axial_, - univ_words.size())); + "axial levels but {} were specified.", + n_univ, n_rings_, n_axial_, univ_words.size())); } // Parse the universes. @@ -503,7 +511,7 @@ HexLattice::HexLattice(pugi::xml_node lat_node) // the following code walks a set of index values across the skewed array // in a manner that matches the input order. Note that i_x = 0, i_a = 0 // or i_a = 0, i_y = 0 corresponds to the center of the hexagonal lattice. - universes_.resize((2*n_rings_-1) * (2*n_rings_-1) * n_axial_, C_NONE); + universes_.resize((2 * n_rings_ - 1) * (2 * n_rings_ - 1) * n_axial_, C_NONE); if (orientation_ == Orientation::y) { fill_lattice_y(univ_words); } else { @@ -523,13 +531,13 @@ void HexLattice::fill_lattice_x(const vector& univ_words) // Map upper region of hexagonal lattice which is found in the // first n_rings-1 rows of the input. - for (int k = 0; k < n_rings_-1; k++) { + for (int k = 0; k < n_rings_ - 1; k++) { // Iterate over the input columns. - for (int j = 0; j < k+n_rings_; j++) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * m - + (2*n_rings_-1) * (i_y+n_rings_-1) - + (i_a+n_rings_-1); + for (int j = 0; j < k + n_rings_; j++) { + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * m + + (2 * n_rings_ - 1) * (i_y + n_rings_ - 1) + + (i_a + n_rings_ - 1); universes_[indx] = std::stoi(univ_words[input_index]); input_index++; // Move to the next right neighbour cell @@ -547,10 +555,10 @@ void HexLattice::fill_lattice_x(const vector& univ_words) i_a = -(n_rings_ - 1) + k; // Iterate over the input columns. - for (int j = 0; j < 2*n_rings_-k-1; j++) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * m - + (2*n_rings_-1) * (i_y+n_rings_-1) - + (i_a+n_rings_-1); + for (int j = 0; j < 2 * n_rings_ - k - 1; j++) { + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * m + + (2 * n_rings_ - 1) * (i_y + n_rings_ - 1) + + (i_a + n_rings_ - 1); universes_[indx] = std::stoi(univ_words[input_index]); input_index++; // Move to the next right neighbour cell @@ -575,15 +583,15 @@ void HexLattice::fill_lattice_y(const vector& univ_words) // Map upper triangular region of hexagonal lattice which is found in the // first n_rings-1 rows of the input. - for (int k = 0; k < n_rings_-1; k++) { + for (int k = 0; k < n_rings_ - 1; k++) { // Walk the index to lower-left neighbor of last row start. i_x -= 1; // Iterate over the input columns. - for (int j = 0; j < k+1; j++) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * m - + (2*n_rings_-1) * (i_a+n_rings_-1) - + (i_x+n_rings_-1); + for (int j = 0; j < k + 1; j++) { + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * m + + (2 * n_rings_ - 1) * (i_a + n_rings_ - 1) + + (i_x + n_rings_ - 1); universes_[indx] = std::stoi(univ_words[input_index]); input_index++; // Walk the index to the right neighbor (which is not adjacent). @@ -592,13 +600,13 @@ void HexLattice::fill_lattice_y(const vector& univ_words) } // Return the lattice index to the start of the current row. - i_x -= 2 * (k+1); - i_a += (k+1); + i_x -= 2 * (k + 1); + i_a += (k + 1); } // Map the middle square region of the hexagonal lattice which is found in // the next 2*n_rings-1 rows of the input. - for (int k = 0; k < 2*n_rings_-1; k++) { + for (int k = 0; k < 2 * n_rings_ - 1; k++) { if ((k % 2) == 0) { // Walk the index to the lower-left neighbor of the last row start. i_x -= 1; @@ -610,9 +618,9 @@ void HexLattice::fill_lattice_y(const vector& univ_words) // Iterate over the input columns. for (int j = 0; j < n_rings_ - (k % 2); j++) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * m - + (2*n_rings_-1) * (i_a+n_rings_-1) - + (i_x+n_rings_-1); + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * m + + (2 * n_rings_ - 1) * (i_a + n_rings_ - 1) + + (i_x + n_rings_ - 1); universes_[indx] = std::stoi(univ_words[input_index]); input_index++; // Walk the index to the right neighbor (which is not adjacent). @@ -621,21 +629,21 @@ void HexLattice::fill_lattice_y(const vector& univ_words) } // Return the lattice index to the start of the current row. - i_x -= 2*(n_rings_ - (k % 2)); + i_x -= 2 * (n_rings_ - (k % 2)); i_a += n_rings_ - (k % 2); } // Map the lower triangular region of the hexagonal lattice. - for (int k = 0; k < n_rings_-1; k++) { + for (int k = 0; k < n_rings_ - 1; k++) { // Walk the index to the lower-right neighbor of the last row start. i_x += 1; i_a -= 1; // Iterate over the input columns. - for (int j = 0; j < n_rings_-k-1; j++) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * m - + (2*n_rings_-1) * (i_a+n_rings_-1) - + (i_x+n_rings_-1); + for (int j = 0; j < n_rings_ - k - 1; j++) { + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * m + + (2 * n_rings_ - 1) * (i_a + n_rings_ - 1) + + (i_x + n_rings_ - 1); universes_[indx] = std::stoi(univ_words[input_index]); input_index++; // Walk the index to the right neighbor (which is not adjacent). @@ -644,7 +652,7 @@ void HexLattice::fill_lattice_y(const vector& univ_words) } // Return lattice index to start of current row. - i_x -= 2*(n_rings_ - k - 1); + i_x -= 2 * (n_rings_ - k - 1); i_a += n_rings_ - k - 1; } } @@ -654,30 +662,32 @@ void HexLattice::fill_lattice_y(const vector& univ_words) int32_t const& HexLattice::operator[](array const& i_xyz) { - int indx = (2*n_rings_-1)*(2*n_rings_-1) * i_xyz[2] - + (2*n_rings_-1) * i_xyz[1] - + i_xyz[0]; + int indx = (2 * n_rings_ - 1) * (2 * n_rings_ - 1) * i_xyz[2] + + (2 * n_rings_ - 1) * i_xyz[1] + i_xyz[0]; return universes_[indx]; } //============================================================================== LatticeIter HexLattice::begin() -{return LatticeIter(*this, n_rings_-1);} +{ + return LatticeIter(*this, n_rings_ - 1); +} ReverseLatticeIter HexLattice::rbegin() -{return ReverseLatticeIter(*this, universes_.size()-n_rings_);} +{ + return ReverseLatticeIter(*this, universes_.size() - n_rings_); +} //============================================================================== bool HexLattice::are_valid_indices(array const& i_xyz) const { // Check if (x, alpha, z) indices are valid, accounting for number of rings - return ((i_xyz[0] >= 0) && (i_xyz[1] >= 0) && (i_xyz[2] >= 0) - && (i_xyz[0] < 2*n_rings_-1) && (i_xyz[1] < 2*n_rings_-1) - && (i_xyz[0] + i_xyz[1] > n_rings_-2) - && (i_xyz[0] + i_xyz[1] < 3*n_rings_-2) - && (i_xyz[2] < n_axial_)); + return ((i_xyz[0] >= 0) && (i_xyz[1] >= 0) && (i_xyz[2] >= 0) && + (i_xyz[0] < 2 * n_rings_ - 1) && (i_xyz[1] < 2 * n_rings_ - 1) && + (i_xyz[0] + i_xyz[1] > n_rings_ - 2) && + (i_xyz[0] + i_xyz[1] < 3 * n_rings_ - 2) && (i_xyz[2] < n_axial_)); } //============================================================================== @@ -704,13 +714,13 @@ std::pair> HexLattice::distance( double gamma_dir; double delta_dir; if (orientation_ == Orientation::y) { - beta_dir = u.x * std::sqrt(3.0) / 2.0 + u.y / 2.0; - gamma_dir = u.x * std::sqrt(3.0) / 2.0 - u.y / 2.0; + beta_dir = u.x * std::sqrt(3.0) / 2.0 + u.y / 2.0; + gamma_dir = u.x * std::sqrt(3.0) / 2.0 - u.y / 2.0; delta_dir = u.y; } else { beta_dir = u.x; - gamma_dir = u.x / 2.0 - u.y * std::sqrt(3.0) / 2.0; - delta_dir = u.x / 2.0 + u.y * std::sqrt(3.0) / 2.0; + gamma_dir = u.x / 2.0 - u.y * std::sqrt(3.0) / 2.0; + delta_dir = u.x / 2.0 + u.y * std::sqrt(3.0) / 2.0; } // Note that hexagonal lattice distance calculations are performed @@ -722,7 +732,7 @@ std::pair> HexLattice::distance( // beta direction double d {INFTY}; array lattice_trans; - double edge = -copysign(0.5*pitch_[0], beta_dir); // Oncoming edge + double edge = -copysign(0.5 * pitch_[0], beta_dir); // Oncoming edge Position r_t; if (beta_dir > 0) { const array i_xyz_t {i_xyz[0] + 1, i_xyz[1], i_xyz[2]}; @@ -747,7 +757,7 @@ std::pair> HexLattice::distance( } // gamma direction - edge = -copysign(0.5*pitch_[0], gamma_dir); + edge = -copysign(0.5 * pitch_[0], gamma_dir); if (gamma_dir > 0) { const array i_xyz_t {i_xyz[0] + 1, i_xyz[1] - 1, i_xyz[2]}; r_t = get_local_position(r, i_xyz_t); @@ -759,7 +769,7 @@ std::pair> HexLattice::distance( if (orientation_ == Orientation::y) { gamma = r_t.x * std::sqrt(3.0) / 2.0 - r_t.y / 2.0; } else { - gamma = r_t.x / 2.0 - r_t.y * std::sqrt(3.0) / 2.0; + gamma = r_t.x / 2.0 - r_t.y * std::sqrt(3.0) / 2.0; } if ((std::abs(gamma - edge) > FP_PRECISION) && gamma_dir != 0) { double this_d = (edge - gamma) / gamma_dir; @@ -774,7 +784,7 @@ std::pair> HexLattice::distance( } // delta direction - edge = -copysign(0.5*pitch_[0], delta_dir); + edge = -copysign(0.5 * pitch_[0], delta_dir); if (delta_dir > 0) { const array i_xyz_t {i_xyz[0], i_xyz[1] + 1, i_xyz[2]}; r_t = get_local_position(r, i_xyz_t); @@ -784,9 +794,9 @@ std::pair> HexLattice::distance( } double delta; if (orientation_ == Orientation::y) { - delta = r_t.y; + delta = r_t.y; } else { - delta = r_t.x / 2.0 + r_t.y * std::sqrt(3.0) / 2.0; + delta = r_t.x / 2.0 + r_t.y * std::sqrt(3.0) / 2.0; } if ((std::abs(delta - edge) > FP_PRECISION) && delta_dir != 0) { double this_d = (edge - delta) / delta_dir; @@ -828,7 +838,9 @@ void HexLattice::get_indices( { // Offset the xyz by the lattice center. Position r_o {r.x - center_.x, r.y - center_.y, r.z}; - if (is_3d_) {r_o.z -= center_.z;} + if (is_3d_) { + r_o.z -= center_.z; + } // Index the z direction, accounting for coincidence result[2] = 0; @@ -888,20 +900,21 @@ void HexLattice::get_indices( const array i_xyz {result[0] + j, result[1] + i, 0}; Position r_t = get_local_position(r, i_xyz); // calculate distance - double d = r_t.x*r_t.x + r_t.y*r_t.y; + double d = r_t.x * r_t.x + r_t.y * r_t.y; // check for coincidence. Because the numerical error incurred // in hex geometry is higher than other geometries, the relative // coincidence is checked here so that coincidence is successfully // detected on large hex lattice with particles far from the origin // which have rounding errors larger than the FP_COINCIDENT thresdhold. - bool on_boundary = coincident(1.0, d_min/d); + bool on_boundary = coincident(1.0, d_min / d); if (d < d_min || on_boundary) { // normalize r_t and find dot product r_t /= std::sqrt(d); double dp = u.x * r_t.x + u.y * r_t.y; // do not update values if particle is on a // boundary and not moving into this cell - if (on_boundary && dp > dp_min) continue; + if (on_boundary && dp > dp_min) + continue; // update values d_min = d; i1_chg = j; @@ -923,37 +936,36 @@ Position HexLattice::get_local_position( { if (orientation_ == Orientation::y) { // x_l = x_g - (center + pitch_x*cos(30)*index_x) - r.x -= center_.x - + std::sqrt(3.0)/2.0 * (i_xyz[0] - n_rings_ + 1) * pitch_[0]; + r.x -= + center_.x + std::sqrt(3.0) / 2.0 * (i_xyz[0] - n_rings_ + 1) * pitch_[0]; // y_l = y_g - (center + pitch_x*index_x + pitch_y*sin(30)*index_y) - r.y -= (center_.y + (i_xyz[1] - n_rings_ + 1) * pitch_[0] - + (i_xyz[0] - n_rings_ + 1) * pitch_[0] / 2.0); + r.y -= (center_.y + (i_xyz[1] - n_rings_ + 1) * pitch_[0] + + (i_xyz[0] - n_rings_ + 1) * pitch_[0] / 2.0); } else { // x_l = x_g - (center + pitch_x*index_a + pitch_y*sin(30)*index_y) - r.x -= (center_.x + (i_xyz[0] - n_rings_ + 1) * pitch_[0] - + (i_xyz[1] - n_rings_ + 1) * pitch_[0] / 2.0); + r.x -= (center_.x + (i_xyz[0] - n_rings_ + 1) * pitch_[0] + + (i_xyz[1] - n_rings_ + 1) * pitch_[0] / 2.0); // y_l = y_g - (center + pitch_y*cos(30)*index_y) - r.y -= center_.y - + std::sqrt(3.0)/2.0 * (i_xyz[1] - n_rings_ + 1) * pitch_[0]; + r.y -= + center_.y + std::sqrt(3.0) / 2.0 * (i_xyz[1] - n_rings_ + 1) * pitch_[0]; } if (is_3d_) { - r.z -= center_.z - (0.5 * n_axial_ - i_xyz[2] - 0.5) * pitch_[1]; - } + r.z -= center_.z - (0.5 * n_axial_ - i_xyz[2] - 0.5) * pitch_[1]; + } return r; } //============================================================================== -bool -HexLattice::is_valid_index(int indx) const +bool HexLattice::is_valid_index(int indx) const { - int nx {2*n_rings_ - 1}; - int ny {2*n_rings_ - 1}; + int nx {2 * n_rings_ - 1}; + int ny {2 * n_rings_ - 1}; int iz = indx / (nx * ny); - int iy = (indx - nx*ny*iz) / nx; - int ix = indx - nx*ny*iz - nx*iy; + int iy = (indx - nx * ny * iz) / nx; + int ix = indx - nx * ny * iz - nx * iy; array i_xyz {ix, iy, iz}; return are_valid_indices(i_xyz); } @@ -962,28 +974,27 @@ HexLattice::is_valid_index(int indx) const int32_t& HexLattice::offset(int map, array const& i_xyz) { - int nx {2*n_rings_ - 1}; - int ny {2*n_rings_ - 1}; + int nx {2 * n_rings_ - 1}; + int ny {2 * n_rings_ - 1}; int nz {n_axial_}; - return offsets_[nx*ny*nz*map + nx*ny*i_xyz[2] + nx*i_xyz[1] + i_xyz[0]]; + return offsets_[nx * ny * nz * map + nx * ny * i_xyz[2] + nx * i_xyz[1] + + i_xyz[0]]; } -int32_t -HexLattice::offset(int map, int indx) const +int32_t HexLattice::offset(int map, int indx) const { - int nx {2*n_rings_ - 1}; - int ny {2*n_rings_ - 1}; + int nx {2 * n_rings_ - 1}; + int ny {2 * n_rings_ - 1}; int nz {n_axial_}; - return offsets_[nx*ny*nz*map + indx]; + return offsets_[nx * ny * nz * map + indx]; } //============================================================================== -std::string -HexLattice::index_to_string(int indx) const +std::string HexLattice::index_to_string(int indx) const { - int nx {2*n_rings_ - 1}; - int ny {2*n_rings_ - 1}; + int nx {2 * n_rings_ - 1}; + int ny {2 * n_rings_ - 1}; int iz {indx / (nx * ny)}; int iy {(indx - nx * ny * iz) / nx}; int ix {indx - nx * ny * iz - nx * iy}; @@ -999,8 +1010,7 @@ HexLattice::index_to_string(int indx) const //============================================================================== -void -HexLattice::to_hdf5_inner(hid_t lat_group) const +void HexLattice::to_hdf5_inner(hid_t lat_group) const { // Write basic lattice information. write_string(lat_group, "type", "hexagonal", false); @@ -1022,19 +1032,19 @@ HexLattice::to_hdf5_inner(hid_t lat_group) const } // Write the universe ids. - hsize_t nx {static_cast(2*n_rings_ - 1)}; - hsize_t ny {static_cast(2*n_rings_ - 1)}; + hsize_t nx {static_cast(2 * n_rings_ - 1)}; + hsize_t ny {static_cast(2 * n_rings_ - 1)}; hsize_t nz {static_cast(n_axial_)}; vector out(nx * ny * nz); for (int m = 0; m < nz; m++) { for (int k = 0; k < ny; k++) { for (int j = 0; j < nx; j++) { - int indx = nx*ny*m + nx*k + j; + int indx = nx * ny * m + nx * k + j; if (j + k < n_rings_ - 1) { // This array position is never used; put a -1 to indicate this. out[indx] = -1; - } else if (j + k > 3*n_rings_ - 3) { + } else if (j + k > 3 * n_rings_ - 3) { // This array position is never used; put a -1 to indicate this. out[indx] = -1; } else { @@ -1068,8 +1078,8 @@ void read_lattices(pugi::xml_node node) if (in_map == model::lattice_map.end()) { model::lattice_map[id] = i_lat; } else { - fatal_error(fmt::format( - "Two or more lattices use the same unique ID: {}", id)); + fatal_error( + fmt::format("Two or more lattices use the same unique ID: {}", id)); } } } diff --git a/src/main.cpp b/src/main.cpp index ccd2005bf..02a850ead 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,8 +8,8 @@ #include "openmc/particle_restart.h" #include "openmc/settings.h" - -int main(int argc, char* argv[]) { +int main(int argc, char* argv[]) +{ using namespace openmc; int err; @@ -29,30 +29,33 @@ int main(int argc, char* argv[]) { // start problem based on mode switch (settings::run_mode) { - case RunMode::FIXED_SOURCE: - case RunMode::EIGENVALUE: - err = openmc_run(); - break; - case RunMode::PLOTTING: - err = openmc_plot_geometry(); - break; - case RunMode::PARTICLE: - if (mpi::master) run_particle_restart(); - err = 0; - break; - case RunMode::VOLUME: - err = openmc_calculate_volumes(); - break; - default: - break; + case RunMode::FIXED_SOURCE: + case RunMode::EIGENVALUE: + err = openmc_run(); + break; + case RunMode::PLOTTING: + err = openmc_plot_geometry(); + break; + case RunMode::PARTICLE: + if (mpi::master) + run_particle_restart(); + err = 0; + break; + case RunMode::VOLUME: + err = openmc_calculate_volumes(); + break; + default: + break; } - if (err) fatal_error(openmc_err_msg); + if (err) + fatal_error(openmc_err_msg); // Finalize and free up memory err = openmc_finalize(); - if (err) fatal_error(openmc_err_msg); + if (err) + fatal_error(openmc_err_msg); - // If MPI is in use and enabled, terminate it + // If MPI is in use and enabled, terminate it #ifdef OPENMC_MPI MPI_Finalize(); #endif diff --git a/src/material.cpp b/src/material.cpp index c942b10a6..ca29ce740 100644 --- a/src/material.cpp +++ b/src/material.cpp @@ -3,8 +3,8 @@ #include // for min, max, sort, fill #include #include -#include #include +#include #include #include "xtensor/xbuilder.hpp" @@ -12,8 +12,8 @@ #include "xtensor/xview.hpp" #include "openmc/capi.h" -#include "openmc/cross_sections.h" #include "openmc/container_util.h" +#include "openmc/cross_sections.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/hdf5_interface.h" @@ -80,8 +80,8 @@ Material::Material(pugi::xml_node node) } else { double val = std::stod(get_node_value(density_node, "value")); if (val <= 0.0) { - fatal_error("Need to specify a positive density on material " - + std::to_string(id_) + "."); + fatal_error("Need to specify a positive density on material " + + std::to_string(id_) + "."); } if (units == "g/cc" || units == "g/cm3") { @@ -93,17 +93,18 @@ Material::Material(pugi::xml_node node) } else if (units == "atom/cc" || units == "atom/cm3") { density_ = 1.0e-24 * val; } else { - fatal_error("Unknown units '" + units + "' specified on material " - + std::to_string(id_) + "."); + fatal_error("Unknown units '" + units + "' specified on material " + + std::to_string(id_) + "."); } } } else { - fatal_error("Must specify element in material " - + std::to_string(id_) + "."); + fatal_error("Must specify element in material " + + std::to_string(id_) + "."); } if (node.child("element")) { - fatal_error("Unable to add an element to material " + std::to_string(id_) + + fatal_error( + "Unable to add an element to material " + std::to_string(id_) + " since the element option has been removed from the xml input. " "Elements can only be added via the Python API, which will expand " "elements into their natural nuclides."); @@ -113,9 +114,10 @@ Material::Material(pugi::xml_node node) // READ AND PARSE TAGS // Check to ensure material has at least one nuclide - if (!check_for_node(node, "nuclide") && !check_for_node(node, "macroscopic")) { - fatal_error("No macroscopic data or nuclides specified on material " - + std::to_string(id_)); + if (!check_for_node(node, "nuclide") && + !check_for_node(node, "macroscopic")) { + fatal_error("No macroscopic data or nuclides specified on material " + + std::to_string(id_)); } // Create list of macroscopic x/s based on those specified, just treat @@ -131,15 +133,15 @@ Material::Material(pugi::xml_node node) if (settings::run_CE && num_macros > 0) { fatal_error("Macroscopic can not be used in continuous-energy mode."); } else if (num_macros > 1) { - fatal_error("Only one macroscopic object permitted per material, " - + std::to_string(id_)); + fatal_error("Only one macroscopic object permitted per material, " + + std::to_string(id_)); } else if (num_macros == 1) { pugi::xml_node node_nuc = *node_macros.begin(); // Check for empty name on nuclide if (!check_for_node(node_nuc, "name")) { - fatal_error("No name specified on macroscopic data in material " - + std::to_string(id_)); + fatal_error("No name specified on macroscopic data in material " + + std::to_string(id_)); } // store nuclide name @@ -157,8 +159,8 @@ Material::Material(pugi::xml_node node) for (auto node_nuc : node.children("nuclide")) { // Check for empty name on nuclide if (!check_for_node(node_nuc, "name")) { - fatal_error("No name specified on nuclide in material " - + std::to_string(id_)); + fatal_error( + "No name specified on nuclide in material " + std::to_string(id_)); } // store nuclide name @@ -174,10 +176,12 @@ Material::Material(pugi::xml_node node) bool has_wo = check_for_node(node_nuc, "wo"); if (!has_ao && !has_wo) { - fatal_error("No atom or weight percent specified for nuclide: " + name); + fatal_error( + "No atom or weight percent specified for nuclide: " + name); } else if (has_ao && has_wo) { fatal_error("Cannot specify both atom and weight percents for a " - "nuclide: " + name); + "nuclide: " + + name); } // Copy atom/weight percents @@ -205,7 +209,8 @@ Material::Material(pugi::xml_node node) auto n = names.size(); nuclide_.reserve(n); atom_density_ = xt::empty({n}); - if (settings::photon_transport) element_.reserve(n); + if (settings::photon_transport) + element_.reserve(n); for (int i = 0; i < n; ++i) { const auto& name {names[i]}; @@ -214,7 +219,8 @@ Material::Material(pugi::xml_node node) // (cross_sections.xml for CE and the MGXS HDF5 for MG) LibraryKey key {Library::Type::neutron, name}; if (data::library_map.find(key) == data::library_map.end()) { - fatal_error("Could not find nuclide " + name + " in the " + fatal_error("Could not find nuclide " + name + + " in the " "nuclear data library."); } @@ -236,8 +242,8 @@ Material::Material(pugi::xml_node node) // Make sure photon cross section data is available LibraryKey key {Library::Type::photon, element}; if (data::library_map.find(key) == data::library_map.end()) { - fatal_error("Could not find element " + element - + " in cross_sections.xml."); + fatal_error( + "Could not find element " + element + " in cross_sections.xml."); } if (data::element_map.find(element) == data::element_map.end()) { @@ -273,13 +279,13 @@ Material::Material(pugi::xml_node node) // Check to make sure either all atom percents or all weight percents are // given if (!(xt::all(atom_density_ >= 0.0) || xt::all(atom_density_ <= 0.0))) { - fatal_error("Cannot mix atom and weight percents in material " - + std::to_string(id_)); + fatal_error( + "Cannot mix atom and weight percents in material " + std::to_string(id_)); } // Determine density if it is a sum value - if (sum_density) density_ = xt::sum(atom_density_)(); - + if (sum_density) + density_ = xt::sum(atom_density_)(); if (check_for_node(node, "temperature")) { temperature_ = std::stod(get_node_value(node, "temperature")); @@ -314,7 +320,7 @@ Material::Material(pugi::xml_node node) LibraryKey key {Library::Type::thermal, name}; if (data::library_map.find(key) == data::library_map.end()) { fatal_error("Could not find thermal scattering data " + name + - " in cross_sections.xml file."); + " in cross_sections.xml file."); } // Determine index of thermal scattering data in global @@ -351,7 +357,8 @@ void Material::finalize() } // Generate material bremsstrahlung data for electrons and positrons - if (settings::photon_transport && settings::electron_treatment == ElectronTreatment::TTB) { + if (settings::photon_transport && + settings::electron_treatment == ElectronTreatment::TTB) { this->init_bremsstrahlung(); } @@ -370,13 +377,14 @@ void Material::normalize_density() for (int i = 0; i < nuclide_.size(); ++i) { // determine atomic weight ratio int i_nuc = nuclide_[i]; - double awr = settings::run_CE ? - data::nuclides[i_nuc]->awr_ : data::mg.nuclides_[i_nuc].awr; + double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_ + : data::mg.nuclides_[i_nuc].awr; // if given weight percent, convert all values so that they are divided // by awr. thus, when a sum is done over the values, it's actually // sum(w/awr) - if (!percent_in_atom) atom_density_(i) = -atom_density_(i) / awr; + if (!percent_in_atom) + atom_density_(i) = -atom_density_(i) / awr; } // determine normalized atom percents. if given atom percents, this is @@ -390,9 +398,9 @@ void Material::normalize_density() double sum_percent = 0.0; for (int i = 0; i < nuclide_.size(); ++i) { int i_nuc = nuclide_[i]; - double awr = settings::run_CE ? - data::nuclides[i_nuc]->awr_ : data::mg.nuclides_[i_nuc].awr; - sum_percent += atom_density_(i)*awr; + double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_ + : data::mg.nuclides_[i_nuc].awr; + sum_percent += atom_density_(i) * awr; } sum_percent = 1.0 / sum_percent; density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent; @@ -436,19 +444,22 @@ void Material::init_thermal() // Check to make sure thermal scattering table matched a nuclide if (!found) { - fatal_error("Thermal scattering table " + data::thermal_scatt[ - table.index_table]->name_ + " did not match any nuclide on material " - + std::to_string(id_)); + fatal_error("Thermal scattering table " + + data::thermal_scatt[table.index_table]->name_ + + " did not match any nuclide on material " + + std::to_string(id_)); } } // Make sure each nuclide only appears in one table. for (int j = 0; j < tables.size(); ++j) { - for (int k = j+1; k < tables.size(); ++k) { + for (int k = j + 1; k < tables.size(); ++k) { if (tables[j].index_nuclide == tables[k].index_nuclide) { int index = nuclide_[tables[j].index_nuclide]; auto name = data::nuclides[index]->name_; - fatal_error(name + " in material " + std::to_string(id_) + " was found " + fatal_error( + name + " in material " + std::to_string(id_) + + " was found " "in multiple thermal scattering tables. Each nuclide can appear in " "only one table per material."); } @@ -488,8 +499,8 @@ void Material::collision_stopping_power(double* s_col, bool positron) double awr = data::nuclides[nuclide_[i]]->awr_; // Get atomic density of nuclide given atom/weight percent - double atom_density = (atom_density_[0] > 0.0) ? - atom_density_[i] : -atom_density_[i] / awr; + double atom_density = + (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr; electron_density += atom_density * elm.Z_; mass_density += atom_density * awr * MASS_NEUTRON; @@ -506,58 +517,60 @@ void Material::collision_stopping_power(double* s_col, bool positron) } log_I /= electron_density; n_conduction /= electron_density; - for (auto& f_i : f) f_i /= electron_density; + for (auto& f_i : f) + f_i /= electron_density; // Get density in g/cm^3 if it is given in atom/b-cm double density = (density_ < 0.0) ? -density_ : mass_density / N_AVOGADRO; // Calculate the square of the plasma energy - double e_p_sq = PLANCK_C * PLANCK_C * PLANCK_C * N_AVOGADRO * - electron_density * density / (2.0 * PI * PI * FINE_STRUCTURE * - MASS_ELECTRON_EV * mass_density); + double e_p_sq = + PLANCK_C * PLANCK_C * PLANCK_C * N_AVOGADRO * electron_density * density / + (2.0 * PI * PI * FINE_STRUCTURE * MASS_ELECTRON_EV * mass_density); // Get the Sternheimer adjustment factor - double rho = sternheimer_adjustment(f, e_b_sq, e_p_sq, n_conduction, log_I, - 1.0e-6, 100); + double rho = + sternheimer_adjustment(f, e_b_sq, e_p_sq, n_conduction, log_I, 1.0e-6, 100); // Classical electron radius in cm constexpr double CM_PER_ANGSTROM {1.0e-8}; - constexpr double r_e = CM_PER_ANGSTROM * PLANCK_C / (2.0 * PI * - FINE_STRUCTURE * MASS_ELECTRON_EV); + constexpr double r_e = + CM_PER_ANGSTROM * PLANCK_C / (2.0 * PI * FINE_STRUCTURE * MASS_ELECTRON_EV); // Constant in expression for collision stopping power constexpr double BARN_PER_CM_SQ {1.0e24}; - double c = BARN_PER_CM_SQ * 2.0 * PI * r_e * r_e * MASS_ELECTRON_EV * - electron_density; + double c = + BARN_PER_CM_SQ * 2.0 * PI * r_e * r_e * MASS_ELECTRON_EV * electron_density; // Loop over incident charged particle energies for (int i = 0; i < data::ttb_e_grid.size(); ++i) { double E = data::ttb_e_grid(i); // Get the density effect correction - double delta = density_effect(f, e_b_sq, e_p_sq, n_conduction, rho, E, - 1.0e-6, 100); + double delta = + density_effect(f, e_b_sq, e_p_sq, n_conduction, rho, E, 1.0e-6, 100); // Square of the ratio of the speed of light to the velocity of the charged // particle - double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) / ((E + MASS_ELECTRON_EV) - * (E + MASS_ELECTRON_EV)); + double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) / + ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV)); double tau = E / MASS_ELECTRON_EV; double F; if (positron) { double t = tau + 2.0; - F = std::log(4.0) - (beta_sq / 12.0) * (23.0 + 14.0 / t + 10.0 / (t * t) - + 4.0 / (t * t * t)); + F = std::log(4.0) - (beta_sq / 12.0) * (23.0 + 14.0 / t + 10.0 / (t * t) + + 4.0 / (t * t * t)); } else { - F = (1.0 - beta_sq) * (1.0 + tau * tau / 8.0 - (2.0 * tau + 1.0) * - std::log(2.0)); + F = (1.0 - beta_sq) * + (1.0 + tau * tau / 8.0 - (2.0 * tau + 1.0) * std::log(2.0)); } // Calculate the collision stopping power for this energy - s_col[i] = c / beta_sq * (2.0 * (std::log(E) - log_I) + std::log(1.0 + tau - / 2.0) + F - delta); + s_col[i] = + c / beta_sq * + (2.0 * (std::log(E) - log_I) + std::log(1.0 + tau / 2.0) + F - delta); } } @@ -575,7 +588,8 @@ void Material::init_bremsstrahlung() for (int particle = 0; particle < 2; ++particle) { // Loop over logic twice, once for electron, once for positron - BremsstrahlungData* ttb = (particle == 0) ? &ttb_->electron : &ttb_->positron; + BremsstrahlungData* ttb = + (particle == 0) ? &ttb_->electron : &ttb_->positron; bool positron = (particle == 1); // Allocate arrays for TTB data @@ -594,16 +608,17 @@ void Material::init_bremsstrahlung() // Get the collision stopping power of the material this->collision_stopping_power(stopping_power_collision.data(), positron); - // Calculate the molecular DCS and the molecular radiative stopping power using - // Bragg's additivity rule. + // Calculate the molecular DCS and the molecular radiative stopping power + // using Bragg's additivity rule. for (int i = 0; i < n; ++i) { // Get pointer to current element const auto& elm = *data::elements[element_[i]]; double awr = data::nuclides[nuclide_[i]]->awr_; - // Get atomic density and mass density of nuclide given atom/weight percent - double atom_density = (atom_density_[0] > 0.0) ? - atom_density_[i] : -atom_density_[i] / awr; + // Get atomic density and mass density of nuclide given atom/weight + // percent + double atom_density = + (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr; // Calculate the "equivalent" atomic number Zeq of the material Z_eq_sq += atom_density * elm.Z_ * elm.Z_; @@ -626,11 +641,14 @@ void Material::init_bremsstrahlung() // Issy-les-Moulineaux, France (2011). if (positron) { for (int i = 0; i < n_e; ++i) { - double t = std::log(1.0 + 1.0e6*data::ttb_e_grid(i)/(Z_eq_sq*MASS_ELECTRON_EV)); - double r = 1.0 - std::exp(-1.2359e-1*t + 6.1274e-2*std::pow(t, 2) - - 3.1516e-2*std::pow(t, 3) + 7.7446e-3*std::pow(t, 4) - - 1.0595e-3*std::pow(t, 5) + 7.0568e-5*std::pow(t, 6) - - 1.808e-6*std::pow(t, 7)); + double t = std::log( + 1.0 + 1.0e6 * data::ttb_e_grid(i) / (Z_eq_sq * MASS_ELECTRON_EV)); + double r = + 1.0 - + std::exp(-1.2359e-1 * t + 6.1274e-2 * std::pow(t, 2) - + 3.1516e-2 * std::pow(t, 3) + 7.7446e-3 * std::pow(t, 4) - + 1.0595e-3 * std::pow(t, 5) + 7.0568e-5 * std::pow(t, 6) - + 1.808e-6 * std::pow(t, 7)); stopping_power_radiative(i) *= r; auto dcs_i = xt::view(dcs, i, xt::all()); dcs_i *= r; @@ -638,8 +656,8 @@ void Material::init_bremsstrahlung() } // Total material stopping power - xt::xtensor stopping_power = stopping_power_collision + - stopping_power_radiative; + xt::xtensor stopping_power = + stopping_power_collision + stopping_power_radiative; // Loop over photon energies xt::xtensor f({n_e}, 0.0); @@ -655,8 +673,8 @@ void Material::init_bremsstrahlung() double k = w / e; // Find the lower bounding index of the reduced photon energy - int i_k = lower_bound_index(data::ttb_k_grid.cbegin(), - data::ttb_k_grid.cend(), k); + int i_k = lower_bound_index( + data::ttb_k_grid.cbegin(), data::ttb_k_grid.cend(), k); // Get the interpolation bounds double k_l = data::ttb_k_grid(i_k); @@ -666,12 +684,12 @@ void Material::init_bremsstrahlung() // Find the value of the DCS using linear interpolation in reduced // photon energy k - double x = x_l + (k - k_l)*(x_r - x_l)/(k_r - k_l); + double x = x_l + (k - k_l) * (x_r - x_l) / (k_r - k_l); // Square of the ratio of the speed of light to the velocity of the // charged particle - double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) / ((e + - MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV)); + double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) / + ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV)); // Compute the integrand of the PDF f(j) = x / (beta_sq * stopping_power(j) * w); @@ -688,19 +706,20 @@ void Material::init_bremsstrahlung() double c = 0.0; for (int j = i; j < n_e - 1; ++j) { c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i), - data::ttb_e_grid(j), data::ttb_e_grid(j+1)); + data::ttb_e_grid(j), data::ttb_e_grid(j + 1)); - ttb->pdf(j+1,i) = c; + ttb->pdf(j + 1, i) = c; } - // Integrate the last two points using trapezoidal rule in log-log space + // Integrate the last two points using trapezoidal rule in log-log space } else { double e_l = std::log(data::ttb_e_grid(i)); - double e_r = std::log(data::ttb_e_grid(i+1)); + double e_r = std::log(data::ttb_e_grid(i + 1)); double x_l = std::log(f(i)); - double x_r = std::log(f(i+1)); + double x_r = std::log(f(i + 1)); - ttb->pdf(i+1,i) = 0.5*(e_r - e_l)*(std::exp(e_l + x_l) + std::exp(e_r + x_r)); + ttb->pdf(i + 1, i) = + 0.5 * (e_r - e_l) * (std::exp(e_l + x_l) + std::exp(e_r + x_r)); } } @@ -708,7 +727,7 @@ void Material::init_bremsstrahlung() for (int j = 1; j < n_e; ++j) { // Set last element of PDF to small non-zero value to enable log-log // interpolation - ttb->pdf(j,j) = std::exp(-500.0); + ttb->pdf(j, j) = std::exp(-500.0); // Loop over photon energies double c = 0.0; @@ -716,12 +735,12 @@ void Material::init_bremsstrahlung() // Integrate the CDF from the PDF using the trapezoidal rule in log-log // space double w_l = std::log(data::ttb_e_grid(i)); - double w_r = std::log(data::ttb_e_grid(i+1)); - double x_l = std::log(ttb->pdf(j,i)); - double x_r = std::log(ttb->pdf(j,i+1)); + double w_r = std::log(data::ttb_e_grid(i + 1)); + double x_l = std::log(ttb->pdf(j, i)); + double x_r = std::log(ttb->pdf(j, i + 1)); - c += 0.5*(w_r - w_l)*(std::exp(w_l + x_l) + std::exp(w_r + x_r)); - ttb->cdf(j,i+1) = c; + c += 0.5 * (w_r - w_l) * (std::exp(w_l + x_l) + std::exp(w_r + x_r)); + ttb->cdf(j, i + 1) = c; } // Set photon number yield @@ -735,8 +754,7 @@ void Material::init_bremsstrahlung() void Material::init_nuclide_index() { - int n = settings::run_CE ? - data::nuclides.size() : data::mg.nuclides_.size(); + int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size(); mat_nuclide_index_.resize(n); std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE); for (int i = 0; i < nuclide_.size(); ++i) { @@ -798,7 +816,8 @@ void Material::calculate_neutron_xs(Particle& p) const ++j; // Don't check for S(a,b) tables if there are no more left - if (j == thermal_tables_.size()) check_sab = false; + if (j == thermal_tables_.size()) + check_sab = false; } } @@ -877,7 +896,8 @@ void Material::set_id(int32_t id) // Make sure no other material has same ID if (model::material_map.find(id) != model::material_map.end()) { - throw std::runtime_error{"Two materials have the same ID: " + std::to_string(id)}; + throw std::runtime_error { + "Two materials have the same ID: " + std::to_string(id)}; } // If no ID specified, auto-assign next ID in sequence @@ -899,7 +919,7 @@ void Material::set_density(double density, gsl::cstring_span units) Expects(density >= 0.0); if (nuclide_.empty()) { - throw std::runtime_error{"No nuclides exist in material yet."}; + throw std::runtime_error {"No nuclides exist in material yet."}; } if (units == "atom/b-cm") { @@ -930,8 +950,8 @@ void Material::set_density(double density, gsl::cstring_span units) density_ *= f; atom_density_ *= f; } else { - throw std::invalid_argument{"Invalid units '" + std::string(units.data()) - + "' specified."}; + throw std::invalid_argument { + "Invalid units '" + std::string(units.data()) + "' specified."}; } } @@ -945,7 +965,8 @@ void Material::set_densities( if (n != nuclide_.size()) { nuclide_.resize(n); atom_density_ = xt::zeros({n}); - if (settings::photon_transport) element_.resize(n); + if (settings::photon_transport) + element_.resize(n); } double sum_density = 0.0; @@ -953,7 +974,8 @@ void Material::set_densities( const auto& nuc {name[i]}; if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) { int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0); - if (err < 0) throw std::runtime_error{openmc_err_msg}; + if (err < 0) + throw std::runtime_error {openmc_err_msg}; } nuclide_[i] = data::nuclide_map.at(nuc); @@ -971,7 +993,8 @@ void Material::set_densities( this->set_density(sum_density, "atom/b-cm"); // Generate material bremsstrahlung data for electrons and positrons - if (settings::photon_transport && settings::electron_treatment == ElectronTreatment::TTB) { + if (settings::photon_transport && + settings::electron_treatment == ElectronTreatment::TTB) { this->init_bremsstrahlung(); } @@ -982,8 +1005,8 @@ void Material::set_densities( double Material::volume() const { if (volume_ < 0.0) { - throw std::runtime_error{"Volume for material with ID=" - + std::to_string(id_) + " not set."}; + throw std::runtime_error { + "Volume for material with ID=" + std::to_string(id_) + " not set."}; } return volume_; } @@ -1077,8 +1100,8 @@ void Material::add_nuclide(const std::string& name, double density) if (data::nuclides[i_nuc]->name_ == name) { double awr = data::nuclides[i_nuc]->awr_; density_ += density - atom_density_(i); - density_gpcc_ += (density - atom_density_(i)) - * awr * MASS_NEUTRON / N_AVOGADRO; + density_gpcc_ += + (density - atom_density_(i)) * awr * MASS_NEUTRON / N_AVOGADRO; atom_density_(i) = density; return; } @@ -1086,7 +1109,8 @@ void Material::add_nuclide(const std::string& name, double density) // If nuclide wasn't found, extend nuclide/density arrays int err = openmc_load_nuclide(name.c_str(), nullptr, 0); - if (err < 0) throw std::runtime_error{openmc_err_msg}; + if (err < 0) + throw std::runtime_error {openmc_err_msg}; // Append new nuclide/density int i_nuc = data::nuclide_map[name]; @@ -1102,13 +1126,13 @@ void Material::add_nuclide(const std::string& name, double density) // Create copy of atom_density_ array with one extra entry xt::xtensor atom_density = xt::zeros({n}); - xt::view(atom_density, xt::range(0, n-1)) = atom_density_; - atom_density(n-1) = density; + xt::view(atom_density, xt::range(0, n - 1)) = atom_density_; + atom_density(n - 1) = density; atom_density_ = atom_density; density_ += density; - density_gpcc_ += density * data::nuclides[i_nuc]->awr_ - * MASS_NEUTRON / N_AVOGADRO; + density_gpcc_ += + density * data::nuclides[i_nuc]->awr_ * MASS_NEUTRON / N_AVOGADRO; } //============================================================================== @@ -1147,10 +1171,12 @@ double sternheimer_adjustment(const vector& f, rho -= (g - 2.0 * log_I) / (2.0 * gp); // If the initial guess is too large, rho can be negative - if (rho < 0.0) rho = rho_0 / 2.0; + if (rho < 0.0) + rho = rho_0 / 2.0; // Check for convergence - if (std::abs(rho - rho_0) / rho_0 < tol) break; + if (std::abs(rho - rho_0) / rho_0 < tol) + break; } // Did not converge if (iter >= max_iter) { @@ -1169,8 +1195,8 @@ double density_effect(const vector& f, const vector& e_b_sq, // Square of the ratio of the speed of light to the velocity of the charged // particle - double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) / ((E + MASS_ELECTRON_EV) * - (E + MASS_ELECTRON_EV)); + double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) / + ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV)); // For nonmetals, delta = 0 for beta < beta_0, where beta_0 is obtained by // setting the frequency w = 0. @@ -1182,7 +1208,8 @@ double density_effect(const vector& f, const vector& e_b_sq, beta_0_sq = 1.0 / (1.0 + beta_0_sq); } double delta = 0.0; - if (beta_sq < beta_0_sq) return delta; + if (beta_sq < beta_0_sq) + return delta; // Compute the square of the frequency w^2 using Newton's method, with the // initial guess of w^2 equal to beta^2 * gamma^2 @@ -1208,22 +1235,24 @@ double density_effect(const vector& f, const vector& e_b_sq, w_sq -= (g + 1.0 - 1.0 / beta_sq) / gp; // If the initial guess is too large, w can be negative - if (w_sq < 0.0) w_sq = w_sq_0 / 2.0; + if (w_sq < 0.0) + w_sq = w_sq_0 / 2.0; // Check for convergence - if (std::abs(w_sq - w_sq_0) / w_sq_0 < tol) break; + if (std::abs(w_sq - w_sq_0) / w_sq_0 < tol) + break; } // Did not converge if (iter >= max_iter) { warning("Maximum Newton-Raphson iterations exceeded: setting density " - "effect correction to zero."); + "effect correction to zero."); return delta; } // Solve for the density effect correction for (int i = 0; i < n; ++i) { double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i]; - delta += f[i] * std::log((l_sq + w_sq)/l_sq); + delta += f[i] * std::log((l_sq + w_sq) / l_sq); } // Include conduction electrons if (n_conduction > 0.0) { @@ -1266,8 +1295,7 @@ void free_memory_material() // C API //============================================================================== -extern "C" int -openmc_get_material_index(int32_t id, int32_t* index) +extern "C" int openmc_get_material_index(int32_t id, int32_t* index) { auto it = model::material_map.find(id); if (it == model::material_map.end()) { @@ -1279,8 +1307,8 @@ openmc_get_material_index(int32_t id, int32_t* index) } } -extern "C" int -openmc_material_add_nuclide(int32_t index, const char* name, double density) +extern "C" int openmc_material_add_nuclide( + int32_t index, const char* name, double density) { int err = 0; if (index >= 0 && index < model::materials.size()) { @@ -1296,8 +1324,8 @@ openmc_material_add_nuclide(int32_t index, const char* name, double density) return err; } -extern "C" int -openmc_material_get_densities(int32_t index, const int** nuclides, const double** densities, int* n) +extern "C" int openmc_material_get_densities( + int32_t index, const int** nuclides, const double** densities, int* n) { if (index >= 0 && index < model::materials.size()) { auto& mat = model::materials[index]; @@ -1316,8 +1344,7 @@ openmc_material_get_densities(int32_t index, const int** nuclides, const double* } } -extern "C" int -openmc_material_get_density(int32_t index, double* density) +extern "C" int openmc_material_get_density(int32_t index, double* density) { if (index >= 0 && index < model::materials.size()) { auto& mat = model::materials[index]; @@ -1329,8 +1356,7 @@ openmc_material_get_density(int32_t index, double* density) } } -extern "C" int -openmc_material_get_fissionable(int32_t index, bool* fissionable) +extern "C" int openmc_material_get_fissionable(int32_t index, bool* fissionable) { if (index >= 0 && index < model::materials.size()) { *fissionable = model::materials[index]->fissionable(); @@ -1341,8 +1367,7 @@ openmc_material_get_fissionable(int32_t index, bool* fissionable) } } -extern "C" int -openmc_material_get_id(int32_t index, int32_t* id) +extern "C" int openmc_material_get_id(int32_t index, int32_t* id) { if (index >= 0 && index < model::materials.size()) { *id = model::materials[index]->id(); @@ -1353,8 +1378,8 @@ openmc_material_get_id(int32_t index, int32_t* id) } } -extern "C" int -openmc_material_get_temperature(int32_t index, double* temperature) +extern "C" int openmc_material_get_temperature( + int32_t index, double* temperature) { if (index < 0 || index >= model::materials.size()) { set_errmsg("Index in materials array is out of bounds."); @@ -1364,9 +1389,7 @@ openmc_material_get_temperature(int32_t index, double* temperature) return 0; } - -extern "C" int -openmc_material_get_volume(int32_t index, double* volume) +extern "C" int openmc_material_get_volume(int32_t index, double* volume) { if (index >= 0 && index < model::materials.size()) { try { @@ -1382,8 +1405,8 @@ openmc_material_get_volume(int32_t index, double* volume) } } -extern "C" int -openmc_material_set_density(int32_t index, double density, const char* units) +extern "C" int openmc_material_set_density( + int32_t index, double density, const char* units) { if (index >= 0 && index < model::materials.size()) { try { @@ -1399,12 +1422,13 @@ openmc_material_set_density(int32_t index, double density, const char* units) return 0; } -extern "C" int -openmc_material_set_densities(int32_t index, int n, const char** name, const double* density) +extern "C" int openmc_material_set_densities( + int32_t index, int n, const char** name, const double* density) { if (index >= 0 && index < model::materials.size()) { try { - model::materials[index]->set_densities({name, name + n}, {density, density + n}); + model::materials[index]->set_densities( + {name, name + n}, {density, density + n}); } catch (const std::exception& e) { set_errmsg(e.what()); return OPENMC_E_UNASSIGNED; @@ -1416,8 +1440,7 @@ openmc_material_set_densities(int32_t index, int n, const char** name, const dou return 0; } -extern "C" int -openmc_material_set_id(int32_t index, int32_t id) +extern "C" int openmc_material_set_id(int32_t index, int32_t id) { if (index >= 0 && index < model::materials.size()) { try { @@ -1433,8 +1456,8 @@ openmc_material_set_id(int32_t index, int32_t id) return 0; } -extern "C" int -openmc_material_get_name(int32_t index, const char** name) { +extern "C" int openmc_material_get_name(int32_t index, const char** name) +{ if (index < 0 || index >= model::materials.size()) { set_errmsg("Index in materials array is out of bounds."); return OPENMC_E_OUT_OF_BOUNDS; @@ -1445,8 +1468,8 @@ openmc_material_get_name(int32_t index, const char** name) { return 0; } -extern "C" int -openmc_material_set_name(int32_t index, const char* name) { +extern "C" int openmc_material_set_name(int32_t index, const char* name) +{ if (index < 0 || index >= model::materials.size()) { set_errmsg("Index in materials array is out of bounds."); return OPENMC_E_OUT_OF_BOUNDS; @@ -1457,8 +1480,7 @@ openmc_material_set_name(int32_t index, const char* name) { return 0; } -extern "C" int -openmc_material_set_volume(int32_t index, double volume) +extern "C" int openmc_material_set_volume(int32_t index, double volume) { if (index >= 0 && index < model::materials.size()) { auto& m {model::materials[index]}; @@ -1475,17 +1497,22 @@ openmc_material_set_volume(int32_t index, double volume) } } -extern "C" int -openmc_extend_materials(int32_t n, int32_t* index_start, int32_t* index_end) +extern "C" int openmc_extend_materials( + int32_t n, int32_t* index_start, int32_t* index_end) { - if (index_start) *index_start = model::materials.size(); - if (index_end) *index_end = model::materials.size() + n - 1; + if (index_start) + *index_start = model::materials.size(); + if (index_end) + *index_end = model::materials.size() + n - 1; for (int32_t i = 0; i < n; i++) { model::materials.push_back(make_unique()); } return 0; } -extern "C" size_t n_materials() { return model::materials.size(); } +extern "C" size_t n_materials() +{ + return model::materials.size(); +} } // namespace openmc diff --git a/src/math_functions.cpp b/src/math_functions.cpp index b9d058b70..32228bcdd 100644 --- a/src/math_functions.cpp +++ b/src/math_functions.cpp @@ -15,16 +15,15 @@ double normal_percentile(double p) { constexpr double p_low = 0.02425; constexpr double a[6] = {-3.969683028665376e1, 2.209460984245205e2, - -2.759285104469687e2, 1.383577518672690e2, - -3.066479806614716e1, 2.506628277459239e0}; + -2.759285104469687e2, 1.383577518672690e2, -3.066479806614716e1, + 2.506628277459239e0}; constexpr double b[5] = {-5.447609879822406e1, 1.615858368580409e2, - -1.556989798598866e2, 6.680131188771972e1, - -1.328068155288572e1}; + -1.556989798598866e2, 6.680131188771972e1, -1.328068155288572e1}; constexpr double c[6] = {-7.784894002430293e-3, -3.223964580411365e-1, - -2.400758277161838, -2.549732539343734, - 4.374664141464968, 2.938163982698783}; + -2.400758277161838, -2.549732539343734, 4.374664141464968, + 2.938163982698783}; constexpr double d[4] = {7.784695709041462e-3, 3.224671290700398e-1, - 2.445134137142996, 3.754408661907416}; + 2.445134137142996, 3.754408661907416}; // The rational approximation used here is from an unpublished work at // http://home.online.no/~pjacklam/notes/invnorm/ @@ -36,34 +35,33 @@ double normal_percentile(double p) // Rational approximation for lower region. q = std::sqrt(-2.0 * std::log(p)); - z = (((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) / - ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0); + z = (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / + ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0); } else if (p <= 1.0 - p_low) { // Rational approximation for central region q = p - 0.5; double r = q * q; - z = (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q / - (((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1.0); + z = (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * + q / + (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1.0); } else { // Rational approximation for upper region - q = std::sqrt(-2.0*std::log(1.0 - p)); - z = -(((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) / - ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0); + q = std::sqrt(-2.0 * std::log(1.0 - p)); + z = -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / + ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1.0); } // Refinement based on Newton's method z = z - (0.5 * std::erfc(-z / std::sqrt(2.0)) - p) * std::sqrt(2.0 * PI) * - std::exp(0.5 * z * z); + std::exp(0.5 * z * z); return z; - } - double t_percentile(double p, int df) { double t; @@ -72,13 +70,13 @@ double t_percentile(double p, int df) // For one degree of freedom, the t-distribution becomes a Cauchy // distribution whose cdf we can invert directly - t = std::tan(PI*(p - 0.5)); + t = std::tan(PI * (p - 0.5)); } else if (df == 2) { - // For two degrees of freedom, the cdf is given by 1/2 + x/(2*sqrt(x^2 + - // 2)). This can be directly inverted to yield the solution below + // For two degrees of freedom, the cdf is given by 1/2 + x/(2*sqrt(x^2 + + // 2)). This can be directly inverted to yield the solution below - t = 2.0 * std::sqrt(2.0)*(p - 0.5) / - std::sqrt(1. - 4. * std::pow(p - 0.5, 2.)); + t = 2.0 * std::sqrt(2.0) * (p - 0.5) / + std::sqrt(1. - 4. * std::pow(p - 0.5, 2.)); } else { // This approximation is from E. Olusegun George and Meenakshi Sivaram, "A // modification of the Fisher-Cornish approximation for the student t @@ -88,15 +86,15 @@ double t_percentile(double p, int df) double k = 1. / (n - 2.); double z = normal_percentile(p); double z2 = z * z; - t = std::sqrt(n * k) * (z + (z2 - 3.) * z * k / 4. + ((5. * z2 - 56.) * z2 + - 75.) * z * k * k / 96. + (((z2 - 27.) * 3. * z2 + 417.) * z2 - 315.) * - z * k * k * k / 384.); + t = std::sqrt(n * k) * + (z + (z2 - 3.) * z * k / 4. + + ((5. * z2 - 56.) * z2 + 75.) * z * k * k / 96. + + (((z2 - 27.) * 3. * z2 + 417.) * z2 - 315.) * z * k * k * k / 384.); } return t; } - void calc_pn_c(int n, double x, double pnx[]) { pnx[0] = 1.; @@ -110,7 +108,6 @@ void calc_pn_c(int n, double x, double pnx[]) } } - double evaluate_legendre(int n, const double data[], double x) { double* pnx = new double[n + 1]; @@ -123,14 +120,12 @@ double evaluate_legendre(int n, const double data[], double x) return val; } - void calc_rn_c(int n, const double uvw[3], double rn[]) { Direction u {uvw}; calc_rn(n, u, rn); } - void calc_rn(int n, Direction u, double rn[]) { // rn[] is assumed to have already been allocated to the correct size @@ -156,379 +151,502 @@ void calc_rn(int n, Direction u, double rn[]) // Now evaluate each switch (l) { - case 1: - // l = 1, m = -1 - rn[i] = -(std::sqrt(w2m1) * std::sin(phi)); - // l = 1, m = 0 - rn[i + 1] = w; - // l = 1, m = 1 - rn[i + 2] = -(std::sqrt(w2m1) * std::cos(phi)); - break; - case 2: - // l = 2, m = -2 - rn[i] = 0.288675134594813 * (-3. * w * w + 3.) * std::sin(2. * phi); - // l = 2, m = -1 - rn[i + 1] = -(1.73205080756888 * w*std::sqrt(w2m1) * std::sin(phi)); - // l = 2, m = 0 - rn[i + 2] = 1.5 * w * w - 0.5; - // l = 2, m = 1 - rn[i + 3] = -(1.73205080756888 * w*std::sqrt(w2m1) * std::cos(phi)); - // l = 2, m = 2 - rn[i + 4] = 0.288675134594813 * (-3. * w * w + 3.) * std::cos(2. * phi); - break; - case 3: - // l = 3, m = -3 - rn[i] = -(0.790569415042095 * std::pow(w2m1, 1.5) * std::sin(3. * phi)); - // l = 3, m = -2 - rn[i + 1] = 1.93649167310371 * w*(w2m1) * std::sin(2.*phi); - // l = 3, m = -1 - rn[i + 2] = -(0.408248290463863*std::sqrt(w2m1)*((7.5)*w * w - 3./2.) * - std::sin(phi)); - // l = 3, m = 0 - rn[i + 3] = 2.5 * std::pow(w, 3) - 1.5 * w; - // l = 3, m = 1 - rn[i + 4] = -(0.408248290463863*std::sqrt(w2m1)*((7.5)*w * w - 3./2.) * - std::cos(phi)); - // l = 3, m = 2 - rn[i + 5] = 1.93649167310371 * w*(w2m1) * std::cos(2.*phi); - // l = 3, m = 3 - rn[i + 6] = -(0.790569415042095 * std::pow(w2m1, 1.5) * std::cos(3.* phi)); - break; - case 4: - // l = 4, m = -4 - rn[i] = 0.739509972887452 * (w2m1 * w2m1) * std::sin(4.0*phi); - // l = 4, m = -3 - rn[i + 1] = -(2.09165006633519 * w * std::pow(w2m1, 1.5) * std::sin(3.* phi)); - // l = 4, m = -2 - rn[i + 2] = 0.074535599249993 * (w2m1)*(52.5 * w * w - 7.5) * std::sin(2. *phi); - // l = 4, m = -1 - rn[i + 3] = -(0.316227766016838*std::sqrt(w2m1)*(17.5 * std::pow(w, 3) - 7.5 * w) * - std::sin(phi)); - // l = 4, m = 0 - rn[i + 4] = 4.375 * std::pow(w, 4) - 3.75 * w * w + 0.375; - // l = 4, m = 1 - rn[i + 5] = -(0.316227766016838*std::sqrt(w2m1)*(17.5 * std::pow(w, 3) - 7.5*w) * - std::cos(phi)); - // l = 4, m = 2 - rn[i + 6] = 0.074535599249993 * (w2m1)*(52.5*w * w - 7.5) * std::cos(2.*phi); - // l = 4, m = 3 - rn[i + 7] = -(2.09165006633519 * w * std::pow(w2m1, 1.5) * std::cos(3.* phi)); - // l = 4, m = 4 - rn[i + 8] = 0.739509972887452 * w2m1 * w2m1 * std::cos(4.0*phi); - break; - case 5: - // l = 5, m = -5 - rn[i] = -(0.701560760020114 * std::pow(w2m1, 2.5) * std::sin(5.0 * phi)); - // l = 5, m = -4 - rn[i + 1] = 2.21852991866236 * w * w2m1 * w2m1 * std::sin(4.0 * phi); - // l = 5, m = -3 - rn[i + 2] = -(0.00996023841111995 * std::pow(w2m1, 1.5) * - ((945.0 /2.)* w * w - 52.5) * std::sin(3.*phi)); - // l = 5, m = -2 - rn[i + 3] = 0.0487950036474267 * (w2m1) - * ((315.0/2.)* std::pow(w, 3) - 52.5 * w) * std::sin(2.*phi); - // l = 5, m = -1 - rn[i + 4] = -(0.258198889747161*std::sqrt(w2m1) * - (39.375 * std::pow(w, 4) - 105.0/4.0 * w * w + 15.0/8.0) * std::sin(phi)); - // l = 5, m = 0 - rn[i + 5] = 7.875 * std::pow(w, 5) - 8.75 * std::pow(w, 3) + 1.875 * w; - // l = 5, m = 1 - rn[i + 6] = -(0.258198889747161 * std::sqrt(w2m1)* - (39.375 * std::pow(w, 4) - 105.0/4.0 * w * w + 15.0/8.0) * std::cos(phi)); - // l = 5, m = 2 - rn[i + 7] = 0.0487950036474267 * (w2m1) * - ((315.0 / 2.) * std::pow(w, 3) - 52.5*w) * std::cos(2.*phi); - // l = 5, m = 3 - rn[i + 8] = -(0.00996023841111995 * std::pow(w2m1, 1.5) * - ((945.0 / 2.) * w * w - 52.5) * std::cos(3.*phi)); - // l = 5, m = 4 - rn[i + 9] = 2.21852991866236 * w * w2m1 * w2m1 * std::cos(4.0*phi); - // l = 5, m = 5 - rn[i + 10] = -(0.701560760020114 * std::pow(w2m1, 2.5) * std::cos(5.0* phi)); - break; - case 6: - // l = 6, m = -6 - rn[i] = 0.671693289381396 * std::pow(w2m1, 3) * std::sin(6.0*phi); - // l = 6, m = -5 - rn[i + 1] = -(2.32681380862329 * w*std::pow(w2m1, 2.5) * std::sin(5.0*phi)); - // l = 6, m = -4 - rn[i + 2] = 0.00104990131391452 * w2m1 * w2m1 * - ((10395.0/2.) * w * w - 945.0/2.) * std::sin(4.0 * phi); - // l = 6, m = -3 - rn[i + 3] = -(0.00575054632785295 * std::pow(w2m1, 1.5) * - ((3465.0/2.) * std::pow(w, 3) - 945.0/2.*w) * std::sin(3.*phi)); - // l = 6, m = -2 - rn[i + 4] = 0.0345032779671177 * (w2m1) * - ((3465.0/8.0)* std::pow(w, 4) - 945.0/4.0 * w * w + 105.0/8.0) * - std::sin(2. * phi); - // l = 6, m = -1 - rn[i + 5] = -(0.218217890235992*std::sqrt(w2m1) * - ((693.0/8.0)* std::pow(w, 5)- 315.0/4.0 * std::pow(w, 3) + (105.0/8.0)*w) * - std::sin(phi)); - // l = 6, m = 0 - rn[i + 6] = 14.4375 * std::pow(w, 6) - 19.6875 * std::pow(w, 4) + 6.5625 * w * w - - 0.3125; - // l = 6, m = 1 - rn[i + 7] = -(0.218217890235992*std::sqrt(w2m1) * - ((693.0/8.0)* std::pow(w, 5)- 315.0/4.0 * std::pow(w, 3) + (105.0/8.0)*w) * - std::cos(phi)); - // l = 6, m = 2 - rn[i + 8] = 0.0345032779671177 * w2m1 * - ((3465.0/8.0)* std::pow(w, 4) -945.0/4.0 * w * w + 105.0/8.0) * - std::cos(2.*phi); - // l = 6, m = 3 - rn[i + 9] = -(0.00575054632785295 * std::pow(w2m1, 1.5) * - ((3465.0/2.) * std::pow(w, 3) - 945.0/2.*w) * std::cos(3.*phi)); - // l = 6, m = 4 - rn[i + 10] = 0.00104990131391452 * w2m1 * w2m1 * - ((10395.0/2.)*w * w - 945.0/2.) * std::cos(4.0*phi); - // l = 6, m = 5 - rn[i + 11] = -(2.32681380862329 * w * std::pow(w2m1, 2.5) * std::cos(5.0*phi)); - // l = 6, m = 6 - rn[i + 12] = 0.671693289381396 * std::pow(w2m1, 3) * std::cos(6.0*phi); - break; - case 7: - // l = 7, m = -7 - rn[i] = -(0.647259849287749 * std::pow(w2m1, 3.5) * std::sin(7.0*phi)); - // l = 7, m = -6 - rn[i + 1] = 2.42182459624969 * w*std::pow(w2m1, 3) * std::sin(6.0*phi); - // l = 7, m = -5 - rn[i + 2] = -(9.13821798555235e-5*std::pow(w2m1, 2.5) * - ((135135.0/2.)*w * w - 10395.0/2.) * std::sin(5.0*phi)); - // l = 7, m = -4 - rn[i + 3] = 0.000548293079133141 * w2m1 * w2m1 * - ((45045.0/2.)*std::pow(w, 3) - 10395.0/2.*w) * std::sin(4.0*phi); - // l = 7, m = -3 - rn[i + 4] = -(0.00363696483726654 * std::pow(w2m1, 1.5) * - ((45045.0/8.0)* std::pow(w, 4) - 10395.0/4.0 * w * w + 945.0/8.0) * - std::sin(3.*phi)); - // l = 7, m = -2 - rn[i + 5] = 0.025717224993682 * (w2m1) * - ((9009.0/8.0)* std::pow(w, 5) -3465.0/4.0 * std::pow(w, 3) + (945.0/8.0)*w) * - std::sin(2.*phi); - // l = 7, m = -1 - rn[i + 6] = -(0.188982236504614*std::sqrt(w2m1) * - ((3003.0/16.0)* std::pow(w, 6) - 3465.0/16.0 * std::pow(w, 4) + - (945.0/16.0)*w * w - 35.0/16.0) * std::sin(phi)); - // l = 7, m = 0 - rn[i + 7] = 26.8125 * std::pow(w, 7) - 43.3125 * std::pow(w, 5) + 19.6875 * std::pow(w, 3) - - 2.1875 * w; - // l = 7, m = 1 - rn[i + 8] = -(0.188982236504614*std::sqrt(w2m1) * ((3003.0/16.0) * std::pow(w, 6) - - 3465.0/16.0 * std::pow(w, 4) + (945.0/16.0)*w * w - 35.0/16.0) * std::cos(phi)); - // l = 7, m = 2 - rn[i + 9] = 0.025717224993682 * (w2m1) * ((9009.0/8.0)* std::pow(w, 5) - - 3465.0/4.0 * std::pow(w, 3) + (945.0/8.0)*w) * std::cos(2.*phi); - // l = 7, m = 3 - rn[i + 10] = -(0.00363696483726654 * std::pow(w2m1, 1.5) * - ((45045.0/8.0)* std::pow(w, 4) - 10395.0/4.0 * w * w + 945.0/8.0) * - std::cos(3.*phi)); - // l = 7, m = 4 - rn[i + 11] = 0.000548293079133141 * w2m1 * w2m1 * - ((45045.0/2.)*std::pow(w, 3) - 10395.0/2.*w) * std::cos(4.0*phi); - // l = 7, m = 5 - rn[i + 12] = -(9.13821798555235e-5*std::pow(w2m1, 2.5) * - ((135135.0/2.)*w * w - 10395.0/2.) * std::cos(5.0*phi)); - // l = 7, m = 6 - rn[i + 13] = 2.42182459624969 * w*std::pow(w2m1, 3) * std::cos(6.0*phi); - // l = 7, m = 7 - rn[i + 14] = -(0.647259849287749 * std::pow(w2m1, 3.5) * std::cos(7.0*phi)); - break; - case 8: - // l = 8, m = -8 - rn[i] = 0.626706654240044 * std::pow(w2m1, 4) * std::sin(8.0*phi); - // l = 8, m = -7 - rn[i + 1] = -(2.50682661696018 * w*std::pow(w2m1, 3.5) * std::sin(7.0*phi)); - // l = 8, m = -6 - rn[i + 2] = 6.77369783729086e-6*std::pow(w2m1, 3)* - ((2027025.0/2.)*w * w - 135135.0/2.) * std::sin(6.0*phi); - // l = 8, m = -5 - rn[i + 3] = -(4.38985792528482e-5*std::pow(w2m1, 2.5) * - ((675675.0/2.)*std::pow(w, 3) - 135135.0/2.*w) * std::sin(5.0*phi)); - // l = 8, m = -4 - rn[i + 4] = 0.000316557156832328 * w2m1 * w2m1 * - ((675675.0/8.0)* std::pow(w, 4) - 135135.0/4.0 * w * w + 10395.0/8.0) * - std::sin(4.0*phi); - // l = 8, m = -3 - rn[i + 5] = -(0.00245204119306875 * std::pow(w2m1, 1.5) * ((135135.0/8.0) * - std::pow(w, 5) - 45045.0/4.0 * std::pow(w, 3) + (10395.0/8.0)*w) * std::sin(3.*phi)); - // l = 8, m = -2 - rn[i + 6] = 0.0199204768222399 * (w2m1) * - ((45045.0/16.0)* std::pow(w, 6)- 45045.0/16.0 * std::pow(w, 4) + - (10395.0/16.0)*w * w - 315.0/16.0) * std::sin(2.*phi); - // l = 8, m = -1 - rn[i + 7] = -(0.166666666666667*std::sqrt(w2m1) * - ((6435.0/16.0)* std::pow(w, 7) - 9009.0/16.0 * std::pow(w, 5) + - (3465.0/16.0)*std::pow(w, 3) - 315.0/16.0 * w) * std::sin(phi)); - // l = 8, m = 0 - rn[i + 8] = 50.2734375 * std::pow(w, 8) - 93.84375 * std::pow(w, 6) + 54.140625 * - std::pow(w, 4) - 9.84375 * w * w + 0.2734375; - // l = 8, m = 1 - rn[i + 9] = -(0.166666666666667*std::sqrt(w2m1) * - ((6435.0/16.0)* std::pow(w, 7) - 9009.0/16.0 * std::pow(w, 5) + - (3465.0/16.0)*std::pow(w, 3) - 315.0/16.0 * w) * std::cos(phi)); - // l = 8, m = 2 - rn[i + 10] = 0.0199204768222399 * (w2m1)*((45045.0/16.0)* std::pow(w, 6)- - 45045.0/16.0 * std::pow(w, 4) + (10395.0/16.0)*w * w - - 315.0/16.0) * std::cos(2.*phi); - // l = 8, m = 3 - rn[i + 11] = -(0.00245204119306875 * std::pow(w2m1, 1.5)* - ((135135.0/8.0) * std::pow(w, 5) - 45045.0/4.0 * std::pow(w, 3) + - (10395.0/8.0)*w) * std::cos(3.*phi)); - // l = 8, m = 4 - rn[i + 12] = 0.000316557156832328 * w2m1 * w2m1*((675675.0/8.0)* std::pow(w, 4) - - 135135.0/4.0 * w * w + 10395.0/8.0) * std::cos(4.0*phi); - // l = 8, m = 5 - rn[i + 13] = -(4.38985792528482e-5*std::pow(w2m1, 2.5)*((675675.0/2.)*std::pow(w, 3) - - 135135.0/2.*w) * std::cos(5.0*phi)); - // l = 8, m = 6 - rn[i + 14] = 6.77369783729086e-6*std::pow(w2m1, 3)*((2027025.0/2.)*w * w - - 135135.0/2.) * std::cos(6.0*phi); - // l = 8, m = 7 - rn[i + 15] = -(2.50682661696018 * w*std::pow(w2m1, 3.5) * std::cos(7.0*phi)); - // l = 8, m = 8 - rn[i + 16] = 0.626706654240044 * std::pow(w2m1, 4) * std::cos(8.0*phi); - break; - case 9: - // l = 9, m = -9 - rn[i] = -(0.609049392175524 * std::pow(w2m1, 4.5) * std::sin(9.0 * phi)); - // l = 9, m = -8 - rn[i + 1] = 2.58397773170915 * w*std::pow(w2m1, 4) * std::sin(8.0 * phi); - // l = 9, m = -7 - rn[i + 2] = -(4.37240315267812e-7*std::pow(w2m1, 3.5) * - ((34459425.0/2.)*w * w - 2027025.0/2.) * std::sin(7.0 * phi)); - // l = 9, m = -6 - rn[i + 3] = 3.02928976464514e-6*std::pow(w2m1, 3)* - ((11486475.0/2.)*std::pow(w, 3) - 2027025.0/2.*w) * std::sin(6.0 * phi); - // l = 9, m = -5 - rn[i + 4] = -(2.34647776186144e-5*std::pow(w2m1, 2.5) * - ((11486475.0/8.0)* std::pow(w, 4) - 2027025.0 / 4.0 * w * w + - 135135.0/8.0) * std::sin(5.0 * phi)); - // l = 9, m = -4 - rn[i + 5] = 0.000196320414650061 * w2m1 * w2m1*((2297295.0/8.0)* std::pow(w, 5) - - 675675.0/4.0 * std::pow(w, 3) + (135135.0/8.0)*w) * std::sin(4.0*phi); - // l = 9, m = -3 - rn[i + 6] = -(0.00173385495536766 * std::pow(w2m1, 1.5) * - ((765765.0/16.0)* std::pow(w, 6) - 675675.0/16.0 * std::pow(w, 4) + - (135135.0/16.0)*w * w - 3465.0/16.0) * std::sin(3. * phi)); - // l = 9, m = -2 - rn[i + 7] = 0.0158910431540932 * (w2m1)*((109395.0/16.0)* std::pow(w, 7)- - 135135.0/16.0 * std::pow(w, 5) + (45045.0/16.0)*std::pow(w, 3) - - 3465.0/16.0 * w) * std::sin(2. * phi); - // l = 9, m = -1 - rn[i + 8] = -(0.149071198499986*std::sqrt(w2m1)*((109395.0/128.0)* std::pow(w, 8) - - 45045.0/32.0 * std::pow(w, 6) + (45045.0/64.0)* std::pow(w, 4) - - 3465.0/32.0 * w * w + 315.0/128.0) * std::sin(phi)); - // l = 9, m = 0 - rn[i + 9] = 94.9609375 * std::pow(w, 9) - 201.09375 * std::pow(w, 7) + - 140.765625 * std::pow(w, 5)- 36.09375 * std::pow(w, 3) + 2.4609375 * w; - // l = 9, m = 1 - rn[i + 10] = -(0.149071198499986*std::sqrt(w2m1)*((109395.0/128.0)* std::pow(w, 8) - - 45045.0/32.0 * std::pow(w, 6) + (45045.0/64.0)* std::pow(w, 4) - - 3465.0/32.0 * w * w + 315.0/128.0) * std::cos(phi)); - // l = 9, m = 2 - rn[i + 11] = 0.0158910431540932 * (w2m1)*((109395.0/16.0)* std::pow(w, 7) - - 135135.0/16.0 * std::pow(w, 5) + (45045.0/16.0)*std::pow(w, 3) - - 3465.0/ 16.0 * w) * std::cos(2. * phi); - // l = 9, m = 3 - rn[i + 12] = -(0.00173385495536766 * std::pow(w2m1, 1.5)*((765765.0/16.0) * - std::pow(w, 6) - 675675.0/16.0 * std::pow(w, 4) + - (135135.0/16.0)* w * w - 3465.0/16.0)* std::cos(3. * phi)); - // l = 9, m = 4 - rn[i + 13] = 0.000196320414650061 * w2m1 * w2m1*((2297295.0/8.0) * std::pow(w, 5) - - 675675.0/4.0 * std::pow(w, 3) + (135135.0/8.0)*w) * std::cos(4.0 * phi); - // l = 9, m = 5 - rn[i + 14] = -(2.34647776186144e-5*std::pow(w2m1, 2.5)*((11486475.0/8.0) * - std::pow(w, 4) - 2027025.0/4.0 * w * w + 135135.0/8.0) * - std::cos(5.0 * phi)); - // l = 9, m = 6 - rn[i + 15] = 3.02928976464514e-6*std::pow(w2m1, 3)*((11486475.0/2.)*std::pow(w, 3) - - 2027025.0/2. * w) * std::cos(6.0 * phi); - // l = 9, m = 7 - rn[i + 16] = -(4.37240315267812e-7*std::pow(w2m1, 3.5)* - ((34459425.0/2.) * w * w - 2027025.0/2.) * std::cos(7.0 * phi)); - // l = 9, m = 8 - rn[i + 17] = 2.58397773170915 * w*std::pow(w2m1, 4) * std::cos(8.0 * phi); - // l = 9, m = 9 - rn[i + 18] = -(0.609049392175524 * std::pow(w2m1, 4.5) * std::cos(9.0 * phi)); - break; - case 10: - // l = 10, m = -10 - rn[i] = 0.593627917136573 * std::pow(w2m1, 5) * std::sin(10.0 * phi); - // l = 10, m = -9 - rn[i + 1] = -(2.65478475211798 * w * std::pow(w2m1, 4.5) * std::sin(9.0 * phi)); - // l = 10, m = -8 - rn[i + 2] = 2.49953651452314e-8 * std::pow(w2m1, 4) * - ((654729075.0/2.) * w * w - 34459425.0/2.) * std::sin(8.0 * phi); - // l = 10, m = -7 - rn[i + 3] = -(1.83677671621093e-7*std::pow(w2m1, 3.5)* - ((218243025.0/2.)*std::pow(w, 3) - 34459425.0/2.*w) * - std::sin(7.0 * phi)); - // l = 10, m = -6 - rn[i + 4] = 1.51464488232257e-6*std::pow(w2m1, 3)*((218243025.0/8.0)* std::pow(w, 4) - - 34459425.0/4.0 * w * w + 2027025.0/8.0) * std::sin(6.0 * phi); - // l = 10, m = -5 - rn[i + 5] = -(1.35473956745817e-5*std::pow(w2m1, 2.5)* - ((43648605.0/8.0)* std::pow(w, 5) - 11486475.0/4.0 * std::pow(w, 3) + - (2027025.0/8.0)*w) * std::sin(5.0 * phi)); - // l = 10, m = -4 - rn[i + 6] = 0.000128521880085575 * w2m1 * w2m1*((14549535.0/16.0)* std::pow(w, 6) - - 11486475.0/16.0 * std::pow(w, 4) + (2027025.0/16.0)*w * w - - 45045.0/16.0) * std::sin(4.0 * phi); - // l = 10, m = -3 - rn[i + 7] = -(0.00127230170115096 * std::pow(w2m1, 1.5)* - ((2078505.0/16.0)* std::pow(w, 7) - 2297295.0/16.0 * std::pow(w, 5) + - (675675.0/16.0)*std::pow(w, 3) - 45045.0/16.0 * w) * std::sin(3. * phi)); - // l = 10, m = -2 - rn[i + 8] = 0.012974982402692 * (w2m1)*((2078505.0/128.0)* std::pow(w, 8) - - 765765.0/32.0 * std::pow(w, 6) + (675675.0/64.0)* std::pow(w, 4) - - 45045.0/32.0 * w * w + 3465.0/128.0) * std::sin(2. * phi); - // l = 10, m = -1 - rn[i + 9] = -(0.134839972492648*std::sqrt(w2m1)*((230945.0/128.0)* std::pow(w, 9) - - 109395.0/32.0 * std::pow(w, 7) + (135135.0/64.0)* std::pow(w, 5) - - 15015.0/32.0 * std::pow(w, 3) + (3465.0/128.0)*w) * std::sin(phi)); - // l = 10, m = 0 - rn[i + 10] = 180.42578125 * std::pow(w, 10) - 427.32421875 * std::pow(w, 8) +351.9140625 - * std::pow(w, 6) - 117.3046875 * std::pow(w, 4) + 13.53515625 * w * w -0.24609375; - // l = 10, m = 1 - rn[i + 11] = -(0.134839972492648*std::sqrt(w2m1)*((230945.0/128.0)* std::pow(w, 9) - - 109395.0/32.0 * std::pow(w, 7) + (135135.0/64.0)* std::pow(w, 5) -15015.0/ - 32.0 * std::pow(w, 3) + (3465.0/128.0)*w) * std::cos(phi)); - // l = 10, m = 2 - rn[i + 12] = 0.012974982402692 * (w2m1)*((2078505.0/128.0)* std::pow(w, 8) - - 765765.0/32.0 * std::pow(w, 6) + (675675.0/64.0)* std::pow(w, 4) - - 45045.0/32.0 * w * w + 3465.0/128.0) * std::cos(2. * phi); - // l = 10, m = 3 - rn[i + 13] = -(0.00127230170115096 * std::pow(w2m1, 1.5)* - ((2078505.0/16.0)* std::pow(w, 7) - 2297295.0/16.0 * std::pow(w, 5) + - (675675.0/16.0)*std::pow(w, 3) - 45045.0/16.0 * w) * std::cos(3. * phi)); - // l = 10, m = 4 - rn[i + 14] = 0.000128521880085575 * w2m1 * w2m1*((14549535.0/16.0)* std::pow(w, 6) - - 11486475.0/16.0 * std::pow(w, 4) + (2027025.0/16.0) * w * w - - 45045.0/16.0) * std::cos(4.0 * phi); - // l = 10, m = 5 - rn[i + 15] = -(1.35473956745817e-5*std::pow(w2m1, 2.5)* - ((43648605.0/8.0)* std::pow(w, 5) - 11486475.0/4.0 * std::pow(w, 3) + - (2027025.0/8.0)*w) * std::cos(5.0 * phi)); - // l = 10, m = 6 - rn[i + 16] = 1.51464488232257e-6*std::pow(w2m1, 3)*((218243025.0/8.0)* std::pow(w, 4) - - 34459425.0/4.0 * w * w + 2027025.0/8.0) * std::cos(6.0 * phi); - // l = 10, m = 7 - rn[i + 17] = -(1.83677671621093e-7*std::pow(w2m1, 3.5) * - ((218243025.0/2.)*std::pow(w, 3) - 34459425.0/2.*w) * std::cos(7.0 * phi)); - // l = 10, m = 8 - rn[i + 18] = 2.49953651452314e-8*std::pow(w2m1, 4)* - ((654729075.0/2.)*w * w - 34459425.0/2.) * std::cos(8.0 * phi); - // l = 10, m = 9 - rn[i + 19] = -(2.65478475211798 * w*std::pow(w2m1, 4.5) * std::cos(9.0 * phi)); - // l = 10, m = 10 - rn[i + 20] = 0.593627917136573 * std::pow(w2m1, 5) * std::cos(10.0 * phi); + case 1: + // l = 1, m = -1 + rn[i] = -(std::sqrt(w2m1) * std::sin(phi)); + // l = 1, m = 0 + rn[i + 1] = w; + // l = 1, m = 1 + rn[i + 2] = -(std::sqrt(w2m1) * std::cos(phi)); + break; + case 2: + // l = 2, m = -2 + rn[i] = 0.288675134594813 * (-3. * w * w + 3.) * std::sin(2. * phi); + // l = 2, m = -1 + rn[i + 1] = -(1.73205080756888 * w * std::sqrt(w2m1) * std::sin(phi)); + // l = 2, m = 0 + rn[i + 2] = 1.5 * w * w - 0.5; + // l = 2, m = 1 + rn[i + 3] = -(1.73205080756888 * w * std::sqrt(w2m1) * std::cos(phi)); + // l = 2, m = 2 + rn[i + 4] = 0.288675134594813 * (-3. * w * w + 3.) * std::cos(2. * phi); + break; + case 3: + // l = 3, m = -3 + rn[i] = -(0.790569415042095 * std::pow(w2m1, 1.5) * std::sin(3. * phi)); + // l = 3, m = -2 + rn[i + 1] = 1.93649167310371 * w * (w2m1)*std::sin(2. * phi); + // l = 3, m = -1 + rn[i + 2] = -(0.408248290463863 * std::sqrt(w2m1) * + ((7.5) * w * w - 3. / 2.) * std::sin(phi)); + // l = 3, m = 0 + rn[i + 3] = 2.5 * std::pow(w, 3) - 1.5 * w; + // l = 3, m = 1 + rn[i + 4] = -(0.408248290463863 * std::sqrt(w2m1) * + ((7.5) * w * w - 3. / 2.) * std::cos(phi)); + // l = 3, m = 2 + rn[i + 5] = 1.93649167310371 * w * (w2m1)*std::cos(2. * phi); + // l = 3, m = 3 + rn[i + 6] = + -(0.790569415042095 * std::pow(w2m1, 1.5) * std::cos(3. * phi)); + break; + case 4: + // l = 4, m = -4 + rn[i] = 0.739509972887452 * (w2m1 * w2m1) * std::sin(4.0 * phi); + // l = 4, m = -3 + rn[i + 1] = + -(2.09165006633519 * w * std::pow(w2m1, 1.5) * std::sin(3. * phi)); + // l = 4, m = -2 + rn[i + 2] = + 0.074535599249993 * (w2m1) * (52.5 * w * w - 7.5) * std::sin(2. * phi); + // l = 4, m = -1 + rn[i + 3] = -(0.316227766016838 * std::sqrt(w2m1) * + (17.5 * std::pow(w, 3) - 7.5 * w) * std::sin(phi)); + // l = 4, m = 0 + rn[i + 4] = 4.375 * std::pow(w, 4) - 3.75 * w * w + 0.375; + // l = 4, m = 1 + rn[i + 5] = -(0.316227766016838 * std::sqrt(w2m1) * + (17.5 * std::pow(w, 3) - 7.5 * w) * std::cos(phi)); + // l = 4, m = 2 + rn[i + 6] = + 0.074535599249993 * (w2m1) * (52.5 * w * w - 7.5) * std::cos(2. * phi); + // l = 4, m = 3 + rn[i + 7] = + -(2.09165006633519 * w * std::pow(w2m1, 1.5) * std::cos(3. * phi)); + // l = 4, m = 4 + rn[i + 8] = 0.739509972887452 * w2m1 * w2m1 * std::cos(4.0 * phi); + break; + case 5: + // l = 5, m = -5 + rn[i] = -(0.701560760020114 * std::pow(w2m1, 2.5) * std::sin(5.0 * phi)); + // l = 5, m = -4 + rn[i + 1] = 2.21852991866236 * w * w2m1 * w2m1 * std::sin(4.0 * phi); + // l = 5, m = -3 + rn[i + 2] = -(0.00996023841111995 * std::pow(w2m1, 1.5) * + ((945.0 / 2.) * w * w - 52.5) * std::sin(3. * phi)); + // l = 5, m = -2 + rn[i + 3] = 0.0487950036474267 * (w2m1) * + ((315.0 / 2.) * std::pow(w, 3) - 52.5 * w) * + std::sin(2. * phi); + // l = 5, m = -1 + rn[i + 4] = + -(0.258198889747161 * std::sqrt(w2m1) * + (39.375 * std::pow(w, 4) - 105.0 / 4.0 * w * w + 15.0 / 8.0) * + std::sin(phi)); + // l = 5, m = 0 + rn[i + 5] = 7.875 * std::pow(w, 5) - 8.75 * std::pow(w, 3) + 1.875 * w; + // l = 5, m = 1 + rn[i + 6] = + -(0.258198889747161 * std::sqrt(w2m1) * + (39.375 * std::pow(w, 4) - 105.0 / 4.0 * w * w + 15.0 / 8.0) * + std::cos(phi)); + // l = 5, m = 2 + rn[i + 7] = 0.0487950036474267 * (w2m1) * + ((315.0 / 2.) * std::pow(w, 3) - 52.5 * w) * + std::cos(2. * phi); + // l = 5, m = 3 + rn[i + 8] = -(0.00996023841111995 * std::pow(w2m1, 1.5) * + ((945.0 / 2.) * w * w - 52.5) * std::cos(3. * phi)); + // l = 5, m = 4 + rn[i + 9] = 2.21852991866236 * w * w2m1 * w2m1 * std::cos(4.0 * phi); + // l = 5, m = 5 + rn[i + 10] = + -(0.701560760020114 * std::pow(w2m1, 2.5) * std::cos(5.0 * phi)); + break; + case 6: + // l = 6, m = -6 + rn[i] = 0.671693289381396 * std::pow(w2m1, 3) * std::sin(6.0 * phi); + // l = 6, m = -5 + rn[i + 1] = + -(2.32681380862329 * w * std::pow(w2m1, 2.5) * std::sin(5.0 * phi)); + // l = 6, m = -4 + rn[i + 2] = 0.00104990131391452 * w2m1 * w2m1 * + ((10395.0 / 2.) * w * w - 945.0 / 2.) * std::sin(4.0 * phi); + // l = 6, m = -3 + rn[i + 3] = -(0.00575054632785295 * std::pow(w2m1, 1.5) * + ((3465.0 / 2.) * std::pow(w, 3) - 945.0 / 2. * w) * + std::sin(3. * phi)); + // l = 6, m = -2 + rn[i + 4] = + 0.0345032779671177 * (w2m1) * + ((3465.0 / 8.0) * std::pow(w, 4) - 945.0 / 4.0 * w * w + 105.0 / 8.0) * + std::sin(2. * phi); + // l = 6, m = -1 + rn[i + 5] = -(0.218217890235992 * std::sqrt(w2m1) * + ((693.0 / 8.0) * std::pow(w, 5) - + 315.0 / 4.0 * std::pow(w, 3) + (105.0 / 8.0) * w) * + std::sin(phi)); + // l = 6, m = 0 + rn[i + 6] = 14.4375 * std::pow(w, 6) - 19.6875 * std::pow(w, 4) + + 6.5625 * w * w - 0.3125; + // l = 6, m = 1 + rn[i + 7] = -(0.218217890235992 * std::sqrt(w2m1) * + ((693.0 / 8.0) * std::pow(w, 5) - + 315.0 / 4.0 * std::pow(w, 3) + (105.0 / 8.0) * w) * + std::cos(phi)); + // l = 6, m = 2 + rn[i + 8] = + 0.0345032779671177 * w2m1 * + ((3465.0 / 8.0) * std::pow(w, 4) - 945.0 / 4.0 * w * w + 105.0 / 8.0) * + std::cos(2. * phi); + // l = 6, m = 3 + rn[i + 9] = -(0.00575054632785295 * std::pow(w2m1, 1.5) * + ((3465.0 / 2.) * std::pow(w, 3) - 945.0 / 2. * w) * + std::cos(3. * phi)); + // l = 6, m = 4 + rn[i + 10] = 0.00104990131391452 * w2m1 * w2m1 * + ((10395.0 / 2.) * w * w - 945.0 / 2.) * std::cos(4.0 * phi); + // l = 6, m = 5 + rn[i + 11] = + -(2.32681380862329 * w * std::pow(w2m1, 2.5) * std::cos(5.0 * phi)); + // l = 6, m = 6 + rn[i + 12] = 0.671693289381396 * std::pow(w2m1, 3) * std::cos(6.0 * phi); + break; + case 7: + // l = 7, m = -7 + rn[i] = -(0.647259849287749 * std::pow(w2m1, 3.5) * std::sin(7.0 * phi)); + // l = 7, m = -6 + rn[i + 1] = + 2.42182459624969 * w * std::pow(w2m1, 3) * std::sin(6.0 * phi); + // l = 7, m = -5 + rn[i + 2] = + -(9.13821798555235e-5 * std::pow(w2m1, 2.5) * + ((135135.0 / 2.) * w * w - 10395.0 / 2.) * std::sin(5.0 * phi)); + // l = 7, m = -4 + rn[i + 3] = 0.000548293079133141 * w2m1 * w2m1 * + ((45045.0 / 2.) * std::pow(w, 3) - 10395.0 / 2. * w) * + std::sin(4.0 * phi); + // l = 7, m = -3 + rn[i + 4] = -(0.00363696483726654 * std::pow(w2m1, 1.5) * + ((45045.0 / 8.0) * std::pow(w, 4) - 10395.0 / 4.0 * w * w + + 945.0 / 8.0) * + std::sin(3. * phi)); + // l = 7, m = -2 + rn[i + 5] = 0.025717224993682 * (w2m1) * + ((9009.0 / 8.0) * std::pow(w, 5) - + 3465.0 / 4.0 * std::pow(w, 3) + (945.0 / 8.0) * w) * + std::sin(2. * phi); + // l = 7, m = -1 + rn[i + 6] = + -(0.188982236504614 * std::sqrt(w2m1) * + ((3003.0 / 16.0) * std::pow(w, 6) - 3465.0 / 16.0 * std::pow(w, 4) + + (945.0 / 16.0) * w * w - 35.0 / 16.0) * + std::sin(phi)); + // l = 7, m = 0 + rn[i + 7] = 26.8125 * std::pow(w, 7) - 43.3125 * std::pow(w, 5) + + 19.6875 * std::pow(w, 3) - 2.1875 * w; + // l = 7, m = 1 + rn[i + 8] = + -(0.188982236504614 * std::sqrt(w2m1) * + ((3003.0 / 16.0) * std::pow(w, 6) - 3465.0 / 16.0 * std::pow(w, 4) + + (945.0 / 16.0) * w * w - 35.0 / 16.0) * + std::cos(phi)); + // l = 7, m = 2 + rn[i + 9] = 0.025717224993682 * (w2m1) * + ((9009.0 / 8.0) * std::pow(w, 5) - + 3465.0 / 4.0 * std::pow(w, 3) + (945.0 / 8.0) * w) * + std::cos(2. * phi); + // l = 7, m = 3 + rn[i + 10] = -(0.00363696483726654 * std::pow(w2m1, 1.5) * + ((45045.0 / 8.0) * std::pow(w, 4) - 10395.0 / 4.0 * w * w + + 945.0 / 8.0) * + std::cos(3. * phi)); + // l = 7, m = 4 + rn[i + 11] = 0.000548293079133141 * w2m1 * w2m1 * + ((45045.0 / 2.) * std::pow(w, 3) - 10395.0 / 2. * w) * + std::cos(4.0 * phi); + // l = 7, m = 5 + rn[i + 12] = + -(9.13821798555235e-5 * std::pow(w2m1, 2.5) * + ((135135.0 / 2.) * w * w - 10395.0 / 2.) * std::cos(5.0 * phi)); + // l = 7, m = 6 + rn[i + 13] = + 2.42182459624969 * w * std::pow(w2m1, 3) * std::cos(6.0 * phi); + // l = 7, m = 7 + rn[i + 14] = + -(0.647259849287749 * std::pow(w2m1, 3.5) * std::cos(7.0 * phi)); + break; + case 8: + // l = 8, m = -8 + rn[i] = 0.626706654240044 * std::pow(w2m1, 4) * std::sin(8.0 * phi); + // l = 8, m = -7 + rn[i + 1] = + -(2.50682661696018 * w * std::pow(w2m1, 3.5) * std::sin(7.0 * phi)); + // l = 8, m = -6 + rn[i + 2] = 6.77369783729086e-6 * std::pow(w2m1, 3) * + ((2027025.0 / 2.) * w * w - 135135.0 / 2.) * + std::sin(6.0 * phi); + // l = 8, m = -5 + rn[i + 3] = -(4.38985792528482e-5 * std::pow(w2m1, 2.5) * + ((675675.0 / 2.) * std::pow(w, 3) - 135135.0 / 2. * w) * + std::sin(5.0 * phi)); + // l = 8, m = -4 + rn[i + 4] = 0.000316557156832328 * w2m1 * w2m1 * + ((675675.0 / 8.0) * std::pow(w, 4) - 135135.0 / 4.0 * w * w + + 10395.0 / 8.0) * + std::sin(4.0 * phi); + // l = 8, m = -3 + rn[i + 5] = -(0.00245204119306875 * std::pow(w2m1, 1.5) * + ((135135.0 / 8.0) * std::pow(w, 5) - + 45045.0 / 4.0 * std::pow(w, 3) + (10395.0 / 8.0) * w) * + std::sin(3. * phi)); + // l = 8, m = -2 + rn[i + 6] = + 0.0199204768222399 * (w2m1) * + ((45045.0 / 16.0) * std::pow(w, 6) - 45045.0 / 16.0 * std::pow(w, 4) + + (10395.0 / 16.0) * w * w - 315.0 / 16.0) * + std::sin(2. * phi); + // l = 8, m = -1 + rn[i + 7] = + -(0.166666666666667 * std::sqrt(w2m1) * + ((6435.0 / 16.0) * std::pow(w, 7) - 9009.0 / 16.0 * std::pow(w, 5) + + (3465.0 / 16.0) * std::pow(w, 3) - 315.0 / 16.0 * w) * + std::sin(phi)); + // l = 8, m = 0 + rn[i + 8] = 50.2734375 * std::pow(w, 8) - 93.84375 * std::pow(w, 6) + + 54.140625 * std::pow(w, 4) - 9.84375 * w * w + 0.2734375; + // l = 8, m = 1 + rn[i + 9] = + -(0.166666666666667 * std::sqrt(w2m1) * + ((6435.0 / 16.0) * std::pow(w, 7) - 9009.0 / 16.0 * std::pow(w, 5) + + (3465.0 / 16.0) * std::pow(w, 3) - 315.0 / 16.0 * w) * + std::cos(phi)); + // l = 8, m = 2 + rn[i + 10] = + 0.0199204768222399 * (w2m1) * + ((45045.0 / 16.0) * std::pow(w, 6) - 45045.0 / 16.0 * std::pow(w, 4) + + (10395.0 / 16.0) * w * w - 315.0 / 16.0) * + std::cos(2. * phi); + // l = 8, m = 3 + rn[i + 11] = -(0.00245204119306875 * std::pow(w2m1, 1.5) * + ((135135.0 / 8.0) * std::pow(w, 5) - + 45045.0 / 4.0 * std::pow(w, 3) + (10395.0 / 8.0) * w) * + std::cos(3. * phi)); + // l = 8, m = 4 + rn[i + 12] = 0.000316557156832328 * w2m1 * w2m1 * + ((675675.0 / 8.0) * std::pow(w, 4) - 135135.0 / 4.0 * w * w + + 10395.0 / 8.0) * + std::cos(4.0 * phi); + // l = 8, m = 5 + rn[i + 13] = -(4.38985792528482e-5 * std::pow(w2m1, 2.5) * + ((675675.0 / 2.) * std::pow(w, 3) - 135135.0 / 2. * w) * + std::cos(5.0 * phi)); + // l = 8, m = 6 + rn[i + 14] = 6.77369783729086e-6 * std::pow(w2m1, 3) * + ((2027025.0 / 2.) * w * w - 135135.0 / 2.) * + std::cos(6.0 * phi); + // l = 8, m = 7 + rn[i + 15] = + -(2.50682661696018 * w * std::pow(w2m1, 3.5) * std::cos(7.0 * phi)); + // l = 8, m = 8 + rn[i + 16] = 0.626706654240044 * std::pow(w2m1, 4) * std::cos(8.0 * phi); + break; + case 9: + // l = 9, m = -9 + rn[i] = -(0.609049392175524 * std::pow(w2m1, 4.5) * std::sin(9.0 * phi)); + // l = 9, m = -8 + rn[i + 1] = + 2.58397773170915 * w * std::pow(w2m1, 4) * std::sin(8.0 * phi); + // l = 9, m = -7 + rn[i + 2] = + -(4.37240315267812e-7 * std::pow(w2m1, 3.5) * + ((34459425.0 / 2.) * w * w - 2027025.0 / 2.) * std::sin(7.0 * phi)); + // l = 9, m = -6 + rn[i + 3] = 3.02928976464514e-6 * std::pow(w2m1, 3) * + ((11486475.0 / 2.) * std::pow(w, 3) - 2027025.0 / 2. * w) * + std::sin(6.0 * phi); + // l = 9, m = -5 + rn[i + 4] = -(2.34647776186144e-5 * std::pow(w2m1, 2.5) * + ((11486475.0 / 8.0) * std::pow(w, 4) - + 2027025.0 / 4.0 * w * w + 135135.0 / 8.0) * + std::sin(5.0 * phi)); + // l = 9, m = -4 + rn[i + 5] = 0.000196320414650061 * w2m1 * w2m1 * + ((2297295.0 / 8.0) * std::pow(w, 5) - + 675675.0 / 4.0 * std::pow(w, 3) + (135135.0 / 8.0) * w) * + std::sin(4.0 * phi); + // l = 9, m = -3 + rn[i + 6] = -( + 0.00173385495536766 * std::pow(w2m1, 1.5) * + ((765765.0 / 16.0) * std::pow(w, 6) - 675675.0 / 16.0 * std::pow(w, 4) + + (135135.0 / 16.0) * w * w - 3465.0 / 16.0) * + std::sin(3. * phi)); + // l = 9, m = -2 + rn[i + 7] = + 0.0158910431540932 * (w2m1) * + ((109395.0 / 16.0) * std::pow(w, 7) - 135135.0 / 16.0 * std::pow(w, 5) + + (45045.0 / 16.0) * std::pow(w, 3) - 3465.0 / 16.0 * w) * + std::sin(2. * phi); + // l = 9, m = -1 + rn[i + 8] = -( + 0.149071198499986 * std::sqrt(w2m1) * + ((109395.0 / 128.0) * std::pow(w, 8) - 45045.0 / 32.0 * std::pow(w, 6) + + (45045.0 / 64.0) * std::pow(w, 4) - 3465.0 / 32.0 * w * w + + 315.0 / 128.0) * + std::sin(phi)); + // l = 9, m = 0 + rn[i + 9] = 94.9609375 * std::pow(w, 9) - 201.09375 * std::pow(w, 7) + + 140.765625 * std::pow(w, 5) - 36.09375 * std::pow(w, 3) + + 2.4609375 * w; + // l = 9, m = 1 + rn[i + 10] = -( + 0.149071198499986 * std::sqrt(w2m1) * + ((109395.0 / 128.0) * std::pow(w, 8) - 45045.0 / 32.0 * std::pow(w, 6) + + (45045.0 / 64.0) * std::pow(w, 4) - 3465.0 / 32.0 * w * w + + 315.0 / 128.0) * + std::cos(phi)); + // l = 9, m = 2 + rn[i + 11] = + 0.0158910431540932 * (w2m1) * + ((109395.0 / 16.0) * std::pow(w, 7) - 135135.0 / 16.0 * std::pow(w, 5) + + (45045.0 / 16.0) * std::pow(w, 3) - 3465.0 / 16.0 * w) * + std::cos(2. * phi); + // l = 9, m = 3 + rn[i + 12] = -( + 0.00173385495536766 * std::pow(w2m1, 1.5) * + ((765765.0 / 16.0) * std::pow(w, 6) - 675675.0 / 16.0 * std::pow(w, 4) + + (135135.0 / 16.0) * w * w - 3465.0 / 16.0) * + std::cos(3. * phi)); + // l = 9, m = 4 + rn[i + 13] = 0.000196320414650061 * w2m1 * w2m1 * + ((2297295.0 / 8.0) * std::pow(w, 5) - + 675675.0 / 4.0 * std::pow(w, 3) + (135135.0 / 8.0) * w) * + std::cos(4.0 * phi); + // l = 9, m = 5 + rn[i + 14] = -(2.34647776186144e-5 * std::pow(w2m1, 2.5) * + ((11486475.0 / 8.0) * std::pow(w, 4) - + 2027025.0 / 4.0 * w * w + 135135.0 / 8.0) * + std::cos(5.0 * phi)); + // l = 9, m = 6 + rn[i + 15] = 3.02928976464514e-6 * std::pow(w2m1, 3) * + ((11486475.0 / 2.) * std::pow(w, 3) - 2027025.0 / 2. * w) * + std::cos(6.0 * phi); + // l = 9, m = 7 + rn[i + 16] = + -(4.37240315267812e-7 * std::pow(w2m1, 3.5) * + ((34459425.0 / 2.) * w * w - 2027025.0 / 2.) * std::cos(7.0 * phi)); + // l = 9, m = 8 + rn[i + 17] = + 2.58397773170915 * w * std::pow(w2m1, 4) * std::cos(8.0 * phi); + // l = 9, m = 9 + rn[i + 18] = + -(0.609049392175524 * std::pow(w2m1, 4.5) * std::cos(9.0 * phi)); + break; + case 10: + // l = 10, m = -10 + rn[i] = 0.593627917136573 * std::pow(w2m1, 5) * std::sin(10.0 * phi); + // l = 10, m = -9 + rn[i + 1] = + -(2.65478475211798 * w * std::pow(w2m1, 4.5) * std::sin(9.0 * phi)); + // l = 10, m = -8 + rn[i + 2] = 2.49953651452314e-8 * std::pow(w2m1, 4) * + ((654729075.0 / 2.) * w * w - 34459425.0 / 2.) * + std::sin(8.0 * phi); + // l = 10, m = -7 + rn[i + 3] = + -(1.83677671621093e-7 * std::pow(w2m1, 3.5) * + ((218243025.0 / 2.) * std::pow(w, 3) - 34459425.0 / 2. * w) * + std::sin(7.0 * phi)); + // l = 10, m = -6 + rn[i + 4] = 1.51464488232257e-6 * std::pow(w2m1, 3) * + ((218243025.0 / 8.0) * std::pow(w, 4) - + 34459425.0 / 4.0 * w * w + 2027025.0 / 8.0) * + std::sin(6.0 * phi); + // l = 10, m = -5 + rn[i + 5] = + -(1.35473956745817e-5 * std::pow(w2m1, 2.5) * + ((43648605.0 / 8.0) * std::pow(w, 5) - + 11486475.0 / 4.0 * std::pow(w, 3) + (2027025.0 / 8.0) * w) * + std::sin(5.0 * phi)); + // l = 10, m = -4 + rn[i + 6] = 0.000128521880085575 * w2m1 * w2m1 * + ((14549535.0 / 16.0) * std::pow(w, 6) - + 11486475.0 / 16.0 * std::pow(w, 4) + + (2027025.0 / 16.0) * w * w - 45045.0 / 16.0) * + std::sin(4.0 * phi); + // l = 10, m = -3 + rn[i + 7] = -(0.00127230170115096 * std::pow(w2m1, 1.5) * + ((2078505.0 / 16.0) * std::pow(w, 7) - + 2297295.0 / 16.0 * std::pow(w, 5) + + (675675.0 / 16.0) * std::pow(w, 3) - 45045.0 / 16.0 * w) * + std::sin(3. * phi)); + // l = 10, m = -2 + rn[i + 8] = 0.012974982402692 * (w2m1) * + ((2078505.0 / 128.0) * std::pow(w, 8) - + 765765.0 / 32.0 * std::pow(w, 6) + + (675675.0 / 64.0) * std::pow(w, 4) - + 45045.0 / 32.0 * w * w + 3465.0 / 128.0) * + std::sin(2. * phi); + // l = 10, m = -1 + rn[i + 9] = -(0.134839972492648 * std::sqrt(w2m1) * + ((230945.0 / 128.0) * std::pow(w, 9) - + 109395.0 / 32.0 * std::pow(w, 7) + + (135135.0 / 64.0) * std::pow(w, 5) - + 15015.0 / 32.0 * std::pow(w, 3) + (3465.0 / 128.0) * w) * + std::sin(phi)); + // l = 10, m = 0 + rn[i + 10] = 180.42578125 * std::pow(w, 10) - + 427.32421875 * std::pow(w, 8) + + 351.9140625 * std::pow(w, 6) - 117.3046875 * std::pow(w, 4) + + 13.53515625 * w * w - 0.24609375; + // l = 10, m = 1 + rn[i + 11] = -(0.134839972492648 * std::sqrt(w2m1) * + ((230945.0 / 128.0) * std::pow(w, 9) - + 109395.0 / 32.0 * std::pow(w, 7) + + (135135.0 / 64.0) * std::pow(w, 5) - + 15015.0 / 32.0 * std::pow(w, 3) + (3465.0 / 128.0) * w) * + std::cos(phi)); + // l = 10, m = 2 + rn[i + 12] = 0.012974982402692 * (w2m1) * + ((2078505.0 / 128.0) * std::pow(w, 8) - + 765765.0 / 32.0 * std::pow(w, 6) + + (675675.0 / 64.0) * std::pow(w, 4) - + 45045.0 / 32.0 * w * w + 3465.0 / 128.0) * + std::cos(2. * phi); + // l = 10, m = 3 + rn[i + 13] = + -(0.00127230170115096 * std::pow(w2m1, 1.5) * + ((2078505.0 / 16.0) * std::pow(w, 7) - + 2297295.0 / 16.0 * std::pow(w, 5) + + (675675.0 / 16.0) * std::pow(w, 3) - 45045.0 / 16.0 * w) * + std::cos(3. * phi)); + // l = 10, m = 4 + rn[i + 14] = 0.000128521880085575 * w2m1 * w2m1 * + ((14549535.0 / 16.0) * std::pow(w, 6) - + 11486475.0 / 16.0 * std::pow(w, 4) + + (2027025.0 / 16.0) * w * w - 45045.0 / 16.0) * + std::cos(4.0 * phi); + // l = 10, m = 5 + rn[i + 15] = + -(1.35473956745817e-5 * std::pow(w2m1, 2.5) * + ((43648605.0 / 8.0) * std::pow(w, 5) - + 11486475.0 / 4.0 * std::pow(w, 3) + (2027025.0 / 8.0) * w) * + std::cos(5.0 * phi)); + // l = 10, m = 6 + rn[i + 16] = 1.51464488232257e-6 * std::pow(w2m1, 3) * + ((218243025.0 / 8.0) * std::pow(w, 4) - + 34459425.0 / 4.0 * w * w + 2027025.0 / 8.0) * + std::cos(6.0 * phi); + // l = 10, m = 7 + rn[i + 17] = + -(1.83677671621093e-7 * std::pow(w2m1, 3.5) * + ((218243025.0 / 2.) * std::pow(w, 3) - 34459425.0 / 2. * w) * + std::cos(7.0 * phi)); + // l = 10, m = 8 + rn[i + 18] = 2.49953651452314e-8 * std::pow(w2m1, 4) * + ((654729075.0 / 2.) * w * w - 34459425.0 / 2.) * + std::cos(8.0 * phi); + // l = 10, m = 9 + rn[i + 19] = + -(2.65478475211798 * w * std::pow(w2m1, 4.5) * std::cos(9.0 * phi)); + // l = 10, m = 10 + rn[i + 20] = 0.593627917136573 * std::pow(w2m1, 5) * std::cos(10.0 * phi); } } } - -void calc_zn(int n, double rho, double phi, double zn[]) { +void calc_zn(int n, double rho, double phi, double zn[]) +{ // =========================================================================== // Determine vector of sin(n*phi) and cos(n*phi). This takes advantage of the // following recurrence relations so that only a single sin/cos have to be @@ -553,7 +671,7 @@ void calc_zn(int n, double rho, double phi, double zn[]) { } for (int i = 0; i <= n; i++) { - sin_phi_vec[i] *= sin_phi; + sin_phi_vec[i] *= sin_phi; } // =========================================================================== @@ -568,10 +686,11 @@ void calc_zn(int n, double rho, double phi, double zn[]) { // Fill the 2nd diagonal (Eq 3.10 in Chong) for (int q = 0; q <= n - 2; q++) { - zn_mat[q][q+2] = (q + 2) * zn_mat[q+2][q+2] - (q + 1) * zn_mat[q][q]; + zn_mat[q][q + 2] = (q + 2) * zn_mat[q + 2][q + 2] - (q + 1) * zn_mat[q][q]; } - // Fill in the rest of the values using the original results (Eq. 3.8 in Chong) + // Fill in the rest of the values using the original results (Eq. 3.8 in + // Chong) for (int p = 4; p <= n; p++) { double k2 = 2 * p * (p - 1) * (p - 2); for (int q = p - 4; q >= 0; q -= 2) { @@ -579,7 +698,7 @@ void calc_zn(int n, double rho, double phi, double zn[]) { double k3 = -q * q * (p - 1) - p * (p - 1) * (p - 2); double k4 = (-p * (p + q - 2) * (p - q - 2)) / 2.; zn_mat[q][p] = - ((k2 * rho * rho + k3) * zn_mat[q][p-2] + k4 * zn_mat[q][p-4]) / k1; + ((k2 * rho * rho + k3) * zn_mat[q][p - 2] + k4 * zn_mat[q][p - 4]) / k1; } } @@ -602,10 +721,10 @@ void calc_zn(int n, double rho, double phi, double zn[]) { i++; } } - } -void calc_zn_rad(int n, double rho, double zn_rad[]) { +void calc_zn_rad(int n, double rho, double zn_rad[]) +{ // Calculate R_p0(rho) as Zn_p0(rho) // Set up the array of the coefficients @@ -616,9 +735,9 @@ void calc_zn_rad(int n, double rho, double zn_rad[]) { // Fill in the rest of the array (Eq 3.8 and Eq 3.10 in Chong) for (int p = 2; p <= n; p += 2) { - int index = int(p/2); + int index = int(p / 2); if (p == 2) { - // Setting up R_22 to calculate R_20 (Eq 3.10 in Chong) + // Setting up R_22 to calculate R_20 (Eq 3.10 in Chong) double R_22 = rho * rho; zn_rad[index] = 2 * R_22 - zn_rad[0]; } else { @@ -627,51 +746,51 @@ void calc_zn_rad(int n, double rho, double zn_rad[]) { double k3 = -q * q * (p - 1) - p * (p - 1) * (p - 2); double k4 = (-p * (p + q - 2) * (p - q - 2)) / 2.; zn_rad[index] = - ((k2 * rho * rho + k3) * zn_rad[index-1] + k4 * zn_rad[index-2]) / k1; + ((k2 * rho * rho + k3) * zn_rad[index - 1] + k4 * zn_rad[index - 2]) / + k1; } } } - -void rotate_angle_c(double uvw[3], double mu, const double* phi, uint64_t* seed) { +void rotate_angle_c(double uvw[3], double mu, const double* phi, uint64_t* seed) +{ Direction u = rotate_angle({uvw}, mu, phi, seed); uvw[0] = u.x; uvw[1] = u.y; uvw[2] = u.z; } - -Direction rotate_angle(Direction u, double mu, const double* phi, uint64_t* seed) +Direction rotate_angle( + Direction u, double mu, const double* phi, uint64_t* seed) { // Sample azimuthal angle in [0,2pi) if none provided double phi_; if (phi != nullptr) { phi_ = (*phi); } else { - phi_ = 2.0*PI*prn(seed); + phi_ = 2.0 * PI * prn(seed); } // Precompute factors to save flops double sinphi = std::sin(phi_); double cosphi = std::cos(phi_); - double a = std::sqrt(std::fmax(0., 1. - mu*mu)); - double b = std::sqrt(std::fmax(0., 1. - u.z*u.z)); + double a = std::sqrt(std::fmax(0., 1. - mu * mu)); + double b = std::sqrt(std::fmax(0., 1. - u.z * u.z)); // Need to treat special case where sqrt(1 - w**2) is close to zero by // expanding about the v component rather than the w component if (b > 1e-10) { - return {mu*u.x + a*(u.x*u.z*cosphi - u.y*sinphi) / b, - mu*u.y + a*(u.y*u.z*cosphi + u.x*sinphi) / b, - mu*u.z - a*b*cosphi}; + return {mu * u.x + a * (u.x * u.z * cosphi - u.y * sinphi) / b, + mu * u.y + a * (u.y * u.z * cosphi + u.x * sinphi) / b, + mu * u.z - a * b * cosphi}; } else { - b = std::sqrt(1. - u.y*u.y); - return {mu*u.x + a*(-u.x*u.y*sinphi + u.z*cosphi) / b, - mu*u.y + a*b*sinphi, - mu*u.z - a*(u.y*u.z*sinphi + u.x*cosphi) / b}; + b = std::sqrt(1. - u.y * u.y); + return {mu * u.x + a * (-u.x * u.y * sinphi + u.z * cosphi) / b, + mu * u.y + a * b * sinphi, + mu * u.z - a * (u.y * u.z * sinphi + u.x * cosphi) / b}; } } - void spline(int n, const double x[], const double y[], double z[]) { vector c_new(n - 1); @@ -679,76 +798,78 @@ void spline(int n, const double x[], const double y[], double z[]) // Set natural boundary conditions c_new[0] = 0.0; z[0] = 0.0; - z[n-1] = 0.0; + z[n - 1] = 0.0; // Solve using tridiagonal matrix algorithm; first do forward sweep for (int i = 1; i < n - 1; i++) { - double a = x[i] - x[i-1]; - double c = x[i+1] - x[i]; - double b = 2.0*(a + c); - double d = 6.0*((y[i+1] - y[i])/c - (y[i] - y[i-1])/a); + double a = x[i] - x[i - 1]; + double c = x[i + 1] - x[i]; + double b = 2.0 * (a + c); + double d = 6.0 * ((y[i + 1] - y[i]) / c - (y[i] - y[i - 1]) / a); - c_new[i] = c/(b - a*c_new[i-1]); - z[i] = (d - a*z[i-1])/(b - a*c_new[i-1]); + c_new[i] = c / (b - a * c_new[i - 1]); + z[i] = (d - a * z[i - 1]) / (b - a * c_new[i - 1]); } // Back substitution for (int i = n - 2; i >= 0; i--) { - z[i] = z[i] - c_new[i]*z[i+1]; + z[i] = z[i] - c_new[i] * z[i + 1]; } } - -double spline_interpolate(int n, const double x[], const double y[], - const double z[], double xint) +double spline_interpolate( + int n, const double x[], const double y[], const double z[], double xint) { // Find the lower bounding index in x of xint int i = n - 1; while (--i) { - if (xint >= x[i]) break; + if (xint >= x[i]) + break; } - double h = x[i+1] - x[i]; + double h = x[i + 1] - x[i]; double r = xint - x[i]; // Compute the coefficients - double b = (y[i+1] - y[i])/h - (h/6.0)*(z[i+1] + 2.0*z[i]); - double c = z[i]/2.0; - double d = (z[i+1] - z[i])/(h*6.0); + double b = (y[i + 1] - y[i]) / h - (h / 6.0) * (z[i + 1] + 2.0 * z[i]); + double c = z[i] / 2.0; + double d = (z[i + 1] - z[i]) / (h * 6.0); - return y[i] + b*r + c*r*r + d*r*r*r; + return y[i] + b * r + c * r * r + d * r * r * r; } - double spline_integrate(int n, const double x[], const double y[], const double z[], double xa, double xb) { // Find the lower bounding index in x of the lower limit of integration. int ia = n - 1; while (--ia) { - if (xa >= x[ia]) break; + if (xa >= x[ia]) + break; } // Find the lower bounding index in x of the upper limit of integration. int ib = n - 1; while (--ib) { - if (xb >= x[ib]) break; + if (xb >= x[ib]) + break; } // Evaluate the integral double s = 0.0; for (int i = ia; i <= ib; i++) { - double h = x[i+1] - x[i]; + double h = x[i + 1] - x[i]; // Compute the coefficients - double b = (y[i+1] - y[i])/h - (h/6.0)*(z[i+1] + 2.0*z[i]); - double c = z[i]/2.0; - double d = (z[i+1] - z[i])/(h*6.0); + double b = (y[i + 1] - y[i]) / h - (h / 6.0) * (z[i + 1] + 2.0 * z[i]); + double c = z[i] / 2.0; + double d = (z[i + 1] - z[i]) / (h * 6.0); // Subtract the integral from x[ia] to xa if (i == ia) { double r = xa - x[ia]; - s = s - (y[i]*r + b/2.0*r*r + c/3.0*r*r*r + d/4.0*r*r*r*r); + s = s - (y[i] * r + b / 2.0 * r * r + c / 3.0 * r * r * r + + d / 4.0 * r * r * r * r); } // Integrate from x[ib] to xb in final interval @@ -757,7 +878,8 @@ double spline_integrate(int n, const double x[], const double y[], } // Accumulate the integral - s = s + y[i]*h + b/2.0*h*h + c/3.0*h*h*h + d/4.0*h*h*h*h; + s = s + y[i] * h + b / 2.0 * h * h + c / 3.0 * h * h * h + + d / 4.0 * h * h * h * h; } return s; @@ -779,8 +901,8 @@ std::complex faddeeva(std::complex z) // For imag(z) < 0, w_int(z) = -conjg(w_fun(conjg(z))) // Note that Faddeeva::w will interpret zero as machine epsilon - return z.imag() > 0.0 ? Faddeeva::w(z) : - -std::conj(Faddeeva::w(std::conj(z))); + return z.imag() > 0.0 ? Faddeeva::w(z) + : -std::conj(Faddeeva::w(std::conj(z))); } std::complex w_derivative(std::complex z, int order) @@ -790,10 +912,10 @@ std::complex w_derivative(std::complex z, int order) case 0: return faddeeva(z); case 1: - return -2.0*z*faddeeva(z) + 2.0i / SQRT_PI; + return -2.0 * z * faddeeva(z) + 2.0i / SQRT_PI; default: - return -2.0*z*w_derivative(z, order-1) - - 2.0*(order-1)*w_derivative(z, order-2); + return -2.0 * z * w_derivative(z, order - 1) - + 2.0 * (order - 1) * w_derivative(z, order - 2); } } diff --git a/src/mesh.cpp b/src/mesh.cpp index 4f85c58c8..4798bfcf5 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -1,9 +1,9 @@ #include "openmc/mesh.h" #include // for copy, equal, min, min_element -#include // for size_t -#include // for ceil -#include +#include // for ceil +#include // for size_t #include +#include #ifdef OPENMC_MPI #include "mpi.h" @@ -11,13 +11,13 @@ #ifdef _OPENMP #include #endif -#include // for fmt #include "xtensor/xbuilder.hpp" #include "xtensor/xeval.hpp" #include "xtensor/xmath.hpp" #include "xtensor/xsort.hpp" #include "xtensor/xtensor.hpp" #include "xtensor/xview.hpp" +#include // for fmt #include "openmc/capi.h" #include "openmc/constants.h" @@ -49,7 +49,6 @@ const bool LIBMESH_ENABLED = true; const bool LIBMESH_ENABLED = false; #endif - namespace model { std::unordered_map mesh_map; @@ -61,7 +60,7 @@ vector> meshes; namespace settings { unique_ptr libmesh_init; const libMesh::Parallel::Communicator* libmesh_comm {nullptr}; -} +} // namespace settings #endif //============================================================================== @@ -76,10 +75,11 @@ const libMesh::Parallel::Communicator* libmesh_comm {nullptr}; //! will be updated to match the intersection point, and `min_distance` will //! also be updated. -inline bool check_intersection_point(double x1, double x0, double y1, - double y0, double z1, double z0, Position& r, double& min_distance) +inline bool check_intersection_point(double x1, double x0, double y1, double y0, + double z1, double z0, Position& r, double& min_distance) { - double dist = std::pow(x1-x0, 2) + std::pow(y1-y0, 2) + std::pow(z1-z0, 2); + double dist = + std::pow(x1 - x0, 2) + std::pow(y1 - y0, 2) + std::pow(z1 - z0, 2); if (dist < min_distance) { r.x = x1; r.y = y1; @@ -102,15 +102,15 @@ Mesh::Mesh(pugi::xml_node node) // Check to make sure 'id' hasn't been used if (model::mesh_map.find(id_) != model::mesh_map.end()) { - fatal_error("Two or more meshes use the same unique ID: " + - std::to_string(id_)); + fatal_error( + "Two or more meshes use the same unique ID: " + std::to_string(id_)); } } } -void -Mesh::set_id(int32_t id) { - Expects(id >=0 || id == C_NONE); +void Mesh::set_id(int32_t id) +{ + Expects(id >= 0 || id == C_NONE); // Clear entry in mesh map in case one was already assigned if (id_ != C_NONE) { @@ -120,7 +120,8 @@ Mesh::set_id(int32_t id) { // Ensure no other mesh has the same ID if (model::mesh_map.find(id) != model::mesh_map.end()) { - throw std::runtime_error{fmt::format("Two meshes have the same ID: {}", id)}; + throw std::runtime_error { + fmt::format("Two meshes have the same ID: {}", id)}; } // If no ID is specified, auto-assign the next ID in the sequence @@ -141,8 +142,8 @@ Mesh::set_id(int32_t id) { // Structured Mesh implementation //============================================================================== -std::string -StructuredMesh::bin_label(int bin) const { +std::string StructuredMesh::bin_label(int bin) const +{ vector ijk(n_dimension_); get_indices_from_bin(bin, ijk.data()); @@ -151,7 +152,7 @@ StructuredMesh::bin_label(int bin) const { } else if (n_dimension_ > 1) { return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]); } else { - return fmt::format("Mesh Index ({})", ijk[0]) ; + return fmt::format("Mesh Index ({})", ijk[0]); } } @@ -159,7 +160,8 @@ StructuredMesh::bin_label(int bin) const { // Unstructured Mesh implementation //============================================================================== -UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node) { +UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node) +{ // check the mesh type if (check_for_node(node, "type")) { @@ -175,9 +177,9 @@ UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node) { if (!file_exists(filename_)) { fatal_error("Mesh file '" + filename_ + "' does not exist!"); } - } - else { - fatal_error(fmt::format("No filename supplied for unstructured mesh with ID: {}", id_)); + } else { + fatal_error(fmt::format( + "No filename supplied for unstructured mesh with ID: {}", id_)); } // check if mesh tally data should be written with @@ -185,42 +187,38 @@ UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node) { if (check_for_node(node, "output")) { output_ = get_node_value_bool(node, "output"); } - } -void -UnstructuredMesh::surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const { +void UnstructuredMesh::surface_bins_crossed( + Position r0, Position r1, const Direction& u, vector& bins) const +{ fatal_error("Unstructured mesh surface tallies are not implemented."); } -std::string -UnstructuredMesh::bin_label(int bin) const { +std::string UnstructuredMesh::bin_label(int bin) const +{ return fmt::format("Mesh Index ({})", bin); }; -void -UnstructuredMesh::to_hdf5(hid_t group) const +void UnstructuredMesh::to_hdf5(hid_t group) const { - hid_t mesh_group = create_group(group, fmt::format("mesh {}", id_)); + hid_t mesh_group = create_group(group, fmt::format("mesh {}", id_)); - write_dataset(mesh_group, "type", "unstructured"); - write_dataset(mesh_group, "filename", filename_); - write_dataset(mesh_group, "library", this->library()); - // write volume of each element - vector tet_vols; - xt::xtensor centroids({static_cast(this->n_bins()), 3}); - for (int i = 0; i < this->n_bins(); i++) { - tet_vols.emplace_back(this->volume(i)); - auto c = this->centroid(i); - xt::view(centroids, i, xt::all()) = xt::xarray({c.x, c.y, c.z}); - } + write_dataset(mesh_group, "type", "unstructured"); + write_dataset(mesh_group, "filename", filename_); + write_dataset(mesh_group, "library", this->library()); + // write volume of each element + vector tet_vols; + xt::xtensor centroids({static_cast(this->n_bins()), 3}); + for (int i = 0; i < this->n_bins(); i++) { + tet_vols.emplace_back(this->volume(i)); + auto c = this->centroid(i); + xt::view(centroids, i, xt::all()) = xt::xarray({c.x, c.y, c.z}); + } - write_dataset(mesh_group, "volumes", tet_vols); - write_dataset(mesh_group, "centroids", centroids); - close_group(mesh_group); + write_dataset(mesh_group, "volumes", tet_vols); + write_dataset(mesh_group, "centroids", centroids); + close_group(mesh_group); } void StructuredMesh::get_indices(Position r, int* ijk, bool* in_mesh) const @@ -229,7 +227,8 @@ void StructuredMesh::get_indices(Position r, int* ijk, bool* in_mesh) const for (int i = 0; i < n_dimension_; ++i) { ijk[i] = get_index_in_direction(r[i], i); - if (ijk[i] < 1 || ijk[i] > shape_[i]) *in_mesh = false; + if (ijk[i] < 1 || ijk[i] > shape_[i]) + *in_mesh = false; } } @@ -239,11 +238,11 @@ int StructuredMesh::get_bin_from_indices(const int* ijk) const case 1: return ijk[0] - 1; case 2: - return (ijk[1] - 1)*shape_[0] + ijk[0] - 1; + return (ijk[1] - 1) * shape_[0] + ijk[0] - 1; case 3: - return ((ijk[2] - 1)*shape_[1] + (ijk[1] - 1))*shape_[0] + ijk[0] - 1; + return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1; default: - throw std::runtime_error{"Invalid number of mesh dimensions"}; + throw std::runtime_error {"Invalid number of mesh dimensions"}; } } @@ -267,7 +266,8 @@ int StructuredMesh::get_bin(Position r) const vector ijk(n_dimension_); bool in_mesh; get_indices(r, ijk.data(), &in_mesh); - if (!in_mesh) return -1; + if (!in_mesh) + return -1; // Convert indices to bin return get_bin_from_indices(ijk.data()); @@ -314,12 +314,12 @@ xt::xtensor StructuredMesh::count_sites( // std::allocator must be used to avoid Valgrind mismatched free() / delete // warnings. int total = cnt.size(); - double* cnt_reduced = std::allocator{}.allocate(total); + double* cnt_reduced = std::allocator {}.allocate(total); #ifdef OPENMC_MPI // collect values from all processors - MPI_Reduce(cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, - mpi::intracomm); + MPI_Reduce( + cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm); // Check if there were sites outside the mesh for any processor if (outside) { @@ -327,7 +327,8 @@ xt::xtensor StructuredMesh::count_sites( } #else std::copy(cnt.data(), cnt.data() + total, cnt_reduced); - if (outside) *outside = outside_; + if (outside) + *outside = outside_; #endif // Adapt reduced values in array back into an xarray @@ -339,7 +340,7 @@ xt::xtensor StructuredMesh::count_sites( bool StructuredMesh::intersects(Position& r0, Position r1, int* ijk) const { - switch(n_dimension_) { + switch (n_dimension_) { case 1: return intersects_1d(r0, r1, ijk); case 2: @@ -347,7 +348,7 @@ bool StructuredMesh::intersects(Position& r0, Position r1, int* ijk) const case 3: return intersects_3d(r0, r1, ijk); default: - throw std::runtime_error{"Invalid number of mesh dimensions."}; + throw std::runtime_error {"Invalid number of mesh dimensions."}; } } @@ -580,24 +581,22 @@ bool StructuredMesh::intersects_3d(Position& r0, Position r1, int* ijk) const return min_dist < INFTY; } -void StructuredMesh::bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const +void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const { // ======================================================================== // Determine where the track intersects the mesh and if it intersects at all. // Compute the length of the entire track. double total_distance = (r1 - r0).norm(); - if (total_distance == 0.0) return; + if (total_distance == 0.0) + return; // While determining if this track intersects the mesh, offset the starting // and ending coords by a bit. This avoid finite-precision errors that can // occur when the mesh surfaces coincide with lattice or geometric surfaces. - Position last_r = r0 + TINY_BIT*u; - Position r = r1 - TINY_BIT*u; + Position last_r = r0 + TINY_BIT * u; + Position r = r1 - TINY_BIT * u; // Determine the mesh indices for the starting and ending coords. Here, we // use arrays for ijk0 and ijk1 instead of vector because we obtain a @@ -620,7 +619,8 @@ void StructuredMesh::bins_crossed(Position r0, // The initial coords do not lie in the mesh. Check to see if the particle // eventually intersects the mesh and compute the relevant coords and // indices. - if (!intersects(last_r, r, ijk0)) return; + if (!intersects(last_r, r, ijk0)) + return; } r = r1; @@ -630,8 +630,9 @@ void StructuredMesh::bins_crossed(Position r0, // any error caused by this assumption will be small. It is important that // ijk0 values are used rather than ijk1 because the previous logic guarantees // ijk0 is a valid mesh bin. - if (total_distance < 2*TINY_BIT) { - for (int i = 0; i < n; ++i) ijk1[i] = ijk0[i]; + if (total_distance < 2 * TINY_BIT) { + for (int i = 0; i < n; ++i) + ijk1[i] = ijk0[i]; } // ======================================================================== @@ -686,24 +687,22 @@ void StructuredMesh::bins_crossed(Position r0, break; } } - if (!in_mesh) break; + if (!in_mesh) + break; } } - //============================================================================== // RegularMesh implementation //============================================================================== -RegularMesh::RegularMesh(pugi::xml_node node) - : StructuredMesh {node} +RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node} { // Determine number of dimensions for mesh if (!check_for_node(node, "dimension")) { fatal_error("Must specify on a regular mesh."); } - shape_ = get_node_xarray(node, "dimension"); int n = n_dimension_ = shape_.size(); if (n != 1 && n != 2 && n != 3) { @@ -713,7 +712,7 @@ RegularMesh::RegularMesh(pugi::xml_node node) // Check that dimensions are all greater than zero if (xt::any(shape_ <= 0)) { fatal_error("All entries on the element for a tally " - "mesh must be positive."); + "mesh must be positive."); } // Check for lower-left coordinates @@ -727,7 +726,7 @@ RegularMesh::RegularMesh(pugi::xml_node node) // Make sure lower_left and dimension match if (shape_.size() != lower_left_.size()) { fatal_error("Number of entries on must be the same " - "as the number of entries on ."); + "as the number of entries on ."); } if (check_for_node(node, "width")) { @@ -742,7 +741,7 @@ RegularMesh::RegularMesh(pugi::xml_node node) auto n = width_.size(); if (n != lower_left_.size()) { fatal_error("Number of entries on must be the same as " - "the number of entries on ."); + "the number of entries on ."); } // Check for negative widths @@ -760,13 +759,13 @@ RegularMesh::RegularMesh(pugi::xml_node node) auto n = upper_right_.size(); if (n != lower_left_.size()) { fatal_error("Number of entries on must be the " - "same as the number of entries on ."); + "same as the number of entries on ."); } // Check that upper-right is above lower-left if (xt::any(upper_right_ < lower_left_)) { fatal_error("The coordinates must be greater than " - "the coordinates on a tally mesh."); + "the coordinates on a tally mesh."); } // Set width @@ -776,7 +775,7 @@ RegularMesh::RegularMesh(pugi::xml_node node) } // Set volume fraction - volume_frac_ = 1.0/xt::prod(shape_)(); + volume_frac_ = 1.0 / xt::prod(shape_)(); } int RegularMesh::get_index_in_direction(double r, int i) const @@ -794,11 +793,8 @@ double RegularMesh::negative_grid_boundary(int* ijk, int i) const return lower_left_[i] + (ijk[i] - 1) * width_[i]; } -void -RegularMesh::surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const +void RegularMesh::surface_bins_crossed( + Position r0, Position r1, const Direction& u, vector& bins) const { // Determine indices for starting and ending location. int n = n_dimension_; @@ -812,7 +808,8 @@ RegularMesh::surface_bins_crossed(Position r0, if (!start_in_mesh) { Position r0_copy = r0; vector ijk0_copy(ijk0); - if (!intersects(r0_copy, r1, ijk0_copy.data())) return; + if (!intersects(r0_copy, r1, ijk0_copy.data())) + return; } // ======================================================================== @@ -820,8 +817,10 @@ RegularMesh::surface_bins_crossed(Position r0, // Calculate number of surface crossings int n_cross = 0; - for (int i = 0; i < n; ++i) n_cross += std::abs(ijk1[i] - ijk0[i]); - if (n_cross == 0) return; + for (int i = 0; i < n; ++i) + n_cross += std::abs(ijk1[i] - ijk0[i]); + if (n_cross == 0) + return; // Bounding coordinates Position xyz_cross; @@ -845,7 +844,7 @@ RegularMesh::surface_bins_crossed(Position r0, if (u[i] == 0) { d[i] = INFTY; } else { - d[i] = (xyz_cross[i] - r0[i])/u[i]; + d[i] = (xyz_cross[i] - r0[i]) / u[i]; } distance = std::min(distance, d[i]); } @@ -869,9 +868,9 @@ RegularMesh::surface_bins_crossed(Position r0, // Outward current on i max surface if (in_mesh) { - int i_surf = 4*i + 3; + int i_surf = 4 * i + 3; int i_mesh = get_bin_from_indices(ijk0.data()); - int i_bin = 4*n*i_mesh + i_surf - 1; + int i_bin = 4 * n * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -890,9 +889,9 @@ RegularMesh::surface_bins_crossed(Position r0, // If the particle crossed the surface, tally the inward current on // i min surface if (in_mesh) { - int i_surf = 4*i + 2; + int i_surf = 4 * i + 2; int i_mesh = get_bin_from_indices(ijk0.data()); - int i_bin = 4*n*i_mesh + i_surf - 1; + int i_bin = 4 * n * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -902,9 +901,9 @@ RegularMesh::surface_bins_crossed(Position r0, // Outward current on i min surface if (in_mesh) { - int i_surf = 4*i + 1; + int i_surf = 4 * i + 1; int i_mesh = get_bin_from_indices(ijk0.data()); - int i_bin = 4*n*i_mesh + i_surf - 1; + int i_bin = 4 * n * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -923,9 +922,9 @@ RegularMesh::surface_bins_crossed(Position r0, // If the particle crossed the surface, tally the inward current on // i max surface if (in_mesh) { - int i_surf = 4*i + 4; + int i_surf = 4 * i + 4; int i_mesh = get_bin_from_indices(ijk0.data()); - int i_bin = 4*n*i_mesh + i_surf - 1; + int i_bin = 4 * n * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -945,13 +944,17 @@ std::pair, vector> RegularMesh::plot( array axes {-1, -1}; if (plot_ur.z == plot_ll.z) { axes[0] = 0; - if (n_dimension_ > 1) axes[1] = 1; + if (n_dimension_ > 1) + axes[1] = 1; } else if (plot_ur.y == plot_ll.y) { axes[0] = 0; - if (n_dimension_ > 2) axes[1] = 2; + if (n_dimension_ > 2) + axes[1] = 2; } else if (plot_ur.x == plot_ll.x) { - if (n_dimension_ > 1) axes[0] = 1; - if (n_dimension_ > 2) axes[1] = 2; + if (n_dimension_ > 1) + axes[0] = 1; + if (n_dimension_ > 2) + axes[1] = 2; } else { fatal_error("Can only plot mesh lines on an axis-aligned plot"); } @@ -960,7 +963,8 @@ std::pair, vector> RegularMesh::plot( array, 2> axis_lines; for (int i_ax = 0; i_ax < 2; ++i_ax) { int axis = axes[i_ax]; - if (axis == -1) continue; + if (axis == -1) + continue; auto& lines {axis_lines[i_ax]}; double coord = lower_left_[axis]; @@ -1018,12 +1022,12 @@ xt::xtensor RegularMesh::count_sites( // std::allocator must be used to avoid Valgrind mismatched free() / delete // warnings. int total = cnt.size(); - double* cnt_reduced = std::allocator{}.allocate(total); + double* cnt_reduced = std::allocator {}.allocate(total); #ifdef OPENMC_MPI // collect values from all processors - MPI_Reduce(cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, - mpi::intracomm); + MPI_Reduce( + cnt.data(), cnt_reduced, total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm); // Check if there were sites outside the mesh for any processor if (outside) { @@ -1031,7 +1035,8 @@ xt::xtensor RegularMesh::count_sites( } #else std::copy(cnt.data(), cnt.data() + total, cnt_reduced); - if (outside) *outside = outside_; + if (outside) + *outside = outside_; #endif // Adapt reduced values in array back into an xarray @@ -1045,8 +1050,7 @@ xt::xtensor RegularMesh::count_sites( // RectilinearMesh implementation //============================================================================== -RectilinearMesh::RectilinearMesh(pugi::xml_node node) - : StructuredMesh {node} +RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node} { n_dimension_ = 3; @@ -1073,19 +1077,19 @@ double RectilinearMesh::negative_grid_boundary(int* ijk, int i) const int RectilinearMesh::set_grid() { shape_ = {static_cast(grid_[0].size()) - 1, - static_cast(grid_[1].size()) - 1, - static_cast(grid_[2].size()) - 1}; + static_cast(grid_[1].size()) - 1, + static_cast(grid_[2].size()) - 1}; for (const auto& g : grid_) { if (g.size() < 2) { set_errmsg("x-, y-, and z- grids for rectilinear meshes " - "must each have at least 2 points"); + "must each have at least 2 points"); return OPENMC_E_INVALID_ARGUMENT; } for (int i = 1; i < g.size(); ++i) { - if (g[i] <= g[i-1]) { + if (g[i] <= g[i - 1]) { set_errmsg("Values in for x-, y-, and z- grids for " - "rectilinear meshes must be sorted and unique."); + "rectilinear meshes must be sorted and unique."); return OPENMC_E_INVALID_ARGUMENT; } } @@ -1097,10 +1101,8 @@ int RectilinearMesh::set_grid() return 0; } -void RectilinearMesh::surface_bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins) const +void RectilinearMesh::surface_bins_crossed( + Position r0, Position r1, const Direction& u, vector& bins) const { // Determine indices for starting and ending location. int ijk0[3], ijk1[3]; @@ -1114,7 +1116,8 @@ void RectilinearMesh::surface_bins_crossed(Position r0, // intersection. Return if the particle does not intersect the mesh at all. if (!start_in_mesh) { // Compute the incoming intersection coordinates and indices. - if (!intersects(r0, r1, ijk0)) return; + if (!intersects(r0, r1, ijk0)) + return; // Determine which surface the particle entered. double min_dist = INFTY; @@ -1124,20 +1127,20 @@ void RectilinearMesh::surface_bins_crossed(Position r0, double d = std::abs(r0[i] - grid_[i][0]); if (d < min_dist) { min_dist = d; - i_surf = 4*i + 2; + i_surf = 4 * i + 2; } } else if (u[i] < 0.0 && ijk0[i] == shape_[i]) { double d = std::abs(r0[i] - grid_[i][shape_[i]]); if (d < min_dist) { min_dist = d; - i_surf = 4*i + 4; + i_surf = 4 * i + 4; } } // u[i] == 0 intentionally skipped } // Add the incoming current bin. int i_mesh = get_bin_from_indices(ijk0); - int i_bin = 4*3*i_mesh + i_surf - 1; + int i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -1156,20 +1159,20 @@ void RectilinearMesh::surface_bins_crossed(Position r0, double d = std::abs(r1[i] - grid_[i][shape_[i]]); if (d < min_dist) { min_dist = d; - i_surf = 4*i + 3; + i_surf = 4 * i + 3; } } else if (u[i] < 0.0 && ijk1[i] == 1) { double d = std::abs(r1[i] - grid_[i][0]); if (d < min_dist) { min_dist = d; - i_surf = 4*i + 1; + i_surf = 4 * i + 1; } } // u[i] == 0 intentionally skipped } // Add the outgoing current bin. int i_mesh = get_bin_from_indices(ijk1); - int i_bin = 4*3*i_mesh + i_surf - 1; + int i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); } @@ -1178,8 +1181,10 @@ void RectilinearMesh::surface_bins_crossed(Position r0, // Calculate number of surface crossings int n_cross = 0; - for (int i = 0; i < 3; ++i) n_cross += std::abs(ijk1[i] - ijk0[i]); - if (n_cross == 0) return; + for (int i = 0; i < 3; ++i) + n_cross += std::abs(ijk1[i] - ijk0[i]); + if (n_cross == 0) + return; // Bounding coordinates Position xyz_cross; @@ -1203,7 +1208,7 @@ void RectilinearMesh::surface_bins_crossed(Position r0, if (u[i] == 0) { d[i] = INFTY; } else { - d[i] = (xyz_cross[i] - r0[i])/u[i]; + d[i] = (xyz_cross[i] - r0[i]) / u[i]; } distance = std::min(distance, d[i]); } @@ -1217,9 +1222,9 @@ void RectilinearMesh::surface_bins_crossed(Position r0, if (u[i] > 0) { // Outward current on i max surface - int i_surf = 4*i + 3; + int i_surf = 4 * i + 3; int i_mesh = get_bin_from_indices(ijk0); - int i_bin = 4*3*i_mesh + i_surf - 1; + int i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); // Advance position @@ -1227,18 +1232,18 @@ void RectilinearMesh::surface_bins_crossed(Position r0, xyz_cross[i] = grid_[i][ijk0[i]]; // Inward current on i min surface - i_surf = 4*i + 2; + i_surf = 4 * i + 2; i_mesh = get_bin_from_indices(ijk0); - i_bin = 4*3*i_mesh + i_surf - 1; + i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); } else { // The particle is moving in the negative i direction // Outward current on i min surface - int i_surf = 4*i + 1; + int i_surf = 4 * i + 1; int i_mesh = get_bin_from_indices(ijk0); - int i_bin = 4*3*i_mesh + i_surf - 1; + int i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); // Advance position @@ -1246,9 +1251,9 @@ void RectilinearMesh::surface_bins_crossed(Position r0, xyz_cross[i] = grid_[i][ijk0[i] - 1]; // Inward current on i min surface - i_surf = 4*i + 4; + i_surf = 4 * i + 4; i_mesh = get_bin_from_indices(ijk0); - i_bin = 4*3*i_mesh + i_surf - 1; + i_bin = 4 * 3 * i_mesh + i_surf - 1; bins.push_back(i_bin); } } @@ -1310,8 +1315,7 @@ void RectilinearMesh::to_hdf5(hid_t group) const // Helper functions for the C API //============================================================================== -int -check_mesh(int32_t index) +int check_mesh(int32_t index) { if (index < 0 || index >= model::meshes.size()) { set_errmsg("Index in meshes array is out of bounds."); @@ -1320,11 +1324,11 @@ check_mesh(int32_t index) return 0; } -template -int -check_mesh_type(int32_t index) +template +int check_mesh_type(int32_t index) { - if (int err = check_mesh(index)) return err; + if (int err = check_mesh(index)) + return err; T* mesh = dynamic_cast(model::meshes[index].get()); if (!mesh) { @@ -1339,16 +1343,17 @@ check_mesh_type(int32_t index) //============================================================================== // Return the type of mesh as a C string -extern "C" int -openmc_mesh_get_type(int32_t index, char* type) +extern "C" int openmc_mesh_get_type(int32_t index, char* type) { - if (int err = check_mesh(index)) return err; + if (int err = check_mesh(index)) + return err; RegularMesh* mesh = dynamic_cast(model::meshes[index].get()); if (mesh) { std::strcpy(type, "regular"); } else { - RectilinearMesh* mesh = dynamic_cast(model::meshes[index].get()); + RectilinearMesh* mesh = + dynamic_cast(model::meshes[index].get()); if (mesh) { std::strcpy(type, "rectilinear"); } @@ -1357,11 +1362,11 @@ openmc_mesh_get_type(int32_t index, char* type) } //! Extend the meshes array by n elements -extern "C" int -openmc_extend_meshes(int32_t n, const char* type, int32_t* index_start, - int32_t* index_end) +extern "C" int openmc_extend_meshes( + int32_t n, const char* type, int32_t* index_start, int32_t* index_end) { - if (index_start) *index_start = model::meshes.size(); + if (index_start) + *index_start = model::meshes.size(); std::string mesh_type; for (int i = 0; i < n; ++i) { @@ -1370,18 +1375,18 @@ openmc_extend_meshes(int32_t n, const char* type, int32_t* index_start, } else if (std::strcmp(type, "rectilinear") == 0) { model::meshes.push_back(make_unique()); } else { - throw std::runtime_error{"Unknown mesh type: " + std::string(type)}; + throw std::runtime_error {"Unknown mesh type: " + std::string(type)}; } } - if (index_end) *index_end = model::meshes.size() - 1; + if (index_end) + *index_end = model::meshes.size() - 1; return 0; } //! Adds a new unstructured mesh to OpenMC -extern "C" int openmc_add_unstructured_mesh(const char filename[], - const char library[], - int* id) +extern "C" int openmc_add_unstructured_mesh( + const char filename[], const char library[], int* id) { std::string lib_name(library); std::string mesh_file(filename); @@ -1403,7 +1408,8 @@ extern "C" int openmc_add_unstructured_mesh(const char filename[], if (!valid_lib) { set_errmsg(fmt::format("Mesh library {} is not supported " - "by this build of OpenMC", lib_name)); + "by this build of OpenMC", + lib_name)); return OPENMC_E_INVALID_ARGUMENT; } @@ -1414,10 +1420,8 @@ extern "C" int openmc_add_unstructured_mesh(const char filename[], 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) +extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index) { auto pair = model::mesh_map.find(id); if (pair == model::mesh_map.end()) { @@ -1429,29 +1433,30 @@ openmc_get_mesh_index(int32_t id, int32_t* index) } //! Return the ID of a mesh -extern "C" int -openmc_mesh_get_id(int32_t index, int32_t* id) +extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id) { - if (int err = check_mesh(index)) return err; + if (int err = check_mesh(index)) + return err; *id = model::meshes[index]->id_; return 0; } //! Set the ID of a mesh -extern "C" int -openmc_mesh_set_id(int32_t index, int32_t id) +extern "C" int openmc_mesh_set_id(int32_t index, int32_t id) { - if (int err = check_mesh(index)) return err; + if (int err = check_mesh(index)) + return err; model::meshes[index]->id_ = id; model::mesh_map[id] = index; return 0; } //! Get the dimension of a regular mesh -extern "C" int -openmc_regular_mesh_get_dimension(int32_t index, int** dims, int* n) +extern "C" int openmc_regular_mesh_get_dimension( + int32_t index, int** dims, int* n) { - if (int err = check_mesh_type(index)) return err; + if (int err = check_mesh_type(index)) + return err; RegularMesh* mesh = dynamic_cast(model::meshes[index].get()); *dims = mesh->shape_.data(); *n = mesh->n_dimension_; @@ -1459,10 +1464,11 @@ openmc_regular_mesh_get_dimension(int32_t index, int** dims, int* n) } //! Set the dimension of a regular mesh -extern "C" int -openmc_regular_mesh_set_dimension(int32_t index, int n, const int* dims) +extern "C" int openmc_regular_mesh_set_dimension( + int32_t index, int n, const int* dims) { - if (int err = check_mesh_type(index)) return err; + if (int err = check_mesh_type(index)) + return err; RegularMesh* mesh = dynamic_cast(model::meshes[index].get()); // Copy dimension @@ -1473,11 +1479,11 @@ openmc_regular_mesh_set_dimension(int32_t index, int n, const int* dims) } //! Get the regular mesh parameters -extern "C" int -openmc_regular_mesh_get_params(int32_t index, double** ll, double** ur, - double** width, int* n) +extern "C" int openmc_regular_mesh_get_params( + int32_t index, double** ll, double** ur, double** width, int* n) { - if (int err = check_mesh_type(index)) return err; + if (int err = check_mesh_type(index)) + return err; RegularMesh* m = dynamic_cast(model::meshes[index].get()); if (m->lower_left_.dimension() == 0) { @@ -1493,11 +1499,11 @@ openmc_regular_mesh_get_params(int32_t index, double** ll, double** ur, } //! Set the regular mesh parameters -extern "C" int -openmc_regular_mesh_set_params(int32_t index, int n, const double* ll, - const double* ur, const double* width) +extern "C" int openmc_regular_mesh_set_params( + int32_t index, int n, const double* ll, const double* ur, const double* width) { - if (int err = check_mesh_type(index)) return err; + if (int err = check_mesh_type(index)) + return err; RegularMesh* m = dynamic_cast(model::meshes[index].get()); vector shape = {static_cast(n)}; @@ -1522,12 +1528,13 @@ openmc_regular_mesh_set_params(int32_t index, int n, const double* ll, } //! Get the rectilinear mesh grid -extern "C" int -openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, int* nx, - double** grid_y, int* ny, double** grid_z, int* nz) +extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, + int* nx, double** grid_y, int* ny, double** grid_z, int* nz) { - if (int err = check_mesh_type(index)) return err; - RectilinearMesh* m = dynamic_cast(model::meshes[index].get()); + if (int err = check_mesh_type(index)) + return err; + RectilinearMesh* m = + dynamic_cast(model::meshes[index].get()); if (m->lower_left_.dimension() == 0) { set_errmsg("Mesh parameters have not been set."); @@ -1545,13 +1552,14 @@ openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, int* nx, } //! Set the rectilienar mesh parameters -extern "C" int -openmc_rectilinear_mesh_set_grid(int32_t index, const double* grid_x, - const int nx, const double* grid_y, const int ny, - const double* grid_z, const int nz) +extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index, + const double* grid_x, const int nx, const double* grid_y, const int ny, + const double* grid_z, const int nz) { - if (int err = check_mesh_type(index)) return err; - RectilinearMesh* m = dynamic_cast(model::meshes[index].get()); + if (int err = check_mesh_type(index)) + return err; + RectilinearMesh* m = + dynamic_cast(model::meshes[index].get()); m->n_dimension_ = 3; m->grid_.resize(m->n_dimension_); @@ -1572,22 +1580,26 @@ openmc_rectilinear_mesh_set_grid(int32_t index, const double* grid_x, #ifdef DAGMC -MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node) { +MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node) +{ initialize(); } -MOABMesh::MOABMesh(const std::string& filename) { +MOABMesh::MOABMesh(const std::string& filename) +{ filename_ = filename; initialize(); } -MOABMesh::MOABMesh(std::shared_ptr external_mbi) { +MOABMesh::MOABMesh(std::shared_ptr external_mbi) +{ mbi_ = external_mbi; filename_ = "unknown (external file)"; this->initialize(); } -void MOABMesh::initialize() { +void MOABMesh::initialize() +{ // Create the MOAB interface and load data from file this->create_interface(); @@ -1606,7 +1618,8 @@ void MOABMesh::initialize() { if (!ehs_.all_of_type(moab::MBTET)) { warning("Non-tetrahedral elements found in unstructured " - "mesh file: " + filename_); + "mesh file: " + + filename_); } // make an entity set for all tetrahedra @@ -1626,11 +1639,11 @@ void MOABMesh::initialize() { build_kdtree(ehs_); } -void -MOABMesh::create_interface() +void MOABMesh::create_interface() { // Do not create a MOAB instance if one is already in memory - if (mbi_) return; + if (mbi_) + return; // create MOAB instance mbi_ = std::make_shared(); @@ -1642,23 +1655,20 @@ MOABMesh::create_interface() } } -void -MOABMesh::build_kdtree(const moab::Range& all_tets) +void MOABMesh::build_kdtree(const moab::Range& all_tets) { moab::Range all_tris; int adj_dim = 2; - moab::ErrorCode rval = mbi_->get_adjacencies(all_tets, - adj_dim, - true, - all_tris, - moab::Interface::UNION); + moab::ErrorCode rval = mbi_->get_adjacencies( + all_tets, adj_dim, true, all_tris, moab::Interface::UNION); if (rval != moab::MB_SUCCESS) { fatal_error("Failed to get adjacent triangles for tets"); } if (!all_tris.all_of_type(moab::MBTRI)) { warning("Non-triangle elements found in tet adjacencies in " - "unstructured mesh file: " + filename_); + "unstructured mesh file: " + + filename_); } // combine into one range @@ -1673,7 +1683,8 @@ MOABMesh::build_kdtree(const moab::Range& all_tets) rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_); if (rval != moab::MB_SUCCESS) { fatal_error("Failed to construct KDTree for the " - "unstructured mesh file: " + filename_); + "unstructured mesh file: " + + filename_); } } @@ -1686,16 +1697,11 @@ void MOABMesh::intersect_track(const moab::CartVect& start, vector tris; // get all intersections with triangles in the tet mesh // (distances are relative to the start point, not the previous intersection) - rval = kdtree_->ray_intersect_triangles(kdtree_root_, - FP_COINCIDENT, - dir.array(), - start.array(), - tris, - hits, - 0, - track_len); + rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT, + dir.array(), start.array(), tris, hits, 0, track_len); if (rval != moab::MB_SUCCESS) { - fatal_error("Failed to compute intersections on unstructured mesh: " + filename_); + fatal_error( + "Failed to compute intersections on unstructured mesh: " + filename_); } // remove duplicate intersection distances @@ -1705,12 +1711,8 @@ void MOABMesh::intersect_track(const moab::CartVect& start, std::sort(hits.begin(), hits.end()); } -void -MOABMesh::bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const +void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const { moab::CartVect start(r0.x, r0.y, r0.z); moab::CartVect end(r1.x, r1.y, r1.z); @@ -1718,7 +1720,8 @@ MOABMesh::bins_crossed(Position r0, dir.normalize(); double track_len = (end - start).length(); - if (track_len == 0.0) return; + if (track_len == 0.0) + return; start -= TINY_BIT * dir; end += TINY_BIT * dir; @@ -1764,7 +1767,6 @@ MOABMesh::bins_crossed(Position r0, bins.push_back(bin); lengths.push_back(segment_length / track_len); - } // tally remaining portion of track after last hit if @@ -1782,14 +1784,15 @@ MOABMesh::bins_crossed(Position r0, } }; -moab::EntityHandle -MOABMesh::get_tet(const Position& r) const +moab::EntityHandle MOABMesh::get_tet(const Position& r) const { moab::CartVect pos(r.x, r.y, r.z); // find the leaf of the kd-tree for this position moab::AdaptiveKDTreeIter kdtree_iter; moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter); - if (rval != moab::MB_SUCCESS) { return 0; } + if (rval != moab::MB_SUCCESS) { + return 0; + } // retrieve the tet elements of this leaf moab::EntityHandle leaf = kdtree_iter.handle(); @@ -1831,7 +1834,7 @@ double MOABMesh::tet_volume(moab::EntityHandle tet) const moab::CartVect p[4]; rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array()); if (rval != moab::MB_SUCCESS) { - fatal_error("Failed to get tet coords"); + fatal_error("Failed to get tet coords"); } return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0])); @@ -1847,8 +1850,8 @@ int MOABMesh::get_bin(Position r) const } } -void -MOABMesh::compute_barycentric_data(const moab::Range& tets) { +void MOABMesh::compute_barycentric_data(const moab::Range& tets) +{ moab::ErrorCode rval; baryc_data_.clear(); @@ -1877,9 +1880,8 @@ MOABMesh::compute_barycentric_data(const moab::Range& tets) { } } -bool -MOABMesh::point_in_tet(const moab::CartVect& r, - moab::EntityHandle tet) const +bool MOABMesh::point_in_tet( + const moab::CartVect& r, moab::EntityHandle tet) const { moab::ErrorCode rval; @@ -1898,7 +1900,8 @@ MOABMesh::point_in_tet(const moab::CartVect& r, rval = mbi_->get_coords(verts.data(), 1, p_zero.array()); if (rval != moab::MB_SUCCESS) { warning("Failed to get coordinates of a vertex in " - "unstructured mesh: " + filename_); + "unstructured mesh: " + + filename_); return false; } @@ -1908,14 +1911,12 @@ MOABMesh::point_in_tet(const moab::CartVect& r, moab::CartVect bary_coords = a_inv * (r - p_zero); - return (bary_coords[0] >= 0.0 && - bary_coords[1] >= 0.0 && + return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 && bary_coords[2] >= 0.0 && bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0); } -int -MOABMesh::get_bin_from_index(int idx) const +int MOABMesh::get_bin_from_index(int idx) const { if (idx >= n_bins()) { fatal_error(fmt::format("Invalid bin index: {}", idx)); @@ -1923,9 +1924,7 @@ MOABMesh::get_bin_from_index(int idx) const return ehs_[idx] - ehs_[0]; } -int -MOABMesh::get_index(const Position& r, - bool* in_mesh) const +int MOABMesh::get_index(const Position& r, bool* in_mesh) const { int bin = get_bin(r); *in_mesh = bin != -1; @@ -1944,8 +1943,7 @@ std::pair, vector> MOABMesh::plot( return {}; } -int -MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const +int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const { int bin = eh - ehs_[0]; if (bin >= n_bins()) { @@ -1954,8 +1952,7 @@ MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const return bin; } -moab::EntityHandle -MOABMesh::get_ent_handle_from_bin(int bin) const +moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const { if (bin >= n_bins()) { fatal_error(fmt::format("Invalid bin index: ", bin)); @@ -1981,8 +1978,7 @@ int MOABMesh::n_surface_bins() const return 2 * tris.size(); } -Position -MOABMesh::centroid(int bin) const +Position MOABMesh::centroid(int bin) const { moab::ErrorCode rval; @@ -2006,7 +2002,7 @@ MOABMesh::centroid(int bin) const // compute the centroid of the element vertices moab::CartVect centroid(0.0, 0.0, 0.0); - for(const auto& coord : coords) { + for (const auto& coord : coords) { centroid += coord; } centroid /= double(coords.size()); @@ -2014,8 +2010,8 @@ MOABMesh::centroid(int bin) const return {centroid[0], centroid[1], centroid[2]}; } -std::pair -MOABMesh::get_score_tags(std::string score) const +std::pair MOABMesh::get_score_tags( + std::string score) const { moab::ErrorCode rval; // add a tag to the mesh @@ -2026,30 +2022,26 @@ MOABMesh::get_score_tags(std::string score) const // create the value tag if not present and get handle double default_val = 0.0; auto val_string = score + "_mean"; - rval = mbi_->tag_get_handle(val_string.c_str(), - 1, - moab::MB_TYPE_DOUBLE, - value_tag, - moab::MB_TAG_DENSE|moab::MB_TAG_CREAT, - &default_val); + rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE, + value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val); if (rval != moab::MB_SUCCESS) { - auto msg = fmt::format("Could not create or retrieve the value tag for the score {}" - " on unstructured mesh {}", score, id_); + auto msg = + fmt::format("Could not create or retrieve the value tag for the score {}" + " on unstructured mesh {}", + score, id_); fatal_error(msg); } // create the std dev tag if not present and get handle moab::Tag error_tag; std::string err_string = score + "_std_dev"; - rval = mbi_->tag_get_handle(err_string.c_str(), - 1, - moab::MB_TYPE_DOUBLE, - error_tag, - moab::MB_TAG_DENSE|moab::MB_TAG_CREAT, - &default_val); + rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE, + error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val); if (rval != moab::MB_SUCCESS) { - auto msg = fmt::format("Could not create or retrieve the error tag for the score {}" - " on unstructured mesh {}", score, id_); + auto msg = + fmt::format("Could not create or retrieve the error tag for the score {}" + " on unstructured mesh {}", + score, id_); fatal_error(msg); } @@ -2057,8 +2049,7 @@ MOABMesh::get_score_tags(std::string score) const return {value_tag, error_tag}; } -void -MOABMesh::add_score(const std::string& score) +void MOABMesh::add_score(const std::string& score) { auto score_tags = get_score_tags(score); tag_names_.push_back(score); @@ -2070,26 +2061,31 @@ void MOABMesh::remove_scores() auto value_name = name + "_mean"; moab::Tag tag; moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag); - if (rval != moab::MB_SUCCESS) return; + if (rval != moab::MB_SUCCESS) + return; rval = mbi_->tag_delete(tag); if (rval != moab::MB_SUCCESS) { auto msg = fmt::format("Failed to delete mesh tag for the score {}" - " on unstructured mesh {}", name, id_); + " on unstructured mesh {}", + name, id_); fatal_error(msg); } auto std_dev_name = name + "_std_dev"; rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag); if (rval != moab::MB_SUCCESS) { - auto msg = fmt::format("Std. Dev. mesh tag does not exist for the score {}" - " on unstructured mesh {}", name, id_); + auto msg = + fmt::format("Std. Dev. mesh tag does not exist for the score {}" + " on unstructured mesh {}", + name, id_); } rval = mbi_->tag_delete(tag); if (rval != moab::MB_SUCCESS) { auto msg = fmt::format("Failed to delete mesh tag for the score {}" - " on unstructured mesh {}", name, id_); + " on unstructured mesh {}", + name, id_); fatal_error(msg); } } @@ -2097,8 +2093,7 @@ void MOABMesh::remove_scores() } void MOABMesh::set_score_data(const std::string& score, - const vector& values, - const vector& std_dev) + const vector& values, const vector& std_dev) { auto score_tags = this->get_score_tags(score); @@ -2107,7 +2102,8 @@ void MOABMesh::set_score_data(const std::string& score, rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data()); if (rval != moab::MB_SUCCESS) { auto msg = fmt::format("Failed to set the tally value for score '{}' " - "on unstructured mesh {}", score, id_); + "on unstructured mesh {}", + score, id_); warning(msg); } @@ -2115,13 +2111,13 @@ void MOABMesh::set_score_data(const std::string& score, rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data()); if (rval != moab::MB_SUCCESS) { auto msg = fmt::format("Failed to set the tally error for score '{}' " - "on unstructured mesh {}", score, id_); + "on unstructured mesh {}", + score, id_); warning(msg); } } -void -MOABMesh::write(const std::string& base_filename) const +void MOABMesh::write(const std::string& base_filename) const { // add extension to the base name auto filename = base_filename + ".vtk"; @@ -2157,7 +2153,8 @@ LibMesh::LibMesh(const std::string& filename) void LibMesh::initialize() { if (!settings::libmesh_comm) { - fatal_error("Attempting to use an unstructured mesh without a libMesh communicator."); + fatal_error( + "Attempting to use an unstructured mesh without a libMesh communicator."); } // assuming that unstructured meshes used in OpenMC are 3D @@ -2168,8 +2165,10 @@ void LibMesh::initialize() m_->prepare_for_use(); // ensure that the loaded mesh is 3 dimensional - if(m_->mesh_dimension() != n_dimension_) { - fatal_error(fmt::format("Mesh file {} specified for use in an unstructured mesh is not a 3D mesh.", filename_)); + if (m_->mesh_dimension() != n_dimension_) { + fatal_error(fmt::format("Mesh file {} specified for use in an unstructured " + "mesh is not a 3D mesh.", + filename_)); } // create an equation system for storing values @@ -2179,12 +2178,11 @@ void LibMesh::initialize() libMesh::ExplicitSystem& eq_sys = equation_systems_->add_system(eq_system_name_); - - #ifdef _OPENMP +#ifdef _OPENMP int n_threads = omp_get_max_threads(); - #else +#else int n_threads = 1; - #endif +#endif for (int i = 0; i < n_threads; i++) { pl_.emplace_back(m_->sub_point_locator()); @@ -2200,23 +2198,25 @@ void LibMesh::initialize() bbox_ = libMesh::MeshTools::create_bounding_box(*m_); } -Position -LibMesh::centroid(int bin) const +Position LibMesh::centroid(int bin) const { const auto& elem = this->get_element_from_bin(bin); auto centroid = elem.centroid(); return {centroid(0), centroid(1), centroid(2)}; } -std::string LibMesh::library() const { return "libmesh"; } +std::string LibMesh::library() const +{ + return "libmesh"; +} int LibMesh::n_bins() const { return m_->n_elem(); } -int -LibMesh::n_surface_bins() const { +int LibMesh::n_surface_bins() const +{ int n_bins = 0; for (int i = 0; i < this->n_bins(); i++) { const libMesh::Elem& e = get_element_from_bin(i); @@ -2225,20 +2225,22 @@ LibMesh::n_surface_bins() const { // the number of surface bins is incremented to for (auto neighbor_ptr : e.neighbor_ptr_range()) { // null neighbor pointer indicates a boundary face - if (!neighbor_ptr) { n_bins++; } + if (!neighbor_ptr) { + n_bins++; + } } } return n_bins; } -void -LibMesh::add_score(const std::string& var_name) +void LibMesh::add_score(const std::string& var_name) { // check if this is a new variable std::string value_name = var_name + "_mean"; if (!variable_map_.count(value_name)) { auto& eqn_sys = equation_systems_->get_system(eq_system_name_); - auto var_num = eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL); + auto var_num = + eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL); variable_map_[value_name] = var_num; } @@ -2246,13 +2248,13 @@ LibMesh::add_score(const std::string& var_name) // check if this is a new variable if (!variable_map_.count(std_dev_name)) { auto& eqn_sys = equation_systems_->get_system(eq_system_name_); - auto var_num = eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL); + auto var_num = + eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL); variable_map_[std_dev_name] = var_num; } } -void -LibMesh::remove_scores() +void LibMesh::remove_scores() { auto& eqn_sys = equation_systems_->get_system(eq_system_name_); eqn_sys.clear(); @@ -2264,7 +2266,9 @@ void LibMesh::set_score_data(const std::string& var_name, { auto& eqn_sys = equation_systems_->get_system(eq_system_name_); - if (!eqn_sys.is_initialized()) { equation_systems_->init(); } + if (!eqn_sys.is_initialized()) { + equation_systems_->init(); + } const libMesh::DofMap& dof_map = eqn_sys.get_dof_map(); @@ -2275,7 +2279,8 @@ void LibMesh::set_score_data(const std::string& var_name, std::string std_dev_name = var_name + "_std_dev"; unsigned int std_dev_num = variable_map_.at(std_dev_name); - for (auto it = m_->local_elements_begin(); it != m_->local_elements_end(); it++) { + for (auto it = m_->local_elements_begin(); it != m_->local_elements_end(); + it++) { auto bin = get_bin_from_element(*it); // set value @@ -2294,37 +2299,36 @@ void LibMesh::set_score_data(const std::string& var_name, void LibMesh::write(const std::string& filename) const { - write_message(fmt::format("Writing file: {}.e for unstructured mesh {}", filename, this->id_)); + write_message(fmt::format( + "Writing file: {}.e for unstructured mesh {}", filename, this->id_)); libMesh::ExodusII_IO exo(*m_); std::set systems_out = {eq_system_name_}; - exo.write_discontinuous_exodusII(filename + ".e", *equation_systems_, &systems_out); + exo.write_discontinuous_exodusII( + filename + ".e", *equation_systems_, &systems_out); } -void -LibMesh::bins_crossed(Position r0, - Position r1, - const Direction& u, - vector& bins, - vector& lengths) const +void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u, + vector& bins, vector& lengths) const { // TODO: Implement triangle crossings here fatal_error("Tracklength tallies on libMesh instances are not implemented."); } -int -LibMesh::get_bin(Position r) const +int LibMesh::get_bin(Position r) const { // look-up a tet using the point locator libMesh::Point p(r.x, r.y, r.z); // quick rejection check - if (!bbox_.contains_point(p)) { return -1; } + if (!bbox_.contains_point(p)) { + return -1; + } - #ifdef _OPENMP +#ifdef _OPENMP int thread_num = omp_get_thread_num(); - #else +#else int thread_num = 0; - #endif +#endif const auto& point_locator = pl_.at(thread_num); @@ -2332,8 +2336,7 @@ LibMesh::get_bin(Position r) const return elem_ptr ? get_bin_from_element(elem_ptr) : -1; } -int -LibMesh::get_bin_from_element(const libMesh::Elem* elem) const +int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const { int bin = elem->id() - first_element_id_; if (bin >= n_bins() || bin < 0) { @@ -2348,15 +2351,14 @@ std::pair, vector> LibMesh::plot( return {}; } -const libMesh::Elem& -LibMesh::get_element_from_bin(int bin) const +const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const { return m_->elem_ref(bin); } double LibMesh::volume(int bin) const { - return m_->elem_ref(bin).volume(); + return m_->elem_ref(bin).volume(); } #endif // LIBMESH @@ -2395,7 +2397,8 @@ void read_meshes(pugi::xml_node root) model::meshes.push_back(make_unique(node)); #endif } else if (mesh_type == "unstructured") { - fatal_error("Unstructured mesh support is not enabled or the mesh library is invalid."); + fatal_error("Unstructured mesh support is not enabled or the mesh " + "library is invalid."); } else { fatal_error("Invalid mesh type: " + mesh_type); } @@ -2431,6 +2434,9 @@ void free_memory_mesh() model::mesh_map.clear(); } -extern "C" int n_meshes() { return model::meshes.size(); } +extern "C" int n_meshes() +{ + return model::meshes.size(); +} } // namespace openmc diff --git a/src/message_passing.cpp b/src/message_passing.cpp index f479d3db7..f87782083 100644 --- a/src/message_passing.cpp +++ b/src/message_passing.cpp @@ -12,7 +12,10 @@ MPI_Comm intracomm {MPI_COMM_NULL}; MPI_Datatype source_site {MPI_DATATYPE_NULL}; #endif -extern "C" bool openmc_master() { return mpi::master; } +extern "C" bool openmc_master() +{ + return mpi::master; +} } // namespace mpi diff --git a/src/mgxs.cpp b/src/mgxs.cpp index 00263b541..1c81f8cde 100644 --- a/src/mgxs.cpp +++ b/src/mgxs.cpp @@ -1,19 +1,19 @@ #include "openmc/mgxs.h" +#include #include #include -#include #include #ifdef _OPENMP #include #endif -#include +#include "xtensor/xadapt.hpp" #include "xtensor/xmath.hpp" #include "xtensor/xsort.hpp" -#include "xtensor/xadapt.hpp" #include "xtensor/xview.hpp" +#include #include "openmc/error.h" #include "openmc/math_functions.h" @@ -22,7 +22,6 @@ #include "openmc/settings.h" #include "openmc/string_utils.h" - namespace openmc { //============================================================================== @@ -37,7 +36,7 @@ void Mgxs::init(const std::string& in_name, double in_awr, // Set the metadata name = in_name; awr = in_awr; - //TODO: Remove adapt when in_KTs is an xtensor + // TODO: Remove adapt when in_KTs is an xtensor kTs = xt::adapt(in_kTs); fissionable = in_fissionable; scatter_format = in_scatter_format; @@ -102,57 +101,56 @@ void Mgxs::metadata_from_hdf5(hid_t xs_id, const vector& temperature, // If only one temperature is available, lets just use nearest temperature // interpolation - if ((num_temps == 1) && (settings::temperature_method == TemperatureMethod::INTERPOLATION)) { + if ((num_temps == 1) && + (settings::temperature_method == TemperatureMethod::INTERPOLATION)) { warning("Cross sections for " + strtrim(name) + " are only available " + "at one temperature. Reverting to the nearest temperature " + "method."); settings::temperature_method = TemperatureMethod::NEAREST; } - switch(settings::temperature_method) { - case TemperatureMethod::NEAREST: - // Determine actual temperatures to read - for (const auto& T : temperature) { - auto i_closest = xt::argmin(xt::abs(available_temps - T))[0]; - double temp_actual = available_temps[i_closest]; - if (std::fabs(temp_actual - T) < settings::temperature_tolerance) { - if (std::find(temps_to_read.begin(), temps_to_read.end(), std::round(temp_actual)) - == temps_to_read.end()) { - temps_to_read.push_back(std::round(temp_actual)); + switch (settings::temperature_method) { + case TemperatureMethod::NEAREST: + // Determine actual temperatures to read + for (const auto& T : temperature) { + auto i_closest = xt::argmin(xt::abs(available_temps - T))[0]; + double temp_actual = available_temps[i_closest]; + if (std::fabs(temp_actual - T) < settings::temperature_tolerance) { + if (std::find(temps_to_read.begin(), temps_to_read.end(), + std::round(temp_actual)) == temps_to_read.end()) { + temps_to_read.push_back(std::round(temp_actual)); + } + } else { + fatal_error(fmt::format("MGXS library does not contain cross sections " + "for {} at or near {} K.", + in_name, std::round(T))); + } + } + break; + + case TemperatureMethod::INTERPOLATION: + for (int i = 0; i < temperature.size(); i++) { + for (int j = 0; j < num_temps; j++) { + if (j == (num_temps - 1)) { + fatal_error("MGXS Library does not contain cross sections for " + + in_name + " at temperatures that bound " + + std::to_string(std::round(temperature[i]))); + } + if ((available_temps[j] <= temperature[i]) && + (temperature[i] < available_temps[j + 1])) { + if (std::find(temps_to_read.begin(), temps_to_read.end(), + std::round(available_temps[j])) == temps_to_read.end()) { + temps_to_read.push_back(std::round((int)available_temps[j])); } - } else { - fatal_error(fmt::format( - "MGXS library does not contain cross sections for {} at or near {} K.", - in_name, std::round(T))); + + if (std::find(temps_to_read.begin(), temps_to_read.end(), + std::round(available_temps[j + 1])) == temps_to_read.end()) { + temps_to_read.push_back(std::round((int)available_temps[j + 1])); + } + break; } } - break; - - case TemperatureMethod::INTERPOLATION: - for (int i = 0; i < temperature.size(); i++) { - for (int j = 0; j < num_temps; j++) { - if (j == (num_temps - 1)) { - fatal_error("MGXS Library does not contain cross sections for " + - in_name + " at temperatures that bound " + - std::to_string(std::round(temperature[i]))); - } - if ((available_temps[j] <= temperature[i]) && - (temperature[i] < available_temps[j + 1])) { - if (std::find(temps_to_read.begin(), - temps_to_read.end(), - std::round(available_temps[j])) == temps_to_read.end()) { - temps_to_read.push_back(std::round((int)available_temps[j])); - } - - if (std::find(temps_to_read.begin(), temps_to_read.end(), - std::round(available_temps[j + 1])) == temps_to_read.end()) { - temps_to_read.push_back(std::round((int) available_temps[j + 1])); - } - break; - } - } - - } + } } std::sort(temps_to_read.begin(), temps_to_read.end()); @@ -162,7 +160,7 @@ void Mgxs::metadata_from_hdf5(hid_t xs_id, const vector& temperature, for (int i = 0; i < n_temperature; i++) { std::string temp_str(std::to_string(temps_to_read[i]) + "K"); - //read exact temperature value + // read exact temperature value read_double(kT_group, temp_str.c_str(), &in_kTs[i], true); } close_group(kT_group); @@ -255,7 +253,7 @@ void Mgxs::metadata_from_hdf5(hid_t xs_id, const vector& temperature, vector in_polar(in_n_pol); double dangle = PI / in_n_pol; for (int p = 0; p < in_n_pol; p++) { - in_polar[p] = (p + 0.5) * dangle; + in_polar[p] = (p + 0.5) * dangle; } vector in_azimuthal(in_n_azi); dangle = 2. * PI / in_n_azi; @@ -265,8 +263,7 @@ void Mgxs::metadata_from_hdf5(hid_t xs_id, const vector& temperature, // Finally use this data to initialize the MGXS Object init(in_name, in_awr, in_kTs, in_fissionable, in_scatter_format, - in_is_isotropic, in_polar, - in_azimuthal); + in_is_isotropic, in_polar, in_azimuthal); } //============================================================================== @@ -283,19 +280,20 @@ Mgxs::Mgxs( // Set number of energy and delayed groups AngleDistributionType final_scatter_format = scatter_format; if (settings::legendre_to_tabular) { - if (scatter_format == AngleDistributionType::LEGENDRE) final_scatter_format = AngleDistributionType::TABULAR; + if (scatter_format == AngleDistributionType::LEGENDRE) + final_scatter_format = AngleDistributionType::TABULAR; } // Load the more specific XsData information for (int t = 0; t < temps_to_read.size(); t++) { - xs[t] = XsData(fissionable, final_scatter_format, n_pol, n_azi, - num_groups, num_delayed_groups); + xs[t] = XsData(fissionable, final_scatter_format, n_pol, n_azi, num_groups, + num_delayed_groups); // Get the temperature as a string and then open the HDF5 group std::string temp_str = std::to_string(temps_to_read[t]) + "K"; hid_t xsdata_grp = open_group(xs_id, temp_str.c_str()); xs[t].from_hdf5(xsdata_grp, fissionable, scatter_format, - final_scatter_format, order_data, is_isotropic, n_pol, n_azi); + final_scatter_format, order_data, is_isotropic, n_pol, n_azi); close_group(xsdata_grp); } // end temperature loop @@ -318,7 +316,8 @@ Mgxs::Mgxs(const std::string& in_name, const vector& mat_kTs, // the fissionable status if we learn differently bool in_fissionable = false; for (int m = 0; m < micros.size(); m++) { - if (micros[m]->fissionable) in_fissionable = true; + if (micros[m]->fissionable) + in_fissionable = true; } // Force all of the following data to be the same; these will be verified // to be true later @@ -328,7 +327,7 @@ Mgxs::Mgxs(const std::string& in_name, const vector& mat_kTs, vector in_azimuthal = micros[0]->azimuthal; init(in_name, in_awr, mat_kTs, in_fissionable, in_scatter_format, - in_is_isotropic, in_polar, in_azimuthal); + in_is_isotropic, in_polar, in_azimuthal); // Create the xs data for each temperature for (int t = 0; t < mat_kTs.size(); t++) { @@ -343,19 +342,18 @@ Mgxs::Mgxs(const std::string& in_name, const vector& mat_kTs, vector micro_t(micros.size(), 0); vector micro_t_interp(micros.size(), 0.); for (int m = 0; m < micros.size(); m++) { - switch(settings::temperature_method) { - case TemperatureMethod::NEAREST: - { - micro_t[m] = xt::argmin(xt::abs(micros[m]->kTs - temp_desired))[0]; - auto temp_actual = micros[m]->kTs[micro_t[m]]; + switch (settings::temperature_method) { + case TemperatureMethod::NEAREST: { + micro_t[m] = xt::argmin(xt::abs(micros[m]->kTs - temp_desired))[0]; + auto temp_actual = micros[m]->kTs[micro_t[m]]; - if (std::abs(temp_actual - temp_desired) >= K_BOLTZMANN * settings::temperature_tolerance) { - fatal_error(fmt::format( - "MGXS Library does not contain cross section for {} at or near {} K.", - name, std::round(temp_desired / K_BOLTZMANN))); - } + if (std::abs(temp_actual - temp_desired) >= + K_BOLTZMANN * settings::temperature_tolerance) { + fatal_error(fmt::format("MGXS Library does not contain cross section " + "for {} at or near {} K.", + name, std::round(temp_desired / K_BOLTZMANN))); } - break; + } break; case TemperatureMethod::INTERPOLATION: // Get a list of bounding temperatures for each actual temperature // present in the model @@ -365,14 +363,14 @@ Mgxs::Mgxs(const std::string& in_name, const vector& mat_kTs, micro_t[m] = k; if (k == 0) { micro_t_interp[m] = (temp_desired - micros[m]->kTs[k]) / - (micros[m]->kTs[k + 1] - micros[m]->kTs[k]); + (micros[m]->kTs[k + 1] - micros[m]->kTs[k]); } else { micro_t_interp[m] = 1.; } } } } // end switch - } // end microscopic temperature loop + } // end microscopic temperature loop // Now combine the microscopic data at each relevant temperature // We will do this by treating the multiple temperatures of a nuclide as @@ -410,7 +408,6 @@ Mgxs::Mgxs(const std::string& in_name, const vector& mat_kTs, // And finally, combine the data combine(mgxs_to_combine, interpolant, temp_indices, t); } // end temperature (t) loop - } //============================================================================== @@ -429,9 +426,8 @@ void Mgxs::combine(const vector& micros, const vector& scalars, //============================================================================== -double -Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, - const int* dg) +double Mgxs::get_xs( + MgxsType xstype, int gin, const int* gout, const double* mu, const int* dg) { // This method assumes that the temperature and angle indices are set #ifdef _OPENMP @@ -443,7 +439,7 @@ Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, int a = cache[0].a; #endif double val; - switch(xstype) { + switch (xstype) { case MgxsType::TOTAL: val = xs_t->total(a, gin); break; @@ -451,7 +447,8 @@ Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, val = fissionable ? xs_t->nu_fission(a, gin) : 0.; break; case MgxsType::ABSORPTION: - val = xs_t->absorption(a, gin);; + val = xs_t->absorption(a, gin); + ; break; case MgxsType::FISSION: val = fissionable ? xs_t->fission(a, gin) : 0.; @@ -490,7 +487,7 @@ Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, // provide an outgoing group-wise sum val = 0.; for (int g = 0; g < xs_t->chi_prompt.shape()[2]; g++) { - val += xs_t->chi_prompt(a, gin, g); + val += xs_t->chi_prompt(a, gin, g); } } } else { @@ -515,7 +512,7 @@ Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, val = 0.; for (int g = 0; g < xs_t->delayed_nu_fission.shape()[2]; g++) { for (int d = 0; d < xs_t->delayed_nu_fission.shape()[3]; d++) { - val += xs_t->delayed_nu_fission(a, d, gin, g); + val += xs_t->delayed_nu_fission(a, d, gin, g); } } } @@ -542,8 +539,7 @@ Mgxs::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu, //============================================================================== -void -Mgxs::sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed) +void Mgxs::sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed) { // This method assumes that the temperature and angle indices are set #ifdef _OPENMP @@ -572,7 +568,8 @@ Mgxs::sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed) double prob_gout = 0.; for (gout = 0; gout < num_groups; ++gout) { prob_gout += xs_t->chi_prompt(cache[tid].a, gin, gout); - if (xi_gout < prob_gout) break; + if (xi_gout < prob_gout) + break; } } else { @@ -581,7 +578,8 @@ Mgxs::sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed) // get the delayed group for (dg = 0; dg < num_delayed_groups; ++dg) { prob_prompt += xs_t->delayed_nu_fission(cache[tid].a, dg, gin); - if (xi_pd < prob_prompt) break; + if (xi_pd < prob_prompt) + break; } // adjust dg in case of round-off error @@ -591,15 +589,16 @@ Mgxs::sample_fission_energy(int gin, int& dg, int& gout, uint64_t* seed) double prob_gout = 0.; for (gout = 0; gout < num_groups; ++gout) { prob_gout += xs_t->chi_delayed(cache[tid].a, dg, gin, gout); - if (xi_gout < prob_gout) break; + if (xi_gout < prob_gout) + break; } } } //============================================================================== -void -Mgxs::sample_scatter(int gin, int& gout, double& mu, double& wgt, uint64_t* seed) +void Mgxs::sample_scatter( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed) { // This method assumes that the temperature and angle indices are set // Sample the data @@ -613,8 +612,7 @@ Mgxs::sample_scatter(int gin, int& gout, double& mu, double& wgt, uint64_t* seed //============================================================================== -void -Mgxs::calculate_xs(Particle& p) +void Mgxs::calculate_xs(Particle& p) { // Set our indices #ifdef _OPENMP @@ -633,22 +631,20 @@ Mgxs::calculate_xs(Particle& p) //============================================================================== -bool -Mgxs::equiv(const Mgxs& that) +bool Mgxs::equiv(const Mgxs& that) { - return ((num_delayed_groups == that.num_delayed_groups) && - (num_groups == that.num_groups) && - (n_pol == that.n_pol) && - (n_azi == that.n_azi) && - (std::equal(polar.begin(), polar.end(), that.polar.begin())) && - (std::equal(azimuthal.begin(), azimuthal.end(), that.azimuthal.begin())) && - (scatter_format == that.scatter_format)); + return ( + (num_delayed_groups == that.num_delayed_groups) && + (num_groups == that.num_groups) && (n_pol == that.n_pol) && + (n_azi == that.n_azi) && + (std::equal(polar.begin(), polar.end(), that.polar.begin())) && + (std::equal(azimuthal.begin(), azimuthal.end(), that.azimuthal.begin())) && + (scatter_format == that.scatter_format)); } //============================================================================== -void -Mgxs::set_temperature_index(double sqrtkT) +void Mgxs::set_temperature_index(double sqrtkT) { // See if we need to find the new index #ifdef _OPENMP @@ -664,8 +660,7 @@ Mgxs::set_temperature_index(double sqrtkT) //============================================================================== -void -Mgxs::set_angle_index(Direction u) +void Mgxs::set_angle_index(Direction u) { // See if we need to find the new index #ifdef _OPENMP @@ -673,9 +668,8 @@ Mgxs::set_angle_index(Direction u) #else int tid = 0; #endif - if (!is_isotropic && - ((u.x != cache[tid].u) || (u.y != cache[tid].v) || - (u.z != cache[tid].w))) { + if (!is_isotropic && ((u.x != cache[tid].u) || (u.y != cache[tid].v) || + (u.z != cache[tid].w))) { // convert direction to polar and azimuthal angles double my_pol = std::acos(u.z); double my_azi = std::atan2(u.y, u.x); diff --git a/src/mgxs_interface.cpp b/src/mgxs_interface.cpp index 227896d80..1a6dab5c6 100644 --- a/src/mgxs_interface.cpp +++ b/src/mgxs_interface.cpp @@ -6,8 +6,8 @@ #include #include "openmc/cell.h" -#include "openmc/cross_sections.h" #include "openmc/container_util.h" +#include "openmc/cross_sections.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/geometry_aux.h" @@ -17,7 +17,6 @@ #include "openmc/nuclide.h" #include "openmc/settings.h" - namespace openmc { //============================================================================== @@ -25,7 +24,7 @@ namespace openmc { //============================================================================== namespace data { - MgxsInterface mg; +MgxsInterface mg; } MgxsInterface::MgxsInterface(const std::string& path_cross_sections, @@ -57,7 +56,8 @@ void MgxsInterface::init() // Check if MGXS Library exists if (!file_exists(cross_sections_path_)) { // Could not find MGXS Library file - fatal_error(fmt::format("Cross sections HDF5 file '{}' does not exist!", cross_sections_path_)); + fatal_error(fmt::format( + "Cross sections HDF5 file '{}' does not exist!", cross_sections_path_)); } write_message("Loading cross section data...", 5); @@ -78,12 +78,12 @@ void MgxsInterface::init() read_attribute(file_id, "version", array); if (array != VERSION_MGXS_LIBRARY) { fatal_error("MGXS Library file version does not match current version " - "supported by OpenMC."); + "supported by OpenMC."); } // ========================================================================== // READ ALL MGXS CROSS SECTION TABLES - for (unsigned i_nuc=0; i_nucname_, kTs[i], mgxs_ptr, atom_densities, - num_energy_groups_, num_delayed_groups_); + num_energy_groups_, num_delayed_groups_); } else { // Preserve the ordering of materials by including a blank entry macro_xs_.emplace_back(); @@ -153,16 +154,18 @@ vector> MgxsInterface::get_mat_kTs() for (const auto& cell : model::cells) { // Skip non-material cells - if (cell->fill_ != C_NONE) continue; + if (cell->fill_ != C_NONE) + continue; for (int j = 0; j < cell->material_.size(); ++j) { // Skip void materials int i_material = cell->material_[j]; - if (i_material == MATERIAL_VOID) continue; + if (i_material == MATERIAL_VOID) + continue; // Get temperature of cell (rounding to nearest integer) - double sqrtkT = cell->sqrtkT_.size() == 1 ? - cell->sqrtkT_[j] : cell->sqrtkT_[0]; + double sqrtkT = + cell->sqrtkT_.size() == 1 ? cell->sqrtkT_[j] : cell->sqrtkT_[0]; double kT = sqrtkT * sqrtkT; // Add temperature if it hasn't already been added @@ -184,7 +187,8 @@ void MgxsInterface::read_header(const std::string& path_cross_sections) // Check if MGXS Library exists if (!file_exists(cross_sections_path_)) { // Could not find MGXS Library file - fatal_error(fmt::format("Cross section HDF5 file '{}' does not exist", cross_sections_path_)); + fatal_error(fmt::format( + "Cross section HDF5 file '{}' does not exist", cross_sections_path_)); } write_message("Reading cross sections HDF5 file...", 5); @@ -209,15 +213,14 @@ void MgxsInterface::read_header(const std::string& path_cross_sections) // Create average energies for (int i = 0; i < energy_bins_.size() - 1; ++i) { - energy_bin_avg_.push_back(0.5* - (energy_bins_[i] + energy_bins_[i+1])); + energy_bin_avg_.push_back(0.5 * (energy_bins_[i] + energy_bins_[i + 1])); } // Add entries into libraries for MG data xs_names_ = group_names(file_id); if (xs_names_.empty()) { fatal_error("At least one MGXS data set must be present in mgxs " - "library file!"); + "library file!"); } // Close MGXS HDF5 file diff --git a/src/nuclide.cpp b/src/nuclide.cpp index a7eff14f9..6d34f309b 100644 --- a/src/nuclide.cpp +++ b/src/nuclide.cpp @@ -21,7 +21,7 @@ #include "xtensor/xview.hpp" #include // for sort, min_element -#include // for to_string, stoi +#include // for to_string, stoi namespace openmc { @@ -74,10 +74,12 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) std::sort(temps_available.begin(), temps_available.end()); // If only one temperature is available, revert to nearest temperature - if (temps_available.size() == 1 && settings::temperature_method == TemperatureMethod::INTERPOLATION) { + if (temps_available.size() == 1 && + settings::temperature_method == TemperatureMethod::INTERPOLATION) { if (mpi::master) { - warning("Cross sections for " + name_ + " are only available at one " - "temperature. Reverting to nearest temperature method."); + warning("Cross sections for " + name_ + + " are only available at one " + "temperature. Reverting to nearest temperature method."); } settings::temperature_method = TemperatureMethod::NEAREST; } @@ -92,12 +94,16 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) double T_max = n > 0 ? settings::temperature_range[1] : INFTY; if (T_max > 0.0) { // Determine first available temperature below or equal to T_min - auto T_min_it = std::upper_bound(temps_available.begin(), temps_available.end(), T_min); - if (T_min_it != temps_available.begin()) --T_min_it; + auto T_min_it = + std::upper_bound(temps_available.begin(), temps_available.end(), T_min); + if (T_min_it != temps_available.begin()) + --T_min_it; // Determine first available temperature above or equal to T_max - auto T_max_it = std::lower_bound(temps_available.begin(), temps_available.end(), T_max); - if (T_max_it != temps_available.end()) ++T_max_it; + auto T_max_it = + std::lower_bound(temps_available.begin(), temps_available.end(), T_max); + if (T_max_it != temps_available.end()) + ++T_max_it; // Add corresponding temperatures to vector for (auto it = T_min_it; it != T_max_it; ++it) { @@ -126,15 +132,18 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) temps_to_read.push_back(std::round(T_actual)); // Write warning for resonance scattering data if 0K is not available - if (std::abs(T_actual - T_desired) > 0 && T_desired == 0 && mpi::master) { - warning(name_ + " does not contain 0K data needed for resonance " - "scattering options selected. Using data at " + std::to_string(T_actual) - + " K instead."); + if (std::abs(T_actual - T_desired) > 0 && T_desired == 0 && + mpi::master) { + warning(name_ + + " does not contain 0K data needed for resonance " + "scattering options selected. Using data at " + + std::to_string(T_actual) + " K instead."); } } } else { - fatal_error("Nuclear data library does not contain cross sections for " + - name_ + " at or near " + std::to_string(T_desired) + " K."); + fatal_error( + "Nuclear data library does not contain cross sections for " + name_ + + " at or near " + std::to_string(T_desired) + " K."); } } break; @@ -145,9 +154,10 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) for (double T_desired : temperature) { bool found_pair = false; for (int j = 0; j < temps_available.size() - 1; ++j) { - if (temps_available[j] <= T_desired && T_desired < temps_available[j + 1]) { + if (temps_available[j] <= T_desired && + T_desired < temps_available[j + 1]) { int T_j = std::round(temps_available[j]); - int T_j1 = std::round(temps_available[j+1]); + int T_j1 = std::round(temps_available[j + 1]); if (!contains(temps_to_read, T_j)) { temps_to_read.push_back(T_j); } @@ -159,8 +169,9 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) } if (!found_pair) { - fatal_error("Nuclear data library does not contain cross sections for " + - name_ +" at temperatures that bound " + std::to_string(T_desired) + " K."); + fatal_error( + "Nuclear data library does not contain cross sections for " + name_ + + " at temperatures that bound " + std::to_string(T_desired) + " K."); } } break; @@ -248,14 +259,15 @@ Nuclide::Nuclide(hid_t group, const vector& temperature) if (temps_to_read.size() > 0) { // Make sure inelastic flags are consistent for different temperatures for (int i = 0; i < urr_data_.size() - 1; ++i) { - if (urr_data_[i].inelastic_flag_ != urr_data_[i+1].inelastic_flag_) { - fatal_error(fmt::format("URR inelastic flag is not consistent for " + if (urr_data_[i].inelastic_flag_ != urr_data_[i + 1].inelastic_flag_) { + fatal_error(fmt::format( + "URR inelastic flag is not consistent for " "multiple temperatures in nuclide {}. This most likely indicates " - "a problem in how the data was processed.", name_)); + "a problem in how the data was processed.", + name_)); } } - if (urr_data_[0].inelastic_flag_ > 0) { for (int i = 0; i < reactions_.size(); i++) { if (reactions_[i]->mt_ == urr_data_[0].inelastic_flag_) { @@ -306,7 +318,8 @@ Nuclide::~Nuclide() data::nuclide_map.erase(name_); } -void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* delayed_photons) +void Nuclide::create_derived( + const Function1D* prompt_photons, const Function1D* delayed_photons) { for (const auto& grid : grid_) { // Allocate and initialize cross section @@ -328,9 +341,9 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* for (const auto& p : rx->products_) { if (p.particle_ == ParticleType::photon) { - auto pprod = xt::view(xs_[t], xt::range(j, j+n), XS_PHOTON_PROD); + auto pprod = xt::view(xs_[t], xt::range(j, j + n), XS_PHOTON_PROD); for (int k = 0; k < n; ++k) { - double E = grid_[t].energy[k+j]; + double E = grid_[t].energy[k + j]; // For fission, artificially increase the photon yield to account // for delayed photons @@ -340,7 +353,7 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* if (prompt_photons && delayed_photons) { double energy_prompt = (*prompt_photons)(E); double energy_delayed = (*delayed_photons)(E); - f = (energy_prompt + energy_delayed)/(energy_prompt); + f = (energy_prompt + energy_delayed) / (energy_prompt); } } } @@ -351,28 +364,30 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* } // Skip redundant reactions - if (rx->redundant_) continue; + if (rx->redundant_) + continue; // Add contribution to total cross section - auto total = xt::view(xs_[t], xt::range(j,j+n), XS_TOTAL); + auto total = xt::view(xs_[t], xt::range(j, j + n), XS_TOTAL); total += xs; // Add contribution to absorption cross section - auto absorption = xt::view(xs_[t], xt::range(j,j+n), XS_ABSORPTION); + auto absorption = xt::view(xs_[t], xt::range(j, j + n), XS_ABSORPTION); if (is_disappearance(rx->mt_)) { absorption += xs; } if (is_fission(rx->mt_)) { fissionable_ = true; - auto fission = xt::view(xs_[t], xt::range(j,j+n), XS_FISSION); + auto fission = xt::view(xs_[t], xt::range(j, j + n), XS_FISSION); fission += xs; absorption += xs; // Keep track of fission reactions if (t == 0) { fission_rx_.push_back(rx.get()); - if (rx->mt_ == N_F) has_partial_fission_ = true; + if (rx->mt_ == N_F) + has_partial_fission_ = true; } } } @@ -393,8 +408,8 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* int n = grid_[t].energy.size(); for (int i = 0; i < n; ++i) { double E = grid_[t].energy[i]; - xs_[t](i, XS_NU_FISSION) = nu(E, EmissionMode::total) - * xs_[t](i, XS_FISSION); + xs_[t](i, XS_NU_FISSION) = + nu(E, EmissionMode::total) * xs_[t](i, XS_FISSION); } } } @@ -409,8 +424,9 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* // Make sure nuclide has 0K data if (energy_0K_.empty()) { - fatal_error("Cannot treat " + name_ + " as a resonant scatterer " - "because 0 K elastic scattering data is not present."); + fatal_error("Cannot treat " + name_ + + " as a resonant scatterer " + "because 0 K elastic scattering data is not present."); } break; } @@ -432,11 +448,13 @@ void Nuclide::create_derived(const Function1D* prompt_photons, const Function1D* for (int i = 0; i < E.size() - 1; ++i) { // Negative cross sections result in a CDF that is not monotonically // increasing. Set all negative xs values to zero. - if (xs[i] < 0.0) xs[i] = 0.0; + if (xs[i] < 0.0) + xs[i] = 0.0; // build xs cdf - xs_cdf_sum += (std::sqrt(E[i])*xs[i] + std::sqrt(E[i+1])*xs[i+1]) - / 2.0 * (E[i+1] - E[i]); + xs_cdf_sum += + (std::sqrt(E[i]) * xs[i] + std::sqrt(E[i + 1]) * xs[i + 1]) / 2.0 * + (E[i + 1] - E[i]); xs_cdf_[i] = xs_cdf_sum; } } @@ -451,10 +469,10 @@ void Nuclide::init_grid() int M = settings::n_log_bins; // Determine equal-logarithmic energy spacing - double spacing = std::log(E_max/E_min)/M; + double spacing = std::log(E_max / E_min) / M; // Create equally log-spaced energy grid - auto umesh = xt::linspace(0.0, M*spacing, M+1); + auto umesh = xt::linspace(0.0, M * spacing, M + 1); for (auto& grid : grid_) { // Resize array for storing grid indices @@ -464,10 +482,11 @@ void Nuclide::init_grid() // equal-logarithmic grid int j = 0; for (int k = 0; k <= M; ++k) { - while (std::log(grid.energy[j + 1]/E_min) <= umesh(k)) { + while (std::log(grid.energy[j + 1] / E_min) <= umesh(k)) { // Ensure that for isotopes where maxval(grid.energy) << E_max that // there are no out-of-bounds issues. - if (j + 2 == grid.energy.size()) break; + if (j + 2 == grid.energy.size()) + break; ++j; } grid.grid_index[k] = j; @@ -477,7 +496,8 @@ void Nuclide::init_grid() double Nuclide::nu(double E, EmissionMode mode, int group) const { - if (!fissionable_) return 0.0; + if (!fissionable_) + return 0.0; switch (mode) { case EmissionMode::prompt: @@ -527,7 +547,7 @@ void Nuclide::calculate_elastic_xs(Particle& p) const if (i_temp >= 0) { const auto& xs = reactions_[0]->xs_[i_temp].value; - micro.elastic = (1.0 - f)*xs[i_grid] + f*xs[i_grid + 1]; + micro.elastic = (1.0 - f) * xs[i_grid] + f * xs[i_grid + 1]; } } @@ -544,17 +564,19 @@ double Nuclide::elastic_xs_0K(double E) const } // check for rare case where two energy points are the same - if (energy_0K_[i_grid] == energy_0K_[i_grid+1]) ++i_grid; + if (energy_0K_[i_grid] == energy_0K_[i_grid + 1]) + ++i_grid; // calculate interpolation factor - double f = (E - energy_0K_[i_grid]) / - (energy_0K_[i_grid + 1] - energy_0K_[i_grid]); + double f = + (E - energy_0K_[i_grid]) / (energy_0K_[i_grid + 1] - energy_0K_[i_grid]); // Calculate microscopic nuclide elastic cross section - return (1.0 - f)*elastic_0K_[i_grid] + f*elastic_0K_[i_grid + 1]; + return (1.0 - f) * elastic_0K_[i_grid] + f * elastic_0K_[i_grid + 1]; } -void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle& p) +void Nuclide::calculate_xs( + int i_sab, int i_log_union, double sab_frac, Particle& p) { auto& micro {p.neutron_xs(index_)}; @@ -612,28 +634,28 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle double f; int i_temp = -1; switch (settings::temperature_method) { - case TemperatureMethod::NEAREST: - { - double max_diff = INFTY; - for (int t = 0; t < kTs_.size(); ++t) { - double diff = std::abs(kTs_[t] - kT); - if (diff < max_diff) { - i_temp = t; - max_diff = diff; - } + case TemperatureMethod::NEAREST: { + double max_diff = INFTY; + for (int t = 0; t < kTs_.size(); ++t) { + double diff = std::abs(kTs_[t] - kT); + if (diff < max_diff) { + i_temp = t; + max_diff = diff; } } - break; + } break; case TemperatureMethod::INTERPOLATION: // Find temperatures that bound the actual temperature for (i_temp = 0; i_temp < kTs_.size() - 1; ++i_temp) { - if (kTs_[i_temp] <= kT && kT < kTs_[i_temp + 1]) break; + if (kTs_[i_temp] <= kT && kT < kTs_[i_temp + 1]) + break; } // Randomly sample between temperature i and i+1 f = (kT - kTs_[i_temp]) / (kTs_[i_temp + 1] - kTs_[i_temp]); - if (f > prn(p.current_seed())) ++i_temp; + if (f > prn(p.current_seed())) + ++i_temp; break; } @@ -652,7 +674,7 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle } else { // Determine bounding indices based on which equal log-spaced // interval the energy is in - int i_low = grid.grid_index[i_log_union]; + int i_low = grid.grid_index[i_log_union]; int i_high = grid.grid_index[i_log_union + 1] + 1; // Perform binary search over reduced range @@ -661,7 +683,8 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle } // check for rare case where two energy points are the same - if (grid.energy[i_grid] == grid.energy[i_grid + 1]) ++i_grid; + if (grid.energy[i_grid] == grid.energy[i_grid + 1]) + ++i_grid; // calculate interpolation factor f = (p.E() - grid.energy[i_grid]) / @@ -672,29 +695,29 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle micro.interp_factor = f; // Calculate microscopic nuclide total cross section - micro.total = (1.0 - f)*xs(i_grid, XS_TOTAL) - + f*xs(i_grid + 1, XS_TOTAL); + micro.total = + (1.0 - f) * xs(i_grid, XS_TOTAL) + f * xs(i_grid + 1, XS_TOTAL); // Calculate microscopic nuclide absorption cross section - micro.absorption = (1.0 - f)*xs(i_grid, XS_ABSORPTION) - + f*xs(i_grid + 1, XS_ABSORPTION); + micro.absorption = + (1.0 - f) * xs(i_grid, XS_ABSORPTION) + f * xs(i_grid + 1, XS_ABSORPTION); if (fissionable_) { // Calculate microscopic nuclide total cross section - micro.fission = (1.0 - f)*xs(i_grid, XS_FISSION) - + f*xs(i_grid + 1, XS_FISSION); + micro.fission = + (1.0 - f) * xs(i_grid, XS_FISSION) + f * xs(i_grid + 1, XS_FISSION); // Calculate microscopic nuclide nu-fission cross section - micro.nu_fission = (1.0 - f)*xs(i_grid, XS_NU_FISSION) - + f*xs(i_grid + 1, XS_NU_FISSION); + micro.nu_fission = (1.0 - f) * xs(i_grid, XS_NU_FISSION) + + f * xs(i_grid + 1, XS_NU_FISSION); } else { micro.fission = 0.0; micro.nu_fission = 0.0; } // Calculate microscopic nuclide photon production cross section - micro.photon_prod = (1.0 - f)*xs(i_grid, XS_PHOTON_PROD) - + f*xs(i_grid + 1, XS_PHOTON_PROD); + micro.photon_prod = (1.0 - f) * xs(i_grid, XS_PHOTON_PROD) + + f * xs(i_grid + 1, XS_PHOTON_PROD); // Depletion-related reactions if (simulation::need_depletion_rx) { @@ -711,18 +734,18 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle const auto& rx = reactions_[i_rx]; const auto& rx_xs = rx->xs_[i_temp].value; - // Physics says that (n,gamma) is not a threshold reaction, so we don't - // need to specifically check its threshold index + // Physics says that (n,gamma) is not a threshold reaction, so we + // don't need to specifically check its threshold index if (j == 0) { - micro.reaction[0] = (1.0 - f)*rx_xs[i_grid] - + f*rx_xs[i_grid + 1]; + micro.reaction[0] = + (1.0 - f) * rx_xs[i_grid] + f * rx_xs[i_grid + 1]; continue; } int threshold = rx->xs_[i_temp].threshold; if (i_grid >= threshold) { - micro.reaction[j] = (1.0 - f)*rx_xs[i_grid - threshold] + - f*rx_xs[i_grid - threshold + 1]; + micro.reaction[j] = (1.0 - f) * rx_xs[i_grid - threshold] + + f * rx_xs[i_grid - threshold + 1]; } else if (j >= 3) { // One can show that the the threshold for (n,(x+1)n) is always // higher than the threshold for (n,xn). Thus, if we are below @@ -746,7 +769,8 @@ void Nuclide::calculate_xs(int i_sab, int i_log_union, double sab_frac, Particle // and sab_elastic cross sections and correct the total and elastic cross // sections. - if (i_sab >= 0) this->calculate_sab_xs(i_sab, sab_frac, p); + if (i_sab >= 0) + this->calculate_sab_xs(i_sab, sab_frac, p); // If the particle is in the unresolved resonance range and there are // probability tables, we need to determine cross sections from the table @@ -784,8 +808,8 @@ void Nuclide::calculate_sab_xs(int i_sab, double sab_frac, Particle& p) this->calculate_elastic_xs(p); // Correct total and elastic cross sections - micro.total = micro.total + micro.thermal - sab_frac*micro.elastic; - micro.elastic = micro.thermal + (1.0 - sab_frac)*micro.elastic; + micro.total = micro.total + micro.thermal - sab_frac * micro.elastic; + micro.elastic = micro.thermal + (1.0 - sab_frac) * micro.elastic; // Save temperature index and thermal fraction micro.index_temp_sab = i_temp; @@ -817,10 +841,14 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const p.stream() = STREAM_TRACKING; int i_low = 0; - while (urr.prob_(i_energy, URRTableParam::CUM_PROB, i_low) <= r) {++i_low;}; + while (urr.prob_(i_energy, URRTableParam::CUM_PROB, i_low) <= r) { + ++i_low; + }; int i_up = 0; - while (urr.prob_(i_energy + 1, URRTableParam::CUM_PROB, i_up) <= r) {++i_up;}; + while (urr.prob_(i_energy + 1, URRTableParam::CUM_PROB, i_up) <= r) { + ++i_up; + }; // Determine elastic, fission, and capture cross sections from the // probability table @@ -834,11 +862,11 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const (urr.energy_(i_energy + 1) - urr.energy_(i_energy)); elastic = (1. - f) * urr.prob_(i_energy, URRTableParam::ELASTIC, i_low) + - f * urr.prob_(i_energy + 1, URRTableParam::ELASTIC, i_up); + f * urr.prob_(i_energy + 1, URRTableParam::ELASTIC, i_up); fission = (1. - f) * urr.prob_(i_energy, URRTableParam::FISSION, i_low) + - f * urr.prob_(i_energy + 1, URRTableParam::FISSION, i_up); + f * urr.prob_(i_energy + 1, URRTableParam::FISSION, i_up); capture = (1. - f) * urr.prob_(i_energy, URRTableParam::N_GAMMA, i_low) + - f * urr.prob_(i_energy + 1, URRTableParam::N_GAMMA, i_up); + f * urr.prob_(i_energy + 1, URRTableParam::N_GAMMA, i_up); } else if (urr.interp_ == Interpolation::log_log) { // Determine interpolation factor on the table f = std::log(p.E() / urr.energy_(i_energy)) / @@ -847,10 +875,10 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const // Calculate the elastic cross section/factor if ((urr.prob_(i_energy, URRTableParam::ELASTIC, i_low) > 0.) && (urr.prob_(i_energy + 1, URRTableParam::ELASTIC, i_up) > 0.)) { - elastic = - std::exp((1. - f) * - std::log(urr.prob_(i_energy, URRTableParam::ELASTIC, i_low)) + - f * std::log(urr.prob_(i_energy + 1, URRTableParam::ELASTIC, i_up))); + elastic = std::exp( + (1. - f) * + std::log(urr.prob_(i_energy, URRTableParam::ELASTIC, i_low)) + + f * std::log(urr.prob_(i_energy + 1, URRTableParam::ELASTIC, i_up))); } else { elastic = 0.; } @@ -858,10 +886,10 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const // Calculate the fission cross section/factor if ((urr.prob_(i_energy, URRTableParam::FISSION, i_low) > 0.) && (urr.prob_(i_energy + 1, URRTableParam::FISSION, i_up) > 0.)) { - fission = - std::exp((1. - f) * - std::log(urr.prob_(i_energy, URRTableParam::FISSION, i_low)) + - f * std::log(urr.prob_(i_energy + 1, URRTableParam::FISSION, i_up))); + fission = std::exp( + (1. - f) * + std::log(urr.prob_(i_energy, URRTableParam::FISSION, i_low)) + + f * std::log(urr.prob_(i_energy + 1, URRTableParam::FISSION, i_up))); } else { fission = 0.; } @@ -869,10 +897,10 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const // Calculate the capture cross section/factor if ((urr.prob_(i_energy, URRTableParam::N_GAMMA, i_low) > 0.) && (urr.prob_(i_energy + 1, URRTableParam::N_GAMMA, i_up) > 0.)) { - capture = - std::exp((1. - f) * - std::log(urr.prob_(i_energy, URRTableParam::N_GAMMA, i_low)) + - f * std::log(urr.prob_(i_energy + 1, URRTableParam::N_GAMMA, i_up))); + capture = std::exp( + (1. - f) * + std::log(urr.prob_(i_energy, URRTableParam::N_GAMMA, i_low)) + + f * std::log(urr.prob_(i_energy + 1, URRTableParam::N_GAMMA, i_up))); } else { capture = 0.; } @@ -889,7 +917,7 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const int xs_index = micro.index_grid - rx->xs_[i_temp].threshold; if (xs_index >= 0) { inelastic = (1. - f) * rx->xs_[i_temp].value[xs_index] + - f * rx->xs_[i_temp].value[xs_index + 1]; + f * rx->xs_[i_temp].value[xs_index + 1]; } } @@ -902,9 +930,15 @@ void Nuclide::calculate_urr_xs(int i_temp, Particle& p) const } // Check for negative values - if (elastic < 0.) {elastic = 0.;} - if (fission < 0.) {fission = 0.;} - if (capture < 0.) {capture = 0.;} + if (elastic < 0.) { + elastic = 0.; + } + if (fission < 0.) { + fission = 0.; + } + if (capture < 0.) { + capture = 0.; + } // Set elastic, absorption, fission, total, and capture x/s. Note that the // total x/s is calculated as a sum of partials instead of the table-provided @@ -933,22 +967,21 @@ std::pair Nuclide::find_temperature(double T) const double kT = K_BOLTZMANN * T; gsl::index n = kTs_.size(); switch (settings::temperature_method) { - case TemperatureMethod::NEAREST: - { - double max_diff = INFTY; - for (gsl::index t = 0; t < n; ++t) { - double diff = std::abs(kTs_[t] - kT); - if (diff < max_diff) { - i_temp = t; - max_diff = diff; - } + case TemperatureMethod::NEAREST: { + double max_diff = INFTY; + for (gsl::index t = 0; t < n; ++t) { + double diff = std::abs(kTs_[t] - kT); + if (diff < max_diff) { + i_temp = t; + max_diff = diff; } } - break; + } break; case TemperatureMethod::INTERPOLATION: // Find temperatures that bound the actual temperature - while (kTs_[i_temp + 1] < kT && i_temp + 1 < n - 1) ++i_temp; + while (kTs_[i_temp + 1] < kT && i_temp + 1 < n - 1) + ++i_temp; // Determine interpolation factor f = (kT - kTs_[i_temp]) / (kTs_[i_temp + 1] - kTs_[i_temp]); @@ -959,15 +992,16 @@ std::pair Nuclide::find_temperature(double T) const return {i_temp, f}; } -double Nuclide::collapse_rate(int MT, double temperature, gsl::span energy, - gsl::span flux) const +double Nuclide::collapse_rate(int MT, double temperature, + gsl::span energy, gsl::span flux) const { Expects(MT > 0); Expects(energy.size() > 0); Expects(energy.size() == flux.size() + 1); int i_rx = reaction_index_[MT]; - if (i_rx < 0) return 0.0; + if (i_rx < 0) + return 0.0; const auto& rx = reactions_[i_rx]; // Determine temperature index @@ -983,9 +1017,10 @@ double Nuclide::collapse_rate(int MT, double temperature, gsl::spancollapse_rate(i_temp + 1, energy, flux, grid_high); - return rr_low + f*(rr_high - rr_low); + return rr_low + f * (rr_high - rr_low); } else { - // If interpolation factor is zero, return reaction rate at lower temperature + // If interpolation factor is zero, return reaction rate at lower + // temperature return rr_low; } } @@ -1000,20 +1035,21 @@ void check_data_version(hid_t file_id) vector version; read_attribute(file_id, "version", version); if (version[0] != HDF5_VERSION[0]) { - fatal_error("HDF5 data format uses version " + std::to_string(version[0]) - + "." + std::to_string(version[1]) + " whereas your installation of " - "OpenMC expects version " + std::to_string(HDF5_VERSION[0]) - + ".x data."); + fatal_error("HDF5 data format uses version " + + std::to_string(version[0]) + "." + + std::to_string(version[1]) + + " whereas your installation of " + "OpenMC expects version " + + std::to_string(HDF5_VERSION[0]) + ".x data."); } } else { fatal_error("HDF5 data does not indicate a version. Your installation of " - "OpenMC expects version " + std::to_string(HDF5_VERSION[0]) + - ".x data."); + "OpenMC expects version " + + std::to_string(HDF5_VERSION[0]) + ".x data."); } } -extern "C" size_t -nuclides_size() +extern "C" size_t nuclides_size() { return data::nuclides.size(); } @@ -1029,7 +1065,8 @@ extern "C" int openmc_load_nuclide(const char* name, const double* temps, int n) LibraryKey key {Library::Type::neutron, name}; const auto& it = data::library_map.find(key); if (it == data::library_map.end()) { - set_errmsg("Nuclide '" + std::string{name} + "' is not present in library."); + set_errmsg( + "Nuclide '" + std::string {name} + "' is not present in library."); return OPENMC_E_DATA; } @@ -1052,7 +1089,8 @@ extern "C" int openmc_load_nuclide(const char* name, const double* temps, int n) // Read multipole file into the appropriate entry on the nuclides array int i_nuclide = data::nuclide_map.at(name); - if (settings::temperature_multipole) read_multipole_data(i_nuclide); + if (settings::temperature_multipole) + read_multipole_data(i_nuclide); // Read elemental data, if necessary if (settings::photon_transport) { @@ -1063,7 +1101,8 @@ extern "C" int openmc_load_nuclide(const char* name, const double* temps, int n) LibraryKey key {Library::Type::photon, element}; const auto& it = data::library_map.find(key); if (it == data::library_map.end()) { - set_errmsg("Element '" + std::string{element} + "' is not present in library."); + set_errmsg("Element '" + std::string {element} + + "' is not present in library."); return OPENMC_E_DATA; } @@ -1087,20 +1126,19 @@ extern "C" int openmc_load_nuclide(const char* name, const double* temps, int n) return 0; } -extern "C" int -openmc_get_nuclide_index(const char* name, int* index) +extern "C" int openmc_get_nuclide_index(const char* name, int* index) { auto it = data::nuclide_map.find(name); if (it == data::nuclide_map.end()) { - set_errmsg("No nuclide named '" + std::string{name} + "' has been loaded."); + set_errmsg( + "No nuclide named '" + std::string {name} + "' has been loaded."); return OPENMC_E_DATA; } *index = it->second; return 0; } -extern "C" int -openmc_nuclide_name(int index, const char** name) +extern "C" int openmc_nuclide_name(int index, const char** name) { if (index >= 0 && index < data::nuclides.size()) { *name = data::nuclides[index]->name_.data(); @@ -1111,9 +1149,9 @@ openmc_nuclide_name(int index, const char** name) } } -extern "C" int -openmc_nuclide_collapse_rate(int index, int MT, double temperature, - const double* energy, const double* flux, int n, double* xs) +extern "C" int openmc_nuclide_collapse_rate(int index, int MT, + double temperature, const double* energy, const double* flux, int n, + double* xs) { if (index < 0 || index >= data::nuclides.size()) { set_errmsg("Index in nuclides vector is out of bounds."); @@ -1121,8 +1159,8 @@ openmc_nuclide_collapse_rate(int index, int MT, double temperature, } try { - *xs = data::nuclides[index]->collapse_rate(MT, temperature, - {energy, energy + n + 1}, {flux, flux + n}); + *xs = data::nuclides[index]->collapse_rate( + MT, temperature, {energy, energy + n + 1}, {flux, flux + n}); } catch (const std::out_of_range& e) { fmt::print("Caught error\n"); set_errmsg(e.what()); diff --git a/src/output.cpp b/src/output.cpp index beac21ddd..73f3a0e9a 100644 --- a/src/output.cpp +++ b/src/output.cpp @@ -1,12 +1,12 @@ #include "openmc/output.h" -#include // for transform, max -#include // for strlen -#include // for time, localtime -#include // for setw, setprecision, put_time -#include // for fixed, scientific, left -#include +#include // for transform, max +#include // for strlen +#include // for time, localtime #include +#include // for setw, setprecision, put_time +#include // for fixed, scientific, left +#include #include #include #include // for pair @@ -46,38 +46,37 @@ namespace openmc { void title() { - fmt::print( - " %%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%\n" - " %%%%%%%%%%%%%%%%%%%%%%%%\n" - " ############### %%%%%%%%%%%%%%%%%%%%%%%%\n" - " ################## %%%%%%%%%%%%%%%%%%%%%%%\n" - " ################### %%%%%%%%%%%%%%%%%%%%%%%\n" - " #################### %%%%%%%%%%%%%%%%%%%%%%\n" - " ##################### %%%%%%%%%%%%%%%%%%%%%\n" - " ###################### %%%%%%%%%%%%%%%%%%%%\n" - " ####################### %%%%%%%%%%%%%%%%%%\n" - " ####################### %%%%%%%%%%%%%%%%%\n" - " ###################### %%%%%%%%%%%%%%%%%\n" - " #################### %%%%%%%%%%%%%%%%%\n" - " ################# %%%%%%%%%%%%%%%%%\n" - " ############### %%%%%%%%%%%%%%%%\n" - " ############ %%%%%%%%%%%%%%%\n" - " ######## %%%%%%%%%%%%%%\n" - " %%%%%%%%%%%\n\n"); + fmt::print(" %%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%\n" + " %%%%%%%%%%%%%%%%%%%%%%%%\n" + " ############### %%%%%%%%%%%%%%%%%%%%%%%%\n" + " ################## %%%%%%%%%%%%%%%%%%%%%%%\n" + " ################### %%%%%%%%%%%%%%%%%%%%%%%\n" + " #################### %%%%%%%%%%%%%%%%%%%%%%\n" + " ##################### %%%%%%%%%%%%%%%%%%%%%\n" + " ###################### %%%%%%%%%%%%%%%%%%%%\n" + " ####################### %%%%%%%%%%%%%%%%%%\n" + " ####################### %%%%%%%%%%%%%%%%%\n" + " ###################### %%%%%%%%%%%%%%%%%\n" + " #################### %%%%%%%%%%%%%%%%%\n" + " ################# %%%%%%%%%%%%%%%%%\n" + " ############### %%%%%%%%%%%%%%%%\n" + " ############ %%%%%%%%%%%%%%%\n" + " ######## %%%%%%%%%%%%%%\n" + " %%%%%%%%%%%\n\n"); // Write version information fmt::print( " | The OpenMC Monte Carlo Code\n" " Copyright | 2011-2021 MIT and OpenMC contributors\n" " License | https://docs.openmc.org/en/latest/license.html\n" - " Version | {}.{}.{}{}\n", VERSION_MAJOR, VERSION_MINOR, - VERSION_RELEASE, VERSION_DEV ? "-dev" : ""); + " Version | {}.{}.{}{}\n", + VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE, VERSION_DEV ? "-dev" : ""); #ifdef GIT_SHA1 fmt::print(" Git SHA1 | {}\n", GIT_SHA1); #endif @@ -99,12 +98,13 @@ void title() //============================================================================== -std::string -header(const char* msg) { +std::string header(const char* msg) +{ // Determine how many times to repeat the '=' character. int n_prefix = (63 - strlen(msg)) / 2; int n_suffix = n_prefix; - if ((strlen(msg) % 2) == 0) ++n_suffix; + if ((strlen(msg) % 2) == 0) + ++n_suffix; // Convert to uppercase. std::string upper(msg); @@ -113,17 +113,22 @@ header(const char* msg) { // Add ===> <=== markers. std::stringstream out; out << ' '; - for (int i = 0; i < n_prefix; i++) out << '='; + for (int i = 0; i < n_prefix; i++) + out << '='; out << "> " << upper << " <"; - for (int i = 0; i < n_suffix; i++) out << '='; + for (int i = 0; i < n_suffix; i++) + out << '='; return out.str(); } -std::string header(const std::string& msg) {return header(msg.c_str());} +std::string header(const std::string& msg) +{ + return header(msg.c_str()); +} -void -header(const char* msg, int level) { +void header(const char* msg, int level) +{ auto out = header(msg); // Print header based on verbosity level. @@ -136,7 +141,7 @@ header(const char* msg, int level) { std::string time_stamp() { std::stringstream ts; - std::time_t t = std::time(nullptr); // get time now + std::time_t t = std::time(nullptr); // get time now ts << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S"); return ts.str(); } @@ -209,7 +214,8 @@ void print_particle(Particle& p) void print_plot() { header("PLOTTING SUMMARY", 5); - if (settings::verbosity < 5) return; + if (settings::verbosity < 5) + return; for (auto pl : model::plots) { // Plot id @@ -227,13 +233,14 @@ void print_plot() } // Plot parameters - fmt::print("Origin: {} {} {}\n", pl.origin_[0], pl.origin_[1], pl.origin_[2]); + fmt::print( + "Origin: {} {} {}\n", pl.origin_[0], pl.origin_[1], pl.origin_[2]); if (PlotType::slice == pl.type_) { fmt::print("Width: {:4} {:4}\n", pl.width_[0], pl.width_[1]); } else if (PlotType::voxel == pl.type_) { - fmt::print("Width: {:4} {:4} {:4}\n", pl.width_[0], pl.width_[1], - pl.width_[2]); + fmt::print( + "Width: {:4} {:4} {:4}\n", pl.width_[0], pl.width_[1], pl.width_[2]); } if (PlotColorBy::cells == pl.color_by_) { @@ -243,7 +250,7 @@ void print_plot() } if (PlotType::slice == pl.type_) { - switch(pl.basis_) { + switch (pl.basis_) { case PlotBasis::xy: fmt::print("Basis: XY\n"); break; @@ -256,7 +263,8 @@ void print_plot() } fmt::print("Pixels: {} {}\n", pl.pixels_[0], pl.pixels_[1]); } else if (PlotType::voxel == pl.type_) { - fmt::print("Voxels: {} {} {}\n", pl.pixels_[0], pl.pixels_[1], pl.pixels_[2]); + fmt::print( + "Voxels: {} {} {}\n", pl.pixels_[0], pl.pixels_[1], pl.pixels_[2]); } fmt::print("\n"); @@ -265,10 +273,9 @@ void print_plot() //============================================================================== -void -print_overlap_check() +void print_overlap_check() { - #ifdef OPENMC_MPI +#ifdef OPENMC_MPI vector temp(model::overlap_check_count); MPI_Reduce(temp.data(), model::overlap_check_count.data(), model::overlap_check_count.size(), MPI_INT64_T, MPI_SUM, 0, mpi::intracomm); @@ -280,7 +287,8 @@ print_overlap_check() vector sparse_cell_ids; for (int i = 0; i < model::cells.size(); i++) { - fmt::print(" {:8} {:17}\n", model::cells[i]->id_, model::overlap_check_count[i]); + fmt::print( + " {:8} {:17}\n", model::cells[i]->id_, model::overlap_check_count[i]); if (model::overlap_check_count[i] < 10) { sparse_cell_ids.push_back(model::cells[i]->id_); } @@ -328,8 +336,8 @@ void print_version() fmt::print("Git SHA1: {}\n", GIT_SHA1); #endif fmt::print("Copyright (c) 2011-2021 Massachusetts Institute of " - "Technology and OpenMC contributors\nMIT/X license at " - "\n"); + "Technology and OpenMC contributors\nMIT/X license at " + "\n"); } } @@ -338,13 +346,11 @@ void print_version() void print_columns() { if (settings::entropy_on) { - fmt::print( - " Bat./Gen. k Entropy Average k \n" - " ========= ======== ======== ====================\n"); + fmt::print(" Bat./Gen. k Entropy Average k \n" + " ========= ======== ======== ====================\n"); } else { - fmt::print( - " Bat./Gen. k Average k\n" - " ========= ======== ====================\n"); + fmt::print(" Bat./Gen. k Average k\n" + " ========= ======== ====================\n"); } } @@ -354,12 +360,14 @@ void print_generation() { // Determine overall generation index and number of active generations int idx = overall_generation() - 1; - int n = simulation::current_batch > settings::n_inactive ? - settings::gen_per_batch*simulation::n_realizations + simulation::current_gen : 0; + int n = simulation::current_batch > settings::n_inactive + ? settings::gen_per_batch * simulation::n_realizations + + simulation::current_gen + : 0; // write out batch/generation and generation k-effective auto batch_and_gen = std::to_string(simulation::current_batch) + "/" + - std::to_string(simulation::current_gen); + std::to_string(simulation::current_gen); fmt::print(" {:>9} {:8.5f}", batch_and_gen, simulation::k_generation[idx]); // write out entropy info @@ -375,11 +383,11 @@ void print_generation() //============================================================================== -void show_time(const char* label, double secs, int indent_level=0) +void show_time(const char* label, double secs, int indent_level = 0) { - int width = 33 - indent_level*2; - fmt::print("{0:{1}} {2:<{3}} = {4:>10.4e} seconds\n", - "", 2*indent_level, label, width, secs); + int width = 33 - indent_level * 2; + fmt::print("{0:{1}} {2:<{3}} = {4:>10.4e} seconds\n", "", 2 * indent_level, + label, width, secs); } void show_rate(const char* label, double particles_per_sec) @@ -393,13 +401,14 @@ void print_runtime() // display header block header("Timing Statistics", 6); - if (settings::verbosity < 6) return; + if (settings::verbosity < 6) + return; // display time elapsed for various sections show_time("Total time for initialization", time_initialize.elapsed()); show_time("Reading cross sections", time_read_xs.elapsed(), 1); - show_time("Total time in simulation", time_inactive.elapsed() + - time_active.elapsed()); + show_time("Total time in simulation", + time_inactive.elapsed() + time_active.elapsed()); show_time("Time in transport only", time_transport.elapsed(), 1); if (settings::event_based) { show_time("Particle initialization", time_event_init.elapsed(), 2); @@ -429,28 +438,34 @@ void print_runtime() double speed_active; if (settings::restart_run) { if (simulation::restart_batch < settings::n_inactive) { - speed_inactive = (settings::n_particles * (settings::n_inactive - - simulation::restart_batch) * settings::gen_per_batch) - / time_inactive.elapsed(); - speed_active = (settings::n_particles * n_active - * settings::gen_per_batch) / time_active.elapsed(); + speed_inactive = (settings::n_particles * + (settings::n_inactive - simulation::restart_batch) * + settings::gen_per_batch) / + time_inactive.elapsed(); + speed_active = + (settings::n_particles * n_active * settings::gen_per_batch) / + time_active.elapsed(); } else { - speed_active = (settings::n_particles * (settings::n_batches - - simulation::restart_batch) * settings::gen_per_batch) - / time_active.elapsed(); + speed_active = (settings::n_particles * + (settings::n_batches - simulation::restart_batch) * + settings::gen_per_batch) / + time_active.elapsed(); } } else { if (settings::n_inactive > 0) { - speed_inactive = (settings::n_particles * settings::n_inactive - * settings::gen_per_batch) / time_inactive.elapsed(); + speed_inactive = (settings::n_particles * settings::n_inactive * + settings::gen_per_batch) / + time_inactive.elapsed(); } - speed_active = (settings::n_particles * n_active * settings::gen_per_batch) - / time_active.elapsed(); + speed_active = + (settings::n_particles * n_active * settings::gen_per_batch) / + time_active.elapsed(); } // display calculation rate - if (!(settings::restart_run && (simulation::restart_batch >= settings::n_inactive)) - && settings::n_inactive > 0) { + if (!(settings::restart_run && + (simulation::restart_batch >= settings::n_inactive)) && + settings::n_inactive > 0) { show_rate("Calculation Rate (inactive)", speed_inactive); } show_rate("Calculation Rate (active)", speed_active); @@ -458,12 +473,14 @@ void print_runtime() //============================================================================== -std::pair -mean_stdev(const double* x, int n) +std::pair mean_stdev(const double* x, int n) { double mean = x[static_cast(TallyResult::SUM)] / n; - double stdev = n > 1 ? std::sqrt(std::max(0.0, ( - x[static_cast(TallyResult::SUM_SQ)]/n - mean*mean)/(n - 1))) : 0.0; + double stdev = + n > 1 ? std::sqrt(std::max(0.0, + (x[static_cast(TallyResult::SUM_SQ)] / n - mean * mean) / + (n - 1))) + : 0.0; return {mean, stdev}; } @@ -473,15 +490,16 @@ void print_results() { // display header block for results header("Results", 4); - if (settings::verbosity < 4) return; + if (settings::verbosity < 4) + return; // Calculate t-value for confidence intervals int n = simulation::n_realizations; double alpha, t_n1, t_n3; if (settings::confidence_intervals) { alpha = 1.0 - CONFIDENCE_LEVEL; - t_n1 = t_percentile(1.0 - alpha/2.0, n - 1); - t_n3 = t_percentile(1.0 - alpha/2.0, n - 3); + t_n1 = t_percentile(1.0 - alpha / 2.0, n - 1); + t_n3 = t_percentile(1.0 - alpha / 2.0, n - 3); } else { t_n1 = 1.0; t_n3 = 1.0; @@ -493,14 +511,14 @@ void print_results() if (n > 1) { if (settings::run_mode == RunMode::EIGENVALUE) { std::tie(mean, stdev) = mean_stdev(>(GlobalTally::K_COLLISION, 0), n); - fmt::print(" k-effective (Collision) = {:.5f} +/- {:.5f}\n", - mean, t_n1 * stdev); + fmt::print(" k-effective (Collision) = {:.5f} +/- {:.5f}\n", mean, + t_n1 * stdev); std::tie(mean, stdev) = mean_stdev(>(GlobalTally::K_TRACKLENGTH, 0), n); - fmt::print(" k-effective (Track-length) = {:.5f} +/- {:.5f}\n", - mean, t_n1 * stdev); + fmt::print(" k-effective (Track-length) = {:.5f} +/- {:.5f}\n", mean, + t_n1 * stdev); std::tie(mean, stdev) = mean_stdev(>(GlobalTally::K_ABSORPTION, 0), n); - fmt::print(" k-effective (Absorption) = {:.5f} +/- {:.5f}\n", - mean, t_n1 * stdev); + fmt::print(" k-effective (Absorption) = {:.5f} +/- {:.5f}\n", mean, + t_n1 * stdev); if (n > 3) { double k_combined[2]; openmc_get_keff(k_combined); @@ -509,11 +527,12 @@ void print_results() } } std::tie(mean, stdev) = mean_stdev(>(GlobalTally::LEAKAGE, 0), n); - fmt::print(" Leakage Fraction = {:.5f} +/- {:.5f}\n", - mean, t_n1 * stdev); + fmt::print( + " Leakage Fraction = {:.5f} +/- {:.5f}\n", mean, t_n1 * stdev); } else { - if (mpi::master) warning("Could not compute uncertainties -- only one " - "active batch simulated!"); + if (mpi::master) + warning("Could not compute uncertainties -- only one " + "active batch simulated!"); if (settings::run_mode == RunMode::EIGENVALUE) { fmt::print(" k-effective (Collision) = {:.5f}\n", @@ -532,30 +551,30 @@ void print_results() //============================================================================== const std::unordered_map score_names = { - {SCORE_FLUX, "Flux"}, - {SCORE_TOTAL, "Total Reaction Rate"}, - {SCORE_SCATTER, "Scattering Rate"}, - {SCORE_NU_SCATTER, "Scattering Production Rate"}, - {SCORE_ABSORPTION, "Absorption Rate"}, - {SCORE_FISSION, "Fission Rate"}, - {SCORE_NU_FISSION, "Nu-Fission Rate"}, - {SCORE_KAPPA_FISSION, "Kappa-Fission Rate"}, - {SCORE_EVENTS, "Events"}, - {SCORE_DECAY_RATE, "Decay Rate"}, + {SCORE_FLUX, "Flux"}, + {SCORE_TOTAL, "Total Reaction Rate"}, + {SCORE_SCATTER, "Scattering Rate"}, + {SCORE_NU_SCATTER, "Scattering Production Rate"}, + {SCORE_ABSORPTION, "Absorption Rate"}, + {SCORE_FISSION, "Fission Rate"}, + {SCORE_NU_FISSION, "Nu-Fission Rate"}, + {SCORE_KAPPA_FISSION, "Kappa-Fission Rate"}, + {SCORE_EVENTS, "Events"}, + {SCORE_DECAY_RATE, "Decay Rate"}, {SCORE_DELAYED_NU_FISSION, "Delayed-Nu-Fission Rate"}, - {SCORE_PROMPT_NU_FISSION, "Prompt-Nu-Fission Rate"}, - {SCORE_INVERSE_VELOCITY, "Flux-Weighted Inverse Velocity"}, - {SCORE_FISS_Q_PROMPT, "Prompt fission power"}, - {SCORE_FISS_Q_RECOV, "Recoverable fission power"}, - {SCORE_CURRENT, "Current"}, + {SCORE_PROMPT_NU_FISSION, "Prompt-Nu-Fission Rate"}, + {SCORE_INVERSE_VELOCITY, "Flux-Weighted Inverse Velocity"}, + {SCORE_FISS_Q_PROMPT, "Prompt fission power"}, + {SCORE_FISS_Q_RECOV, "Recoverable fission power"}, + {SCORE_CURRENT, "Current"}, }; //! Create an ASCII output file showing all tally results. -void -write_tallies() +void write_tallies() { - if (model::tallies.empty()) return; + if (model::tallies.empty()) + return; // Open the tallies.out file. std::ofstream tallies_out; @@ -567,7 +586,8 @@ write_tallies() // Write header block. std::string tally_header("TALLY " + std::to_string(tally.id_)); - if (!tally.name_.empty()) tally_header += ": " + tally.name_; + if (!tally.name_.empty()) + tally_header += ": " + tally.name_; fmt::print(tallies_out, "{}\n\n", header(tally_header)); if (!tally.writable_) { @@ -579,7 +599,7 @@ write_tallies() double t_value = 1; if (settings::confidence_intervals) { auto alpha = 1 - CONFIDENCE_LEVEL; - t_value = t_percentile(1 - alpha*0.5, tally.n_realizations_ - 1); + t_value = t_percentile(1 - alpha * 0.5, tally.n_realizations_ - 1); } // Write derivative information. @@ -591,7 +611,8 @@ write_tallies() deriv.diff_material); break; case DerivativeVariable::NUCLIDE_DENSITY: - fmt::print(tallies_out, " Nuclide density derivative Material {} Nuclide {}\n", + fmt::print(tallies_out, + " Nuclide density derivative Material {} Nuclide {}\n", deriv.diff_material, data::nuclides[deriv.diff_nuclide]->name_); break; case DerivativeVariable::TEMPERATURE: @@ -600,7 +621,8 @@ write_tallies() break; default: fatal_error(fmt::format("Differential tally dependent variable for " - "tally {} not defined in output.cpp", tally.id_)); + "tally {} not defined in output.cpp", + tally.id_)); } } @@ -648,13 +670,14 @@ write_tallies() // Write the score, mean, and uncertainty. indent += 2; for (auto score : tally.scores_) { - std::string score_name = score > 0 ? reaction_name(score) - : score_names.at(score); + std::string score_name = + score > 0 ? reaction_name(score) : score_names.at(score); double mean, stdev; - std::tie(mean, stdev) = mean_stdev( - &tally.results_(filter_index, score_index, 0), tally.n_realizations_); - fmt::print(tallies_out, "{0:{1}}{2:<36} {3:.6} +/- {4:.6}\n", - "", indent + 1, score_name, mean, t_value * stdev); + std::tie(mean, stdev) = + mean_stdev(&tally.results_(filter_index, score_index, 0), + tally.n_realizations_); + fmt::print(tallies_out, "{0:{1}}{2:<36} {3:.6} +/- {4:.6}\n", "", + indent + 1, score_name, mean, t_value * stdev); score_index += 1; } indent -= 2; diff --git a/src/particle.cpp b/src/particle.cpp index ef5c3199a..7579f5f5a 100644 --- a/src/particle.cpp +++ b/src/particle.cpp @@ -22,9 +22,9 @@ #include "openmc/physics_mg.h" #include "openmc/random_lcg.h" #include "openmc/settings.h" +#include "openmc/simulation.h" #include "openmc/source.h" #include "openmc/surface.h" -#include "openmc/simulation.h" #include "openmc/tallies/derivative.h" #include "openmc/tallies/tally.h" #include "openmc/tallies/tally_scoring.h" @@ -83,8 +83,7 @@ void Particle::from_source(const SourceSite* src) E_last() = E(); } -void -Particle::event_calculate_xs() +void Particle::event_calculate_xs() { // Set the random number stream stream() = STREAM_TRACKING; @@ -119,7 +118,8 @@ Particle::event_calculate_xs() if (write_track()) write_particle_track(*this); - if (settings::check_overlaps) check_cell_overlap(*this); + if (settings::check_overlaps) + check_cell_overlap(*this); // Calculate microscopic and macroscopic cross sections if (material() != MATERIAL_VOID) { @@ -147,8 +147,7 @@ Particle::event_calculate_xs() } } -void -Particle::event_advance() +void Particle::event_advance() { // Find the distance to the nearest boundary boundary() = distance_to_boundary(*this); @@ -187,8 +186,7 @@ Particle::event_advance() } } -void -Particle::event_cross_surface() +void Particle::event_cross_surface() { // Set surface that particle is on and adjust coordinate levels surface() = boundary().surface_index; @@ -217,8 +215,7 @@ Particle::event_cross_surface() } } -void -Particle::event_collide() +void Particle::event_collide() { // Score collision estimate of keff if (settings::run_mode == RunMode::EIGENVALUE && @@ -245,7 +242,8 @@ Particle::event_collide() // Score collision estimator tallies -- this is done after a collision // has occurred rather than before because we need information on the // outgoing energy for any tallies with an outgoing energy filter - if (!model::active_collision_tallies.empty()) score_collision_tally(*this); + if (!model::active_collision_tallies.empty()) + score_collision_tally(*this); if (!model::active_analog_tallies.empty()) { if (settings::run_CE) { score_analog_tally_ce(*this); @@ -285,15 +283,15 @@ Particle::event_collide() } // Score flux derivative accumulators for differential tallies. - if (!model::active_tallies.empty()) score_collision_derivative(*this); + if (!model::active_tallies.empty()) + score_collision_derivative(*this); - #ifdef DAGMC +#ifdef DAGMC history().reset(); - #endif +#endif } -void -Particle::event_revive_from_secondary() +void Particle::event_revive_from_secondary() { // If particle has too many events, display warning and kill it ++n_event(); @@ -319,12 +317,11 @@ Particle::event_revive_from_secondary() } } -void -Particle::event_death() +void Particle::event_death() { - #ifdef DAGMC +#ifdef DAGMC history().reset(); - #endif +#endif // Finish particle track output. if (write_track()) { @@ -332,8 +329,8 @@ Particle::event_death() finalize_particle_track(*this); } - // Contribute tally reduction variables to global accumulator - #pragma omp atomic +// Contribute tally reduction variables to global accumulator +#pragma omp atomic global_tally_absorption += keff_tally_absorption(); #pragma omp atomic global_tally_collision += keff_tally_collision(); @@ -356,9 +353,7 @@ Particle::event_death() } } - -void -Particle::cross_surface() +void Particle::cross_surface() { int i_surface = std::abs(surface()); // TODO: off-by-one @@ -381,10 +376,11 @@ Particle::cross_surface() int64_t idx = simulation::surf_source_bank.thread_safe_append(site); } - // if we're crossing a CSG surface, make sure the DAG history is reset - #ifdef DAGMC - if (surf->geom_type_ == GeometryType::CSG) history().reset(); - #endif +// if we're crossing a CSG surface, make sure the DAG history is reset +#ifdef DAGMC + if (surf->geom_type_ == GeometryType::CSG) + history().reset(); +#endif // Handle any applicable boundary conditions. if (surf->bc_ && settings::run_mode != RunMode::PLOTTING) { @@ -399,8 +395,10 @@ Particle::cross_surface() // in DAGMC, we know what the next cell should be if (surf->geom_type_ == GeometryType::DAG) { auto surfp = dynamic_cast(surf); - auto cellp = dynamic_cast(model::cells[cell_last(n_coord() - 1)].get()); - auto univp = static_cast(model::universes[coord(n_coord() - 1).universe].get()); + auto cellp = + dynamic_cast(model::cells[cell_last(n_coord() - 1)].get()); + auto univp = static_cast( + model::universes[coord(n_coord() - 1).universe].get()); // determine the next cell for this crossing int32_t i_cell = next_cell(univp, cellp, surfp) - 1; // save material and temp @@ -447,8 +445,7 @@ Particle::cross_surface() } } -void -Particle::cross_vacuum_bc(const Surface& surf) +void Particle::cross_vacuum_bc(const Surface& surf) { // Kill the particle alive() = false; @@ -474,8 +471,7 @@ Particle::cross_vacuum_bc(const Surface& surf) } } -void -Particle::cross_reflective_bc(const Surface& surf, Direction new_u) +void Particle::cross_reflective_bc(const Surface& surf, Direction new_u) { // Do not handle reflective boundary conditions on lower universes if (n_coord() != 1) { @@ -515,8 +511,8 @@ Particle::cross_reflective_bc(const Surface& surf, Direction new_u) // (unless we're using a dagmc model, which has exactly one universe) n_coord() = 1; if (surf.geom_type_ != GeometryType::DAG && !neighbor_list_find_cell(*this)) { - this->mark_as_lost("Couldn't find particle after reflecting from surface " - + std::to_string(surf.id_) + "."); + this->mark_as_lost("Couldn't find particle after reflecting from surface " + + std::to_string(surf.id_) + "."); return; } @@ -529,9 +525,8 @@ Particle::cross_reflective_bc(const Surface& surf, Direction new_u) } } -void -Particle::cross_periodic_bc(const Surface& surf, Position new_r, - Direction new_u, int new_surface) +void Particle::cross_periodic_bc( + const Surface& surf, Position new_r, Direction new_u, int new_surface) { // Do not handle periodic boundary conditions on lower universes if (n_coord() != 1) { @@ -580,8 +575,7 @@ Particle::cross_periodic_bc(const Surface& surf, Position new_r, } } -void -Particle::mark_as_lost(const char* message) +void Particle::mark_as_lost(const char* message) { // Print warning and write lost particle file warning(message); @@ -594,27 +588,27 @@ Particle::mark_as_lost(const char* message) // Count the total number of simulated particles (on this processor) auto n = simulation::current_batch * settings::gen_per_batch * - simulation::work_per_rank; + simulation::work_per_rank; // Abort the simulation if the maximum number of lost particles has been // reached if (simulation::n_lost_particles >= settings::max_lost_particles && - simulation::n_lost_particles >= settings::rel_max_lost_particles*n) { + simulation::n_lost_particles >= settings::rel_max_lost_particles * n) { fatal_error("Maximum number of lost particles has been reached."); } } -void -Particle::write_restart() const +void Particle::write_restart() const { // Dont write another restart file if in particle restart mode - if (settings::run_mode == RunMode::PARTICLE) return; + if (settings::run_mode == RunMode::PARTICLE) + return; // Set up file name auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output, simulation::current_batch, id()); -#pragma omp critical (WriteParticleRestart) +#pragma omp critical(WriteParticleRestart) { // Create file hid_t file_id = file_open(filename, 'w'); @@ -633,32 +627,33 @@ Particle::write_restart() const write_dataset(file_id, "current_generation", simulation::current_gen); write_dataset(file_id, "n_particles", settings::n_particles); switch (settings::run_mode) { - case RunMode::FIXED_SOURCE: - write_dataset(file_id, "run_mode", "fixed source"); - break; - case RunMode::EIGENVALUE: - write_dataset(file_id, "run_mode", "eigenvalue"); - break; - case RunMode::PARTICLE: - write_dataset(file_id, "run_mode", "particle restart"); - break; - default: - break; + case RunMode::FIXED_SOURCE: + write_dataset(file_id, "run_mode", "fixed source"); + break; + case RunMode::EIGENVALUE: + write_dataset(file_id, "run_mode", "eigenvalue"); + break; + case RunMode::PARTICLE: + write_dataset(file_id, "run_mode", "particle restart"); + break; + default: + break; } write_dataset(file_id, "id", id()); write_dataset(file_id, "type", static_cast(type())); int64_t i = current_work(); if (settings::run_mode == RunMode::EIGENVALUE) { - //take source data from primary bank for eigenvalue simulation - write_dataset(file_id, "weight", simulation::source_bank[i-1].wgt); - write_dataset(file_id, "energy", simulation::source_bank[i-1].E); - write_dataset(file_id, "xyz", simulation::source_bank[i-1].r); - write_dataset(file_id, "uvw", simulation::source_bank[i-1].u); + // take source data from primary bank for eigenvalue simulation + write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt); + write_dataset(file_id, "energy", simulation::source_bank[i - 1].E); + write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r); + write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u); } else if (settings::run_mode == RunMode::FIXED_SOURCE) { // re-sample using rng random number seed used to generate source particle - int64_t id = (simulation::total_gen + overall_generation() - 1)*settings::n_particles + - simulation::work_index[mpi::rank] + i; + int64_t id = (simulation::total_gen + overall_generation() - 1) * + settings::n_particles + + simulation::work_index[mpi::rank] + i; uint64_t seed = init_seed(id, STREAM_SOURCE); // re-sample source site auto site = sample_external_source(&seed); @@ -699,7 +694,7 @@ ParticleType str_to_particle_type(std::string str) } else if (str == "positron") { return ParticleType::positron; } else { - throw std::invalid_argument{fmt::format("Invalid particle name: {}", str)}; + throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)}; } } diff --git a/src/particle_restart.cpp b/src/particle_restart.cpp index 7150bc6da..e0295ceb5 100644 --- a/src/particle_restart.cpp +++ b/src/particle_restart.cpp @@ -24,7 +24,8 @@ namespace openmc { void read_particle_restart(Particle& p, RunMode& previous_run_mode) { // Write meessage - write_message(5, "Loading particle restart file {}", settings::path_particle_restart); + write_message( + 5, "Loading particle restart file {}", settings::path_particle_restart); // Open file hid_t file_id = file_open(settings::path_particle_restart, 'r'); @@ -102,7 +103,8 @@ void run_particle_restart() particle_seed = p.id(); break; default: - throw std::runtime_error{"Unexpected run mode: " + + throw std::runtime_error { + "Unexpected run mode: " + std::to_string(static_cast(previous_run_mode))}; } init_particle_seeds(particle_seed, p.seeds()); diff --git a/src/photon.cpp b/src/photon.cpp index 1e9a2557a..24d76140d 100644 --- a/src/photon.cpp +++ b/src/photon.cpp @@ -58,18 +58,18 @@ PhotonInteraction::PhotonInteraction(hid_t group) read_dataset(rgroup, "xs", coherent_); hid_t dset = open_dataset(rgroup, "integrated_scattering_factor"); - coherent_int_form_factor_ = Tabulated1D{dset}; + coherent_int_form_factor_ = Tabulated1D {dset}; close_dataset(dset); if (object_exists(group, "anomalous_real")) { dset = open_dataset(rgroup, "anomalous_real"); - coherent_anomalous_real_ = Tabulated1D{dset}; + coherent_anomalous_real_ = Tabulated1D {dset}; close_dataset(dset); } if (object_exists(group, "anomalous_imag")) { dset = open_dataset(rgroup, "anomalous_imag"); - coherent_anomalous_imag_ = Tabulated1D{dset}; + coherent_anomalous_imag_ = Tabulated1D {dset}; close_dataset(dset); } close_group(rgroup); @@ -78,7 +78,7 @@ PhotonInteraction::PhotonInteraction(hid_t group) rgroup = open_group(group, "incoherent"); read_dataset(rgroup, "xs", incoherent_); dset = open_dataset(rgroup, "scattering_factor"); - incoherent_form_factor_ = Tabulated1D{dset}; + incoherent_form_factor_ = Tabulated1D {dset}; close_dataset(dset); close_group(rgroup); @@ -116,8 +116,8 @@ PhotonInteraction::PhotonInteraction(hid_t group) read_attribute(rgroup, "designators", designators); auto n_shell = designators.size(); if (n_shell == 0) { - throw std::runtime_error{"Photoatomic data for " + name_ + - " does not have subshell data."}; + throw std::runtime_error { + "Photoatomic data for " + name_ + " does not have subshell data."}; } for (int i = 0; i < n_shell; ++i) { @@ -167,7 +167,8 @@ PhotonInteraction::PhotonInteraction(hid_t group) xt::xtensor matrix; read_dataset(tgroup, "transitions", matrix); - shell.transition_subshells = xt::view(matrix, xt::all(), xt::range(0, 2)); + shell.transition_subshells = + xt::view(matrix, xt::all(), xt::range(0, 2)); shell.transition_energy = xt::view(matrix, xt::all(), 2); shell.transition_probability = xt::view(matrix, xt::all(), 3); shell.transition_probability /= xt::sum(shell.transition_probability)(); @@ -201,11 +202,12 @@ PhotonInteraction::PhotonInteraction(hid_t group) profile_cdf_ = xt::empty({n_shell, n_profile}); for (int i = 0; i < n_shell; ++i) { double c = 0.0; - profile_cdf_(i,0) = 0.0; + profile_cdf_(i, 0) = 0.0; for (int j = 0; j < n_profile - 1; ++j) { - c += 0.5*(data::compton_profile_pz(j+1) - data::compton_profile_pz(j)) * - (profile_pdf_(i,j) + profile_pdf_(i,j+1)); - profile_cdf_(i,j+1) = c; + c += 0.5 * + (data::compton_profile_pz(j + 1) - data::compton_profile_pz(j)) * + (profile_pdf_(i, j) + profile_pdf_(i, j + 1)); + profile_cdf_(i, j + 1) = c; } } @@ -237,18 +239,19 @@ PhotonInteraction::PhotonInteraction(hid_t group) const auto& E {electron_energy}; double cutoff = settings::energy_cutoff[photon]; if (cutoff > E(0)) { - size_t i_grid = lower_bound_index(E.cbegin(), E.cend(), - settings::energy_cutoff[photon]); + size_t i_grid = lower_bound_index( + E.cbegin(), E.cend(), settings::energy_cutoff[photon]); // calculate interpolation factor double f = (std::log(cutoff) - std::log(E(i_grid))) / - (std::log(E(i_grid+1)) - std::log(E(i_grid))); + (std::log(E(i_grid + 1)) - std::log(E(i_grid))); // Interpolate bremsstrahlung DCS at the cutoff energy and truncate xt::xtensor dcs({n_e - i_grid, n_k}); for (int i = 0; i < n_k; ++i) { - double y = std::exp(std::log(dcs_(i_grid,i)) + - f*(std::log(dcs_(i_grid+1,i)) - std::log(dcs_(i_grid,i)))); + double y = std::exp( + std::log(dcs_(i_grid, i)) + + f * (std::log(dcs_(i_grid + 1, i)) - std::log(dcs_(i_grid, i)))); auto col_i = xt::view(dcs, xt::all(), i); col_i(0) = y; for (int j = i_grid + 1; j < n_e; ++j) { @@ -259,7 +262,7 @@ PhotonInteraction::PhotonInteraction(hid_t group) xt::xtensor frst {cutoff}; electron_energy = xt::concatenate(xt::xtuple( - frst, xt::view(electron_energy, xt::range(i_grid+1, n_e)))); + frst, xt::view(electron_energy, xt::range(i_grid + 1, n_e)))); } // Set incident particle energy grid @@ -273,15 +276,15 @@ PhotonInteraction::PhotonInteraction(hid_t group) // Integrate over reduced photon energy double c = 0.0; for (int j = 0; j < data::ttb_k_grid.size() - 1; ++j) { - c += 0.5 * (dcs_(i, j+1) + dcs_(i, j)) * (data::ttb_k_grid(j+1) - - data::ttb_k_grid(j)); + c += 0.5 * (dcs_(i, j + 1) + dcs_(i, j)) * + (data::ttb_k_grid(j + 1) - data::ttb_k_grid(j)); } double e = data::ttb_e_grid(i); // Square of the ratio of the speed of light to the velocity of the // charged particle - double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) / ((e + - MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV)); + double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) / + ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV)); stopping_power_radiative_(i) = Z_ * Z_ / beta_sq * e * c; } @@ -292,10 +295,10 @@ PhotonInteraction::PhotonInteraction(hid_t group) energy_ = xt::log(energy_); coherent_ = xt::where(coherent_ > 0.0, xt::log(coherent_), -500.0); incoherent_ = xt::where(incoherent_ > 0.0, xt::log(incoherent_), -500.0); - photoelectric_total_ = xt::where(photoelectric_total_ > 0.0, - xt::log(photoelectric_total_), -500.0); - pair_production_total_ = xt::where(pair_production_total_ > 0.0, - xt::log(pair_production_total_), -500.0); + photoelectric_total_ = xt::where( + photoelectric_total_ > 0.0, xt::log(photoelectric_total_), -500.0); + pair_production_total_ = xt::where( + pair_production_total_ > 0.0, xt::log(pair_production_total_), -500.0); heating_ = xt::where(heating_ > 0.0, xt::log(heating_), -500.0); } @@ -315,12 +318,14 @@ void PhotonInteraction::compton_scatter(double alpha, bool doppler, // Note that the parameter used here does not correspond exactly to the // momentum transfer q in ENDF-102 Eq. (27.2). Rather, this is the // parameter as defined by Hubbell, where the actual data comes from - double x = MASS_ELECTRON_EV/PLANCK_C*alpha*std::sqrt(0.5*(1.0 - *mu)); + double x = + MASS_ELECTRON_EV / PLANCK_C * alpha * std::sqrt(0.5 * (1.0 - *mu)); // Calculate S(x, Z) and S(x_max, Z) double form_factor_x = incoherent_form_factor_(x); if (form_factor_xmax == 0.0) { - form_factor_xmax = incoherent_form_factor_(MASS_ELECTRON_EV/PLANCK_C*alpha); + form_factor_xmax = + incoherent_form_factor_(MASS_ELECTRON_EV / PLANCK_C * alpha); } // Perform rejection on form factor @@ -328,7 +333,7 @@ void PhotonInteraction::compton_scatter(double alpha, bool doppler, if (doppler) { double E_out; this->compton_doppler(alpha, *mu, &E_out, i_shell, seed); - *alpha_out = E_out/MASS_ELECTRON_EV; + *alpha_out = E_out / MASS_ELECTRON_EV; } else { *i_shell = -1; } @@ -337,8 +342,8 @@ void PhotonInteraction::compton_scatter(double alpha, bool doppler, } } -void PhotonInteraction::compton_doppler(double alpha, double mu, - double* E_out, int* i_shell, uint64_t* seed) const +void PhotonInteraction::compton_doppler( + double alpha, double mu, double* E_out, int* i_shell, uint64_t* seed) const { auto n = data::compton_profile_pz.size(); @@ -349,23 +354,24 @@ void PhotonInteraction::compton_doppler(double alpha, double mu, double c = 0.0; for (shell = 0; shell < electron_pdf_.size(); ++shell) { c += electron_pdf_(shell); - if (rn < c) break; + if (rn < c) + break; } // Determine binding energy of shell double E_b = binding_energy_(shell); // Determine p_z,max - double E = alpha*MASS_ELECTRON_EV; + double E = alpha * MASS_ELECTRON_EV; if (E < E_b) { - *E_out = alpha/(1 + alpha*(1 - mu))*MASS_ELECTRON_EV; + *E_out = alpha / (1 + alpha * (1 - mu)) * MASS_ELECTRON_EV; break; } - double pz_max = -FINE_STRUCTURE*(E_b - (E - E_b)*alpha*(1.0 - mu)) / - std::sqrt(2.0*E*(E - E_b)*(1.0 - mu) + E_b*E_b); + double pz_max = -FINE_STRUCTURE * (E_b - (E - E_b) * alpha * (1.0 - mu)) / + std::sqrt(2.0 * E * (E - E_b) * (1.0 - mu) + E_b * E_b); if (pz_max < 0.0) { - *E_out = alpha/(1 + alpha*(1 - mu))*MASS_ELECTRON_EV; + *E_out = alpha / (1 + alpha * (1 - mu)) * MASS_ELECTRON_EV; break; } @@ -384,15 +390,16 @@ void PhotonInteraction::compton_doppler(double alpha, double mu, if (pz_l == pz_r) { c_max = c_l; } else if (p_l == p_r) { - c_max = c_l + (pz_max - pz_l)*p_l; + c_max = c_l + (pz_max - pz_l) * p_l; } else { - double m = (p_l - p_r)/(pz_l - pz_r); - c_max = c_l + (std::pow((m*(pz_max - pz_l) + p_l), 2) - p_l*p_l)/(2.0*m); + double m = (p_l - p_r) / (pz_l - pz_r); + c_max = c_l + (std::pow((m * (pz_max - pz_l) + p_l), 2) - p_l * p_l) / + (2.0 * m); } } // Sample value on bounded cdf - c = prn(seed)*c_max; + c = prn(seed) * c_max; // Determine pz corresponding to sampled cdf value auto cdf_shell = xt::view(profile_cdf_, shell, xt::all()); @@ -406,28 +413,28 @@ void PhotonInteraction::compton_doppler(double alpha, double mu, if (pz_l == pz_r) { pz = pz_l; } else if (p_l == p_r) { - pz = pz_l + (c - c_l)/p_l; + pz = pz_l + (c - c_l) / p_l; } else { - double m = (p_l - p_r)/(pz_l - pz_r); - pz = pz_l + (std::sqrt(p_l*p_l + 2.0*m*(c - c_l)) - p_l)/m; + double m = (p_l - p_r) / (pz_l - pz_r); + pz = pz_l + (std::sqrt(p_l * p_l + 2.0 * m * (c - c_l)) - p_l) / m; } // Determine outgoing photon energy corresponding to electron momentum // (solve Eq. 39 in LA-UR-04-0487 for E') - double momentum_sq = std::pow((pz/FINE_STRUCTURE), 2); - double f = 1.0 + alpha*(1.0 - mu); - double a = momentum_sq - f*f; - double b = 2.0*E*(f - momentum_sq*mu); - c = E*E*(momentum_sq - 1.0); + double momentum_sq = std::pow((pz / FINE_STRUCTURE), 2); + double f = 1.0 + alpha * (1.0 - mu); + double a = momentum_sq - f * f; + double b = 2.0 * E * (f - momentum_sq * mu); + c = E * E * (momentum_sq - 1.0); - double quad = b*b - 4.0*a*c; + double quad = b * b - 4.0 * a * c; if (quad < 0) { - *E_out = alpha/(1 + alpha*(1 - mu))*MASS_ELECTRON_EV; + *E_out = alpha / (1 + alpha * (1 - mu)) * MASS_ELECTRON_EV; break; } quad = std::sqrt(quad); - double E_out1 = -(b + quad)/(2.0*a); - double E_out2 = -(b - quad)/(2.0*a); + double E_out1 = -(b + quad) / (2.0 * a); + double E_out2 = -(b - quad) / (2.0 * a); // Determine solution to quadratic equation that is positive if (E_out1 > 0.0) { @@ -445,7 +452,8 @@ void PhotonInteraction::compton_doppler(double alpha, double mu, continue; } } - if (*E_out < E - E_b) break; + if (*E_out < E - E_b) + break; } *i_shell = shell; @@ -469,45 +477,48 @@ void PhotonInteraction::calculate_xs(Particle& p) const } // check for case where two energy points are the same - if (energy_(i_grid) == energy_(i_grid+1)) ++i_grid; + if (energy_(i_grid) == energy_(i_grid + 1)) + ++i_grid; // calculate interpolation factor - double f = (log_E - energy_(i_grid)) / (energy_(i_grid+1) - energy_(i_grid)); + double f = + (log_E - energy_(i_grid)) / (energy_(i_grid + 1) - energy_(i_grid)); auto& xs {p.photon_xs(index_)}; xs.index_grid = i_grid; xs.interp_factor = f; // Calculate microscopic coherent cross section - xs.coherent = std::exp(coherent_(i_grid) + - f*(coherent_(i_grid+1) - coherent_(i_grid))); + xs.coherent = std::exp( + coherent_(i_grid) + f * (coherent_(i_grid + 1) - coherent_(i_grid))); // Calculate microscopic incoherent cross section - xs.incoherent = std::exp(incoherent_(i_grid) + - f*(incoherent_(i_grid+1) - incoherent_(i_grid))); + xs.incoherent = std::exp( + incoherent_(i_grid) + f * (incoherent_(i_grid + 1) - incoherent_(i_grid))); // Calculate microscopic photoelectric cross section xs.photoelectric = 0.0; for (const auto& shell : shells_) { // Check threshold of reaction int i_start = shell.threshold; - if (i_grid < i_start) continue; + if (i_grid < i_start) + continue; // Evaluation subshell photoionization cross section xs.photoelectric += - std::exp(shell.cross_section(i_grid-i_start) + - f*(shell.cross_section(i_grid+1-i_start) - - shell.cross_section(i_grid-i_start))); + std::exp(shell.cross_section(i_grid - i_start) + + f * (shell.cross_section(i_grid + 1 - i_start) - + shell.cross_section(i_grid - i_start))); } // Calculate microscopic pair production cross section xs.pair_production = std::exp( - pair_production_total_(i_grid) + f*( - pair_production_total_(i_grid+1) - - pair_production_total_(i_grid))); + pair_production_total_(i_grid) + + f * (pair_production_total_(i_grid + 1) - pair_production_total_(i_grid))); // Calculate microscopic total cross section - xs.total = xs.coherent + xs.incoherent + xs.photoelectric + xs.pair_production; + xs.total = + xs.coherent + xs.incoherent + xs.photoelectric + xs.pair_production; xs.last_E = p.E(); } @@ -516,25 +527,26 @@ double PhotonInteraction::rayleigh_scatter(double alpha, uint64_t* seed) const double mu; while (true) { // Determine maximum value of x^2 - double x2_max = std::pow(MASS_ELECTRON_EV/PLANCK_C*alpha, 2); + double x2_max = std::pow(MASS_ELECTRON_EV / PLANCK_C * alpha, 2); // Determine F(x^2_max, Z) double F_max = coherent_int_form_factor_(x2_max); // Sample cumulative distribution - double F = prn(seed)*F_max; + double F = prn(seed) * F_max; // Determine x^2 corresponding to F const auto& x {coherent_int_form_factor_.x()}; const auto& y {coherent_int_form_factor_.y()}; int i = lower_bound_index(y.cbegin(), y.cend(), F); - double r = (F - y[i]) / (y[i+1] - y[i]); - double x2 = x[i] + r*(x[i+1] - x[i]); + double r = (F - y[i]) / (y[i + 1] - y[i]); + double x2 = x[i] + r * (x[i + 1] - x[i]); // Calculate mu - mu = 1.0 - 2.0*x2/x2_max; + mu = 1.0 - 2.0 * x2 / x2_max; - if (prn(seed) < 0.5*(1.0 + mu*mu)) break; + if (prn(seed) < 0.5 * (1.0 + mu * mu)) + break; } return mu; } @@ -543,24 +555,18 @@ void PhotonInteraction::pair_production(double alpha, double* E_electron, double* E_positron, double* mu_electron, double* mu_positron, uint64_t* seed) const { - constexpr double r[] { - 122.81, 73.167, 69.228, 67.301, 64.696, 61.228, - 57.524, 54.033, 50.787, 47.851, 46.373, 45.401, - 44.503, 43.815, 43.074, 42.321, 41.586, 40.953, - 40.524, 40.256, 39.756, 39.144, 38.462, 37.778, - 37.174, 36.663, 35.986, 35.317, 34.688, 34.197, - 33.786, 33.422, 33.068, 32.740, 32.438, 32.143, - 31.884, 31.622, 31.438, 31.142, 30.950, 30.758, - 30.561, 30.285, 30.097, 29.832, 29.581, 29.411, - 29.247, 29.085, 28.930, 28.721, 28.580, 28.442, - 28.312, 28.139, 27.973, 27.819, 27.675, 27.496, - 27.285, 27.093, 26.911, 26.705, 26.516, 26.304, - 26.108, 25.929, 25.730, 25.577, 25.403, 25.245, - 25.100, 24.941, 24.790, 24.655, 24.506, 24.391, - 24.262, 24.145, 24.039, 23.922, 23.813, 23.712, - 23.621, 23.523, 23.430, 23.331, 23.238, 23.139, - 23.048, 22.967, 22.833, 22.694, 22.624, 22.545, - 22.446, 22.358, 22.264}; + constexpr double r[] {122.81, 73.167, 69.228, 67.301, 64.696, 61.228, 57.524, + 54.033, 50.787, 47.851, 46.373, 45.401, 44.503, 43.815, 43.074, 42.321, + 41.586, 40.953, 40.524, 40.256, 39.756, 39.144, 38.462, 37.778, 37.174, + 36.663, 35.986, 35.317, 34.688, 34.197, 33.786, 33.422, 33.068, 32.740, + 32.438, 32.143, 31.884, 31.622, 31.438, 31.142, 30.950, 30.758, 30.561, + 30.285, 30.097, 29.832, 29.581, 29.411, 29.247, 29.085, 28.930, 28.721, + 28.580, 28.442, 28.312, 28.139, 27.973, 27.819, 27.675, 27.496, 27.285, + 27.093, 26.911, 26.705, 26.516, 26.304, 26.108, 25.929, 25.730, 25.577, + 25.403, 25.245, 25.100, 24.941, 24.790, 24.655, 24.506, 24.391, 24.262, + 24.145, 24.039, 23.922, 23.813, 23.712, 23.621, 23.523, 23.430, 23.331, + 23.238, 23.139, 23.048, 22.967, 22.833, 22.694, 22.624, 22.545, 22.446, + 22.358, 22.264}; // The reduced screening radius r is the ratio of the screening radius to // the Compton wavelength of the electron, where the screening radius is @@ -575,27 +581,35 @@ void PhotonInteraction::pair_production(double alpha, double* E_electron, // Compute the high-energy Coulomb correction double a = Z_ / FINE_STRUCTURE; - double c = a*a*(1.0/(1.0 + a*a) + 0.202059 + a*a*(-0.03693 + a*a*(0.00835 + - a*a*(-0.00201 + a*a*(0.00049 + a*a*(-0.00012 + a*a*0.00003)))))); + double c = + a * a * + (1.0 / (1.0 + a * a) + 0.202059 + + a * a * + (-0.03693 + + a * a * + (0.00835 + + a * a * + (-0.00201 + + a * a * (0.00049 + a * a * (-0.00012 + a * a * 0.00003)))))); // The analytical approximation of the DCS underestimates the cross section // at low energies. The correction factor f compensates for this. - double q = std::sqrt(2.0/alpha); - double f = q*(-0.1774 - 12.10*a + 11.18*a*a) - + q*q*(8.523 + 73.26*a - 44.41*a*a) - + q*q*q*(-13.52 - 121.1*a + 96.41*a*a) - + q*q*q*q*(8.946 + 62.05*a - 63.41*a*a); + double q = std::sqrt(2.0 / alpha); + double f = q * (-0.1774 - 12.10 * a + 11.18 * a * a) + + q * q * (8.523 + 73.26 * a - 44.41 * a * a) + + q * q * q * (-13.52 - 121.1 * a + 96.41 * a * a) + + q * q * q * q * (8.946 + 62.05 * a - 63.41 * a * a); // Calculate phi_1(1/2) and phi_2(1/2). The unnormalized PDF for the reduced // energy is given by p = 2*(1/2 - e)^2*phi_1(e) + phi_2(e), where phi_1 and // phi_2 are non-negative and maximum at e = 1/2. - double b = 2.0*r[Z_]/alpha; - double t1 = 2.0*std::log(1.0 + b*b); - double t2 = b*std::atan(1.0/b); - double t3 = b*b*(4.0 - 4.0*t2 - 3.0*std::log(1.0 + 1.0/(b*b))); - double t4 = 4.0*std::log(r[Z_]) - 4.0*c + f; - double phi1_max = 7.0/3.0 - t1 - 6.0*t2 - t3 + t4; - double phi2_max = 11.0/6.0 - t1 - 3.0*t2 + 0.5*t3 + t4; + double b = 2.0 * r[Z_] / alpha; + double t1 = 2.0 * std::log(1.0 + b * b); + double t2 = b * std::atan(1.0 / b); + double t3 = b * b * (4.0 - 4.0 * t2 - 3.0 * std::log(1.0 + 1.0 / (b * b))); + double t4 = 4.0 * std::log(r[Z_]) - 4.0 * c + f; + double phi1_max = 7.0 / 3.0 - t1 - 6.0 * t2 - t3 + t4; + double phi2_max = 11.0 / 6.0 - t1 - 3.0 * t2 + 0.5 * t3 + t4; // To aid sampling, the unnormalized PDF can be expressed as // p = u_1*U_1(e)*pi_1(e) + u_2*U_2(e)*pi_2(e), where pi_1 and pi_2 are @@ -604,7 +618,7 @@ void PhotonInteraction::pair_production(double alpha, double* E_electron, // U_1 = phi_1(e)/phi_1(1/2) and U_2 = phi_2(e)/phi_2(1/2) are valid // rejection functions. The reduced energy can now be sampled using a // combination of the composition and rejection methods. - double u1 = 2.0/3.0*std::pow(0.5 - 1.0/alpha, 2)*phi1_max; + double u1 = 2.0 / 3.0 * std::pow(0.5 - 1.0 / alpha, 2) * phi1_max; double u2 = phi2_max; double e; while (true) { @@ -613,54 +627,58 @@ void PhotonInteraction::pair_production(double alpha, double* E_electron, // Sample the index i in (1, 2) using the point probabilities // p(1) = u_1/(u_1 + u_2) and p(2) = u_2/(u_1 + u_2) int i; - if (prn(seed) < u1/(u1 + u2)) { + if (prn(seed) < u1 / (u1 + u2)) { i = 1; // Sample e from pi_1 using the inverse transform method - e = rn >= 0.5 ? - 0.5 + (0.5 - 1.0/alpha)*std::pow(2.0*rn - 1.0, 1.0/3.0) : - 0.5 - (0.5 - 1.0/alpha)*std::pow(1.0 - 2.0*rn, 1.0/3.0); + e = rn >= 0.5 + ? 0.5 + (0.5 - 1.0 / alpha) * std::pow(2.0 * rn - 1.0, 1.0 / 3.0) + : 0.5 - (0.5 - 1.0 / alpha) * std::pow(1.0 - 2.0 * rn, 1.0 / 3.0); } else { i = 2; // Sample e from pi_2 using the inverse transform method - e = 1.0/alpha + (0.5 - 1.0/alpha)*2.0*rn; + e = 1.0 / alpha + (0.5 - 1.0 / alpha) * 2.0 * rn; } // Calculate phi_i(e) and deliver e if rn <= U_i(e) - b = r[Z_]/(2.0*alpha*e*(1.0 - e)); - t1 = 2.0*std::log(1.0 + b*b); - t2 = b*std::atan(1.0/b); - t3 = b*b*(4.0 - 4.0*t2 - 3.0*std::log(1.0 + 1.0/(b*b))); + b = r[Z_] / (2.0 * alpha * e * (1.0 - e)); + t1 = 2.0 * std::log(1.0 + b * b); + t2 = b * std::atan(1.0 / b); + t3 = b * b * (4.0 - 4.0 * t2 - 3.0 * std::log(1.0 + 1.0 / (b * b))); if (i == 1) { - double phi1 = 7.0/3.0 - t1 - 6.0*t2 - t3 + t4; - if (prn(seed) <= phi1/phi1_max) break; + double phi1 = 7.0 / 3.0 - t1 - 6.0 * t2 - t3 + t4; + if (prn(seed) <= phi1 / phi1_max) + break; } else { - double phi2 = 11.0/6.0 - t1 - 3.0*t2 + 0.5*t3 + t4; - if (prn(seed) <= phi2/phi2_max) break; + double phi2 = 11.0 / 6.0 - t1 - 3.0 * t2 + 0.5 * t3 + t4; + if (prn(seed) <= phi2 / phi2_max) + break; } } // Compute the kinetic energy of the electron and the positron - *E_electron = (alpha*e - 1.0)*MASS_ELECTRON_EV; - *E_positron = (alpha*(1.0 - e) - 1.0)*MASS_ELECTRON_EV; + *E_electron = (alpha * e - 1.0) * MASS_ELECTRON_EV; + *E_positron = (alpha * (1.0 - e) - 1.0) * MASS_ELECTRON_EV; // Sample the scattering angle of the electron. The cosine of the polar // angle of the direction relative to the incident photon is sampled from // p(mu) = C/(1 - beta*mu)^2 using the inverse transform method. - double beta = std::sqrt(*E_electron*(*E_electron + 2.0*MASS_ELECTRON_EV)) - / (*E_electron + MASS_ELECTRON_EV) ; + double beta = + std::sqrt(*E_electron * (*E_electron + 2.0 * MASS_ELECTRON_EV)) / + (*E_electron + MASS_ELECTRON_EV); double rn = uniform_distribution(-1., 1., seed); - *mu_electron = (rn + beta)/(rn*beta + 1.0); + *mu_electron = (rn + beta) / (rn * beta + 1.0); // Sample the scattering angle of the positron - beta = std::sqrt(*E_positron*(*E_positron + 2.0*MASS_ELECTRON_EV)) - / (*E_positron + MASS_ELECTRON_EV); + beta = std::sqrt(*E_positron * (*E_positron + 2.0 * MASS_ELECTRON_EV)) / + (*E_positron + MASS_ELECTRON_EV); rn = uniform_distribution(-1., 1., seed); - *mu_positron = (rn + beta)/(rn*beta + 1.0); + *mu_positron = (rn + beta) / (rn * beta + 1.0); } -void PhotonInteraction::atomic_relaxation(const ElectronSubshell& shell, Particle& p) const +void PhotonInteraction::atomic_relaxation( + const ElectronSubshell& shell, Particle& p) const { // If no transitions, assume fluorescent photon from captured free electron if (shell.n_transitions == 0) { @@ -676,7 +694,8 @@ void PhotonInteraction::atomic_relaxation(const ElectronSubshell& shell, Particl int i_transition; for (i_transition = 0; i_transition < shell.n_transitions; ++i_transition) { c += shell.transition_probability(i_transition); - if (rn < c) break; + if (rn < c) + break; } // Get primary and secondary subshell designators @@ -719,54 +738,56 @@ void PhotonInteraction::atomic_relaxation(const ElectronSubshell& shell, Particl std::pair klein_nishina(double alpha, uint64_t* seed) { double alpha_out, mu; - double beta = 1.0 + 2.0*alpha; + double beta = 1.0 + 2.0 * alpha; if (alpha < 3.0) { // Kahn's rejection method - double t = beta/(beta + 8.0); + double t = beta / (beta + 8.0); double x; while (true) { if (prn(seed) < t) { // Left branch of flow chart double r = uniform_distribution(0.0, 2.0, seed); - x = 1.0 + alpha*r; - if (prn(seed) < 4.0/x*(1.0 - 1.0/x)) { + x = 1.0 + alpha * r; + if (prn(seed) < 4.0 / x * (1.0 - 1.0 / x)) { mu = 1 - r; break; } } else { // Right branch of flow chart - x = beta/(1.0 + 2.0*alpha*prn(seed)); - mu = 1.0 + (1.0 - x)/alpha; - if (prn(seed) < 0.5*(mu*mu + 1.0/x)) break; + x = beta / (1.0 + 2.0 * alpha * prn(seed)); + mu = 1.0 + (1.0 - x) / alpha; + if (prn(seed) < 0.5 * (mu * mu + 1.0 / x)) + break; } } - alpha_out = alpha/x; + alpha_out = alpha / x; } else { // Koblinger's direct method double gamma = 1.0 - std::pow(beta, -2); - double s = prn(seed)*(4.0/alpha + 0.5*gamma + - (1.0 - (1.0 + beta)/(alpha*alpha))*std::log(beta)); - if (s <= 2.0/alpha) { + double s = + prn(seed) * (4.0 / alpha + 0.5 * gamma + + (1.0 - (1.0 + beta) / (alpha * alpha)) * std::log(beta)); + if (s <= 2.0 / alpha) { // For first term, x = 1 + 2ar // Therefore, a' = a/(1 + 2ar) - alpha_out = alpha/(1.0 + 2.0*alpha*prn(seed)); - } else if (s <= 4.0/alpha) { + alpha_out = alpha / (1.0 + 2.0 * alpha * prn(seed)); + } else if (s <= 4.0 / alpha) { // For third term, x = beta/(1 + 2ar) // Therefore, a' = a(1 + 2ar)/beta - alpha_out = alpha*(1.0 + 2.0*alpha*prn(seed))/beta; - } else if (s <= 4.0/alpha + 0.5*gamma) { + alpha_out = alpha * (1.0 + 2.0 * alpha * prn(seed)) / beta; + } else if (s <= 4.0 / alpha + 0.5 * gamma) { // For fourth term, x = 1/sqrt(1 - gamma*r) // Therefore, a' = a*sqrt(1 - gamma*r) - alpha_out = alpha*std::sqrt(1.0 - gamma*prn(seed)); + alpha_out = alpha * std::sqrt(1.0 - gamma * prn(seed)); } else { // For third term, x = beta^r // Therefore, a' = a/beta^r - alpha_out = alpha/std::pow(beta, prn(seed)); + alpha_out = alpha / std::pow(beta, prn(seed)); } // Calculate cosine of scattering angle based on basic relation - mu = 1.0 + 1.0/alpha - 1.0/alpha_out; + mu = 1.0 + 1.0 / alpha - 1.0 / alpha_out; } return {alpha_out, mu}; } diff --git a/src/physics.cpp b/src/physics.cpp index f0228ac4e..a466c0f9d 100644 --- a/src/physics.cpp +++ b/src/physics.cpp @@ -16,18 +16,18 @@ #include "openmc/random_dist.h" #include "openmc/random_lcg.h" #include "openmc/reaction.h" -#include "openmc/secondary_uncorrelated.h" #include "openmc/search.h" +#include "openmc/secondary_uncorrelated.h" #include "openmc/settings.h" #include "openmc/simulation.h" #include "openmc/string_utils.h" -#include "openmc/thermal.h" #include "openmc/tallies/tally.h" +#include "openmc/thermal.h" #include #include // for max, min, max_element -#include // for sqrt, exp, log, abs, copysign +#include // for sqrt, exp, log, abs, copysign namespace openmc { @@ -103,15 +103,16 @@ void sample_neutron_reaction(Particle& p) if (settings::run_mode == RunMode::EIGENVALUE) { create_fission_sites(p, i_nuclide, rx); } else if (settings::run_mode == RunMode::FIXED_SOURCE && - settings::create_fission_neutrons) { + settings::create_fission_neutrons) { create_fission_sites(p, i_nuclide, rx); // Make sure particle population doesn't grow out of control for // subcritical multiplication problems. if (p.secondary_bank().size() >= 10000) { - fatal_error("The secondary particle bank appears to be growing without " - "bound. You are likely running a subcritical multiplication problem " - "with k-effective close to or greater than one."); + fatal_error( + "The secondary particle bank appears to be growing without " + "bound. You are likely running a subcritical multiplication problem " + "with k-effective close to or greater than one."); } } } @@ -151,8 +152,7 @@ void sample_neutron_reaction(Particle& p) } } -void -create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx) +void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx) { // If uniform fission source weighting is turned on, we increase or decrease // the expected number of fission sites produced @@ -165,10 +165,12 @@ create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx) // Sample the number of neutrons produced int nu = static_cast(nu_t); - if (prn(p.current_seed()) <= (nu_t - nu)) ++nu; + if (prn(p.current_seed()) <= (nu_t - nu)) + ++nu; // If no neutrons were produced then don't continue - if (nu == 0) return; + if (nu == 0) + return; // Initialize the counter of delayed neutrons encountered for each delayed // group. @@ -204,12 +206,14 @@ create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx) if (use_fission_bank) { int64_t idx = simulation::fission_bank.thread_safe_append(site); if (idx == -1) { - warning("The shared fission bank is full. Additional fission sites created " - "in this generation will not be banked. Results may be non-deterministic."); + warning( + "The shared fission bank is full. Additional fission sites created " + "in this generation will not be banked. Results may be " + "non-deterministic."); - // Decrement number of particle progeny as storage was unsuccessful. This - // step is needed so that the sum of all progeny is equal to the size - // of the shared fission bank. + // Decrement number of particle progeny as storage was unsuccessful. + // This step is needed so that the sum of all progeny is equal to the + // size of the shared fission bank. p.n_progeny()--; // Break out of loop as no more sites can be added to fission bank @@ -230,9 +234,9 @@ create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx) // Write fission particles to nuBank p.nu_bank().emplace_back(); NuBank* nu_bank_entry = &p.nu_bank().back(); - nu_bank_entry->wgt = site.wgt; - nu_bank_entry->E = site.E; - nu_bank_entry->delayed_group = site.delayed_group; + nu_bank_entry->wgt = site.wgt; + nu_bank_entry->E = site.E; + nu_bank_entry->delayed_group = site.delayed_group; } // If shared fission bank was full, and no fissions could be added, @@ -294,7 +298,8 @@ void sample_photon_reaction(Particle& p) if (prob > cutoff) { double alpha_out, mu; int i_shell; - element.compton_scatter(alpha, true, &alpha_out, &mu, &i_shell, p.current_seed()); + element.compton_scatter( + alpha, true, &alpha_out, &mu, &i_shell, p.current_seed()); // Determine binding energy of shell. The binding energy is 0.0 if // doppler broadening is not used. @@ -306,12 +311,13 @@ void sample_photon_reaction(Particle& p) } // Create Compton electron - double phi = uniform_distribution(0., 2.0*PI, p.current_seed()); - double E_electron = (alpha - alpha_out)*MASS_ELECTRON_EV - e_b; + double phi = uniform_distribution(0., 2.0 * PI, p.current_seed()); + double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b; int electron = static_cast(ParticleType::electron); if (E_electron >= settings::energy_cutoff[electron]) { - double mu_electron = (alpha - alpha_out*mu) - / std::sqrt(alpha*alpha + alpha_out*alpha_out - 2.0*alpha*alpha_out*mu); + double mu_electron = (alpha - alpha_out * mu) / + std::sqrt(alpha * alpha + alpha_out * alpha_out - + 2.0 * alpha * alpha_out * mu); Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed()); p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron); } @@ -342,12 +348,13 @@ void sample_photon_reaction(Particle& p) // Check threshold of reaction int i_start = shell.threshold; - if (i_grid < i_start) continue; + if (i_grid < i_start) + continue; // Evaluation subshell photoionization cross section double xs = std::exp(shell.cross_section(i_grid - i_start) + - f*(shell.cross_section(i_grid + 1 - i_start) - - shell.cross_section(i_grid - i_start))); + f * (shell.cross_section(i_grid + 1 - i_start) - + shell.cross_section(i_grid - i_start))); prob += xs; if (prob > cutoff) { @@ -359,19 +366,21 @@ void sample_photon_reaction(Particle& p) double mu; while (true) { double r = prn(p.current_seed()); - if (4.0*(1.0 - r)*r >= prn(p.current_seed())) { - double rel_vel = std::sqrt(E_electron * (E_electron + - 2.0*MASS_ELECTRON_EV)) / (E_electron + MASS_ELECTRON_EV); - mu = (2.0*r + rel_vel - 1.0) / (2.0*rel_vel*r - rel_vel + 1.0); + if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) { + double rel_vel = + std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) / + (E_electron + MASS_ELECTRON_EV); + mu = + (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0); break; } } - double phi = uniform_distribution(0., 2.0*PI, p.current_seed()); + double phi = uniform_distribution(0., 2.0 * PI, p.current_seed()); Direction u; u.x = mu; - u.y = std::sqrt(1.0 - mu*mu)*std::cos(phi); - u.z = std::sqrt(1.0 - mu*mu)*std::sin(phi); + u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi); + u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi); // Create secondary electron p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron); @@ -394,8 +403,8 @@ void sample_photon_reaction(Particle& p) if (prob > cutoff) { double E_electron, E_positron; double mu_electron, mu_positron; - element.pair_production(alpha, &E_electron, &E_positron, - &mu_electron, &mu_positron, p.current_seed()); + element.pair_production(alpha, &E_electron, &E_positron, &mu_electron, + &mu_positron, p.current_seed()); // Create secondary electron Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed()); @@ -464,12 +473,13 @@ int sample_nuclide(Particle& p) // Increment probability to compare to cutoff prob += atom_density * p.neutron_xs(i_nuclide).total; - if (prob >= cutoff) return i_nuclide; + if (prob >= cutoff) + return i_nuclide; } // If we reach here, no nuclide was sampled p.write_restart(); - throw std::runtime_error{"Did not sample any nuclide during collision."}; + throw std::runtime_error {"Did not sample any nuclide during collision."}; } int sample_element(Particle& p) @@ -535,21 +545,25 @@ Reaction& sample_fission(int i_nuclide, Particle& p) for (auto& rx : nuc->fission_rx_) { // if energy is below threshold for this reaction, skip it int threshold = rx->xs_[i_temp].threshold; - if (i_grid < threshold) continue; + if (i_grid < threshold) + continue; // add to cumulative probability - prob += (1.0 - f) * rx->xs_[i_temp].value[i_grid - threshold] - + f*rx->xs_[i_temp].value[i_grid - threshold + 1]; + prob += (1.0 - f) * rx->xs_[i_temp].value[i_grid - threshold] + + f * rx->xs_[i_temp].value[i_grid - threshold + 1]; // Create fission bank sites if fission occurs - if (prob > cutoff) return *rx; + if (prob > cutoff) + return *rx; } // If we reached here, no reaction was sampled - throw std::runtime_error{"No fission reaction was sampled for " + nuc->name_}; + throw std::runtime_error { + "No fission reaction was sampled for " + nuc->name_}; } -void sample_photon_product(int i_nuclide, Particle& p, int* i_rx, int* i_product) +void sample_photon_product( + int i_nuclide, Particle& p, int* i_rx, int* i_product) { // Get grid index and interpolation factor and sample photon production cdf int i_temp = p.neutron_xs(i_nuclide).index_temp; @@ -565,11 +579,12 @@ void sample_photon_product(int i_nuclide, Particle& p, int* i_rx, int* i_product int threshold = rx->xs_[i_temp].threshold; // if energy is below threshold for this reaction, skip it - if (i_grid < threshold) continue; + if (i_grid < threshold) + continue; // Evaluate neutron cross section - double xs = ((1.0 - f) * rx->xs_[i_temp].value[i_grid - threshold] - + f*(rx->xs_[i_temp].value[i_grid - threshold + 1])); + double xs = ((1.0 - f) * rx->xs_[i_temp].value[i_grid - threshold] + + f * (rx->xs_[i_temp].value[i_grid - threshold + 1])); for (int j = 0; j < rx->products_.size(); ++j) { if (rx->products_[j].particle_ == ParticleType::photon) { @@ -581,7 +596,7 @@ void sample_photon_product(int i_nuclide, Particle& p, int* i_rx, int* i_product if (nuc->prompt_photons_ && nuc->delayed_photons_) { double energy_prompt = (*nuc->prompt_photons_)(p.E()); double energy_delayed = (*nuc->delayed_photons_)(p.E()); - f = (energy_prompt + energy_delayed)/(energy_prompt); + f = (energy_prompt + energy_delayed) / (energy_prompt); } } } @@ -591,7 +606,8 @@ void sample_photon_product(int i_nuclide, Particle& p, int* i_rx, int* i_product *i_rx = i; *i_product = j; - if (prob > cutoff) return; + if (prob > cutoff) + return; } } } @@ -640,8 +656,8 @@ void scatter(Particle& p, int i_nuclide) // Get pointer to nuclide and grid index/interpolation factor const auto& nuc {data::nuclides[i_nuclide]}; const auto& micro {p.neutron_xs(i_nuclide)}; - int i_temp = micro.index_temp; - int i_grid = micro.index_grid; + int i_temp = micro.index_temp; + int i_grid = micro.index_grid; double f = micro.interp_factor; // For tallying purposes, this routine might be called directly. In that @@ -698,11 +714,12 @@ void scatter(Particle& p, int i_nuclide) // if energy is below threshold for this reaction, skip it const auto& xs {nuc->reactions_[i]->xs_[i_temp]}; - if (i_grid < xs.threshold) continue; + if (i_grid < xs.threshold) + continue; // add to cumulative probability - prob += (1.0 - f)*xs.value[i_grid - xs.threshold] + - f*xs.value[i_grid - xs.threshold + 1]; + prob += (1.0 - f) * xs.value[i_grid - xs.threshold] + + f * xs.value[i_grid - xs.threshold + 1]; } // Perform collision physics for inelastic scattering @@ -726,8 +743,7 @@ void scatter(Particle& p, int i_nuclide) } } -void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, - Particle& p) +void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p) { // get pointer to nuclide const auto& nuc {data::nuclides[i_nuclide]}; @@ -736,7 +752,7 @@ void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, double awr = nuc->awr_; // Neutron velocity in LAB - Direction v_n = vel*p.u(); + Direction v_n = vel * p.u(); // Sample velocity of target nucleus Direction v_t {}; @@ -746,7 +762,7 @@ void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, } // Velocity of center-of-mass - Direction v_cm = (v_n + awr*v_t)/(awr + 1.0); + Direction v_cm = (v_n + awr * v_t) / (awr + 1.0); // Transform to CM frame v_n -= v_cm; @@ -766,7 +782,7 @@ void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, } // Determine direction cosines in CM - Direction u_cm = v_n/vel; + Direction u_cm = v_n / vel; // Rotate neutron velocity vector to new angle -- note that the speed of the // neutron in CM does not change in elastic scattering. However, the speed @@ -823,12 +839,12 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, if (E > settings::res_scat_energy_max) { return {}; - // lower resonance scattering energy bound (should be no resonances below) + // lower resonance scattering energy bound (should be no resonances below) } else if (E < settings::res_scat_energy_min) { sampling_method = ResScatMethod::cxs; } - // otherwise, use free gas model + // otherwise, use free gas model } else { if (E >= FREE_GAS_THRESHOLD * kT && nuc.awr_ > 1.0) { return {}; @@ -848,7 +864,7 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, case ResScatMethod::rvs: { double E_red = std::sqrt(nuc.awr_ * E / kT); double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_; - double E_up = (E_red + 4.0)*(E_red + 4.0) * kT / nuc.awr_; + double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_; // find lower and upper energy bound indices // lower index @@ -858,8 +874,8 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, } else if (E_low > nuc.energy_0K_.back()) { i_E_low = nuc.energy_0K_.size() - 2; } else { - i_E_low = lower_bound_index(nuc.energy_0K_.begin(), - nuc.energy_0K_.end(), E_low); + i_E_low = + lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low); } // upper index @@ -869,8 +885,8 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, } else if (E_up > nuc.energy_0K_.back()) { i_E_up = nuc.energy_0K_.size() - 2; } else { - i_E_up = lower_bound_index(nuc.energy_0K_.begin(), - nuc.energy_0K_.end(), E_up); + i_E_up = + lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up); } if (i_E_up == i_E_low) { @@ -882,70 +898,74 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, if (sampling_method == ResScatMethod::dbrc) { // interpolate xs since we're not exactly at the energy indices double xs_low = nuc.elastic_0K_[i_E_low]; - double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) - / (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]); + double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) / + (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]); xs_low += m * (E_low - nuc.energy_0K_[i_E_low]); double xs_up = nuc.elastic_0K_[i_E_up]; - m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) - / (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]); + m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) / + (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]); xs_up += m * (E_up - nuc.energy_0K_[i_E_up]); // get max 0K xs value over range of practical relative energies - double xs_max = *std::max_element(&nuc.elastic_0K_[i_E_low + 1], - &nuc.elastic_0K_[i_E_up + 1]); + double xs_max = *std::max_element( + &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]); xs_max = std::max({xs_low, xs_max, xs_up}); while (true) { double E_rel; Direction v_target; while (true) { - // sample target velocity with the constant cross section (cxs) approx. + // sample target velocity with the constant cross section (cxs) + // approx. v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed); Direction v_rel = v_neut - v_target; E_rel = v_rel.dot(v_rel); - if (E_rel < E_up) break; + if (E_rel < E_up) + break; } // perform Doppler broadening rejection correction (dbrc) double xs_0K = nuc.elastic_xs_0K(E_rel); double R = xs_0K / xs_max; - if (prn(seed) < R) return v_target; + if (prn(seed) < R) + return v_target; } } else if (sampling_method == ResScatMethod::rvs) { // interpolate xs CDF since we're not exactly at the energy indices // cdf value at lower bound attainable energy - double m = (nuc.xs_cdf_[i_E_low] - nuc.xs_cdf_[i_E_low - 1]) - / (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]); - double cdf_low = nuc.xs_cdf_[i_E_low - 1] - + m * (E_low - nuc.energy_0K_[i_E_low]); - if (E_low <= nuc.energy_0K_.front()) cdf_low = 0.0; + double m = (nuc.xs_cdf_[i_E_low] - nuc.xs_cdf_[i_E_low - 1]) / + (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]); + double cdf_low = + nuc.xs_cdf_[i_E_low - 1] + m * (E_low - nuc.energy_0K_[i_E_low]); + if (E_low <= nuc.energy_0K_.front()) + cdf_low = 0.0; // cdf value at upper bound attainable energy - m = (nuc.xs_cdf_[i_E_up] - nuc.xs_cdf_[i_E_up - 1]) - / (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]); - double cdf_up = nuc.xs_cdf_[i_E_up - 1] - + m*(E_up - nuc.energy_0K_[i_E_up]); + m = (nuc.xs_cdf_[i_E_up] - nuc.xs_cdf_[i_E_up - 1]) / + (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]); + double cdf_up = + nuc.xs_cdf_[i_E_up - 1] + m * (E_up - nuc.energy_0K_[i_E_up]); while (true) { // directly sample Maxwellian double E_t = -kT * std::log(prn(seed)); // sample a relative energy using the xs cdf - double cdf_rel = cdf_low + prn(seed)*(cdf_up - cdf_low); - int i_E_rel = lower_bound_index(&nuc.xs_cdf_[i_E_low-1], - &nuc.xs_cdf_[i_E_up+1], cdf_rel); + double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low); + int i_E_rel = lower_bound_index( + &nuc.xs_cdf_[i_E_low - 1], &nuc.xs_cdf_[i_E_up + 1], cdf_rel); double E_rel = nuc.energy_0K_[i_E_low + i_E_rel]; - double m = (nuc.xs_cdf_[i_E_low + i_E_rel] - - nuc.xs_cdf_[i_E_low + i_E_rel - 1]) - / (nuc.energy_0K_[i_E_low + i_E_rel + 1] - - nuc.energy_0K_[i_E_low + i_E_rel]); + double m = (nuc.xs_cdf_[i_E_low + i_E_rel] - + nuc.xs_cdf_[i_E_low + i_E_rel - 1]) / + (nuc.energy_0K_[i_E_low + i_E_rel + 1] - + nuc.energy_0K_[i_E_low + i_E_rel]); E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel - 1]) / m; // perform rejection sampling on cosine between // neutron and target velocities double mu = (E_t + nuc.awr_ * (E - E_rel)) / - (2.0 * std::sqrt(nuc.awr_ * E * E_t)); + (2.0 * std::sqrt(nuc.awr_ * E * E_t)); if (std::abs(mu) < 1.0) { // set and accept target velocity @@ -954,17 +974,17 @@ Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u, } } } - } // case RVS, DBRC + } // case RVS, DBRC } // switch (sampling_method) UNREACHABLE(); } -Direction -sample_cxs_target_velocity(double awr, double E, Direction u, double kT, uint64_t* seed) +Direction sample_cxs_target_velocity( + double awr, double E, Direction u, double kT, uint64_t* seed) { double beta_vn = std::sqrt(awr * E / kT); - double alpha = 1.0/(1.0 + std::sqrt(PI)*beta_vn/2.0); + double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0); double beta_vt_sq; double mu; @@ -978,15 +998,15 @@ sample_cxs_target_velocity(double awr, double E, Direction u, double kT, uint64_ // y*e^(-y). This can be done with sampling scheme C45 from the Monte // Carlo sampler - beta_vt_sq = -std::log(r1*r2); + beta_vt_sq = -std::log(r1 * r2); } else { // With probability 1-alpha, we sample the distribution p(y) = y^2 * // e^(-y^2). This can be done with sampling scheme C61 from the Monte // Carlo sampler - double c = std::cos(PI/2.0 * prn(seed)); - beta_vt_sq = -std::log(r1) - std::log(r2)*c*c; + double c = std::cos(PI / 2.0 * prn(seed)); + beta_vt_sq = -std::log(r1) - std::log(r2) * c * c; } // Determine beta * vt @@ -996,15 +1016,17 @@ sample_cxs_target_velocity(double awr, double E, Direction u, double kT, uint64_ mu = uniform_distribution(-1., 1., seed); // Determine rejection probability - double accept_prob = std::sqrt(beta_vn*beta_vn + beta_vt_sq - - 2*beta_vn*beta_vt*mu) / (beta_vn + beta_vt); + double accept_prob = + std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) / + (beta_vn + beta_vt); // Perform rejection sampling on vt and mu - if (prn(seed) < accept_prob) break; + if (prn(seed) < accept_prob) + break; } // Determine speed of target nucleus - double vt = std::sqrt(beta_vt_sq*kT/awr); + double vt = std::sqrt(beta_vt_sq * kT / awr); // Determine velocity vector of target nucleus based on neutron's velocity // and the sampled angle between them @@ -1025,7 +1047,7 @@ void sample_fission_neutron(int i_nuclide, const Reaction& rx, double E_in, // DELAYED NEUTRON SAMPLED // sampled delayed precursor group - double xi = prn(seed)*nu_d; + double xi = prn(seed) * nu_d; double prob = 0.0; int group; for (group = 1; group < nuc->n_precursor_; ++group) { @@ -1034,7 +1056,8 @@ void sample_fission_neutron(int i_nuclide, const Reaction& rx, double E_in, // Check if this group is sampled prob += yield; - if (xi < prob) break; + if (xi < prob) + break; } // if the sum of the probabilities is slightly less than one and the @@ -1061,14 +1084,16 @@ void sample_fission_neutron(int i_nuclide, const Reaction& rx, double E_in, // resample if energy is greater than maximum neutron energy constexpr int neutron = static_cast(ParticleType::neutron); - if (site->E < data::energy_max[neutron]) break; + if (site->E < data::energy_max[neutron]) + break; // check for large number of resamples ++n_sample; if (n_sample == MAX_SAMPLE) { // particle_write_restart(p) fatal_error("Resampled energy distribution maximum number of times " - "for nuclide " + nuc->name_); + "for nuclide " + + nuc->name_); } } @@ -1095,17 +1120,18 @@ void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p) // determine outgoing energy in lab double A = nuc.awr_; - E = E_cm + (E_in + 2.0*mu*(A + 1.0) * std::sqrt(E_in*E_cm)) - / ((A + 1.0)*(A + 1.0)); + E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) / + ((A + 1.0) * (A + 1.0)); // determine outgoing angle in lab - mu = mu*std::sqrt(E_cm/E) + 1.0/(A+1.0) * std::sqrt(E_in/E); + mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E); } // Because of floating-point roundoff, it may be possible for mu to be // outside of the range [-1,1). In these cases, we just set mu to exactly -1 // or 1 - if (std::abs(mu) > 1.0) mu = std::copysign(1.0, mu); + if (std::abs(mu) > 1.0) + mu = std::copysign(1.0, mu); // Set outgoing energy and scattering angle p.E() = E; @@ -1133,7 +1159,8 @@ void sample_secondary_photons(Particle& p, int i_nuclide) double y_t = p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total; int y = static_cast(y_t); - if (prn(p.current_seed()) <= y_t - y) ++y; + if (prn(p.current_seed()) <= y_t - y) + ++y; // Sample each secondary photon for (int i = 0; i < y; ++i) { diff --git a/src/physics_common.cpp b/src/physics_common.cpp index 2a63b188d..f6820f81f 100644 --- a/src/physics_common.cpp +++ b/src/physics_common.cpp @@ -1,7 +1,7 @@ #include "openmc/physics_common.h" -#include "openmc/settings.h" #include "openmc/random_lcg.h" +#include "openmc/settings.h" namespace openmc { @@ -23,4 +23,4 @@ void russian_roulette(Particle& p) } } -} //namespace openmc +} // namespace openmc diff --git a/src/physics_mg.cpp b/src/physics_mg.cpp index 1d47bac0d..eaf13b441 100644 --- a/src/physics_mg.cpp +++ b/src/physics_mg.cpp @@ -2,8 +2,8 @@ #include -#include #include "xtensor/xarray.hpp" +#include #include "openmc/bank.h" #include "openmc/constants.h" @@ -22,8 +22,7 @@ namespace openmc { -void -collision_mg(Particle& p) +void collision_mg(Particle& p) { // Add to the collision counter for the particle p.n_collision()++; @@ -37,8 +36,7 @@ collision_mg(Particle& p) } } -void -sample_reaction(Particle& p) +void sample_reaction(Particle& p) { // Create fission bank sites. Note that while a fission reaction is sampled, // it never actually "happens", i.e. the weight of the particle does not @@ -46,9 +44,9 @@ sample_reaction(Particle& p) // absorption (including fission) if (model::materials[p.material()]->fissionable_) { - if (settings::run_mode == RunMode::EIGENVALUE || - (settings::run_mode == RunMode::FIXED_SOURCE && - settings::create_fission_neutrons)) { + if (settings::run_mode == RunMode::EIGENVALUE || + (settings::run_mode == RunMode::FIXED_SOURCE && + settings::create_fission_neutrons)) { create_fission_sites(p); } } @@ -74,8 +72,7 @@ sample_reaction(Particle& p) } } -void -scatter(Particle& p) +void scatter(Particle& p) { data::mg.macro_xs_[p.material()].sample_scatter( p.g_last(), p.g(), p.mu(), p.wgt(), p.current_seed()); @@ -90,8 +87,7 @@ scatter(Particle& p) p.event() = TallyEvent::SCATTER; } -void -create_fission_sites(Particle& p) +void create_fission_sites(Particle& p) { // If uniform fission source weighting is turned on, we increase or decrease // the expected number of fission sites produced @@ -108,7 +104,8 @@ create_fission_sites(Particle& p) } // If no neutrons were produced then don't continue - if (nu == 0) return; + if (nu == 0) + return; // Initialize the counter of delayed neutrons encountered for each delayed // group. @@ -138,10 +135,10 @@ create_fission_sites(Particle& p) // Sample the cosine of the angle, assuming fission neutrons are emitted // isotropically - double mu = 2.*prn(p.current_seed()) - 1.; + double mu = 2. * prn(p.current_seed()) - 1.; // Sample the azimuthal angle uniformly in [0, 2.pi) - double phi = 2. * PI * prn(p.current_seed() ); + double phi = 2. * PI * prn(p.current_seed()); site.u.x = mu; site.u.y = std::sqrt(1. - mu * mu) * std::cos(phi); site.u.z = std::sqrt(1. - mu * mu) * std::sin(phi); @@ -163,12 +160,14 @@ create_fission_sites(Particle& p) if (use_fission_bank) { int64_t idx = simulation::fission_bank.thread_safe_append(site); if (idx == -1) { - warning("The shared fission bank is full. Additional fission sites created " - "in this generation will not be banked. Results may be non-deterministic."); + warning( + "The shared fission bank is full. Additional fission sites created " + "in this generation will not be banked. Results may be " + "non-deterministic."); - // Decrement number of particle progeny as storage was unsuccessful. This - // step is needed so that the sum of all progeny is equal to the size - // of the shared fission bank. + // Decrement number of particle progeny as storage was unsuccessful. + // This step is needed so that the sum of all progeny is equal to the + // size of the shared fission bank. p.n_progeny()--; // Break out of loop as no more sites can be added to fission bank @@ -189,9 +188,9 @@ create_fission_sites(Particle& p) // Write fission particles to nuBank p.nu_bank().emplace_back(); NuBank* nu_bank_entry = &p.nu_bank().back(); - nu_bank_entry->wgt = site.wgt; - nu_bank_entry->E = site.E; - nu_bank_entry->delayed_group = site.delayed_group; + nu_bank_entry->wgt = site.wgt; + nu_bank_entry->E = site.E; + nu_bank_entry->delayed_group = site.delayed_group; } // If shared fission bank was full, and no fissions could be added, @@ -213,8 +212,7 @@ create_fission_sites(Particle& p) } } -void -absorption(Particle& p) +void absorption(Particle& p) { if (settings::survival_biasing) { // Determine weight absorbed in survival biasing @@ -237,4 +235,4 @@ absorption(Particle& p) } } -} //namespace openmc +} // namespace openmc diff --git a/src/plot.cpp b/src/plot.cpp index c3ef36467..789437691 100644 --- a/src/plot.cpp +++ b/src/plot.cpp @@ -4,14 +4,14 @@ #include #include +#include "xtensor/xview.hpp" #include #include -#include "xtensor/xview.hpp" #include "openmc/constants.h" +#include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/geometry.h" -#include "openmc/error.h" #include "openmc/hdf5_interface.h" #include "openmc/material.h" #include "openmc/mesh.h" @@ -30,24 +30,24 @@ namespace openmc { // Constants //============================================================================== - constexpr int PLOT_LEVEL_LOWEST {-1}; //!< lower bound on plot universe level constexpr int32_t NOT_FOUND {-2}; constexpr int32_t OVERLAP {-3}; -IdData::IdData(size_t h_res, size_t v_res) - : data_({v_res, h_res, 3}, NOT_FOUND) -{ } +IdData::IdData(size_t h_res, size_t v_res) : data_({v_res, h_res, 3}, NOT_FOUND) +{} -void -IdData::set_value(size_t y, size_t x, const Particle& p, int level) { +void IdData::set_value(size_t y, size_t x, const Particle& p, int level) +{ // set cell data if (p.n_coord() <= level) { data_(y, x, 0) = NOT_FOUND; data_(y, x, 1) = NOT_FOUND; } else { data_(y, x, 0) = model::cells.at(p.coord(level).cell)->id_; - data_(y, x, 1) = level == p.n_coord() - 1 ? p.cell_instance() : cell_instance_at_level(p, level); + data_(y, x, 1) = level == p.n_coord() - 1 + ? p.cell_instance() + : cell_instance_at_level(p, level); } // set material data @@ -61,25 +61,27 @@ IdData::set_value(size_t y, size_t x, const Particle& p, int level) { } } -void IdData::set_overlap(size_t y, size_t x) { +void IdData::set_overlap(size_t y, size_t x) +{ xt::view(data_, y, x, xt::all()) = OVERLAP; } PropertyData::PropertyData(size_t h_res, size_t v_res) : data_({v_res, h_res, 2}, NOT_FOUND) -{ } +{} -void -PropertyData::set_value(size_t y, size_t x, const Particle& p, int level) { +void PropertyData::set_value(size_t y, size_t x, const Particle& p, int level) +{ Cell* c = model::cells.at(p.coord(p.n_coord() - 1).cell).get(); data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN; if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) { Material* m = model::materials.at(p.material()).get(); - data_(y,x,1) = m->density_gpcc_; + data_(y, x, 1) = m->density_gpcc_; } } -void PropertyData::set_overlap(size_t y, size_t x) { +void PropertyData::set_overlap(size_t y, size_t x) +{ data_(y, x) = OVERLAP; } @@ -99,8 +101,7 @@ uint64_t plotter_seed = 1; // RUN_PLOT controls the logic for making one or many plots //============================================================================== -extern "C" -int openmc_plot_geometry() +extern "C" int openmc_plot_geometry() { for (auto& pl : model::plots) { write_message(5, "Processing plot {}: {}...", pl.id_, pl.path_plot_); @@ -116,7 +117,6 @@ int openmc_plot_geometry() return 0; } - void read_plots_xml() { // Check if plots.xml exists @@ -160,32 +160,35 @@ void create_ppm(Plot const& pl) int idx = pl.color_by_ == PlotColorBy::cells ? 0 : 2; auto id = ids.data_(y, x, idx); // no setting needed if not found - if (id == NOT_FOUND) { continue; } + if (id == NOT_FOUND) { + continue; + } if (id == OVERLAP) { - data(x,y) = pl.overlap_color_; + data(x, y) = pl.overlap_color_; continue; } if (PlotColorBy::cells == pl.color_by_) { - data(x,y) = pl.colors_[model::cell_map[id]]; + data(x, y) = pl.colors_[model::cell_map[id]]; } else if (PlotColorBy::mats == pl.color_by_) { if (id == MATERIAL_VOID) { - data(x,y) = WHITE; + data(x, y) = WHITE; continue; } - data(x,y) = pl.colors_[model::material_map[id]]; + data(x, y) = pl.colors_[model::material_map[id]]; } // color_by if-else - } // x for loop - } // y for loop + } // x for loop + } // y for loop // draw mesh lines if present - if (pl.index_meshlines_mesh_ >= 0) {draw_mesh_lines(pl, data);} + if (pl.index_meshlines_mesh_ >= 0) { + draw_mesh_lines(pl, data); + } // write ppm data to file output_ppm(pl, data); } -void -Plot::set_id(pugi::xml_node plot_node) +void Plot::set_id(pugi::xml_node plot_node) { // Copy data into plots if (check_for_node(plot_node, "id")) { @@ -196,12 +199,12 @@ Plot::set_id(pugi::xml_node plot_node) // Check to make sure 'id' hasn't been used if (model::plot_map.find(id_) != model::plot_map.end()) { - fatal_error(fmt::format("Two or more plots use the same unique ID: {}", id_)); + fatal_error( + fmt::format("Two or more plots use the same unique ID: {}", id_)); } } -void -Plot::set_type(pugi::xml_node plot_node) +void Plot::set_type(pugi::xml_node plot_node) { // Copy plot type // Default is slice @@ -212,19 +215,17 @@ Plot::set_type(pugi::xml_node plot_node) // set type using node value if (type_str == "slice") { type_ = PlotType::slice; - } - else if (type_str == "voxel") { + } else if (type_str == "voxel") { type_ = PlotType::voxel; } else { // if we're here, something is wrong - fatal_error(fmt::format("Unsupported plot type '{}' in plot {}", - type_str, id_)); + fatal_error( + fmt::format("Unsupported plot type '{}' in plot {}", type_str, id_)); } } } -void -Plot::set_output_path(pugi::xml_node plot_node) +void Plot::set_output_path(pugi::xml_node plot_node) { // Set output file path std::string filename; @@ -235,7 +236,7 @@ Plot::set_output_path(pugi::xml_node plot_node) filename = fmt::format("plot_{}", id_); } // add appropriate file extension to name - switch(type_) { + switch (type_) { case PlotType::slice: filename.append(".ppm"); break; @@ -253,7 +254,8 @@ Plot::set_output_path(pugi::xml_node plot_node) pixels_[0] = pxls[0]; pixels_[1] = pxls[1]; } else { - fatal_error(fmt::format(" must be length 2 in slice plot {}", id_)); + fatal_error( + fmt::format(" must be length 2 in slice plot {}", id_)); } } else if (PlotType::voxel == type_) { if (pxls.size() == 3) { @@ -261,13 +263,13 @@ Plot::set_output_path(pugi::xml_node plot_node) pixels_[1] = pxls[1]; pixels_[2] = pxls[2]; } else { - fatal_error(fmt::format(" must be length 3 in voxel plot {}", id_)); + fatal_error( + fmt::format(" must be length 3 in voxel plot {}", id_)); } } } -void -Plot::set_bg_color(pugi::xml_node plot_node) +void Plot::set_bg_color(pugi::xml_node plot_node) { // Copy plot background color if (check_for_node(plot_node, "background")) { @@ -285,8 +287,7 @@ Plot::set_bg_color(pugi::xml_node plot_node) } } -void -Plot::set_basis(pugi::xml_node plot_node) +void Plot::set_basis(pugi::xml_node plot_node) { // Copy plot basis if (PlotType::slice == type_) { @@ -301,14 +302,13 @@ Plot::set_basis(pugi::xml_node plot_node) } else if ("yz" == pl_basis) { basis_ = PlotBasis::yz; } else { - fatal_error(fmt::format("Unsupported plot basis '{}' in plot {}", - pl_basis, id_)); + fatal_error( + fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id_)); } } } -void -Plot::set_origin(pugi::xml_node plot_node) +void Plot::set_origin(pugi::xml_node plot_node) { // Copy plotting origin auto pl_origin = get_node_array(plot_node, "origin"); @@ -319,8 +319,7 @@ Plot::set_origin(pugi::xml_node plot_node) } } -void -Plot::set_width(pugi::xml_node plot_node) +void Plot::set_width(pugi::xml_node plot_node) { // Copy plotting width vector pl_width = get_node_array(plot_node, "width"); @@ -329,20 +328,21 @@ Plot::set_width(pugi::xml_node plot_node) width_.x = pl_width[0]; width_.y = pl_width[1]; } else { - fatal_error(fmt::format(" must be length 2 in slice plot {}", id_)); + fatal_error( + fmt::format(" must be length 2 in slice plot {}", id_)); } } else if (PlotType::voxel == type_) { if (pl_width.size() == 3) { pl_width = get_node_array(plot_node, "width"); width_ = pl_width; } else { - fatal_error(fmt::format(" must be length 3 in voxel plot {}", id_)); + fatal_error( + fmt::format(" must be length 3 in voxel plot {}", id_)); } } } -void -Plot::set_universe(pugi::xml_node plot_node) +void Plot::set_universe(pugi::xml_node plot_node) { // Copy plot universe level if (check_for_node(plot_node, "level")) { @@ -355,8 +355,7 @@ Plot::set_universe(pugi::xml_node plot_node) } } -void -Plot::set_default_colors(pugi::xml_node plot_node) +void Plot::set_default_colors(pugi::xml_node plot_node) { // Copy plot color type and initialize all colors randomly std::string pl_color_by = "cell"; @@ -366,12 +365,12 @@ Plot::set_default_colors(pugi::xml_node plot_node) if ("cell" == pl_color_by) { color_by_ = PlotColorBy::cells; colors_.resize(model::cells.size()); - } else if("material" == pl_color_by) { + } else if ("material" == pl_color_by) { color_by_ = PlotColorBy::mats; colors_.resize(model::materials.size()); } else { - fatal_error(fmt::format("Unsupported plot color type '{}' in plot {}", - pl_color_by, id_)); + fatal_error(fmt::format( + "Unsupported plot color type '{}' in plot {}", pl_color_by, id_)); } for (auto& c : colors_) { @@ -383,12 +382,12 @@ Plot::set_default_colors(pugi::xml_node plot_node) } } -void -Plot::set_user_colors(pugi::xml_node plot_node) +void Plot::set_user_colors(pugi::xml_node plot_node) { if (!plot_node.select_nodes("color").empty() && PlotType::voxel == type_) { if (mpi::master) { - warning(fmt::format("Color specifications ignored in voxel plot {}", id_)); + warning( + fmt::format("Color specifications ignored in voxel plot {}", id_)); } } @@ -403,8 +402,8 @@ Plot::set_user_colors(pugi::xml_node plot_node) if (check_for_node(cn, "id")) { col_id = std::stoi(get_node_value(cn, "id")); } else { - fatal_error(fmt::format( - "Must specify id for color specification in plot {}", id_)); + fatal_error( + fmt::format("Must specify id for color specification in plot {}", id_)); } // Add RGB if (PlotColorBy::cells == color_by_) { @@ -412,8 +411,8 @@ Plot::set_user_colors(pugi::xml_node plot_node) col_id = model::cell_map[col_id]; colors_[col_id] = user_rgb; } else { - fatal_error(fmt::format("Could not find cell {} specified in plot {}", - col_id, id_)); + fatal_error(fmt::format( + "Could not find cell {} specified in plot {}", col_id, id_)); } } else if (PlotColorBy::mats == color_by_) { if (model::material_map.find(col_id) != model::material_map.end()) { @@ -427,8 +426,7 @@ Plot::set_user_colors(pugi::xml_node plot_node) } // color node loop } -void -Plot::set_meshlines(pugi::xml_node plot_node) +void Plot::set_meshlines(pugi::xml_node plot_node) { // Deal with meshlines pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines"); @@ -448,7 +446,8 @@ Plot::set_meshlines(pugi::xml_node plot_node) meshtype = get_node_value(meshlines_node, "meshtype"); } else { fatal_error(fmt::format( - "Must specify a meshtype for meshlines specification in plot {}", id_)); + "Must specify a meshtype for meshlines specification in plot {}", + id_)); } // Ensure that there is a linewidth for this meshlines specification @@ -458,7 +457,8 @@ Plot::set_meshlines(pugi::xml_node plot_node) meshlines_width_ = std::stoi(meshline_width); } else { fatal_error(fmt::format( - "Must specify a linewidth for meshlines specification in plot {}", id_)); + "Must specify a linewidth for meshlines specification in plot {}", + id_)); } // Check for color @@ -466,7 +466,8 @@ Plot::set_meshlines(pugi::xml_node plot_node) // Check and make sure 3 values are specified for RGB vector ml_rgb = get_node_array(meshlines_node, "color"); if (ml_rgb.size() != 3) { - fatal_error(fmt::format("Bad RGB for meshlines color in plot {}", id_)); + fatal_error( + fmt::format("Bad RGB for meshlines color in plot {}", id_)); } meshlines_color_ = ml_rgb; } @@ -477,8 +478,8 @@ Plot::set_meshlines(pugi::xml_node plot_node) fatal_error(fmt::format("No UFS mesh for meshlines on plot {}", id_)); } else { for (int i = 0; i < model::meshes.size(); ++i) { - if (const auto* m - = dynamic_cast(model::meshes[i].get())) { + if (const auto* m = + dynamic_cast(model::meshes[i].get())) { if (m == simulation::ufs_mesh) { index_meshlines_mesh_ = i; } @@ -489,11 +490,12 @@ Plot::set_meshlines(pugi::xml_node plot_node) } } else if ("entropy" == meshtype) { if (!simulation::entropy_mesh) { - fatal_error(fmt::format("No entropy mesh for meshlines on plot {}", id_)); + fatal_error( + fmt::format("No entropy mesh for meshlines on plot {}", id_)); } else { for (int i = 0; i < model::meshes.size(); ++i) { - if (const auto* m - = dynamic_cast(model::meshes[i].get())) { + if (const auto* m = + dynamic_cast(model::meshes[i].get())) { if (m == simulation::entropy_mesh) { index_meshlines_mesh_ = i; } @@ -510,18 +512,20 @@ Plot::set_meshlines(pugi::xml_node plot_node) } else { std::stringstream err_msg; fatal_error(fmt::format("Must specify a mesh id for meshlines tally " - "mesh specification in plot {}", id_)); + "mesh specification in plot {}", + id_)); } // find the tally index int idx; int err = openmc_get_mesh_index(tally_mesh_id, &idx); if (err != 0) { fatal_error(fmt::format("Could not find mesh {} specified in " - "meshlines for plot {}", tally_mesh_id, id_)); + "meshlines for plot {}", + tally_mesh_id, id_)); } index_meshlines_mesh_ = idx; } else { - fatal_error(fmt::format("Invalid type for meshlines on plot {}", id_ )); + fatal_error(fmt::format("Invalid type for meshlines on plot {}", id_)); } } else { fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id_)); @@ -529,8 +533,7 @@ Plot::set_meshlines(pugi::xml_node plot_node) } } -void -Plot::set_mask(pugi::xml_node plot_node) +void Plot::set_mask(pugi::xml_node plot_node) { // Deal with masks pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask"); @@ -549,7 +552,8 @@ Plot::set_mask(pugi::xml_node plot_node) // Determine how many components there are and allocate vector iarray = get_node_array(mask_node, "components"); if (iarray.size() == 0) { - fatal_error(fmt::format("Missing in mask of plot {}", id_)); + fatal_error( + fmt::format("Missing in mask of plot {}", id_)); } // First we need to change the user-specified identifiers to indices @@ -557,19 +561,19 @@ Plot::set_mask(pugi::xml_node plot_node) for (auto& col_id : iarray) { if (PlotColorBy::cells == color_by_) { if (model::cell_map.find(col_id) != model::cell_map.end()) { - col_id = model::cell_map[col_id]; - } - else { + col_id = model::cell_map[col_id]; + } else { fatal_error(fmt::format("Could not find cell {} specified in the " - "mask in plot {}", col_id, id_)); + "mask in plot {}", + col_id, id_)); } } else if (PlotColorBy::mats == color_by_) { if (model::material_map.find(col_id) != model::material_map.end()) { col_id = model::material_map[col_id]; - } - else { + } else { fatal_error(fmt::format("Could not find material {} specified in " - "the mask in plot {}", col_id, id_)); + "the mask in plot {}", + col_id, id_)); } } } @@ -592,7 +596,8 @@ Plot::set_mask(pugi::xml_node plot_node) } } -void Plot::set_overlap_color(pugi::xml_node plot_node) { +void Plot::set_overlap_color(pugi::xml_node plot_node) +{ color_overlaps_ = false; if (check_for_node(plot_node, "show_overlaps")) { color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps"); @@ -600,7 +605,8 @@ void Plot::set_overlap_color(pugi::xml_node plot_node) { if (check_for_node(plot_node, "overlap_color")) { if (!color_overlaps_) { warning(fmt::format( - "Overlap color specified in plot {} but overlaps won't be shown.", id_)); + "Overlap color specified in plot {} but overlaps won't be shown.", + id_)); } vector olap_clr = get_node_array(plot_node, "overlap_color"); if (olap_clr.size() == 3) { @@ -620,7 +626,7 @@ void Plot::set_overlap_color(pugi::xml_node plot_node) { } Plot::Plot(pugi::xml_node plot_node) - : index_meshlines_mesh_{-1}, overlap_color_{RED} + : index_meshlines_mesh_ {-1}, overlap_color_ {RED} { set_id(plot_node); set_type(plot_node); @@ -660,7 +666,7 @@ void output_ppm(Plot const& pl, const ImageData& data) // Write color for each pixel for (int y = 0; y < pl.pixels_[1]; y++) { for (int x = 0; x < pl.pixels_[0]; x++) { - RGBColor rgb = data(x,y); + RGBColor rgb = data(x, y); of << rgb.red << rgb.green << rgb.blue; } } @@ -677,16 +683,16 @@ void draw_mesh_lines(Plot const& pl, ImageData& data) rgb = pl.meshlines_color_; int ax1, ax2; - switch(pl.basis_) { - case PlotBasis::xy : + switch (pl.basis_) { + case PlotBasis::xy: ax1 = 0; ax2 = 1; break; - case PlotBasis::xz : + case PlotBasis::xz: ax1 = 0; ax2 = 2; break; - case PlotBasis::yz : + case PlotBasis::yz: ax1 = 1; ax2 = 2; break; @@ -705,18 +711,20 @@ void draw_mesh_lines(Plot const& pl, ImageData& data) Position width = ur_plot - ll_plot; // Find the (axis-aligned) lines of the mesh that intersect this plot. - auto axis_lines = model::meshes[pl.index_meshlines_mesh_] - ->plot(ll_plot, ur_plot); + auto axis_lines = + model::meshes[pl.index_meshlines_mesh_]->plot(ll_plot, ur_plot); // Find the bounds along the second axis (accounting for low-D meshes). int ax2_min, ax2_max; if (axis_lines.second.size() > 0) { double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2]; ax2_min = (1.0 - frac) * pl.pixels_[1]; - if (ax2_min < 0) ax2_min = 0; + if (ax2_min < 0) + ax2_min = 0; frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2]; ax2_max = (1.0 - frac) * pl.pixels_[1]; - if (ax2_max > pl.pixels_[1]) ax2_max = pl.pixels_[1]; + if (ax2_max > pl.pixels_[1]) + ax2_max = pl.pixels_[1]; } else { ax2_min = 0; ax2_max = pl.pixels_[1]; @@ -728,10 +736,10 @@ void draw_mesh_lines(Plot const& pl, ImageData& data) int ax1_ind = frac * pl.pixels_[0]; for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) { for (int plus = 0; plus <= pl.meshlines_width_; plus++) { - if (ax1_ind+plus >= 0 && ax1_ind+plus < pl.pixels_[0]) - data(ax1_ind+plus, ax2_ind) = rgb; - if (ax1_ind-plus >= 0 && ax1_ind-plus < pl.pixels_[0]) - data(ax1_ind-plus, ax2_ind) = rgb; + if (ax1_ind + plus >= 0 && ax1_ind + plus < pl.pixels_[0]) + data(ax1_ind + plus, ax2_ind) = rgb; + if (ax1_ind - plus >= 0 && ax1_ind - plus < pl.pixels_[0]) + data(ax1_ind - plus, ax2_ind) = rgb; } } } @@ -741,10 +749,12 @@ void draw_mesh_lines(Plot const& pl, ImageData& data) if (axis_lines.first.size() > 0) { double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1]; ax1_min = frac * pl.pixels_[0]; - if (ax1_min < 0) ax1_min = 0; + if (ax1_min < 0) + ax1_min = 0; frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1]; ax1_max = frac * pl.pixels_[0]; - if (ax1_max > pl.pixels_[0]) ax1_max = pl.pixels_[0]; + if (ax1_max > pl.pixels_[0]) + ax1_max = pl.pixels_[0]; } else { ax1_min = 0; ax1_max = pl.pixels_[0]; @@ -756,10 +766,10 @@ void draw_mesh_lines(Plot const& pl, ImageData& data) int ax2_ind = (1.0 - frac) * pl.pixels_[1]; for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) { for (int plus = 0; plus <= pl.meshlines_width_; plus++) { - if (ax2_ind+plus >= 0 && ax2_ind+plus < pl.pixels_[1]) - data(ax1_ind, ax2_ind+plus) = rgb; - if (ax2_ind-plus >= 0 && ax2_ind-plus < pl.pixels_[1]) - data(ax1_ind, ax2_ind-plus) = rgb; + if (ax2_ind + plus >= 0 && ax2_ind + plus < pl.pixels_[1]) + data(ax1_ind, ax2_ind + plus) = rgb; + if (ax2_ind - plus >= 0 && ax2_ind - plus < pl.pixels_[1]) + data(ax1_ind, ax2_ind - plus) = rgb; } } } @@ -782,9 +792,9 @@ void create_voxel(Plot const& pl) { // compute voxel widths in each direction array vox; - vox[0] = pl.width_[0]/(double)pl.pixels_[0]; - vox[1] = pl.width_[1]/(double)pl.pixels_[1]; - vox[2] = pl.width_[2]/(double)pl.pixels_[2]; + vox[0] = pl.width_[0] / (double)pl.pixels_[0]; + vox[1] = pl.width_[1] / (double)pl.pixels_[1]; + vox[2] = pl.width_[2] / (double)pl.pixels_[2]; // initial particle position Position ll = pl.origin_ - pl.width_ / 2.; @@ -832,7 +842,7 @@ void create_voxel(Plot const& pl) ProgressBar pb; for (int z = 0; z < pl.pixels_[2]; z++) { // update progress bar - pb.set_value(100.*(double)z/(double)(pl.pixels_[2]-1)); + pb.set_value(100. * (double)z / (double)(pl.pixels_[2] - 1)); // update z coordinate pltbase.origin_.z = ll.z + z * vox[2]; @@ -842,7 +852,8 @@ void create_voxel(Plot const& pl) // select only cell/material ID data and flip the y-axis int idx = pl.color_by_ == PlotColorBy::cells ? 0 : 2; - xt::xtensor data_slice = xt::view(ids.data_, xt::all(), xt::all(), idx); + xt::xtensor data_slice = + xt::view(ids.data_, xt::all(), xt::all(), idx); xt::xtensor data_flipped = xt::flip(data_slice, 0); // Write to HDF5 dataset @@ -853,14 +864,13 @@ void create_voxel(Plot const& pl) file_close(file_id); } -void -voxel_init(hid_t file_id, const hsize_t* dims, - hid_t* dspace, hid_t* dset, hid_t* memspace) +void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset, + hid_t* memspace) { // Create dataspace/dataset for voxel data *dspace = H5Screate_simple(3, dims, nullptr); *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT, - H5P_DEFAULT, H5P_DEFAULT); + H5P_DEFAULT, H5P_DEFAULT); // Create dataspace for a slice of the voxel hsize_t dims_slice[2] {dims[1], dims[2]}; @@ -872,28 +882,25 @@ voxel_init(hid_t file_id, const hsize_t* dims, H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr); } - -void -voxel_write_slice(int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf) +void voxel_write_slice( + int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf) { hssize_t offset[3] {x, 0, 0}; H5Soffset_simple(dspace, offset); H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf); } - -void -voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace) +void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace) { H5Dclose(dset); H5Sclose(dspace); H5Sclose(memspace); } -RGBColor random_color(void) { - return {int(prn(&model::plotter_seed)*255), - int(prn(&model::plotter_seed)*255), - int(prn(&model::plotter_seed)*255)}; +RGBColor random_color(void) +{ + return {int(prn(&model::plotter_seed) * 255), + int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)}; } extern "C" int openmc_id_map(const void* plot, int32_t* data_out) @@ -917,7 +924,8 @@ extern "C" int openmc_id_map(const void* plot, int32_t* data_out) return 0; } -extern "C" int openmc_property_map(const void* plot, double* data_out) { +extern "C" int openmc_property_map(const void* plot, double* data_out) +{ auto plt = reinterpret_cast(plot); if (!plt) { @@ -937,5 +945,4 @@ extern "C" int openmc_property_map(const void* plot, double* data_out) { return 0; } - } // namespace openmc diff --git a/src/position.cpp b/src/position.cpp index 46611df99..5b3613b28 100644 --- a/src/position.cpp +++ b/src/position.cpp @@ -6,8 +6,7 @@ namespace openmc { // Position implementation //============================================================================== -Position& -Position::operator+=(Position other) +Position& Position::operator+=(Position other) { x += other.x; y += other.y; @@ -15,8 +14,7 @@ Position::operator+=(Position other) return *this; } -Position& -Position::operator+=(double v) +Position& Position::operator+=(double v) { x += v; y += v; @@ -24,8 +22,7 @@ Position::operator+=(double v) return *this; } -Position& -Position::operator-=(Position other) +Position& Position::operator-=(Position other) { x -= other.x; y -= other.y; @@ -33,8 +30,7 @@ Position::operator-=(Position other) return *this; } -Position& -Position::operator-=(double v) +Position& Position::operator-=(double v) { x -= v; y -= v; @@ -42,8 +38,7 @@ Position::operator-=(double v) return *this; } -Position& -Position::operator*=(Position other) +Position& Position::operator*=(Position other) { x *= other.x; y *= other.y; @@ -51,8 +46,7 @@ Position::operator*=(Position other) return *this; } -Position& -Position::operator*=(double v) +Position& Position::operator*=(double v) { x *= v; y *= v; @@ -60,8 +54,7 @@ Position::operator*=(double v) return *this; } -Position& -Position::operator/=(Position other) +Position& Position::operator/=(Position other) { x /= other.x; y /= other.y; @@ -69,8 +62,7 @@ Position::operator/=(Position other) return *this; } -Position& -Position::operator/=(double v) +Position& Position::operator/=(double v) { x /= v; y /= v; @@ -78,23 +70,19 @@ Position::operator/=(double v) return *this; } -Position -Position::operator-() const +Position Position::operator-() const { return {-x, -y, -z}; } Position Position::rotate(const vector& rotation) const { - return { - x*rotation[0] + y*rotation[1] + z*rotation[2], - x*rotation[3] + y*rotation[4] + z*rotation[5], - x*rotation[6] + y*rotation[7] + z*rotation[8] - }; + return {x * rotation[0] + y * rotation[1] + z * rotation[2], + x * rotation[3] + y * rotation[4] + z * rotation[5], + x * rotation[6] + y * rotation[7] + z * rotation[8]}; } -std::ostream& -operator<<(std::ostream& os, Position r) +std::ostream& operator<<(std::ostream& os, Position r) { os << "(" << r.x << ", " << r.y << ", " << r.z << ")"; return os; diff --git a/src/progress_bar.cpp b/src/progress_bar.cpp index ab77c72f9..538b50b87 100644 --- a/src/progress_bar.cpp +++ b/src/progress_bar.cpp @@ -1,17 +1,19 @@ #include "openmc/progress_bar.h" -#include -#include #include +#include +#include -#if defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) +#if defined(__unix__) || defined(__unix) || \ + (defined(__APPLE__) && defined(__MACH__)) #include #endif #define BAR_WIDTH 72 -bool is_terminal() { +bool is_terminal() +{ #ifdef _POSIX_VERSION return isatty(STDOUT_FILENO) != 0; #else @@ -19,15 +21,17 @@ bool is_terminal() { #endif } -ProgressBar::ProgressBar() { +ProgressBar::ProgressBar() +{ // initialize bar set_value(0.0); } -void -ProgressBar::set_value(double val) { +void ProgressBar::set_value(double val) +{ - if (!is_terminal()) return; + if (!is_terminal()) + return; // set the bar percentage if (val >= 100.0) { @@ -50,17 +54,19 @@ ProgressBar::set_value(double val) { } else if (val < 0.0) { bar.append(remaining_width, ' '); } else { - int width = (int)((double)remaining_width*val/100); + int width = (int)((double)remaining_width * val / 100); bar.append(width, '='); bar.append(1, '>'); - bar.append(remaining_width-width-1, ' '); + bar.append(remaining_width - width - 1, ' '); } bar.append("|+"); // write the bar std::cout << '\r' << bar << std::flush; - if (val >= 100.0) { std::cout << "\n"; } + if (val >= 100.0) { + std::cout << "\n"; + } // reset the bar value bar = ""; diff --git a/src/random_lcg.cpp b/src/random_lcg.cpp index 38174be65..581d69617 100644 --- a/src/random_lcg.cpp +++ b/src/random_lcg.cpp @@ -2,26 +2,25 @@ #include - namespace openmc { // Starting seed int64_t master_seed {1}; // LCG parameters -constexpr uint64_t prn_mult {6364136223846793005ULL}; // multiplication -constexpr uint64_t prn_add {1442695040888963407ULL}; // additive factor, c -constexpr uint64_t prn_stride {152917LL}; // stride between particles +constexpr uint64_t prn_mult {6364136223846793005ULL}; // multiplication +constexpr uint64_t prn_add {1442695040888963407ULL}; // additive factor, c +constexpr uint64_t prn_stride {152917LL}; // stride between particles //============================================================================== // PRN //============================================================================== -// 64 bit implementation of the PCG-RXS-M-XS 64-bit state / 64-bit output geneator -// Adapted from: https://github.com/imneme/pcg-c +// 64 bit implementation of the PCG-RXS-M-XS 64-bit state / 64-bit output +// geneator Adapted from: https://github.com/imneme/pcg-c // @techreport{oneill:pcg2014, -// title = "PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation", -// author = "Melissa E. O'Neill", +// title = "PCG: A Family of Simple Fast Space-Efficient Statistically Good +// Algorithms for Random Number Generation", author = "Melissa E. O'Neill", // institution = "Harvey Mudd College", // address = "Claremont, CA", // number = "HMC-CS-2014-0905", @@ -35,7 +34,8 @@ double prn(uint64_t* seed) *seed = (prn_mult * (*seed) + prn_add); // Permute the output - uint64_t word = ((*seed >> ((*seed >> 59u) + 5u)) ^ *seed) * 12605985483714917081ull; + uint64_t word = + ((*seed >> ((*seed >> 59u) + 5u)) ^ *seed) * 12605985483714917081ull; uint64_t result = (word >> 43u) ^ word; // Convert output from unsigned integer to double @@ -58,7 +58,8 @@ double future_prn(int64_t n, uint64_t seed) uint64_t init_seed(int64_t id, int offset) { - return future_seed(static_cast(id) * prn_stride, master_seed + offset); + return future_seed( + static_cast(id) * prn_stride, master_seed + offset); } //============================================================================== @@ -68,7 +69,8 @@ uint64_t init_seed(int64_t id, int offset) void init_particle_seeds(int64_t id, uint64_t* seeds) { for (int i = 0; i < N_STREAMS; i++) { - seeds[i] = future_seed(static_cast(id) * prn_stride, master_seed + i); + seeds[i] = + future_seed(static_cast(id) * prn_stride, master_seed + i); } } @@ -94,8 +96,8 @@ uint64_t future_seed(uint64_t n, uint64_t seed) // and C which can then be used to find x_N = G*x_0 + C mod 2^M. // Initialize constants - uint64_t g {prn_mult}; - uint64_t c {prn_add}; + uint64_t g {prn_mult}; + uint64_t c {prn_add}; uint64_t g_new {1}; uint64_t c_new {0}; @@ -120,7 +122,10 @@ uint64_t future_seed(uint64_t n, uint64_t seed) // API FUNCTIONS //============================================================================== -extern "C" int64_t openmc_get_seed() {return master_seed;} +extern "C" int64_t openmc_get_seed() +{ + return master_seed; +} extern "C" void openmc_set_seed(int64_t new_seed) { diff --git a/src/reaction.cpp b/src/reaction.cpp index ddb82a224..c929677f2 100644 --- a/src/reaction.cpp +++ b/src/reaction.cpp @@ -7,8 +7,8 @@ #include #include "openmc/constants.h" -#include "openmc/hdf5_interface.h" #include "openmc/endf.h" +#include "openmc/hdf5_interface.h" #include "openmc/random_lcg.h" #include "openmc/search.h" #include "openmc/secondary_uncorrelated.h" @@ -80,7 +80,8 @@ double Reaction::collapse_rate(gsl::index i_temp, i_low = i_threshold; while (energy[j_start + 1] < grid[i_low]) { ++j_start; - if (j_start + 1 == energy.size()) return 0.0; + if (j_start + 1 == energy.size()) + return 0.0; } } @@ -93,14 +94,16 @@ double Reaction::collapse_rate(gsl::index i_temp, // Determine energy grid index corresponding to group high int i_high = i_low; - while (grid[i_high + 1] < E_group_high && i_high + 1 < grid.size() - 1) ++i_high; + while (grid[i_high + 1] < E_group_high && i_high + 1 < grid.size() - 1) + ++i_high; // Loop over energy grid points within [E_group_low, E_group_high] for (; i_low <= i_high; ++i_low) { // Determine bounding grid energies and cross sections double E_l = grid[i_low]; double E_r = grid[i_low + 1]; - if (E_l == E_r) continue; + if (E_l == E_r) + continue; double xs_l = xs[i_low - i_threshold]; double xs_r = xs[i_low + 1 - i_threshold]; @@ -111,9 +114,9 @@ double Reaction::collapse_rate(gsl::index i_temp, // Determine average cross section across segment double m = (xs_r - xs_l) / (E_r - E_l); - double xs_low = xs_l + m*(E_low - E_l); - double xs_high = xs_l + m*(E_high - E_l); - double xs_avg = 0.5*(xs_low + xs_high); + double xs_low = xs_l + m * (E_low - E_l); + double xs_high = xs_l + m * (E_high - E_l); + double xs_avg = 0.5 * (xs_low + xs_high); // Add contribution from segment double dE = (E_high - E_low); @@ -123,7 +126,8 @@ double Reaction::collapse_rate(gsl::index i_temp, i_low = i_high; // Check for end of energy grid - if (i_low + 1 == grid.size()) break; + if (i_low + 1 == grid.size()) + break; } return xs_flux_sum; @@ -290,8 +294,8 @@ void initialize_maps() // Create photoelectric subshells for (int mt = 534; mt <= 572; ++mt) { - REACTION_NAME_MAP[mt] = fmt::format("photoelectric, {} subshell", - SUBSHELLS[mt - 534]); + REACTION_NAME_MAP[mt] = + fmt::format("photoelectric, {} subshell", SUBSHELLS[mt - 534]); } // Invert name map to create type map @@ -303,7 +307,8 @@ void initialize_maps() std::string reaction_name(int mt) { // Initialize remainder of name map and all of type map - if (REACTION_TYPE_MAP.empty()) initialize_maps(); + if (REACTION_TYPE_MAP.empty()) + initialize_maps(); // Get reaction name from map auto it = REACTION_NAME_MAP.find(mt); @@ -317,11 +322,13 @@ std::string reaction_name(int mt) int reaction_type(std::string name) { // Initialize remainder of name map and all of type map - if (REACTION_TYPE_MAP.empty()) initialize_maps(); + if (REACTION_TYPE_MAP.empty()) + initialize_maps(); // (n,total) exists in REACTION_TYPE_MAP for MT=1, but we need this to return // the special SCORE_TOTAL score - if (name == "(n,total)") return SCORE_TOTAL; + if (name == "(n,total)") + return SCORE_TOTAL; // Check if type map has an entry for this reaction name auto it = REACTION_TYPE_MAP.find(name); @@ -356,12 +363,18 @@ int reaction_type(std::string name) try { MT = std::stoi(name); } catch (const std::invalid_argument& ex) { - throw std::invalid_argument("Invalid tally score \"" + name + "\". See the docs " - "for details: https://docs.openmc.org/en/stable/usersguide/tallies.html#scores"); + throw std::invalid_argument( + "Invalid tally score \"" + name + + "\". See the docs " + "for details: " + "https://docs.openmc.org/en/stable/usersguide/tallies.html#scores"); } if (MT < 1) - throw std::invalid_argument("Invalid tally score \"" + name + "\". See the docs " - "for details: https://docs.openmc.org/en/stable/usersguide/tallies.html#scores"); + throw std::invalid_argument( + "Invalid tally score \"" + name + + "\". See the docs " + "for details: " + "https://docs.openmc.org/en/stable/usersguide/tallies.html#scores"); return MT; } diff --git a/src/reaction_product.cpp b/src/reaction_product.cpp index f73f63335..4cef8d3a9 100644 --- a/src/reaction_product.cpp +++ b/src/reaction_product.cpp @@ -44,7 +44,8 @@ ReactionProduct::ReactionProduct(hid_t group) read_attribute(group, "decay_rate", decay_rate_); } else if (particle_ == ParticleType::neutron) { warning(fmt::format("Decay rate doesn't exist for delayed neutron " - "emission ({}).", object_name(group))); + "emission ({}).", + object_name(group))); } } @@ -82,8 +83,8 @@ ReactionProduct::ReactionProduct(hid_t group) } } -void ReactionProduct::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void ReactionProduct::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { auto n = applicability_.size(); if (n > 1) { @@ -105,4 +106,4 @@ void ReactionProduct::sample(double E_in, double& E_out, double& mu, } } -} +} // namespace openmc diff --git a/src/scattdata.cpp b/src/scattdata.cpp index a0341b153..2fb896de0 100644 --- a/src/scattdata.cpp +++ b/src/scattdata.cpp @@ -1,8 +1,8 @@ #include "openmc/scattdata.h" #include -#include #include +#include #include "xtensor/xbuilder.hpp" #include "xtensor/xview.hpp" @@ -19,10 +19,9 @@ namespace openmc { // ScattData base-class methods //============================================================================== -void -ScattData::base_init(int order, const xt::xtensor& in_gmin, - const xt::xtensor& in_gmax, const double_2dvec& in_energy, - const double_2dvec& in_mult) +void ScattData::base_init(int order, const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_energy, + const double_2dvec& in_mult) { size_t groups = in_energy.size(); @@ -48,8 +47,9 @@ ScattData::base_init(int order, const xt::xtensor& in_gmin, if (num_converted > 0) { // Raise a warning to the user if we did have to do the conversion - std::string msg = std::to_string(num_converted) + - "entries in the Multiplicity Matrix were changed from 0 to 1"; + std::string msg = + std::to_string(num_converted) + + "entries in the Multiplicity Matrix were changed from 0 to 1"; warning(msg); } @@ -57,7 +57,8 @@ ScattData::base_init(int order, const xt::xtensor& in_gmin, double norm = std::accumulate(energy[gin].begin(), energy[gin].end(), 0.); if (norm != 0.) { - for (auto& n : energy[gin]) n /= norm; + for (auto& n : energy[gin]) + n /= norm; } // Initialize the distribution data @@ -75,7 +76,7 @@ void ScattData::base_combine(size_t max_order, size_t order_dim, xt::xtensor& in_gmin, xt::xtensor& in_gmax, double_2dvec& sparse_mult, double_3dvec& sparse_scatter) { - size_t groups = those_scatts[0] -> energy.size(); + size_t groups = those_scatts[0]->energy.size(); // Now allocate and zero our storage spaces xt::xtensor this_nuscatt_matrix({groups, groups, order_dim}, 0.); @@ -97,10 +98,9 @@ void ScattData::base_combine(size_t max_order, size_t order_dim, for (int gin = 0; gin < groups; gin++) { for (int go = 0; go < groups; go++) { this_nuscatt_P0(gin, go) += - scalars[i] * that->get_xs(MgxsType::NU_SCATTER, gin, &go, nullptr); + scalars[i] * that->get_xs(MgxsType::NU_SCATTER, gin, &go, nullptr); this_scatt_P0(gin, go) += - scalars[i] * - that->get_xs(MgxsType::SCATTER, gin, &go, nullptr); + scalars[i] * that->get_xs(MgxsType::SCATTER, gin, &go, nullptr); } } } @@ -122,7 +122,8 @@ void ScattData::base_combine(size_t max_order, size_t order_dim, break; } } - if (non_zero) break; + if (non_zero) + break; } int gmax_; for (gmax_ = groups - 1; gmax_ >= 0; gmax_--) { @@ -133,7 +134,8 @@ void ScattData::base_combine(size_t max_order, size_t order_dim, break; } } - if (non_zero) break; + if (non_zero) + break; } // treat the case of all values being 0 @@ -161,11 +163,9 @@ void ScattData::base_combine(size_t max_order, size_t order_dim, } } - //============================================================================== -void -ScattData::sample_energy(int gin, int& gout, int& i_gout, uint64_t* seed) +void ScattData::sample_energy(int gin, int& gout, int& i_gout, uint64_t* seed) { // Sample the outgoing group double xi = prn(seed); @@ -173,15 +173,16 @@ ScattData::sample_energy(int gin, int& gout, int& i_gout, uint64_t* seed) i_gout = 0; for (gout = gmin[gin]; gout < gmax[gin]; ++gout) { prob += energy[gin][i_gout]; - if (xi < prob) break; + if (xi < prob) + break; ++i_gout; } } //============================================================================== -double -ScattData::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu) +double ScattData::get_xs( + MgxsType xstype, int gin, const int* gout, const double* mu) { // Set the outgoing group offset index as needed int i_gout = 0; @@ -195,16 +196,17 @@ ScattData::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu) } double val = scattxs[gin]; - switch(xstype) { + switch (xstype) { case MgxsType::NU_SCATTER: - if (gout != nullptr) val *= energy[gin][i_gout]; + if (gout != nullptr) + val *= energy[gin][i_gout]; break; case MgxsType::SCATTER: if (gout != nullptr) { val *= energy[gin][i_gout] / mult[gin][i_gout]; } else { - val /= std::inner_product(mult[gin].begin(), mult[gin].end(), - energy[gin].begin(), 0.0); + val /= std::inner_product( + mult[gin].begin(), mult[gin].end(), energy[gin].begin(), 0.0); } break; case MgxsType::NU_SCATTER_FMU: @@ -235,10 +237,9 @@ ScattData::get_xs(MgxsType xstype, int gin, const int* gout, const double* mu) // ScattDataLegendre methods //============================================================================== -void -ScattDataLegendre::init(const xt::xtensor& in_gmin, - const xt::xtensor& in_gmax, const double_2dvec& in_mult, - const double_3dvec& coeffs) +void ScattDataLegendre::init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs) { size_t groups = coeffs.size(); size_t order = coeffs[0][0].size(); @@ -268,7 +269,8 @@ ScattDataLegendre::init(const xt::xtensor& in_gmin, double norm = matrix[gin][i_gout][0]; in_energy[gin][i_gout] = norm; if (norm != 0.) { - for (auto& n : matrix[gin][i_gout]) n /= norm; + for (auto& n : matrix[gin][i_gout]) + n /= norm; } } } @@ -284,7 +286,8 @@ ScattDataLegendre::init(const xt::xtensor& in_gmin, dist[gin][i_gout] = matrix[gin][i_gout]; } max_val[gin].resize(num_groups); - for (auto& n : max_val[gin]) n = 0.; + for (auto& n : max_val[gin]) + n = 0.; } // Now update the maximum value @@ -293,8 +296,7 @@ ScattDataLegendre::init(const xt::xtensor& in_gmin, //============================================================================== -void -ScattDataLegendre::update_max_val() +void ScattDataLegendre::update_max_val() { size_t groups = max_val.size(); // Step through the polynomial with fixed number of points to identify the @@ -315,11 +317,12 @@ ScattDataLegendre::update_max_val() } // Calculate probability - double f = evaluate_legendre(dist[gin][i_gout].size() - 1, - dist[gin][i_gout].data(), mu); + double f = evaluate_legendre( + dist[gin][i_gout].size() - 1, dist[gin][i_gout].data(), mu); // if this is a new maximum, store it - if (f > max_val[gin][i_gout]) max_val[gin][i_gout] = f; + if (f > max_val[gin][i_gout]) + max_val[gin][i_gout] = f; } // end imu loop // Since we may not have caught the true max, add 10% margin @@ -330,25 +333,23 @@ ScattDataLegendre::update_max_val() //============================================================================== -double -ScattDataLegendre::calc_f(int gin, int gout, double mu) +double ScattDataLegendre::calc_f(int gin, int gout, double mu) { double f; if ((gout < gmin[gin]) || (gout > gmax[gin])) { f = 0.; } else { int i_gout = gout - gmin[gin]; - f = evaluate_legendre(dist[gin][i_gout].size() - 1, - dist[gin][i_gout].data(), mu); + f = evaluate_legendre( + dist[gin][i_gout].size() - 1, dist[gin][i_gout].data(), mu); } return f; } //============================================================================== -void -ScattDataLegendre::sample(int gin, int& gout, double& mu, double& wgt, - uint64_t* seed) +void ScattDataLegendre::sample( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed) { // Sample the outgoing energy using the base-class method int i_gout; @@ -363,7 +364,8 @@ ScattDataLegendre::sample(int gin, int& gout, double& mu, double& wgt, double f = calc_f(gin, gout, mu); if (f > 0.) { double u = prn(seed) * M; - if (u <= f) break; + if (u <= f) + break; } } if (samples == MAX_SAMPLE) { @@ -388,10 +390,11 @@ void ScattDataLegendre::combine( fatal_error("Cannot combine the ScattData objects!"); } size_t that_order = that->get_order(); - if (that_order > max_order) max_order = that_order; + if (that_order > max_order) + max_order = that_order; } - size_t groups = those_scatts[0] -> energy.size(); + size_t groups = those_scatts[0]->energy.size(); xt::xtensor in_gmin({groups}, 0); xt::xtensor in_gmax({groups}, 0); @@ -403,7 +406,7 @@ void ScattDataLegendre::combine( // matrices size_t order_dim = max_order + 1; ScattData::base_combine(max_order, order_dim, those_scatts, scalars, in_gmin, - in_gmax, sparse_mult, sparse_scatter); + in_gmax, sparse_mult, sparse_scatter); // Got everything we need, store it. init(in_gmin, in_gmax, sparse_mult, sparse_scatter); @@ -411,8 +414,7 @@ void ScattDataLegendre::combine( //============================================================================== -xt::xtensor -ScattDataLegendre::get_matrix(size_t max_order) +xt::xtensor ScattDataLegendre::get_matrix(size_t max_order) { // Get the sizes and initialize the data to 0 size_t groups = energy.size(); @@ -423,8 +425,8 @@ ScattDataLegendre::get_matrix(size_t max_order) for (int i_gout = 0; i_gout < energy[gin].size(); i_gout++) { int gout = i_gout + gmin[gin]; for (int l = 0; l < order_dim; l++) { - matrix(gin, gout, l) = scattxs[gin] * energy[gin][i_gout] * - dist[gin][i_gout][l]; + matrix(gin, gout, l) = + scattxs[gin] * energy[gin][i_gout] * dist[gin][i_gout][l]; } } } @@ -435,10 +437,9 @@ ScattDataLegendre::get_matrix(size_t max_order) // ScattDataHistogram methods //============================================================================== -void -ScattDataHistogram::init(const xt::xtensor& in_gmin, - const xt::xtensor& in_gmax, const double_2dvec& in_mult, - const double_3dvec& coeffs) +void ScattDataHistogram::init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs) { size_t groups = coeffs.size(); size_t order = coeffs[0][0].size(); @@ -451,8 +452,8 @@ ScattDataHistogram::init(const xt::xtensor& in_gmin, scattxs = xt::zeros({groups}); for (int gin = 0; gin < groups; gin++) { for (int i_gout = 0; i_gout < matrix[gin].size(); i_gout++) { - scattxs[gin] += std::accumulate(matrix[gin][i_gout].begin(), - matrix[gin][i_gout].end(), 0.); + scattxs[gin] += std::accumulate( + matrix[gin][i_gout].begin(), matrix[gin][i_gout].end(), 0.); } } @@ -463,11 +464,12 @@ ScattDataHistogram::init(const xt::xtensor& in_gmin, int num_groups = in_gmax[gin] - in_gmin[gin] + 1; in_energy[gin].resize(num_groups); for (int i_gout = 0; i_gout < num_groups; i_gout++) { - double norm = std::accumulate(matrix[gin][i_gout].begin(), - matrix[gin][i_gout].end(), 0.); + double norm = std::accumulate( + matrix[gin][i_gout].begin(), matrix[gin][i_gout].end(), 0.); in_energy[gin][i_gout] = norm; if (norm != 0.) { - for (auto& n : matrix[gin][i_gout]) n /= norm; + for (auto& n : matrix[gin][i_gout]) + n /= norm; } } } @@ -492,8 +494,8 @@ ScattDataHistogram::init(const xt::xtensor& in_gmin, // Integrate the histogram dist[gin][i_gout][0] = dmu * matrix[gin][i_gout][0]; for (int imu = 1; imu < order; imu++) { - dist[gin][i_gout][imu] = dmu * matrix[gin][i_gout][imu] + - dist[gin][i_gout][imu - 1]; + dist[gin][i_gout][imu] = + dmu * matrix[gin][i_gout][imu] + dist[gin][i_gout][imu - 1]; } // Now re-normalize for integral to unity @@ -510,8 +512,7 @@ ScattDataHistogram::init(const xt::xtensor& in_gmin, //============================================================================== -double -ScattDataHistogram::calc_f(int gin, int gout, double mu) +double ScattDataHistogram::calc_f(int gin, int gout, double mu) { double f; if ((gout < gmin[gin]) || (gout > gmax[gin])) { @@ -534,9 +535,8 @@ ScattDataHistogram::calc_f(int gin, int gout, double mu) //============================================================================== -void -ScattDataHistogram::sample(int gin, int& gout, double& mu, double& wgt, - uint64_t* seed) +void ScattDataHistogram::sample( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed) { // Sample the outgoing energy using the base-class method int i_gout; @@ -549,9 +549,9 @@ ScattDataHistogram::sample(int gin, int& gout, double& mu, double& wgt, if (xi < dist[gin][i_gout][0]) { imu = 0; } else { - imu = std::upper_bound(dist[gin][i_gout].begin(), - dist[gin][i_gout].end(), xi) - - dist[gin][i_gout].begin(); + imu = + std::upper_bound(dist[gin][i_gout].begin(), dist[gin][i_gout].end(), xi) - + dist[gin][i_gout].begin(); } // Randomly select mu within the imu bin @@ -569,8 +569,7 @@ ScattDataHistogram::sample(int gin, int& gout, double& mu, double& wgt, //============================================================================== -xt::xtensor -ScattDataHistogram::get_matrix(size_t max_order) +xt::xtensor ScattDataHistogram::get_matrix(size_t max_order) { // Get the sizes and initialize the data to 0 size_t groups = energy.size(); @@ -582,8 +581,8 @@ ScattDataHistogram::get_matrix(size_t max_order) for (int i_gout = 0; i_gout < energy[gin].size(); i_gout++) { int gout = i_gout + gmin[gin]; for (int l = 0; l < order_dim; l++) { - matrix(gin, gout, l) = scattxs[gin] * energy[gin][i_gout] * - fmu[gin][i_gout][l]; + matrix(gin, gout, l) = + scattxs[gin] * energy[gin][i_gout] * fmu[gin][i_gout][l]; } } } @@ -599,7 +598,8 @@ void ScattDataHistogram::combine( size_t max_order = those_scatts[0]->get_order(); for (int i = 0; i < those_scatts.size(); i++) { // Lets also make sure these items are combineable - ScattDataHistogram* that = dynamic_cast(those_scatts[i]); + ScattDataHistogram* that = + dynamic_cast(those_scatts[i]); if (!that) { fatal_error("Cannot combine the ScattData objects!"); } @@ -608,7 +608,7 @@ void ScattDataHistogram::combine( } } - size_t groups = those_scatts[0] -> energy.size(); + size_t groups = those_scatts[0]->energy.size(); xt::xtensor in_gmin({groups}, 0); xt::xtensor in_gmax({groups}, 0); @@ -620,7 +620,7 @@ void ScattDataHistogram::combine( // matrices size_t order_dim = max_order; ScattData::base_combine(max_order, order_dim, those_scatts, scalars, in_gmin, - in_gmax, sparse_mult, sparse_scatter); + in_gmax, sparse_mult, sparse_scatter); // Got everything we need, store it. init(in_gmin, in_gmax, sparse_mult, sparse_scatter); @@ -630,10 +630,9 @@ void ScattDataHistogram::combine( // ScattDataTabular methods //============================================================================== -void -ScattDataTabular::init(const xt::xtensor& in_gmin, - const xt::xtensor& in_gmax, const double_2dvec& in_mult, - const double_3dvec& coeffs) +void ScattDataTabular::init(const xt::xtensor& in_gmin, + const xt::xtensor& in_gmax, const double_2dvec& in_mult, + const double_3dvec& coeffs) { size_t groups = coeffs.size(); size_t order = coeffs[0][0].size(); @@ -651,8 +650,8 @@ ScattDataTabular::init(const xt::xtensor& in_gmin, for (int gin = 0; gin < groups; gin++) { for (int i_gout = 0; i_gout < matrix[gin].size(); i_gout++) { for (int imu = 1; imu < order; imu++) { - scattxs[gin] += 0.5 * dmu * (matrix[gin][i_gout][imu - 1] + - matrix[gin][i_gout][imu]); + scattxs[gin] += + 0.5 * dmu * (matrix[gin][i_gout][imu - 1] + matrix[gin][i_gout][imu]); } } } @@ -665,8 +664,8 @@ ScattDataTabular::init(const xt::xtensor& in_gmin, for (int i_gout = 0; i_gout < num_groups; i_gout++) { double norm = 0.; for (int imu = 1; imu < order; imu++) { - norm += 0.5 * dmu * (matrix[gin][i_gout][imu - 1] + - matrix[gin][i_gout][imu]); + norm += + 0.5 * dmu * (matrix[gin][i_gout][imu - 1] + matrix[gin][i_gout][imu]); } in_energy[gin][i_gout] = norm; } @@ -687,15 +686,15 @@ ScattDataTabular::init(const xt::xtensor& in_gmin, // Ensure positivity for (auto& val : fmu[gin][i_gout]) { - if (val < 0.) val = 0.; + if (val < 0.) + val = 0.; } // Now re-normalize for numerical integration issues and to take care of // the above negative fix-up. Also accrue the CDF double norm = 0.; for (int imu = 1; imu < order; imu++) { - norm += 0.5 * dmu * (fmu[gin][i_gout][imu - 1] + - fmu[gin][i_gout][imu]); + norm += 0.5 * dmu * (fmu[gin][i_gout][imu - 1] + fmu[gin][i_gout][imu]); // incorporate to the CDF dist[gin][i_gout][imu] = norm; } @@ -713,8 +712,7 @@ ScattDataTabular::init(const xt::xtensor& in_gmin, //============================================================================== -double -ScattDataTabular::calc_f(int gin, int gout, double mu) +double ScattDataTabular::calc_f(int gin, int gout, double mu) { double f; if ((gout < gmin[gin]) || (gout > gmax[gin])) { @@ -738,9 +736,8 @@ ScattDataTabular::calc_f(int gin, int gout, double mu) //============================================================================== -void -ScattDataTabular::sample(int gin, int& gout, double& mu, double& wgt, - uint64_t* seed) +void ScattDataTabular::sample( + int gin, int& gout, double& mu, double& wgt, uint64_t* seed) { // Sample the outgoing energy using the base-class method int i_gout; @@ -754,7 +751,8 @@ ScattDataTabular::sample(int gin, int& gout, double& mu, double& wgt, int k; for (k = 0; k < NP - 1; k++) { double c_k1 = dist[gin][i_gout][k + 1]; - if (xi < c_k1) break; + if (xi < c_k1) + break; c_k = c_k1; } @@ -763,16 +761,17 @@ ScattDataTabular::sample(int gin, int& gout, double& mu, double& wgt, // Find the pdf values we want double p0 = fmu[gin][i_gout][k]; - double mu0 = this -> mu[k]; + double mu0 = this->mu[k]; double p1 = fmu[gin][i_gout][k + 1]; - double mu1 = this -> mu[k + 1]; + double mu1 = this->mu[k + 1]; if (p0 == p1) { mu = mu0 + (xi - c_k) / p0; } else { double frac = (p1 - p0) / (mu1 - mu0); - mu = mu0 + (std::sqrt(std::max(0., p0 * p0 + 2. * frac * (xi - c_k))) - - p0) / frac; + mu = + mu0 + + (std::sqrt(std::max(0., p0 * p0 + 2. * frac * (xi - c_k))) - p0) / frac; } if (mu < -1.) { @@ -787,8 +786,7 @@ ScattDataTabular::sample(int gin, int& gout, double& mu, double& wgt, //============================================================================== -xt::xtensor -ScattDataTabular::get_matrix(size_t max_order) +xt::xtensor ScattDataTabular::get_matrix(size_t max_order) { // Get the sizes and initialize the data to 0 size_t groups = energy.size(); @@ -800,8 +798,8 @@ ScattDataTabular::get_matrix(size_t max_order) for (int i_gout = 0; i_gout < energy[gin].size(); i_gout++) { int gout = i_gout + gmin[gin]; for (int l = 0; l < order_dim; l++) { - matrix(gin, gout, l) = scattxs[gin] * energy[gin][i_gout] * - fmu[gin][i_gout][l]; + matrix(gin, gout, l) = + scattxs[gin] * energy[gin][i_gout] * fmu[gin][i_gout][l]; } } } @@ -826,7 +824,7 @@ void ScattDataTabular::combine( } } - size_t groups = those_scatts[0] -> energy.size(); + size_t groups = those_scatts[0]->energy.size(); xt::xtensor in_gmin({groups}, 0); xt::xtensor in_gmax({groups}, 0); @@ -838,7 +836,7 @@ void ScattDataTabular::combine( // matrices size_t order_dim = max_order; ScattData::base_combine(max_order, order_dim, those_scatts, scalars, in_gmin, - in_gmax, sparse_mult, sparse_scatter); + in_gmax, sparse_mult, sparse_scatter); // Got everything we need, store it. init(in_gmin, in_gmax, sparse_mult, sparse_scatter); @@ -848,8 +846,7 @@ void ScattDataTabular::combine( // module-level methods //============================================================================== -void -convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab) +void convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab) { // See if the user wants us to figure out how many points to use int n_mu = settings::legendre_to_tabular_points; @@ -880,13 +877,14 @@ convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab) tab.fmu[gin][i_gout].resize(n_mu); for (int imu = 0; imu < n_mu; imu++) { tab.fmu[gin][i_gout][imu] = - evaluate_legendre(leg.dist[gin][i_gout].size() - 1, - leg.dist[gin][i_gout].data(), tab.mu[imu]); + evaluate_legendre(leg.dist[gin][i_gout].size() - 1, + leg.dist[gin][i_gout].data(), tab.mu[imu]); } // Ensure positivity for (auto& val : tab.fmu[gin][i_gout]) { - if (val < 0.) val = 0.; + if (val < 0.) + val = 0.; } // Now re-normalize for numerical integration issues and to take care of @@ -894,8 +892,8 @@ convert_legendre_to_tabular(ScattDataLegendre& leg, ScattDataTabular& tab) double norm = 0.; tab.dist[gin][i_gout][0] = 0.; for (int imu = 1; imu < n_mu; imu++) { - norm += 0.5 * tab.dmu * (tab.fmu[gin][i_gout][imu - 1] + - tab.fmu[gin][i_gout][imu]); + norm += 0.5 * tab.dmu * + (tab.fmu[gin][i_gout][imu - 1] + tab.fmu[gin][i_gout][imu]); // incorporate to the CDF tab.dist[gin][i_gout][imu] = norm; } diff --git a/src/secondary_kalbach.cpp b/src/secondary_kalbach.cpp index 637650b43..4a7878343 100644 --- a/src/secondary_kalbach.cpp +++ b/src/secondary_kalbach.cpp @@ -60,7 +60,7 @@ KalbachMann::KalbachMann(hid_t group) int j = offsets[i]; int n; if (i < n_energy - 1) { - n = offsets[i+1] - j; + n = offsets[i + 1] - j; } else { n = eout.shape()[1] - j; } @@ -71,11 +71,11 @@ KalbachMann::KalbachMann(hid_t group) d.n_discrete = n_discrete[i]; // Copy data - d.e_out = xt::view(eout, 0, xt::range(j, j+n)); - d.p = xt::view(eout, 1, xt::range(j, j+n)); - d.c = xt::view(eout, 2, xt::range(j, j+n)); - d.r = xt::view(eout, 3, xt::range(j, j+n)); - d.a = xt::view(eout, 4, xt::range(j, j+n)); + d.e_out = xt::view(eout, 0, xt::range(j, j + n)); + d.p = xt::view(eout, 1, xt::range(j, j + n)); + d.c = xt::view(eout, 2, xt::range(j, j + n)); + d.r = xt::view(eout, 3, xt::range(j, j + n)); + d.a = xt::view(eout, 4, xt::range(j, j + n)); // To get answers that match ACE data, for now we still use the tabulated // CDF values that were passed through to the HDF5 library. At a later @@ -87,20 +87,20 @@ KalbachMann::KalbachMann(hid_t group) if (k == 0) { d.c[k] = d.p[k]; } else { - d.c[k] = d.c[k-1] + d.p[k]; + d.c[k] = d.c[k - 1] + d.p[k]; } } // Continuous portion for (int k = d.n_discrete; k < n; ++k) { if (k == d.n_discrete) { - d.c[k] = d.c[k-1] + d.p[k]; + d.c[k] = d.c[k - 1] + d.p[k]; } else { if (d.interpolation == Interpolation::histogram) { - d.c[k] = d.c[k-1] + d.p[k-1]*(d.e_out[k] - d.e_out[k-1]); + d.c[k] = d.c[k - 1] + d.p[k - 1] * (d.e_out[k] - d.e_out[k - 1]); } else if (d.interpolation == Interpolation::lin_lin) { - d.c[k] = d.c[k-1] + 0.5*(d.p[k-1] + d.p[k]) * - (d.e_out[k] - d.e_out[k-1]); + d.c[k] = d.c[k - 1] + 0.5 * (d.p[k - 1] + d.p[k]) * + (d.e_out[k] - d.e_out[k - 1]); } } } @@ -114,7 +114,8 @@ KalbachMann::KalbachMann(hid_t group) } // incoming energies } -void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) const +void KalbachMann::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Find energy bin and calculate interpolation factor -- if the energy is // outside the range of the tabulated energies, choose the first or last bins @@ -129,7 +130,7 @@ void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) r = 1.0; } else { i = lower_bound_index(energy_.begin(), energy_.end(), E_in); - r = (E_in - energy_[i]) / (energy_[i+1] - energy_[i]); + r = (E_in - energy_[i]) / (energy_[i + 1] - energy_[i]); } // Sample between the ith and [i+1]th bin @@ -141,13 +142,13 @@ void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) double E_i_1 = distribution_[i].e_out[n_discrete]; double E_i_K = distribution_[i].e_out[n_energy_out - 1]; - n_energy_out = distribution_[i+1].e_out.size(); - n_discrete = distribution_[i+1].n_discrete; - double E_i1_1 = distribution_[i+1].e_out[n_discrete]; - double E_i1_K = distribution_[i+1].e_out[n_energy_out - 1]; + n_energy_out = distribution_[i + 1].e_out.size(); + n_discrete = distribution_[i + 1].n_discrete; + double E_i1_1 = distribution_[i + 1].e_out[n_discrete]; + double E_i1_K = distribution_[i + 1].e_out[n_energy_out - 1]; - double E_1 = E_i_1 + r*(E_i1_1 - E_i_1); - double E_K = E_i_K + r*(E_i1_K - E_i_K); + double E_1 = E_i_1 + r * (E_i1_1 - E_i_1); + double E_K = E_i_K + r * (E_i1_K - E_i_K); // Determine outgoing energy bin n_energy_out = distribution_[l].e_out.size(); @@ -171,8 +172,9 @@ void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) double c_k1; for (int j = n_discrete; j < end; ++j) { k = j; - c_k1 = distribution_[l].c[k+1]; - if (r1 < c_k1) break; + c_k1 = distribution_[l].c[k + 1]; + if (r1 < c_k1) + break; k = j + 1; c_k = c_k1; } @@ -183,7 +185,7 @@ void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) if (distribution_[l].interpolation == Interpolation::histogram) { // Histogram interpolation if (p_l_k > 0.0 && k >= n_discrete) { - E_out = E_l_k + (r1 - c_k)/p_l_k; + E_out = E_l_k + (r1 - c_k) / p_l_k; } else { E_out = E_l_k; } @@ -194,41 +196,46 @@ void KalbachMann::sample(double E_in, double& E_out, double& mu, uint64_t* seed) } else { // Linear-linear interpolation - double E_l_k1 = distribution_[l].e_out[k+1]; - double p_l_k1 = distribution_[l].p[k+1]; + double E_l_k1 = distribution_[l].e_out[k + 1]; + double p_l_k1 = distribution_[l].p[k + 1]; - double frac = (p_l_k1 - p_l_k)/(E_l_k1 - E_l_k); + double frac = (p_l_k1 - p_l_k) / (E_l_k1 - E_l_k); if (frac == 0.0) { - E_out = E_l_k + (r1 - c_k)/p_l_k; + E_out = E_l_k + (r1 - c_k) / p_l_k; } else { - E_out = E_l_k + (std::sqrt(std::max(0.0, p_l_k*p_l_k + - 2.0*frac*(r1 - c_k))) - p_l_k)/frac; + E_out = + E_l_k + + (std::sqrt(std::max(0.0, p_l_k * p_l_k + 2.0 * frac * (r1 - c_k))) - + p_l_k) / + frac; } // Determine Kalbach-Mann parameters - km_r = distribution_[l].r[k] + (E_out - E_l_k)/(E_l_k1 - E_l_k) * - (distribution_[l].r[k+1] - distribution_[l].r[k]); - km_a = distribution_[l].a[k] + (E_out - E_l_k)/(E_l_k1 - E_l_k) * - (distribution_[l].a[k+1] - distribution_[l].a[k]); + km_r = distribution_[l].r[k] + + (E_out - E_l_k) / (E_l_k1 - E_l_k) * + (distribution_[l].r[k + 1] - distribution_[l].r[k]); + km_a = distribution_[l].a[k] + + (E_out - E_l_k) / (E_l_k1 - E_l_k) * + (distribution_[l].a[k + 1] - distribution_[l].a[k]); } // Now interpolate between incident energy bins i and i + 1 if (k >= n_discrete) { if (l == i) { - E_out = E_1 + (E_out - E_i_1)*(E_K - E_1)/(E_i_K - E_i_1); + E_out = E_1 + (E_out - E_i_1) * (E_K - E_1) / (E_i_K - E_i_1); } else { - E_out = E_1 + (E_out - E_i1_1)*(E_K - E_1)/(E_i1_K - E_i1_1); + E_out = E_1 + (E_out - E_i1_1) * (E_K - E_1) / (E_i1_K - E_i1_1); } } // Sampled correlated angle from Kalbach-Mann parameters if (prn(seed) > km_r) { double T = uniform_distribution(-1., 1., seed) * std::sinh(km_a); - mu = std::log(T + std::sqrt(T*T + 1.0))/km_a; + mu = std::log(T + std::sqrt(T * T + 1.0)) / km_a; } else { double r1 = prn(seed); - mu = std::log(r1*std::exp(km_a) + (1.0 - r1)*std::exp(-km_a))/km_a; + mu = std::log(r1 * std::exp(km_a) + (1.0 - r1) * std::exp(-km_a)) / km_a; } } -} +} // namespace openmc diff --git a/src/secondary_nbody.cpp b/src/secondary_nbody.cpp index 0b27f3d08..da0bb81c4 100644 --- a/src/secondary_nbody.cpp +++ b/src/secondary_nbody.cpp @@ -22,8 +22,8 @@ NBodyPhaseSpace::NBodyPhaseSpace(hid_t group) read_attribute(group, "q_value", Q_); } -void NBodyPhaseSpace::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void NBodyPhaseSpace::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // By definition, the distribution of the angle is isotropic for an N-body // phase space distribution @@ -31,7 +31,7 @@ void NBodyPhaseSpace::sample(double E_in, double& E_out, double& mu, // Determine E_max parameter double Ap = mass_ratio_; - double E_max = (Ap - 1.0)/Ap * (A_/(A_ + 1.0)*E_in + Q_); + double E_max = (Ap - 1.0) / Ap * (A_ / (A_ + 1.0) * E_in + Q_); // x is essentially a Maxwellian distribution double x = maxwell_spectrum(1.0, seed); @@ -46,7 +46,7 @@ void NBodyPhaseSpace::sample(double E_in, double& E_out, double& mu, r1 = prn(seed); r2 = prn(seed); r3 = prn(seed); - y = -std::log(r1*r2*r3); + y = -std::log(r1 * r2 * r3); break; case 5: r1 = prn(seed); @@ -55,14 +55,15 @@ void NBodyPhaseSpace::sample(double E_in, double& E_out, double& mu, r4 = prn(seed); r5 = prn(seed); r6 = prn(seed); - y = -std::log(r1*r2*r3*r4) - std::log(r5) * std::pow(std::cos(PI/2.0*r6), 2); + y = -std::log(r1 * r2 * r3 * r4) - + std::log(r5) * std::pow(std::cos(PI / 2.0 * r6), 2); break; default: - throw std::runtime_error{"N-body phase space with >5 bodies."}; + throw std::runtime_error {"N-body phase space with >5 bodies."}; } // Now determine v and E_out - double v = x/(x + y); + double v = x / (x + y); E_out = E_max * v; } diff --git a/src/secondary_thermal.cpp b/src/secondary_thermal.cpp index dd86c0d07..e3ecdcd48 100644 --- a/src/secondary_thermal.cpp +++ b/src/secondary_thermal.cpp @@ -19,7 +19,7 @@ void get_energy_index( f = 0.0; if (E >= energies.front()) { i = lower_bound_index(energies.begin(), energies.end(), E); - f = (E - energies[i]) / (energies[i+1] - energies[i]); + f = (E - energies[i]) / (energies[i + 1] - energies[i]); } } @@ -27,13 +27,10 @@ void get_energy_index( // CoherentElasticAE implementation //============================================================================== -CoherentElasticAE::CoherentElasticAE(const CoherentElasticXS& xs) - : xs_{xs} -{ } +CoherentElasticAE::CoherentElasticAE(const CoherentElasticXS& xs) : xs_ {xs} {} -void -CoherentElasticAE::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void CoherentElasticAE::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Get index and interpolation factor for elastic grid int i; @@ -43,14 +40,14 @@ CoherentElasticAE::sample(double E_in, double& E_out, double& mu, // Sample a Bragg edge between 1 and i const auto& factors = xs_.factors(); - double prob = prn(seed) * factors[i+1]; + double prob = prn(seed) * factors[i + 1]; int k = 0; if (prob >= factors.front()) { - k = lower_bound_index(factors.begin(), factors.begin() + (i+1), prob); + k = lower_bound_index(factors.begin(), factors.begin() + (i + 1), prob); } // Characteristic scattering cosine for this Bragg edge (ENDF-102, Eq. 7-2) - mu = 1.0 - 2.0*energies[k] / E_in; + mu = 1.0 - 2.0 * energies[k] / E_in; // Energy doesn't change in elastic scattering (ENDF-102, Eq. 7-1) E_out = E_in; @@ -65,13 +62,12 @@ IncoherentElasticAE::IncoherentElasticAE(hid_t group) read_dataset(group, "debye_waller", debye_waller_); } -void -IncoherentElasticAE::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void IncoherentElasticAE::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Sample angle by inverting the distribution in ENDF-102, Eq. 7.4 double c = 2 * E_in * debye_waller_; - mu = std::log(1.0 + prn(seed)*(std::exp(2.0*c) - 1))/c - 1.0; + mu = std::log(1.0 + prn(seed) * (std::exp(2.0 * c) - 1)) / c - 1.0; // Energy doesn't change in elastic scattering (ENDF-102, Eq. 7.4) E_out = E_in; @@ -88,9 +84,8 @@ IncoherentElasticAEDiscrete::IncoherentElasticAEDiscrete( read_dataset(group, "mu_out", mu_out_); } -void -IncoherentElasticAEDiscrete::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void IncoherentElasticAEDiscrete::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Get index and interpolation factor for elastic grid int i; @@ -109,23 +104,24 @@ IncoherentElasticAEDiscrete::sample(double E_in, double& E_out, double& mu, // discrete mu value itself. // Interpolate kth mu value between distributions at energies i and i+1 - mu = mu_out_(i, k) + f*(mu_out_(i+1, k) - mu_out_(i, k)); + mu = mu_out_(i, k) + f * (mu_out_(i + 1, k) - mu_out_(i, k)); // Inteprolate (k-1)th mu value between distributions at energies i and i+1. // When k==0, pick a value that will smear the cosine out to a minimum of -1. - double mu_left = (k == 0) ? - -1.0 - (mu + 1.0) : - mu_out_(i, k-1) + f*(mu_out_(i+1, k-1) - mu_out_(i, k-1)); + double mu_left = (k == 0) ? -1.0 - (mu + 1.0) + : mu_out_(i, k - 1) + + f * (mu_out_(i + 1, k - 1) - mu_out_(i, k - 1)); // Inteprolate (k+1)th mu value between distributions at energies i and i+1. // When k is the last discrete value, pick a value that will smear the cosine // out to a maximum of 1. - double mu_right = (k == n_mu - 1) ? - 1.0 + (1.0 - mu) : - mu_out_(i, k+1) + f*(mu_out_(i+1, k+1) - mu_out_(i, k+1)); + double mu_right = + (k == n_mu - 1) + ? 1.0 + (1.0 - mu) + : mu_out_(i, k + 1) + f * (mu_out_(i + 1, k + 1) - mu_out_(i, k + 1)); // Smear cosine - mu += std::min(mu - mu_left, mu_right - mu)*(prn(seed) - 0.5); + mu += std::min(mu - mu_left, mu_right - mu) * (prn(seed) - 0.5); // Energy doesn't change in elastic scattering E_out = E_in; @@ -144,9 +140,8 @@ IncoherentInelasticAEDiscrete::IncoherentInelasticAEDiscrete( read_dataset(group, "skewed", skewed_); } -void -IncoherentInelasticAEDiscrete::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void IncoherentInelasticAEDiscrete::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Get index and interpolation factor for inelastic grid int i; @@ -187,22 +182,22 @@ IncoherentInelasticAEDiscrete::sample(double E_in, double& E_out, double& mu, } // Determine outgoing energy corresponding to E_in[i] and E_in[i+1] - double E_ij = energy_out_(i, j); - double E_i1j = energy_out_(i+1, j); + double E_ij = energy_out_(i, j); + double E_i1j = energy_out_(i + 1, j); // Outgoing energy - E_out = (1 - f)*E_ij + f*E_i1j; + E_out = (1 - f) * E_ij + f * E_i1j; // Sample outgoing cosine bin int m = mu_out_.shape()[2]; int k = prn(seed) * m; // Determine outgoing cosine corresponding to E_in[i] and E_in[i+1] - double mu_ijk = mu_out_(i, j, k); - double mu_i1jk = mu_out_(i+1, j, k); + double mu_ijk = mu_out_(i, j, k); + double mu_i1jk = mu_out_(i + 1, j, k); // Cosine of angle between incoming and outgoing neutron - mu = (1 - f)*mu_ijk + f*mu_i1jk; + mu = (1 - f) * mu_ijk + f * mu_i1jk; } //============================================================================== @@ -245,12 +240,10 @@ IncoherentInelasticAE::IncoherentInelasticAE(hid_t group) distribution_.emplace_back(std::move(d)); } - } -void -IncoherentInelasticAE::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void IncoherentInelasticAE::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Get index and interpolation factor for inelastic grid int i; @@ -269,7 +262,8 @@ IncoherentInelasticAE::sample(double E_in, double& E_out, double& mu, std::size_t j; for (j = 0; j < n - 1; ++j) { c_j1 = distribution_[l].e_out_cdf[j + 1]; - if (r1 < c_j1) break; + if (r1 < c_j1) + break; c_j = c_j1; } @@ -289,14 +283,16 @@ IncoherentInelasticAE::sample(double E_in, double& E_out, double& mu, if (frac == 0.0) { E_out = E_l_j + (r1 - c_j) / p_l_j; } else { - E_out = E_l_j + (std::sqrt(std::max(0.0, p_l_j*p_l_j + - 2.0*frac*(r1 - c_j))) - p_l_j) / frac; + E_out = E_l_j + + (std::sqrt(std::max(0.0, p_l_j * p_l_j + 2.0 * frac * (r1 - c_j))) - + p_l_j) / + frac; } // Adjustment of outgoing energy double E_l = energy_[l]; - if (E_out < 0.5*E_l) { - E_out *= 2.0*E_in/E_l - 1.0; + if (E_out < 0.5 * E_l) { + E_out *= 2.0 * E_in / E_l - 1.0; } else { E_out += E_in - E_l; } @@ -309,26 +305,28 @@ IncoherentInelasticAE::sample(double E_in, double& E_out, double& mu, // a bin of width 0.5*min(mu[k] - mu[k-1], mu[k+1] - mu[k]) centered on the // discrete mu value itself. const auto& mu_l = distribution_[l].mu; - f = (r1 - c_j)/(c_j1 - c_j); + f = (r1 - c_j) / (c_j1 - c_j); // Interpolate kth mu value between distributions at energies j and j+1 - mu = mu_l(j, k) + f*(mu_l(j+1, k) - mu_l(j, k)); + mu = mu_l(j, k) + f * (mu_l(j + 1, k) - mu_l(j, k)); // Inteprolate (k-1)th mu value between distributions at energies j and j+1. // When k==0, pick a value that will smear the cosine out to a minimum of -1. - double mu_left = (k == 0) ? - mu_left = -1.0 - (mu + 1.0) : - mu_left = mu_l(j, k-1) + f*(mu_l(j+1, k-1) - mu_l(j, k-1)); + double mu_left = + (k == 0) + ? mu_left = -1.0 - (mu + 1.0) + : mu_left = mu_l(j, k - 1) + f * (mu_l(j + 1, k - 1) - mu_l(j, k - 1)); // Inteprolate (k+1)th mu value between distributions at energies j and j+1. // When k is the last discrete value, pick a value that will smear the cosine // out to a maximum of 1. - double mu_right = (k == n_mu - 1) ? - mu_right = 1.0 + (1.0 - mu) : - mu_right = mu_l(j, k+1) + f*(mu_l(j+1, k+1) - mu_l(j, k+1)); + double mu_right = + (k == n_mu - 1) + ? mu_right = 1.0 + (1.0 - mu) + : mu_right = mu_l(j, k + 1) + f * (mu_l(j + 1, k + 1) - mu_l(j, k + 1)); // Smear cosine - mu += std::min(mu - mu_left, mu_right - mu)*(prn(seed) - 0.5); + mu += std::min(mu - mu_left, mu_right - mu) * (prn(seed) - 0.5); } } // namespace openmc diff --git a/src/secondary_uncorrelated.cpp b/src/secondary_uncorrelated.cpp index 39b3eb4ed..5cbb76fb9 100644 --- a/src/secondary_uncorrelated.cpp +++ b/src/secondary_uncorrelated.cpp @@ -1,6 +1,6 @@ #include "openmc/secondary_uncorrelated.h" -#include // for string +#include // for string #include @@ -19,7 +19,7 @@ UncorrelatedAngleEnergy::UncorrelatedAngleEnergy(hid_t group) // Check if angle group is present & read if (object_exists(group, "angle")) { hid_t angle_group = open_group(group, "angle"); - angle_ = AngleDistribution{angle_group}; + angle_ = AngleDistribution {angle_group}; close_group(angle_group); } @@ -31,28 +31,27 @@ UncorrelatedAngleEnergy::UncorrelatedAngleEnergy(hid_t group) read_attribute(energy_group, "type", type); using UPtrEDist = unique_ptr; if (type == "discrete_photon") { - energy_ = UPtrEDist{new DiscretePhoton{energy_group}}; + energy_ = UPtrEDist {new DiscretePhoton {energy_group}}; } else if (type == "level") { - energy_ = UPtrEDist{new LevelInelastic{energy_group}}; + energy_ = UPtrEDist {new LevelInelastic {energy_group}}; } else if (type == "continuous") { - energy_ = UPtrEDist{new ContinuousTabular{energy_group}}; + energy_ = UPtrEDist {new ContinuousTabular {energy_group}}; } else if (type == "maxwell") { - energy_ = UPtrEDist{new MaxwellEnergy{energy_group}}; + energy_ = UPtrEDist {new MaxwellEnergy {energy_group}}; } else if (type == "evaporation") { - energy_ = UPtrEDist{new Evaporation{energy_group}}; + energy_ = UPtrEDist {new Evaporation {energy_group}}; } else if (type == "watt") { - energy_ = UPtrEDist{new WattEnergy{energy_group}}; + energy_ = UPtrEDist {new WattEnergy {energy_group}}; } else { - warning(fmt::format("Energy distribution type '{}' not implemented.", type)); + warning( + fmt::format("Energy distribution type '{}' not implemented.", type)); } close_group(energy_group); } - } -void -UncorrelatedAngleEnergy::sample(double E_in, double& E_out, double& mu, - uint64_t* seed) const +void UncorrelatedAngleEnergy::sample( + double E_in, double& E_out, double& mu, uint64_t* seed) const { // Sample cosine of scattering angle if (!angle_.empty()) { diff --git a/src/settings.cpp b/src/settings.cpp index 2617da978..3b507fa4e 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,6 +1,6 @@ #include "openmc/settings.h" -#include // for ceil, pow +#include // for ceil, pow #include // for numeric_limits #include @@ -38,38 +38,38 @@ namespace openmc { namespace settings { // Default values for boolean flags -bool assume_separate {false}; -bool check_overlaps {false}; -bool cmfd_run {false}; -bool confidence_intervals {false}; +bool assume_separate {false}; +bool check_overlaps {false}; +bool cmfd_run {false}; +bool confidence_intervals {false}; bool create_fission_neutrons {true}; -bool dagmc {false}; -bool delayed_photon_scaling {true}; -bool entropy_on {false}; -bool event_based {false}; -bool legendre_to_tabular {true}; -bool material_cell_offsets {true}; -bool output_summary {true}; -bool output_tallies {true}; -bool particle_restart_run {false}; -bool photon_transport {false}; -bool reduce_tallies {true}; -bool res_scat_on {false}; -bool restart_run {false}; -bool run_CE {true}; -bool source_latest {false}; -bool source_separate {false}; -bool source_write {true}; -bool surf_source_write {false}; -bool surf_source_read {false}; -bool survival_biasing {false}; -bool temperature_multipole {false}; -bool trigger_on {false}; -bool trigger_predict {false}; -bool ufs_on {false}; -bool urr_ptables_on {true}; -bool write_all_tracks {false}; -bool write_initial_source {false}; +bool dagmc {false}; +bool delayed_photon_scaling {true}; +bool entropy_on {false}; +bool event_based {false}; +bool legendre_to_tabular {true}; +bool material_cell_offsets {true}; +bool output_summary {true}; +bool output_tallies {true}; +bool particle_restart_run {false}; +bool photon_transport {false}; +bool reduce_tallies {true}; +bool res_scat_on {false}; +bool restart_run {false}; +bool run_CE {true}; +bool source_latest {false}; +bool source_separate {false}; +bool source_write {true}; +bool surf_source_write {false}; +bool surf_source_read {false}; +bool survival_biasing {false}; +bool temperature_multipole {false}; +bool trigger_on {false}; +bool trigger_predict {false}; +bool ufs_on {false}; +bool urr_ptables_on {true}; +bool write_all_tracks {false}; +bool write_initial_source {false}; std::string path_cross_sections; std::string path_input; @@ -138,24 +138,27 @@ void get_run_parameters(pugi::xml_node node_base) // Get maximum number of in flight particles for event-based mode if (check_for_node(node_base, "max_particles_in_flight")) { - max_particles_in_flight = std::stoll(get_node_value(node_base, - "max_particles_in_flight")); + max_particles_in_flight = + std::stoll(get_node_value(node_base, "max_particles_in_flight")); } // Get number of basic batches if (check_for_node(node_base, "batches")) { n_batches = std::stoi(get_node_value(node_base, "batches")); } - if (!trigger_on) n_max_batches = n_batches; + if (!trigger_on) + n_max_batches = n_batches; // Get max number of lost particles if (check_for_node(node_base, "max_lost_particles")) { - max_lost_particles = std::stoi(get_node_value(node_base, "max_lost_particles")); + max_lost_particles = + std::stoi(get_node_value(node_base, "max_lost_particles")); } // Get relative number of lost particles if (check_for_node(node_base, "rel_max_lost_particles")) { - rel_max_lost_particles = std::stod(get_node_value(node_base, "rel_max_lost_particles")); + rel_max_lost_particles = + std::stod(get_node_value(node_base, "rel_max_lost_particles")); } // Get number of inactive batches @@ -164,7 +167,8 @@ void get_run_parameters(pugi::xml_node node_base) n_inactive = std::stoi(get_node_value(node_base, "inactive")); } if (check_for_node(node_base, "generations_per_batch")) { - gen_per_batch = std::stoi(get_node_value(node_base, "generations_per_batch")); + gen_per_batch = + std::stoi(get_node_value(node_base, "generations_per_batch")); } // Preallocate space for keff and entropy by generation @@ -192,8 +196,8 @@ void get_run_parameters(pugi::xml_node node_base) } if (check_for_node(node_keff_trigger, "threshold")) { - keff_trigger.threshold = std::stod(get_node_value( - node_keff_trigger, "threshold")); + keff_trigger.threshold = + std::stod(get_node_value(node_keff_trigger, "threshold")); if (keff_trigger.threshold <= 0) { fatal_error("keff trigger threshold must be positive"); } @@ -213,13 +217,15 @@ void read_settings_xml() std::string filename = path_input + "settings.xml"; if (!file_exists(filename)) { if (run_mode != RunMode::PLOTTING) { - fatal_error(fmt::format( - "Settings XML file '{}' does not exist! In order " - "to run OpenMC, you first need a set of input files; at a minimum, this " - "includes settings.xml, geometry.xml, and materials.xml. Please consult " - "the user's guide at https://docs.openmc.org for further " - "information.", filename - )); + fatal_error( + fmt::format("Settings XML file '{}' does not exist! In order " + "to run OpenMC, you first need a set of input files; at a " + "minimum, this " + "includes settings.xml, geometry.xml, and materials.xml. " + "Please consult " + "the user's guide at https://docs.openmc.org for further " + "information.", + filename)); } else { // The settings.xml file is optional if we just want to make a plot. return; @@ -255,7 +261,8 @@ void read_settings_xml() // To this point, we haven't displayed any output since we didn't know what // the verbosity is. Now that we checked for it, show the title if necessary if (mpi::master) { - if (verbosity >= 2) title(); + if (verbosity >= 2) + title(); } write_message("Reading settings XML file...", 5); @@ -271,11 +278,12 @@ void read_settings_xml() // Look for deprecated cross_sections.xml file in settings.xml if (check_for_node(root, "cross_sections")) { - warning("Setting cross_sections in settings.xml has been deprecated." - " The cross_sections are now set in materials.xml and the " - "cross_sections input to materials.xml and the OPENMC_CROSS_SECTIONS" - " environment variable will take precendent over setting " - "cross_sections in settings.xml."); + warning( + "Setting cross_sections in settings.xml has been deprecated." + " The cross_sections are now set in materials.xml and the " + "cross_sections input to materials.xml and the OPENMC_CROSS_SECTIONS" + " environment variable will take precendent over setting " + "cross_sections in settings.xml."); path_cross_sections = get_node_value(root, "cross_sections"); } @@ -300,17 +308,18 @@ void read_settings_xml() trigger_on = get_node_value_bool(node_trigger, "active"); if (trigger_on) { - if (check_for_node(node_trigger, "max_batches") ){ + if (check_for_node(node_trigger, "max_batches")) { n_max_batches = std::stoi(get_node_value(node_trigger, "max_batches")); } else { fatal_error(" must be specified with triggers"); } // Get the batch interval to check triggers - if (!check_for_node(node_trigger, "batch_interval")){ + if (!check_for_node(node_trigger, "batch_interval")) { trigger_predict = true; } else { - trigger_batch_interval = std::stoi(get_node_value(node_trigger, "batch_interval")); + trigger_batch_interval = + std::stoi(get_node_value(node_trigger, "batch_interval")); if (trigger_batch_interval <= 0) { fatal_error("Trigger batch interval must be greater than zero"); } @@ -361,7 +370,8 @@ void read_settings_xml() // Read run parameters get_run_parameters(node_mode); - // Check number of active batches, inactive batches, max lost particles and particles + // Check number of active batches, inactive batches, max lost particles and + // particles if (n_batches <= n_inactive) { fatal_error("Number of active batches must be greater than zero."); } else if (n_inactive < 0) { @@ -399,7 +409,7 @@ void read_settings_xml() if (!run_CE && photon_transport) { fatal_error("Photon transport is not currently supported in " - "multigroup mode"); + "multigroup mode"); } } @@ -408,14 +418,16 @@ void read_settings_xml() n_log_bins = std::stoi(get_node_value(root, "log_grid_bins")); if (n_log_bins < 1) { fatal_error("Number of bins for logarithmic grid must be greater " - "than zero."); + "than zero."); } } // Number of OpenMP threads if (check_for_node(root, "threads")) { - if (mpi::master) warning("The element has been deprecated. Use " - "the OMP_NUM_THREADS environment variable to set the number of threads."); + if (mpi::master) + warning("The element has been deprecated. Use " + "the OMP_NUM_THREADS environment variable to set the number of " + "threads."); } // ========================================================================== @@ -456,7 +468,8 @@ void read_settings_xml() model::external_sources.push_back(make_unique(path)); } - // If no source specified, default to isotropic point source at origin with Watt spectrum + // If no source specified, default to isotropic point source at origin with + // Watt spectrum if (model::external_sources.empty()) { model::external_sources.push_back(make_unique( UPtrSpace {new SpatialPoint({0.0, 0.0, 0.0})}, @@ -488,20 +501,24 @@ void read_settings_xml() weight_survive = std::stod(get_node_value(node_cutoff, "weight_avg")); } if (check_for_node(node_cutoff, "energy_neutron")) { - energy_cutoff[0] = std::stod(get_node_value(node_cutoff, "energy_neutron")); + energy_cutoff[0] = + std::stod(get_node_value(node_cutoff, "energy_neutron")); } else if (check_for_node(node_cutoff, "energy")) { warning("The use of an cutoff is deprecated and should " - "be replaced by ."); + "be replaced by ."); energy_cutoff[0] = std::stod(get_node_value(node_cutoff, "energy")); } if (check_for_node(node_cutoff, "energy_photon")) { - energy_cutoff[1] = std::stod(get_node_value(node_cutoff, "energy_photon")); + energy_cutoff[1] = + std::stod(get_node_value(node_cutoff, "energy_photon")); } if (check_for_node(node_cutoff, "energy_electron")) { - energy_cutoff[2] = std::stof(get_node_value(node_cutoff, "energy_electron")); + energy_cutoff[2] = + std::stof(get_node_value(node_cutoff, "energy_electron")); } if (check_for_node(node_cutoff, "energy_positron")) { - energy_cutoff[3] = std::stod(get_node_value(node_cutoff, "energy_positron")); + energy_cutoff[3] = + std::stod(get_node_value(node_cutoff, "energy_positron")); } } @@ -510,10 +527,10 @@ void read_settings_xml() auto temp = get_node_array(root, "trace"); if (temp.size() != 3) { fatal_error("Must provide 3 integers for that specify the " - "batch, generation, and particle number."); + "batch, generation, and particle number."); } - trace_batch = temp.at(0); - trace_gen = temp.at(1); + trace_batch = temp.at(0); + trace_gen = temp.at(1); trace_particle = temp.at(2); } @@ -522,7 +539,8 @@ void read_settings_xml() // Get values and make sure there are three per particle auto temp = get_node_array(root, "track"); if (temp.size() % 3 != 0) { - fatal_error("Number of integers specified in 'track' is not " + fatal_error( + "Number of integers specified in 'track' is not " "divisible by 3. Please provide 3 integers per particle to be " "tracked."); } @@ -530,8 +548,8 @@ void read_settings_xml() // Reshape into track_identifiers int n_tracks = temp.size() / 3; for (int i = 0; i < n_tracks; ++i) { - track_identifiers.push_back({temp[3*i], temp[3*i + 1], - temp[3*i + 2]}); + track_identifiers.push_back( + {temp[3 * i], temp[3 * i + 1], temp[3 * i + 2]}); } } @@ -546,16 +564,18 @@ void read_settings_xml() "Mesh {} specified for Shannon entropy does not exist.", temp)); } - auto* m = dynamic_cast( - model::meshes[model::mesh_map.at(temp)].get()); - if (!m) fatal_error("Only regular meshes can be used as an entropy mesh"); + auto* m = + dynamic_cast(model::meshes[model::mesh_map.at(temp)].get()); + if (!m) + fatal_error("Only regular meshes can be used as an entropy mesh"); simulation::entropy_mesh = m; // Turn on Shannon entropy calculation entropy_on = true; } else if (check_for_node(root, "entropy")) { - fatal_error("Specifying a Shannon entropy mesh via the element " + fatal_error( + "Specifying a Shannon entropy mesh via the element " "is deprecated. Please create a mesh using and then reference " "it by specifying its ID in an element."); } @@ -565,18 +585,22 @@ void read_settings_xml() auto temp = std::stoi(get_node_value(root, "ufs_mesh")); if (model::mesh_map.find(temp) == model::mesh_map.end()) { fatal_error(fmt::format("Mesh {} specified for uniform fission site " - "method does not exist.", temp)); + "method does not exist.", + temp)); } - auto* m = dynamic_cast(model::meshes[model::mesh_map.at(temp)].get()); - if (!m) fatal_error("Only regular meshes can be used as a UFS mesh"); + auto* m = + dynamic_cast(model::meshes[model::mesh_map.at(temp)].get()); + if (!m) + fatal_error("Only regular meshes can be used as a UFS mesh"); simulation::ufs_mesh = m; // Turn on uniform fission source weighting ufs_on = true; } else if (check_for_node(root, "uniform_fs")) { - fatal_error("Specifying a UFS mesh via the element " + fatal_error( + "Specifying a UFS mesh via the element " "is deprecated. Please create a mesh using and then reference " "it by specifying its ID in a element."); } @@ -655,7 +679,8 @@ void read_settings_xml() // Get maximum number of particles to be banked per surface if (check_for_node(node_ssw, "max_particles")) { - max_surface_particles = std::stoll(get_node_value(node_ssw, "max_particles")); + max_surface_particles = + std::stoll(get_node_value(node_ssw, "max_particles")); } } @@ -665,7 +690,8 @@ void read_settings_xml() if (!source_separate) { for (const auto& b : sourcepoint_batch) { if (!contains(statepoint_batch, b)) { - fatal_error("Sourcepoint batches are not a subset of statepoint batches."); + fatal_error( + "Sourcepoint batches are not a subset of statepoint batches."); } } } @@ -725,14 +751,15 @@ void read_settings_xml() } else if (temp == "dbrc") { res_scat_method = ResScatMethod::dbrc; } else { - fatal_error("Unrecognized resonance elastic scattering method: " - + temp + "."); + fatal_error( + "Unrecognized resonance elastic scattering method: " + temp + "."); } } // Minimum energy for resonance scattering if (check_for_node(node_res_scat, "energy_min")) { - res_scat_energy_min = std::stod(get_node_value(node_res_scat, "energy_min")); + res_scat_energy_min = + std::stod(get_node_value(node_res_scat, "energy_min")); } if (res_scat_energy_min < 0.0) { fatal_error("Lower resonance scattering energy bound is negative"); @@ -740,16 +767,18 @@ void read_settings_xml() // Maximum energy for resonance scattering if (check_for_node(node_res_scat, "energy_max")) { - res_scat_energy_max = std::stod(get_node_value(node_res_scat, "energy_max")); + res_scat_energy_max = + std::stod(get_node_value(node_res_scat, "energy_max")); } if (res_scat_energy_max < res_scat_energy_min) { fatal_error("Upper resonance scattering energy bound is below the " - "lower resonance scattering energy bound."); + "lower resonance scattering energy bound."); } // Get resonance scattering nuclides if (check_for_node(node_res_scat, "nuclides")) { - res_scat_nuclides = get_node_array(node_res_scat, "nuclides"); + res_scat_nuclides = + get_node_array(node_res_scat, "nuclides"); } } @@ -760,7 +789,8 @@ void read_settings_xml() // Get temperature settings if (check_for_node(root, "temperature_default")) { - temperature_default = std::stod(get_node_value(root, "temperature_default")); + temperature_default = + std::stod(get_node_value(root, "temperature_default")); } if (check_for_node(root, "temperature_method")) { auto temp = get_node_value(root, "temperature_method", true, true); @@ -773,7 +803,8 @@ void read_settings_xml() } } if (check_for_node(root, "temperature_tolerance")) { - temperature_tolerance = std::stod(get_node_value(root, "temperature_tolerance")); + temperature_tolerance = + std::stod(get_node_value(root, "temperature_tolerance")); } if (check_for_node(root, "temperature_multipole")) { temperature_multipole = get_node_value_bool(root, "temperature_multipole"); @@ -796,10 +827,11 @@ void read_settings_xml() // Check for the number of points if (check_for_node(node_tab_leg, "num_points")) { - legendre_to_tabular_points = std::stoi(get_node_value( - node_tab_leg, "num_points")); + legendre_to_tabular_points = + std::stoi(get_node_value(node_tab_leg, "num_points")); if (legendre_to_tabular_points <= 1 && !run_CE) { - fatal_error("The 'num_points' subelement/attribute of the " + fatal_error( + "The 'num_points' subelement/attribute of the " " element must contain a value greater than 1"); } } @@ -808,13 +840,15 @@ void read_settings_xml() // Check whether create fission sites if (run_mode == RunMode::FIXED_SOURCE) { if (check_for_node(root, "create_fission_neutrons")) { - create_fission_neutrons = get_node_value_bool(root, "create_fission_neutrons"); + create_fission_neutrons = + get_node_value_bool(root, "create_fission_neutrons"); } } // Check whether to scale fission photon yields if (check_for_node(root, "delayed_photon_scaling")) { - delayed_photon_scaling = get_node_value_bool(root, "delayed_photon_scaling"); + delayed_photon_scaling = + get_node_value_bool(root, "delayed_photon_scaling"); } // Check whether to use event-based parallelism @@ -828,7 +862,8 @@ void read_settings_xml() } } -void free_memory_settings() { +void free_memory_settings() +{ settings::statepoint_batch.clear(); settings::sourcepoint_batch.clear(); settings::source_write_surf_id.clear(); @@ -839,9 +874,8 @@ void free_memory_settings() { // C API functions //============================================================================== -extern "C" int -openmc_set_n_batches(int32_t n_batches, bool set_max_batches, - bool add_statepoint_batch) +extern "C" int openmc_set_n_batches( + int32_t n_batches, bool set_max_batches, bool add_statepoint_batch) { if (settings::n_inactive >= n_batches) { set_errmsg("Number of active batches must be greater than zero."); @@ -879,8 +913,7 @@ openmc_set_n_batches(int32_t n_batches, bool set_max_batches, return 0; } -extern "C" int -openmc_get_n_batches(int* n_batches, bool get_max_batches) +extern "C" int openmc_get_n_batches(int* n_batches, bool get_max_batches) { *n_batches = get_max_batches ? settings::n_max_batches : settings::n_batches; diff --git a/src/simulation.cpp b/src/simulation.cpp index e6de68b7e..e29c4da25 100644 --- a/src/simulation.cpp +++ b/src/simulation.cpp @@ -17,11 +17,11 @@ #include "openmc/settings.h" #include "openmc/source.h" #include "openmc/state_point.h" -#include "openmc/timer.h" #include "openmc/tallies/derivative.h" #include "openmc/tallies/filter.h" #include "openmc/tallies/tally.h" #include "openmc/tallies/trigger.h" +#include "openmc/timer.h" #include "openmc/track_output.h" #ifdef _OPENMP @@ -39,14 +39,13 @@ #include #include - //============================================================================== // C API functions //============================================================================== // OPENMC_RUN encompasses all the main logic where iterations are performed -// over the batches, generations, and histories in a fixed source or k-eigenvalue -// calculation. +// over the batches, generations, and histories in a fixed source or +// k-eigenvalue calculation. int openmc_run() { @@ -69,7 +68,8 @@ int openmc_simulation_init() using namespace openmc; // Skip if simulation has already been initialized - if (simulation::initialized) return 0; + if (simulation::initialized) + return 0; // Initialize nuclear data (energy limits, log grid) if (settings::run_CE) { @@ -85,8 +85,8 @@ int openmc_simulation_init() // If doing an event-based simulation, intialize the particle buffer // and event queues if (settings::event_based) { - int64_t event_buffer_length = std::min(simulation::work_per_rank, - settings::max_particles_in_flight); + int64_t event_buffer_length = + std::min(simulation::work_per_rank, settings::max_particles_in_flight); init_event_queues(event_buffer_length); } @@ -125,7 +125,8 @@ int openmc_simulation_init() header("FIXED SOURCE TRANSPORT SIMULATION", 3); } else if (settings::run_mode == RunMode::EIGENVALUE) { header("K EIGENVALUE SIMULATION", 3); - if (settings::verbosity >= 7) print_columns(); + if (settings::verbosity >= 7) + print_columns(); } } @@ -139,7 +140,8 @@ int openmc_simulation_finalize() using namespace openmc; // Skip if simulation was never run - if (!simulation::initialized) return 0; + if (!simulation::initialized) + return 0; // Stop active batch timer and start finalization timer simulation::time_active.stop(); @@ -151,14 +153,15 @@ int openmc_simulation_finalize() } // Increment total number of generations - simulation::total_gen += simulation::current_batch*settings::gen_per_batch; + simulation::total_gen += simulation::current_batch * settings::gen_per_batch; #ifdef OPENMC_MPI broadcast_results(); #endif // Write tally results to tallies.out - if (settings::output_tallies && mpi::master) write_tallies(); + if (settings::output_tallies && mpi::master) + write_tallies(); // Deactivate all tallies for (auto& t : model::tallies) { @@ -169,10 +172,13 @@ int openmc_simulation_finalize() simulation::time_finalize.stop(); simulation::time_total.stop(); if (mpi::master) { - if (settings::verbosity >= 6) print_runtime(); - if (settings::verbosity >= 4) print_results(); + if (settings::verbosity >= 6) + print_runtime(); + if (settings::verbosity >= 4) + print_results(); } - if (settings::check_overlaps) print_overlap_check(); + if (settings::check_overlaps) + print_overlap_check(); // Reset flags simulation::initialized = false; @@ -229,7 +235,8 @@ int openmc_next_batch(int* status) return 0; } -bool openmc_is_statepoint_batch() { +bool openmc_is_statepoint_batch() +{ using namespace openmc; using openmc::simulation::current_gen; @@ -283,14 +290,13 @@ void allocate_banks() simulation::source_bank.resize(simulation::work_per_rank); // Allocate fission bank - init_fission_bank(3*simulation::work_per_rank); + init_fission_bank(3 * simulation::work_per_rank); } if (settings::surf_source_write) { // Allocate surface source bank simulation::surf_source_bank.reserve(settings::max_surface_particles); } - } void initialize_batch() @@ -311,7 +317,7 @@ void initialize_batch() if (!settings::restart_run) { first_inactive = settings::n_inactive > 0 && simulation::current_batch == 1; first_active = simulation::current_batch == settings::n_inactive + 1; - } else if (simulation::current_batch == simulation::restart_batch + 1){ + } else if (simulation::current_batch == simulation::restart_batch + 1) { first_inactive = simulation::restart_batch < settings::n_inactive; first_active = !first_inactive; } @@ -345,21 +351,23 @@ void finalize_batch() } // Check_triggers - if (mpi::master) check_triggers(); + if (mpi::master) + check_triggers(); #ifdef OPENMC_MPI MPI_Bcast(&simulation::satisfy_triggers, 1, MPI_C_BOOL, 0, mpi::intracomm); #endif - if (simulation::satisfy_triggers || (settings::trigger_on && - simulation::current_batch == settings::n_max_batches)) { + if (simulation::satisfy_triggers || + (settings::trigger_on && + simulation::current_batch == settings::n_max_batches)) { settings::statepoint_batch.insert(simulation::current_batch); } // Write out state point if it's been specified for this batch and is not // a CMFD run instance - if (contains(settings::statepoint_batch, simulation::current_batch) - && !settings::cmfd_run) { - if (contains(settings::sourcepoint_batch, simulation::current_batch) - && settings::source_write && !settings::source_separate) { + if (contains(settings::statepoint_batch, simulation::current_batch) && + !settings::cmfd_run) { + if (contains(settings::sourcepoint_batch, simulation::current_batch) && + settings::source_write && !settings::source_separate) { bool b = (settings::run_mode == RunMode::EIGENVALUE); openmc_statepoint_write(nullptr, &b); } else { @@ -370,8 +378,8 @@ void finalize_batch() if (settings::run_mode == RunMode::EIGENVALUE) { // Write out a separate source point if it's been specified for this batch - if (contains(settings::sourcepoint_batch, simulation::current_batch) - && settings::source_write && settings::source_separate) { + if (contains(settings::sourcepoint_batch, simulation::current_batch) && + settings::source_write && settings::source_separate) { write_source_point(nullptr); } @@ -383,7 +391,8 @@ void finalize_batch() } // Write out surface source if requested. - if (settings::surf_source_write && simulation::current_batch == settings::n_batches) { + if (settings::surf_source_write && + simulation::current_batch == settings::n_batches) { auto filename = settings::path_output + "surface_source.h5"; write_source_point(filename.c_str(), true); } @@ -396,7 +405,8 @@ void initialize_generation() simulation::fission_bank.resize(0); // Count source sites if using uniform fission source weighting - if (settings::ufs_on) ufs_count_sites(); + if (settings::ufs_on) + ufs_count_sites(); // Store current value of tracklength k simulation::keff_generation = simulation::global_tallies( @@ -411,8 +421,10 @@ void finalize_generation() // Update global tallies with the accumulation variables if (settings::run_mode == RunMode::EIGENVALUE) { gt(GlobalTally::K_COLLISION, TallyResult::VALUE) += global_tally_collision; - gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) += global_tally_absorption; - gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) += global_tally_tracklength; + gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) += + global_tally_absorption; + gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) += + global_tally_tracklength; } gt(GlobalTally::LEAKAGE, TallyResult::VALUE) += global_tally_leakage; @@ -434,7 +446,8 @@ void finalize_generation() synchronize_bank(); // Calculate shannon entropy - if (settings::entropy_on) shannon_entropy(); + if (settings::entropy_on) + shannon_entropy(); // Collect results and statistics calculate_generation_keff(); @@ -444,7 +457,6 @@ void finalize_generation() if (mpi::master && settings::verbosity >= 7) { print_generation(); } - } } @@ -456,8 +468,9 @@ void initialize_history(Particle& p, int64_t index_source) p.from_source(&simulation::source_bank[index_source - 1]); } else if (settings::run_mode == RunMode::FIXED_SOURCE) { // initialize random number seed - int64_t id = (simulation::total_gen + overall_generation() - 1)*settings::n_particles + - simulation::work_index[mpi::rank] + index_source; + int64_t id = (simulation::total_gen + overall_generation() - 1) * + settings::n_particles + + simulation::work_index[mpi::rank] + index_source; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample from external source distribution or custom library then set auto site = sample_external_source(&seed); @@ -506,8 +519,8 @@ void initialize_history(Particle& p, int64_t index_source) write_message("Simulating Particle {}", p.id()); } - // Add paricle's starting weight to count for normalizing tallies later - #pragma omp atomic +// Add paricle's starting weight to count for normalizing tallies later +#pragma omp atomic simulation::total_weight += p.wgt(); // Force calculation of cross-sections by setting last energy to zero @@ -523,7 +536,7 @@ void initialize_history(Particle& p, int64_t index_source) int overall_generation() { using namespace simulation; - return settings::gen_per_batch*(current_batch - 1) + current_gen; + return settings::gen_per_batch * (current_batch - 1) + current_gen; } void calculate_work() @@ -542,7 +555,8 @@ void calculate_work() int64_t work_i = i < remainder ? min_work + 1 : min_work; // Set number of particles - if (mpi::rank == i) simulation::work_per_rank = work_i; + if (mpi::rank == i) + simulation::work_per_rank = work_i; // Set index into source bank for rank i i_bank += work_i; @@ -558,10 +572,10 @@ void initialize_data() for (const auto& nuc : data::nuclides) { if (nuc->grid_.size() >= 1) { int neutron = static_cast(ParticleType::neutron); - data::energy_min[neutron] = std::max(data::energy_min[neutron], - nuc->grid_[0].energy.front()); - data::energy_max[neutron] = std::min(data::energy_max[neutron], - nuc->grid_[0].energy.back()); + data::energy_min[neutron] = + std::max(data::energy_min[neutron], nuc->grid_[0].energy.front()); + data::energy_max[neutron] = + std::min(data::energy_max[neutron], nuc->grid_[0].energy.back()); } } @@ -570,10 +584,10 @@ void initialize_data() if (elem->energy_.size() >= 1) { int photon = static_cast(ParticleType::photon); int n = elem->energy_.size(); - data::energy_min[photon] = std::max(data::energy_min[photon], - std::exp(elem->energy_(1))); - data::energy_max[photon] = std::min(data::energy_max[photon], - std::exp(elem->energy_(n - 1))); + data::energy_min[photon] = + std::max(data::energy_min[photon], std::exp(elem->energy_(1))); + data::energy_max[photon] = + std::min(data::energy_max[photon], std::exp(elem->energy_(n - 1))); } } @@ -583,10 +597,10 @@ void initialize_data() if (data::ttb_e_grid.size() >= 1) { int photon = static_cast(ParticleType::photon); int n_e = data::ttb_e_grid.size(); - data::energy_min[photon] = std::max(data::energy_min[photon], - std::exp(data::ttb_e_grid(1))); - data::energy_max[photon] = std::min(data::energy_max[photon], - std::exp(data::ttb_e_grid(n_e - 1))); + data::energy_min[photon] = + std::max(data::energy_min[photon], std::exp(data::ttb_e_grid(1))); + data::energy_max[photon] = std::min( + data::energy_max[photon], std::exp(data::ttb_e_grid(n_e - 1))); } } } @@ -603,7 +617,7 @@ void initialize_data() data::energy_max[neutron], nuc->name_); if (mpi::master && data::energy_max[neutron] < 20.0e6) { warning("Maximum neutron energy is below 20 MeV. This may bias " - "the results."); + "the results."); } break; } @@ -615,12 +629,14 @@ void initialize_data() nuc->init_grid(); } int neutron = static_cast(ParticleType::neutron); - simulation::log_spacing = std::log(data::energy_max[neutron] / - data::energy_min[neutron]) / settings::n_log_bins; + simulation::log_spacing = + std::log(data::energy_max[neutron] / data::energy_min[neutron]) / + settings::n_log_bins; } #ifdef OPENMC_MPI -void broadcast_results() { +void broadcast_results() +{ // Broadcast tally results so that each process has access to results for (auto& t : model::tallies) { // Create a new datatype that consists of all values for a given filter @@ -643,8 +659,8 @@ void broadcast_results() { // These guys are needed so that non-master processes can calculate the // combined estimate of k-effective - double temp[] {simulation::k_col_abs, simulation::k_col_tra, - simulation::k_abs_tra}; + double temp[] { + simulation::k_col_abs, simulation::k_col_tra, simulation::k_abs_tra}; MPI_Bcast(temp, 3, MPI_DOUBLE, 0, mpi::intracomm); simulation::k_col_abs = temp[0]; simulation::k_col_tra = temp[1]; @@ -678,7 +694,7 @@ void transport_history_based_single_particle(Particle& p) void transport_history_based() { - #pragma omp parallel for schedule(runtime) +#pragma omp parallel for schedule(runtime) for (int64_t i_work = 1; i_work <= simulation::work_per_rank; ++i_work) { Particle p; initialize_history(p, i_work); @@ -698,7 +714,8 @@ void transport_event_based() // loop is executed multiple times until all particles have been completed. while (remaining_work > 0) { // Figure out # of particles to run for this subiteration - int64_t n_particles = std::min(remaining_work, settings::max_particles_in_flight); + int64_t n_particles = + std::min(remaining_work, settings::max_particles_in_flight); // Initialize all particle histories for this subiteration process_init_events(n_particles, source_offset); @@ -706,8 +723,7 @@ void transport_event_based() // Event-based transport loop while (true) { // Determine which event kernel has the longest queue - int64_t max = std::max({ - simulation::calculate_fuel_xs_queue.size(), + int64_t max = std::max({simulation::calculate_fuel_xs_queue.size(), simulation::calculate_nonfuel_xs_queue.size(), simulation::advance_particle_queue.size(), simulation::surface_crossing_queue.size(), diff --git a/src/source.cpp b/src/source.cpp index 909e87125..9c897dcf3 100644 --- a/src/source.cpp +++ b/src/source.cpp @@ -1,6 +1,6 @@ #include "openmc/source.h" -#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) +#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #define HAS_DYNAMIC_LINKING #endif @@ -10,8 +10,8 @@ #include // for dlopen, dlsym, dlclose, dlerror #endif -#include #include "xtensor/xadapt.hpp" +#include #include "openmc/bank.h" #include "openmc/capi.h" @@ -46,8 +46,11 @@ vector> external_sources; // IndependentSource implementation //============================================================================== -IndependentSource::IndependentSource(UPtrSpace space, UPtrAngle angle, UPtrDist energy) - : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { } +IndependentSource::IndependentSource( + UPtrSpace space, UPtrAngle angle, UPtrDist energy) + : space_ {std::move(space)}, angle_ {std::move(angle)}, energy_ { + std::move(energy)} +{} IndependentSource::IndependentSource(pugi::xml_node node) { @@ -84,17 +87,17 @@ IndependentSource::IndependentSource(pugi::xml_node node) if (check_for_node(node_space, "type")) type = get_node_value(node_space, "type", true, true); if (type == "cartesian") { - space_ = UPtrSpace{new CartesianIndependent(node_space)}; + space_ = UPtrSpace {new CartesianIndependent(node_space)}; } else if (type == "cylindrical") { - space_ = UPtrSpace{new CylindricalIndependent(node_space)}; + space_ = UPtrSpace {new CylindricalIndependent(node_space)}; } else if (type == "spherical") { - space_ = UPtrSpace{new SphericalIndependent(node_space)}; + space_ = UPtrSpace {new SphericalIndependent(node_space)}; } else if (type == "box") { - space_ = UPtrSpace{new SpatialBox(node_space)}; + space_ = UPtrSpace {new SpatialBox(node_space)}; } else if (type == "fission") { - space_ = UPtrSpace{new SpatialBox(node_space, true)}; + space_ = UPtrSpace {new SpatialBox(node_space, true)}; } else if (type == "point") { - space_ = UPtrSpace{new SpatialPoint(node_space)}; + space_ = UPtrSpace {new SpatialPoint(node_space)}; } else { fatal_error(fmt::format( "Invalid spatial distribution for external source: {}", type)); @@ -102,7 +105,7 @@ IndependentSource::IndependentSource(pugi::xml_node node) } else { // If no spatial distribution specified, make it a point source - space_ = UPtrSpace{new SpatialPoint()}; + space_ = UPtrSpace {new SpatialPoint()}; } // Determine external source angular distribution @@ -115,18 +118,18 @@ IndependentSource::IndependentSource(pugi::xml_node node) if (check_for_node(node_angle, "type")) type = get_node_value(node_angle, "type", true, true); if (type == "isotropic") { - angle_ = UPtrAngle{new Isotropic()}; + angle_ = UPtrAngle {new Isotropic()}; } else if (type == "monodirectional") { - angle_ = UPtrAngle{new Monodirectional(node_angle)}; + angle_ = UPtrAngle {new Monodirectional(node_angle)}; } else if (type == "mu-phi") { - angle_ = UPtrAngle{new PolarAzimuthal(node_angle)}; + angle_ = UPtrAngle {new PolarAzimuthal(node_angle)}; } else { fatal_error(fmt::format( "Invalid angular distribution for external source: {}", type)); } } else { - angle_ = UPtrAngle{new Isotropic()}; + angle_ = UPtrAngle {new Isotropic()}; } // Determine external source energy distribution @@ -135,7 +138,7 @@ IndependentSource::IndependentSource(pugi::xml_node node) energy_ = distribution_from_xml(node_dist); } else { // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1 - energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)}; + energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)}; } } } @@ -171,13 +174,14 @@ SourceSite IndependentSource::sample(uint64_t* seed) const if (space_box->only_fissionable()) { // Determine material const auto& c = model::cells[cell_index]; - auto mat_index = c->material_.size() == 1 - ? c->material_[0] : c->material_[instance]; + auto mat_index = + c->material_.size() == 1 ? c->material_[0] : c->material_[instance]; if (mat_index == MATERIAL_VOID) { found = false; } else { - if (!model::materials[mat_index]->fissionable_) found = false; + if (!model::materials[mat_index]->fissionable_) + found = false; } } } @@ -187,7 +191,7 @@ SourceSite IndependentSource::sample(uint64_t* seed) const if (!found) { ++n_reject; if (n_reject >= EXTSRC_REJECT_THRESHOLD && - static_cast(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) { + static_cast(n_accept) / n_reject <= EXTSRC_REJECT_FRACTION) { fatal_error("More than 95% of external source sites sampled were " "rejected. Please check your external source definition."); } @@ -219,7 +223,8 @@ SourceSite IndependentSource::sample(uint64_t* seed) const site.E = energy_->sample(seed); // Resample if energy falls outside minimum or maximum particle energy - if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break; + if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) + break; } // Set delayed group @@ -264,7 +269,7 @@ FileSource::FileSource(std::string path) SourceSite FileSource::sample(uint64_t* seed) const { - size_t i_site = sites_.size()*prn(seed); + size_t i_site = sites_.size() * prn(seed); return sites_[i_site]; } @@ -272,7 +277,8 @@ SourceSite FileSource::sample(uint64_t* seed) const // CustomSourceWrapper implementation //============================================================================== -CustomSourceWrapper::CustomSourceWrapper(std::string path, std::string parameters) +CustomSourceWrapper::CustomSourceWrapper( + std::string path, std::string parameters) { #ifdef HAS_DYNAMIC_LINKING // Open the library @@ -291,7 +297,8 @@ CustomSourceWrapper::CustomSourceWrapper(std::string path, std::string parameter // check for any dlsym errors auto dlsym_error = dlerror(); if (dlsym_error) { - std::string error_msg = fmt::format("Couldn't open the openmc_create_source symbol: {}", dlsym_error); + std::string error_msg = fmt::format( + "Couldn't open the openmc_create_source symbol: {}", dlsym_error); dlclose(shared_library_); fatal_error(error_msg); } @@ -301,14 +308,15 @@ CustomSourceWrapper::CustomSourceWrapper(std::string path, std::string parameter #else fatal_error("Custom source libraries have not yet been implemented for " - "non-POSIX systems"); + "non-POSIX systems"); #endif } CustomSourceWrapper::~CustomSourceWrapper() { // Make sure custom source is cleared before closing shared library - if (custom_source_.get()) custom_source_.reset(); + if (custom_source_.get()) + custom_source_.reset(); #ifdef HAS_DYNAMIC_LINKING dlclose(shared_library_); @@ -326,12 +334,12 @@ void initialize_source() { write_message("Initializing source particles...", 5); - // Generation source sites from specified distribution in user input - #pragma omp parallel for +// Generation source sites from specified distribution in user input +#pragma omp parallel for for (int64_t i = 0; i < simulation::work_per_rank; ++i) { // initialize random number seed - int64_t id = simulation::total_gen*settings::n_particles + - simulation::work_index[mpi::rank] + i + 1; + int64_t id = simulation::total_gen * settings::n_particles + + simulation::work_index[mpi::rank] + i + 1; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample external source distribution @@ -358,11 +366,12 @@ SourceSite sample_external_source(uint64_t* seed) // Sample from among multiple source distributions int i = 0; if (model::external_sources.size() > 1) { - double xi = prn(seed)*total_strength; + double xi = prn(seed) * total_strength; double c = 0.0; for (; i < model::external_sources.size(); ++i) { c += model::external_sources[i]->strength(); - if (xi < c) break; + if (xi < c) + break; } } diff --git a/src/state_point.cpp b/src/state_point.cpp index f98727a08..51de51216 100644 --- a/src/state_point.cpp +++ b/src/state_point.cpp @@ -4,9 +4,9 @@ #include // for int64_t #include -#include #include "xtensor/xbuilder.hpp" // for empty_like #include "xtensor/xview.hpp" +#include #include "openmc/bank.h" #include "openmc/capi.h" @@ -30,8 +30,7 @@ namespace openmc { -extern "C" int -openmc_statepoint_write(const char* filename, bool* write_source) +extern "C" int openmc_statepoint_write(const char* filename, bool* write_source) { simulation::time_statepoint.start(); @@ -44,8 +43,8 @@ openmc_statepoint_write(const char* filename, bool* write_source) int w = std::to_string(settings::n_max_batches).size(); // Set filename for state point - filename_ = fmt::format("{0}statepoint.{1:0{2}}.h5", - settings::path_output, simulation::current_batch, w); + filename_ = fmt::format("{0}statepoint.{1:0{2}}.h5", settings::path_output, + simulation::current_batch, w); } // Determine whether or not to write the source bank @@ -81,8 +80,8 @@ openmc_statepoint_write(const char* filename, bool* write_source) write_dataset(file_id, "seed", openmc_get_seed()); // Write run information - write_dataset(file_id, "energy_mode", settings::run_CE ? - "continuous-energy" : "multi-group"); + write_dataset(file_id, "energy_mode", + settings::run_CE ? "continuous-energy" : "multi-group"); switch (settings::run_mode) { case RunMode::FIXED_SOURCE: write_dataset(file_id, "run_mode", "fixed source"); @@ -116,20 +115,21 @@ openmc_statepoint_write(const char* filename, bool* write_source) if (!model::tally_derivs.empty()) { hid_t derivs_group = create_group(tallies_group, "derivatives"); for (const auto& deriv : model::tally_derivs) { - hid_t deriv_group = create_group(derivs_group, - "derivative " + std::to_string(deriv.id)); + hid_t deriv_group = + create_group(derivs_group, "derivative " + std::to_string(deriv.id)); write_dataset(deriv_group, "material", deriv.diff_material); if (deriv.variable == DerivativeVariable::DENSITY) { write_dataset(deriv_group, "independent variable", "density"); } else if (deriv.variable == DerivativeVariable::NUCLIDE_DENSITY) { write_dataset(deriv_group, "independent variable", "nuclide_density"); - write_dataset(deriv_group, "nuclide", - data::nuclides[deriv.diff_nuclide]->name_); + write_dataset( + deriv_group, "nuclide", data::nuclides[deriv.diff_nuclide]->name_); } else if (deriv.variable == DerivativeVariable::TEMPERATURE) { write_dataset(deriv_group, "independent variable", "temperature"); } else { - fatal_error("Independent variable for derivative " - + std::to_string(deriv.id) + " not defined in state_point.cpp"); + fatal_error("Independent variable for derivative " + + std::to_string(deriv.id) + + " not defined in state_point.cpp"); } close_group(deriv_group); } @@ -149,8 +149,8 @@ openmc_statepoint_write(const char* filename, bool* write_source) // Write info for each filter for (const auto& filt : model::tally_filters) { - hid_t filter_group = create_group(filters_group, - "filter " + std::to_string(filt->id())); + hid_t filter_group = + create_group(filters_group, "filter " + std::to_string(filt->id())); filt->to_statepoint(filter_group); close_group(filter_group); } @@ -169,10 +169,10 @@ openmc_statepoint_write(const char* filename, bool* write_source) // Write all tally information except results for (const auto& tally : model::tallies) { - hid_t tally_group = create_group(tallies_group, - "tally " + std::to_string(tally->id_)); + hid_t tally_group = + create_group(tallies_group, "tally " + std::to_string(tally->id_)); - write_dataset(tally_group, "name", tally->name_); + write_dataset(tally_group, "name", tally->name_); if (tally->writable_) { write_attribute(tally_group, "internal", 0); @@ -217,18 +217,19 @@ openmc_statepoint_write(const char* filename, bool* write_source) } write_dataset(tally_group, "nuclides", nuclides); - if (tally->deriv_ != C_NONE) write_dataset(tally_group, "derivative", - model::tally_derivs[tally->deriv_].id); + if (tally->deriv_ != C_NONE) + write_dataset( + tally_group, "derivative", model::tally_derivs[tally->deriv_].id); // Write the tally score bins vector scores; - for (auto sc : tally->scores_) scores.push_back(reaction_name(sc)); + for (auto sc : tally->scores_) + scores.push_back(reaction_name(sc)); write_dataset(tally_group, "n_score_bins", scores.size()); write_dataset(tally_group, "score_bins", scores); close_group(tally_group); } - } if (settings::reduce_tallies) { @@ -242,7 +243,8 @@ openmc_statepoint_write(const char* filename, bool* write_source) // Write all tally results for (const auto& tally : model::tallies) { - if (!tally->writable_) continue; + if (!tally->writable_) + continue; // Write sum and sum_sq for each bin std::string name = "tally " + std::to_string(tally->id_); hid_t tally_group = open_group(tallies_group, name.c_str()); @@ -275,23 +277,30 @@ openmc_statepoint_write(const char* filename, bool* write_source) // Write out the runtime metrics. using namespace simulation; hid_t runtime_group = create_group(file_id, "runtime"); - write_dataset(runtime_group, "total initialization", time_initialize.elapsed()); - write_dataset(runtime_group, "reading cross sections", time_read_xs.elapsed()); - write_dataset(runtime_group, "simulation", time_inactive.elapsed() - + time_active.elapsed()); + write_dataset( + runtime_group, "total initialization", time_initialize.elapsed()); + write_dataset( + runtime_group, "reading cross sections", time_read_xs.elapsed()); + write_dataset(runtime_group, "simulation", + time_inactive.elapsed() + time_active.elapsed()); write_dataset(runtime_group, "transport", time_transport.elapsed()); if (settings::run_mode == RunMode::EIGENVALUE) { write_dataset(runtime_group, "inactive batches", time_inactive.elapsed()); } write_dataset(runtime_group, "active batches", time_active.elapsed()); if (settings::run_mode == RunMode::EIGENVALUE) { - write_dataset(runtime_group, "synchronizing fission bank", time_bank.elapsed()); - write_dataset(runtime_group, "sampling source sites", time_bank_sample.elapsed()); - write_dataset(runtime_group, "SEND-RECV source sites", time_bank_sendrecv.elapsed()); + write_dataset( + runtime_group, "synchronizing fission bank", time_bank.elapsed()); + write_dataset( + runtime_group, "sampling source sites", time_bank_sample.elapsed()); + write_dataset( + runtime_group, "SEND-RECV source sites", time_bank_sendrecv.elapsed()); } - write_dataset(runtime_group, "accumulating tallies", time_tallies.elapsed()); + write_dataset( + runtime_group, "accumulating tallies", time_tallies.elapsed()); write_dataset(runtime_group, "total", time_total.elapsed()); - write_dataset(runtime_group, "writing statepoints", time_statepoint.elapsed()); + write_dataset( + runtime_group, "writing statepoints", time_statepoint.elapsed()); close_group(runtime_group); file_close(file_id); @@ -305,9 +314,11 @@ openmc_statepoint_write(const char* filename, bool* write_source) // Write the source bank if desired if (write_source_) { - if (mpi::master || parallel) file_id = file_open(filename_, 'a', true); + if (mpi::master || parallel) + file_id = file_open(filename_, 'a', true); write_source_bank(file_id, false); - if (mpi::master || parallel) file_close(file_id); + if (mpi::master || parallel) + file_close(file_id); } #if defined(LIBMESH) || defined(DAGMC) @@ -327,7 +338,7 @@ void restart_set_keff() simulation::k_sum[0] += simulation::k_generation[i]; simulation::k_sum[1] += std::pow(simulation::k_generation[i], 2); } - int n = settings::gen_per_batch*simulation::n_realizations; + int n = settings::gen_per_batch * simulation::n_realizations; simulation::keff = simulation::k_sum[0] / n; } else { simulation::keff = simulation::k_generation.back(); @@ -354,7 +365,8 @@ void load_state_point() array array; read_attribute(file_id, "version", array); if (array != VERSION_STATEPOINT) { - fatal_error("State point version does not match current version in OpenMC."); + fatal_error( + "State point version does not match current version in OpenMC."); } // Read and overwrite random number seed @@ -367,10 +379,10 @@ void load_state_point() read_dataset(file_id, "energy_mode", word); if (word == "multi-group" && settings::run_CE) { fatal_error("State point file is from multigroup run but current run is " - "continous energy."); + "continous energy."); } else if (word == "continuous-energy" && !settings::run_CE) { fatal_error("State point file is from continuous-energy run but current " - "run is multigroup!"); + "run is multigroup!"); } // Read and overwrite run information except number of batches @@ -393,7 +405,7 @@ void load_state_point() if (simulation::restart_batch > settings::n_batches) { fatal_error("The number batches specified in settings.xml is fewer " - " than the number of batches in the given statepoint file."); + " than the number of batches in the given statepoint file."); } // Logical flag for source present in statepoint file @@ -435,8 +447,8 @@ void load_state_point() if (mpi::master) { #endif // Read global tally data - read_dataset_lowlevel(file_id, "global_tallies", H5T_NATIVE_DOUBLE, - H5S_ALL, false, simulation::global_tallies.data()); + read_dataset_lowlevel(file_id, "global_tallies", H5T_NATIVE_DOUBLE, H5S_ALL, + false, simulation::global_tallies.data()); // Check if tally results are present bool present; @@ -451,7 +463,7 @@ void load_state_point() std::string name = "tally " + std::to_string(tally->id_); hid_t tally_group = open_group(tallies_group, name.c_str()); - int internal=0; + int internal = 0; if (attribute_exists(tally_group, "internal")) { read_attribute(tally_group, "internal", internal); } @@ -481,8 +493,8 @@ void load_state_point() file_close(file_id); // Write message - write_message("Loading source file " + settings::path_sourcepoint - + "...", 5); + write_message( + "Loading source file " + settings::path_sourcepoint + "...", 5); // Open source file file_id = file_open(settings::path_sourcepoint.c_str(), 'r', true); @@ -490,15 +502,14 @@ void load_state_point() // Read source read_source_bank(file_id, simulation::source_bank, true); - } // Close file file_close(file_id); } - -hid_t h5banktype() { +hid_t h5banktype() +{ // Create compound type for position hid_t postype = H5Tcreate(H5T_COMPOUND, sizeof(struct Position)); H5Tinsert(postype, "x", HOFFSET(Position, x), H5T_NATIVE_DOUBLE); @@ -540,7 +551,8 @@ vector calculate_surf_source_size() // surface source banks per process int64_t size = simulation::surf_source_bank.size(); MPI_Scan(&size, bank_size.data(), 1, MPI_INT64_T, MPI_SUM, mpi::intracomm); - MPI_Allgather(bank_size.data(), 1, MPI_INT64_T, surf_source_index.data(), 1, MPI_INT64_T, mpi::intracomm); + MPI_Allgather(bank_size.data(), 1, MPI_INT64_T, surf_source_index.data(), 1, + MPI_INT64_T, mpi::intracomm); surf_source_index.insert(surf_source_index.begin(), 0); #else surf_source_index.push_back(0); @@ -550,8 +562,7 @@ vector calculate_surf_source_size() return surf_source_index; } -void -write_source_point(const char* filename, bool surf_source_bank) +void write_source_point(const char* filename, bool surf_source_bank) { // When using parallel HDF5, the file is written to collectively by all // processes. With MPI-only, the file is opened and written by the master @@ -570,8 +581,8 @@ write_source_point(const char* filename, bool surf_source_bank) // Determine width for zero padding int w = std::to_string(settings::n_max_batches).size(); - filename_ = fmt::format("{0}source.{1:0{2}}.h5", - settings::path_output, simulation::current_batch, w); + filename_ = fmt::format("{0}source.{1:0{2}}.h5", settings::path_output, + simulation::current_batch, w); } hid_t file_id; @@ -583,11 +594,11 @@ write_source_point(const char* filename, bool surf_source_bank) // Get pointer to source bank and write to file write_source_bank(file_id, surf_source_bank); - if (mpi::master || parallel) file_close(file_id); + if (mpi::master || parallel) + file_close(file_id); } -void -write_source_bank(hid_t group_id, bool surf_source_bank) +void write_source_bank(hid_t group_id, bool surf_source_bank) { hid_t banktype = h5banktype(); @@ -612,7 +623,7 @@ write_source_bank(hid_t group_id, bool surf_source_bank) // Copy data in a SharedArray into a vector. surf_source_bank_vector.resize(count_size); surf_source_bank_vector.assign(simulation::surf_source_bank.data(), - simulation::surf_source_bank.data() + count_size); + simulation::surf_source_bank.data() + count_size); source_bank = &surf_source_bank_vector; } @@ -620,8 +631,8 @@ write_source_bank(hid_t group_id, bool surf_source_bank) // Set size of total dataspace for all procs and rank hsize_t dims[] {static_cast(dims_size)}; hid_t dspace = H5Screate_simple(1, dims, nullptr); - hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace, - H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace, H5P_DEFAULT, + H5P_DEFAULT, H5P_DEFAULT); // Create another data space but for each proc individually hsize_t count[] {static_cast(count_size)}; @@ -651,7 +662,7 @@ write_source_bank(hid_t group_id, bool surf_source_bank) hsize_t dims[] {static_cast(dims_size)}; hid_t dspace = H5Screate_simple(1, dims, nullptr); hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace, - H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); // Save source bank sites since the array is overwritten below #ifdef OPENMC_MPI @@ -660,23 +671,26 @@ write_source_bank(hid_t group_id, bool surf_source_bank) for (int i = 0; i < mpi::n_procs; ++i) { // Create memory space - hsize_t count[] {static_cast((*bank_index)[i+1] - (*bank_index)[i])}; + hsize_t count[] { + static_cast((*bank_index)[i + 1] - (*bank_index)[i])}; hid_t memspace = H5Screate_simple(1, count, nullptr); #ifdef OPENMC_MPI // Receive source sites from other processes if (i > 0) MPI_Recv(source_bank->data(), count[0], mpi::source_site, i, i, - mpi::intracomm, MPI_STATUS_IGNORE); + mpi::intracomm, MPI_STATUS_IGNORE); #endif // Select hyperslab for this dataspace dspace = H5Dget_space(dset); hsize_t start[] {static_cast((*bank_index)[i])}; - H5Sselect_hyperslab(dspace, H5S_SELECT_SET, start, nullptr, count, nullptr); + H5Sselect_hyperslab( + dspace, H5S_SELECT_SET, start, nullptr, count, nullptr); // Write data to hyperslab - H5Dwrite(dset, banktype, memspace, dspace, H5P_DEFAULT, (*source_bank).data()); + H5Dwrite( + dset, banktype, memspace, dspace, H5P_DEFAULT, (*source_bank).data()); H5Sclose(memspace); H5Sclose(dspace); @@ -691,8 +705,8 @@ write_source_bank(hid_t group_id, bool surf_source_bank) #endif } else { #ifdef OPENMC_MPI - MPI_Send(source_bank->data(), count_size, mpi::source_site, - 0, mpi::rank, mpi::intracomm); + MPI_Send(source_bank->data(), count_size, mpi::source_site, 0, mpi::rank, + mpi::intracomm); #endif } #endif @@ -707,7 +721,8 @@ std::string dtype_member_names(hid_t dtype_id) std::string names; for (int i = 0; i < nmembers; i++) { names = names.append(H5Tget_member_name(dtype_id, i)); - if (i < nmembers - 1) names += ", "; + if (i < nmembers - 1) + names += ", "; } return names; } @@ -725,9 +740,11 @@ void read_source_bank( auto file_member_names = dtype_member_names(dtype); auto bank_member_names = dtype_member_names(banktype); if (file_member_names != bank_member_names) { - fatal_error(fmt::format("Source site attributes in file do not match what is " + fatal_error(fmt::format( + "Source site attributes in file do not match what is " "expected for this version of OpenMC. File attributes = ({}). Expected " - "attributes = ({})", file_member_names, bank_member_names)); + "attributes = ({})", + file_member_names, bank_member_names)); } hid_t dspace = H5Dget_space(dset); @@ -736,7 +753,8 @@ void read_source_bank( // Make sure vector is big enough in case where we're reading entire source on // each process - if (!distribute) sites.resize(n_sites); + if (!distribute) + sites.resize(n_sites); hid_t memspace; if (distribute) { @@ -751,13 +769,14 @@ void read_source_bank( // Select hyperslab for each process hsize_t offset = simulation::work_index[mpi::rank]; - H5Sselect_hyperslab(dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr); + H5Sselect_hyperslab( + dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr); } else { memspace = H5S_ALL; } #ifdef PHDF5 - // Read data in parallel + // Read data in parallel hid_t plist = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE); H5Dread(dset, banktype, memspace, dspace, plist, sites.data()); @@ -768,35 +787,41 @@ void read_source_bank( // Close all ids H5Sclose(dspace); - if (distribute) H5Sclose(memspace); + if (distribute) + H5Sclose(memspace); H5Dclose(dset); H5Tclose(banktype); } -void write_unstructured_mesh_results() { +void write_unstructured_mesh_results() +{ for (auto& tally : model::tallies) { vector tally_scores; for (auto filter_idx : tally->filters()) { auto& filter = model::tally_filters[filter_idx]; - if (filter->type() != "mesh") continue; + if (filter->type() != "mesh") + continue; // check if the filter uses an unstructured mesh auto mesh_filter = dynamic_cast(filter.get()); auto mesh_idx = mesh_filter->mesh(); - auto umesh = dynamic_cast(model::meshes[mesh_idx].get()); + auto umesh = + dynamic_cast(model::meshes[mesh_idx].get()); - if (!umesh) continue; + if (!umesh) + continue; - if (!umesh->output_) continue; + if (!umesh->output_) + continue; // if this tally has more than one filter, print // warning and skip writing the mesh if (tally->filters().size() > 1) { warning(fmt::format("Skipping unstructured mesh writing for tally " "{}. More than one filter is present on the tally.", - tally->id_)); + tally->id_)); break; } @@ -805,9 +830,8 @@ void write_unstructured_mesh_results() { for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) { for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) { // combine the score and nuclide into a name for the value - auto score_str = fmt::format("{}_{}", - tally->score_name(score_idx), - tally->nuclide_name(nuc_idx)); + auto score_str = fmt::format("{}_{}", tally->score_name(score_idx), + tally->nuclide_name(nuc_idx)); // add this score to the mesh // (this is in a separate loop because all variables need to be added // to libMesh's equation system before any are initialized, which @@ -819,12 +843,11 @@ void write_unstructured_mesh_results() { for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) { for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) { // combine the score and nuclide into a name for the value - auto score_str = fmt::format("{}_{}", - tally->score_name(score_idx), - tally->nuclide_name(nuc_idx)); + auto score_str = fmt::format("{}_{}", tally->score_name(score_idx), + tally->nuclide_name(nuc_idx)); // index for this nuclide and score - int nuc_score_idx = score_idx + nuc_idx*tally->scores_.size(); + int nuc_score_idx = score_idx + nuc_idx * tally->scores_.size(); // construct result vectors vector mean_vec(umesh->n_bins()), @@ -833,21 +856,25 @@ void write_unstructured_mesh_results() { // get the volume for this bin double volume = umesh->volume(j); // compute the mean - double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) / n_realizations; + double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) / + n_realizations; mean_vec.at(j) = mean / volume; // compute the standard deviation - double sum_sq = tally->results_(j , nuc_score_idx, TallyResult::SUM_SQ); + double sum_sq = + tally->results_(j, nuc_score_idx, TallyResult::SUM_SQ); double std_dev {0.0}; if (n_realizations > 1) { - std_dev = sum_sq/n_realizations - mean*mean; + std_dev = sum_sq / n_realizations - mean * mean; std_dev = std::sqrt(std_dev / (n_realizations - 1)); } std_dev_vec[j] = std_dev / volume; } #ifdef OPENMC_MPI - MPI_Bcast(mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm); - MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0, mpi::intracomm); + MPI_Bcast( + mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm); + MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0, + mpi::intracomm); #endif // set the data for this score umesh->set_score_data(score_str, mean_vec, std_dev_vec); @@ -857,12 +884,11 @@ void write_unstructured_mesh_results() { // Generate a file name based on the tally id // and the current batch number size_t batch_width {std::to_string(settings::n_max_batches).size()}; - std::string filename = fmt::format("tally_{0}.{1:0{2}}", - tally->id_, - simulation::current_batch, - batch_width); + std::string filename = fmt::format("tally_{0}.{1:0{2}}", tally->id_, + simulation::current_batch, batch_width); - if (umesh->library() == "moab" && !mpi::master) continue; + if (umesh->library() == "moab" && !mpi::master) + continue; // Write the unstructured mesh and data to file umesh->write(filename); @@ -891,8 +917,8 @@ void write_tally_results_nr(hid_t file_id) #ifdef OPENMC_MPI // Reduce global tallies xt::xtensor gt_reduced = xt::empty_like(gt); - MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, - MPI_SUM, 0, mpi::intracomm); + MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0, + mpi::intracomm); // Transfer values to value on master if (mpi::master) { @@ -910,8 +936,10 @@ void write_tally_results_nr(hid_t file_id) for (const auto& t : model::tallies) { // Skip any tallies that are not active - if (!t->active_) continue; - if (!t->writable_) continue; + if (!t->active_) + continue; + if (!t->writable_) + continue; if (mpi::master && !attribute_exists(file_id, "tallies_present")) { write_attribute(file_id, "tallies_present", 1); @@ -919,7 +947,8 @@ void write_tally_results_nr(hid_t file_id) // Get view of accumulated tally values auto values_view = xt::view(t->results_, xt::all(), xt::all(), - xt::range(static_cast(TallyResult::SUM), static_cast(TallyResult::SUM_SQ) + 1)); + xt::range(static_cast(TallyResult::SUM), + static_cast(TallyResult::SUM_SQ) + 1)); // Make copy of tally values in contiguous array xt::xtensor values = values_view; @@ -946,7 +975,8 @@ void write_tally_results_nr(hid_t file_id) // Put in temporary tally result xt::xtensor results_copy = xt::zeros_like(t->results_); auto copy_view = xt::view(results_copy, xt::all(), xt::all(), - xt::range(static_cast(TallyResult::SUM), static_cast(TallyResult::SUM_SQ) + 1)); + xt::range(static_cast(TallyResult::SUM), + static_cast(TallyResult::SUM_SQ) + 1)); copy_view = values; // Write reduced tally results to file @@ -957,8 +987,8 @@ void write_tally_results_nr(hid_t file_id) } else { // Receive buffer not significant at other processors #ifdef OPENMC_MPI - MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, - 0, mpi::intracomm); + MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0, + mpi::intracomm); #endif } } diff --git a/src/string_utils.cpp b/src/string_utils.cpp index 5ad977aab..3b1c1b4a6 100644 --- a/src/string_utils.cpp +++ b/src/string_utils.cpp @@ -14,7 +14,6 @@ std::string& strtrim(std::string& s) return s; } - char* strtrim(char* c_str) { std::string std_str; @@ -25,16 +24,16 @@ char* strtrim(char* c_str) return c_str; } - -std::string to_element(const std::string& name) { +std::string to_element(const std::string& name) +{ int pos = name.find_first_of("0123456789"); return name.substr(0, pos); } - void to_lower(std::string& str) { - for (int i = 0; i < str.size(); i++) str[i] = std::tolower(str[i]); + for (int i = 0; i < str.size(); i++) + str[i] = std::tolower(str[i]); } int word_count(std::string const& str) @@ -42,7 +41,9 @@ int word_count(std::string const& str) std::stringstream stream(str); std::string dum; int count = 0; - while (stream >> dum) {count++;} + while (stream >> dum) { + count++; + } return count; } @@ -50,7 +51,7 @@ vector split(const std::string& in) { vector out; - for (int i = 0; i < in.size(); ) { + for (int i = 0; i < in.size();) { // Increment i until we find a non-whitespace character. if (std::isspace(in[i])) { i++; @@ -58,10 +59,12 @@ vector split(const std::string& in) } else { // Find the next whitespace character at j. int j = i + 1; - while (j < in.size() && std::isspace(in[j]) == 0) {j++;} + while (j < in.size() && std::isspace(in[j]) == 0) { + j++; + } // Push-back everything between i and j. - out.push_back(in.substr(i, j-i)); + out.push_back(in.substr(i, j - i)); i = j + 1; // j is whitespace so leapfrog to j+1 } } @@ -71,13 +74,15 @@ vector split(const std::string& in) bool ends_with(const std::string& value, const std::string& ending) { - if (ending.size() > value.size()) return false; + if (ending.size() > value.size()) + return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } bool starts_with(const std::string& value, const std::string& beginning) { - if (beginning.size() > value.size()) return false; + if (beginning.size() > value.size()) + return false; return std::equal(beginning.begin(), beginning.end(), value.begin()); } diff --git a/src/summary.cpp b/src/summary.cpp index 26bf20fe4..fc81ac7bb 100644 --- a/src/summary.cpp +++ b/src/summary.cpp @@ -12,8 +12,8 @@ #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/output.h" -#include "openmc/surface.h" #include "openmc/settings.h" +#include "openmc/surface.h" namespace openmc { @@ -100,19 +100,23 @@ void write_geometry(hid_t file) write_attribute(geom_group, "n_lattices", model::lattices.size()); auto cells_group = create_group(geom_group, "cells"); - for (const auto& c : model::cells) c->to_hdf5(cells_group); + for (const auto& c : model::cells) + c->to_hdf5(cells_group); close_group(cells_group); auto surfaces_group = create_group(geom_group, "surfaces"); - for (const auto& surf : model::surfaces) surf->to_hdf5(surfaces_group); + for (const auto& surf : model::surfaces) + surf->to_hdf5(surfaces_group); close_group(surfaces_group); auto universes_group = create_group(geom_group, "universes"); - for (const auto& u : model::universes) u->to_hdf5(universes_group); + for (const auto& u : model::universes) + u->to_hdf5(universes_group); close_group(universes_group); auto lattices_group = create_group(geom_group, "lattices"); - for (const auto& lat : model::lattices) lat->to_hdf5(lattices_group); + for (const auto& lat : model::lattices) + lat->to_hdf5(lattices_group); close_group(lattices_group); close_group(geom_group); @@ -137,7 +141,8 @@ void write_materials(hid_t file) extern "C" int openmc_properties_export(const char* filename) { // Only write from master process - if (!mpi::master) return 0; + if (!mpi::master) + return 0; // Set a default filename if none was passed std::string name = filename ? filename : "properties.h5"; @@ -211,7 +216,8 @@ extern "C" int openmc_properties_import(const char* filename) if (n != openmc::model::cells.size()) { close_group(geom_group); file_close(file); - set_errmsg(fmt::format("Number of cells in {} doesn't match current model.", filename)); + set_errmsg(fmt::format( + "Number of cells in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } @@ -234,7 +240,8 @@ extern "C" int openmc_properties_import(const char* filename) if (n != openmc::model::materials.size()) { close_group(materials_group); file_close(file); - set_errmsg(fmt::format("Number of materials in {} doesn't match current model.", filename)); + set_errmsg(fmt::format( + "Number of materials in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } diff --git a/src/surface.cpp b/src/surface.cpp index 1de606198..c19de1e00 100644 --- a/src/surface.cpp +++ b/src/surface.cpp @@ -1,8 +1,8 @@ #include "openmc/surface.h" #include -#include #include +#include #include #include @@ -24,22 +24,22 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map surface_map; - vector> surfaces; +std::unordered_map surface_map; +vector> surfaces; } // namespace model //============================================================================== // Helper functions for reading the "coeffs" node of an XML surface element //============================================================================== -void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double& c1) { // Check the given number of coefficients. std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 1) { - fatal_error(fmt::format("Surface {} expects 1 coeff but was given {}", - surf_id, n_words)); + fatal_error(fmt::format( + "Surface {} expects 1 coeff but was given {}", surf_id, n_words)); } // Parse the coefficients. @@ -49,15 +49,15 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1) } } -void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, - double &c3) +void read_coeffs( + pugi::xml_node surf_node, int surf_id, double& c1, double& c2, double& c3) { // Check the given number of coefficients. std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 3) { - fatal_error(fmt::format("Surface {} expects 3 coeffs but was given {}", - surf_id, n_words)); + fatal_error(fmt::format( + "Surface {} expects 3 coeffs but was given {}", surf_id, n_words)); } // Parse the coefficients. @@ -67,15 +67,15 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, } } -void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, - double &c3, double &c4) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double& c1, double& c2, + double& c3, double& c4) { // Check the given number of coefficients. std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 4) { - fatal_error(fmt::format("Surface {} expects 4 coeffs but was given ", - surf_id, n_words)); + fatal_error(fmt::format( + "Surface {} expects 4 coeffs but was given ", surf_id, n_words)); } // Parse the coefficients. @@ -85,21 +85,21 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, } } -void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, - double &c3, double &c4, double &c5, double &c6, double &c7, - double &c8, double &c9, double &c10) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double& c1, double& c2, + double& c3, double& c4, double& c5, double& c6, double& c7, double& c8, + double& c9, double& c10) { // Check the given number of coefficients. std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 10) { - fatal_error(fmt::format("Surface {} expects 10 coeffs but was given {}", - surf_id, n_words)); + fatal_error(fmt::format( + "Surface {} expects 10 coeffs but was given {}", surf_id, n_words)); } // Parse the coefficients. int stat = sscanf(coeffs.c_str(), "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", - &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); + &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); if (stat != 10) { fatal_error("Something went wrong reading surface coeffs"); } @@ -129,12 +129,12 @@ Surface::Surface(pugi::xml_node surf_node) if (check_for_node(surf_node, "boundary")) { std::string surf_bc = get_node_value(surf_node, "boundary", true, true); - if (surf_bc == "transmission" || surf_bc == "transmit" ||surf_bc.empty()) { + if (surf_bc == "transmission" || surf_bc == "transmit" || surf_bc.empty()) { // Leave the bc_ a nullptr } else if (surf_bc == "vacuum") { bc_ = std::make_shared(); - } else if (surf_bc == "reflective" || surf_bc == "reflect" - || surf_bc == "reflecting") { + } else if (surf_bc == "reflective" || surf_bc == "reflect" || + surf_bc == "reflecting") { bc_ = std::make_shared(); } else if (surf_bc == "white") { bc_ = std::make_shared(); @@ -142,14 +142,13 @@ Surface::Surface(pugi::xml_node surf_node) // periodic BC's are handled separately } else { fatal_error(fmt::format("Unknown boundary condition \"{}\" specified " - "on surface {}", surf_bc, id_)); + "on surface {}", + surf_bc, id_)); } } - } -bool -Surface::sense(Position r, Direction u) const +bool Surface::sense(Position r, Direction u) const { // Evaluate the surface equation at the particle's coordinates to determine // which side the particle is on. @@ -165,8 +164,7 @@ Surface::sense(Position r, Direction u) const return f > 0.0; } -Direction -Surface::reflect(Position r, Direction u, Particle* p) const +Direction Surface::reflect(Position r, Direction u, Particle* p) const { // Determine projection of direction onto normal and squared magnitude of // normal. @@ -176,8 +174,8 @@ Surface::reflect(Position r, Direction u, Particle* p) const return u.reflect(n); } -Direction -Surface::diffuse_reflect(Position r, Direction u, uint64_t* seed) const +Direction Surface::diffuse_reflect( + Position r, Direction u, uint64_t* seed) const { // Diffuse reflect direction according to the normal. // cosine distribution @@ -187,18 +185,17 @@ Surface::diffuse_reflect(Position r, Direction u, uint64_t* seed) const const double projection = n.dot(u); // sample from inverse function, u=sqrt(rand) since p(u)=2u, so F(u)=u^2 - const double mu = (projection>=0.0) ? - -std::sqrt(prn(seed)) : std::sqrt(prn(seed)); + const double mu = + (projection >= 0.0) ? -std::sqrt(prn(seed)) : std::sqrt(prn(seed)); // sample azimuthal distribution uniformly u = rotate_angle(n, mu, nullptr, seed); // normalize the direction - return u/u.norm(); + return u / u.norm(); } -void -Surface::to_hdf5(hid_t group_id) const +void Surface::to_hdf5(hid_t group_id) const { hid_t surf_group = create_group(group_id, fmt::format("surface {}", id_)); @@ -223,10 +220,12 @@ Surface::to_hdf5(hid_t group_id) const close_group(surf_group); } -CSGSurface::CSGSurface() : Surface{} { +CSGSurface::CSGSurface() : Surface {} +{ geom_type_ = GeometryType::CSG; }; -CSGSurface::CSGSurface(pugi::xml_node surf_node) : Surface{surf_node} { +CSGSurface::CSGSurface(pugi::xml_node surf_node) : Surface {surf_node} +{ geom_type_ = GeometryType::CSG; }; @@ -235,13 +234,16 @@ CSGSurface::CSGSurface(pugi::xml_node surf_node) : Surface{surf_node} { //============================================================================== // The template parameter indicates the axis normal to the plane. -template double -axis_aligned_plane_distance(Position r, Direction u, bool coincident, double offset) +template +double axis_aligned_plane_distance( + Position r, Direction u, bool coincident, double offset) { const double f = offset - r[i]; - if (coincident || std::abs(f) < FP_COINCIDENT || u[i] == 0.0) return INFTY; + if (coincident || std::abs(f) < FP_COINCIDENT || u[i] == 0.0) + return INFTY; const double d = f / u[i]; - if (d < 0.0) return INFTY; + if (d < 0.0) + return INFTY; return d; } @@ -249,8 +251,7 @@ axis_aligned_plane_distance(Position r, Direction u, bool coincident, double off // SurfaceXPlane implementation //============================================================================== -SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, x0_); } @@ -277,8 +278,7 @@ void SurfaceXPlane::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox -SurfaceXPlane::bounding_box(bool pos_side) const +BoundingBox SurfaceXPlane::bounding_box(bool pos_side) const { if (pos_side) { return {x0_, INFTY, -INFTY, INFTY, -INFTY, INFTY}; @@ -291,8 +291,7 @@ SurfaceXPlane::bounding_box(bool pos_side) const // SurfaceYPlane implementation //============================================================================== -SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, y0_); } @@ -319,8 +318,7 @@ void SurfaceYPlane::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox -SurfaceYPlane::bounding_box(bool pos_side) const +BoundingBox SurfaceYPlane::bounding_box(bool pos_side) const { if (pos_side) { return {-INFTY, INFTY, y0_, INFTY, -INFTY, INFTY}; @@ -333,8 +331,7 @@ SurfaceYPlane::bounding_box(bool pos_side) const // SurfaceZPlane implementation //============================================================================== -SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, z0_); } @@ -361,8 +358,7 @@ void SurfaceZPlane::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox -SurfaceZPlane::bounding_box(bool pos_side) const +BoundingBox SurfaceZPlane::bounding_box(bool pos_side) const { if (pos_side) { return {-INFTY, INFTY, -INFTY, INFTY, z0_, INFTY}; @@ -375,34 +371,31 @@ SurfaceZPlane::bounding_box(bool pos_side) const // SurfacePlane implementation //============================================================================== -SurfacePlane::SurfacePlane(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfacePlane::SurfacePlane(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, A_, B_, C_, D_); } -double -SurfacePlane::evaluate(Position r) const +double SurfacePlane::evaluate(Position r) const { - return A_*r.x + B_*r.y + C_*r.z - D_; + return A_ * r.x + B_ * r.y + C_ * r.z - D_; } -double -SurfacePlane::distance(Position r, Direction u, bool coincident) const +double SurfacePlane::distance(Position r, Direction u, bool coincident) const { - const double f = A_*r.x + B_*r.y + C_*r.z - D_; - const double projection = A_*u.x + B_*u.y + C_*u.z; + const double f = A_ * r.x + B_ * r.y + C_ * r.z - D_; + const double projection = A_ * u.x + B_ * u.y + C_ * u.z; if (coincident || std::abs(f) < FP_COINCIDENT || projection == 0.0) { return INFTY; } else { const double d = -f / projection; - if (d < 0.0) return INFTY; + if (d < 0.0) + return INFTY; return d; } } -Direction -SurfacePlane::normal(Position r) const +Direction SurfacePlane::normal(Position r) const { return {A_, B_, C_}; } @@ -421,30 +414,31 @@ void SurfacePlane::to_hdf5_inner(hid_t group_id) const // The template parameters indicate the axes perpendicular to the axis of the // cylinder. offset1 and offset2 should correspond with i1 and i2, // respectively. -template double -axis_aligned_cylinder_evaluate(Position r, double offset1, - double offset2, double radius) +template +double axis_aligned_cylinder_evaluate( + Position r, double offset1, double offset2, double radius) { const double r1 = r.get() - offset1; const double r2 = r.get() - offset2; - return r1*r1 + r2*r2 - radius*radius; + return r1 * r1 + r2 * r2 - radius * radius; } // The first template parameter indicates which axis the cylinder is aligned to. // The other two parameters indicate the other two axes. offset1 and offset2 // should correspond with i2 and i3, respectively. -template double -axis_aligned_cylinder_distance(Position r, Direction u, - bool coincident, double offset1, double offset2, double radius) +template +double axis_aligned_cylinder_distance(Position r, Direction u, bool coincident, + double offset1, double offset2, double radius) { const double a = 1.0 - u.get() * u.get(); // u^2 + v^2 - if (a == 0.0) return INFTY; + if (a == 0.0) + return INFTY; const double r2 = r.get() - offset1; const double r3 = r.get() - offset2; const double k = r2 * u.get() + r3 * u.get(); - const double c = r2*r2 + r3*r3 - radius*radius; - const double quad = k*k - a*c; + const double c = r2 * r2 + r3 * r3 - radius * radius; + const double quad = k * k - a * c; if (quad < 0.0) { // No intersection with cylinder. @@ -471,7 +465,8 @@ axis_aligned_cylinder_distance(Position r, Direction u, // positive or negative. If positive, the smaller distance is the one // with positive sign on sqrt(quad). const double d = (-k - sqrt(quad)) / a; - if (d < 0.0) return INFTY; + if (d < 0.0) + return INFTY; return d; } } @@ -479,8 +474,9 @@ axis_aligned_cylinder_distance(Position r, Direction u, // The first template parameter indicates which axis the cylinder is aligned to. // The other two parameters indicate the other two axes. offset1 and offset2 // should correspond with i2 and i3, respectively. -template Direction -axis_aligned_cylinder_normal(Position r, double offset1, double offset2) +template +Direction axis_aligned_cylinder_normal( + Position r, double offset1, double offset2) { Direction u; u.get() = 2.0 * (r.get() - offset1); @@ -504,10 +500,11 @@ double SurfaceXCylinder::evaluate(Position r) const return axis_aligned_cylinder_evaluate<1, 2>(r, y0_, z0_, radius_); } -double SurfaceXCylinder::distance(Position r, Direction u, bool coincident) const +double SurfaceXCylinder::distance( + Position r, Direction u, bool coincident) const { - return axis_aligned_cylinder_distance<0, 1, 2>(r, u, coincident, y0_, z0_, - radius_); + return axis_aligned_cylinder_distance<0, 1, 2>( + r, u, coincident, y0_, z0_, radius_); } Direction SurfaceXCylinder::normal(Position r) const @@ -522,9 +519,11 @@ void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox SurfaceXCylinder::bounding_box(bool pos_side) const { +BoundingBox SurfaceXCylinder::bounding_box(bool pos_side) const +{ if (!pos_side) { - return {-INFTY, INFTY, y0_ - radius_, y0_ + radius_, z0_ - radius_, z0_ + radius_}; + return {-INFTY, INFTY, y0_ - radius_, y0_ + radius_, z0_ - radius_, + z0_ + radius_}; } else { return {}; } @@ -544,10 +543,11 @@ double SurfaceYCylinder::evaluate(Position r) const return axis_aligned_cylinder_evaluate<0, 2>(r, x0_, z0_, radius_); } -double SurfaceYCylinder::distance(Position r, Direction u, bool coincident) const +double SurfaceYCylinder::distance( + Position r, Direction u, bool coincident) const { - return axis_aligned_cylinder_distance<1, 0, 2>(r, u, coincident, x0_, z0_, - radius_); + return axis_aligned_cylinder_distance<1, 0, 2>( + r, u, coincident, x0_, z0_, radius_); } Direction SurfaceYCylinder::normal(Position r) const @@ -562,9 +562,11 @@ void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox SurfaceYCylinder::bounding_box(bool pos_side) const { +BoundingBox SurfaceYCylinder::bounding_box(bool pos_side) const +{ if (!pos_side) { - return {x0_ - radius_, x0_ + radius_, -INFTY, INFTY, z0_ - radius_, z0_ + radius_}; + return {x0_ - radius_, x0_ + radius_, -INFTY, INFTY, z0_ - radius_, + z0_ + radius_}; } else { return {}; } @@ -585,10 +587,11 @@ double SurfaceZCylinder::evaluate(Position r) const return axis_aligned_cylinder_evaluate<0, 1>(r, x0_, y0_, radius_); } -double SurfaceZCylinder::distance(Position r, Direction u, bool coincident) const +double SurfaceZCylinder::distance( + Position r, Direction u, bool coincident) const { - return axis_aligned_cylinder_distance<2, 0, 1>(r, u, coincident, x0_, y0_, - radius_); + return axis_aligned_cylinder_distance<2, 0, 1>( + r, u, coincident, x0_, y0_, radius_); } Direction SurfaceZCylinder::normal(Position r) const @@ -603,21 +606,21 @@ void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox SurfaceZCylinder::bounding_box(bool pos_side) const { +BoundingBox SurfaceZCylinder::bounding_box(bool pos_side) const +{ if (!pos_side) { - return {x0_ - radius_, x0_ + radius_, y0_ - radius_, y0_ + radius_, -INFTY, INFTY}; + return {x0_ - radius_, x0_ + radius_, y0_ - radius_, y0_ + radius_, -INFTY, + INFTY}; } else { return {}; } } - //============================================================================== // SurfaceSphere implementation //============================================================================== -SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, x0_, y0_, z0_, radius_); } @@ -627,7 +630,7 @@ double SurfaceSphere::evaluate(Position r) const const double x = r.x - x0_; const double y = r.y - y0_; const double z = r.z - z0_; - return x*x + y*y + z*z - radius_*radius_; + return x * x + y * y + z * z - radius_ * radius_; } double SurfaceSphere::distance(Position r, Direction u, bool coincident) const @@ -635,9 +638,9 @@ double SurfaceSphere::distance(Position r, Direction u, bool coincident) const const double x = r.x - x0_; const double y = r.y - y0_; const double z = r.z - z0_; - const double k = x*u.x + y*u.y + z*u.z; - const double c = x*x + y*y + z*z - radius_*radius_; - const double quad = k*k - c; + const double k = x * u.x + y * u.y + z * u.z; + const double c = x * x + y * y + z * z - radius_ * radius_; + const double quad = k * k - c; if (quad < 0.0) { // No intersection with sphere. @@ -663,14 +666,15 @@ double SurfaceSphere::distance(Position r, Direction u, bool coincident) const // or negative. If positive, the smaller distance is the one with positive // sign on sqrt(quad). const double d = -k - sqrt(quad); - if (d < 0.0) return INFTY; + if (d < 0.0) + return INFTY; return d; } } Direction SurfaceSphere::normal(Position r) const { - return {2.0*(r.x - x0_), 2.0*(r.y - y0_), 2.0*(r.z - z0_)}; + return {2.0 * (r.x - x0_), 2.0 * (r.y - y0_), 2.0 * (r.z - z0_)}; } void SurfaceSphere::to_hdf5_inner(hid_t group_id) const @@ -680,11 +684,11 @@ void SurfaceSphere::to_hdf5_inner(hid_t group_id) const write_dataset(group_id, "coefficients", coeffs); } -BoundingBox SurfaceSphere::bounding_box(bool pos_side) const { +BoundingBox SurfaceSphere::bounding_box(bool pos_side) const +{ if (!pos_side) { - return {x0_ - radius_, x0_ + radius_, - y0_ - radius_, y0_ + radius_, - z0_ - radius_, z0_ + radius_}; + return {x0_ - radius_, x0_ + radius_, y0_ - radius_, y0_ + radius_, + z0_ - radius_, z0_ + radius_}; } else { return {}; } @@ -697,23 +701,22 @@ BoundingBox SurfaceSphere::bounding_box(bool pos_side) const { // The first template parameter indicates which axis the cone is aligned to. // The other two parameters indicate the other two axes. offset1, offset2, // and offset3 should correspond with i1, i2, and i3, respectively. -template double -axis_aligned_cone_evaluate(Position r, double offset1, - double offset2, double offset3, double radius_sq) +template +double axis_aligned_cone_evaluate( + Position r, double offset1, double offset2, double offset3, double radius_sq) { const double r1 = r.get() - offset1; const double r2 = r.get() - offset2; const double r3 = r.get() - offset3; - return r2*r2 + r3*r3 - radius_sq*r1*r1; + return r2 * r2 + r3 * r3 - radius_sq * r1 * r1; } // The first template parameter indicates which axis the cone is aligned to. // The other two parameters indicate the other two axes. offset1, offset2, // and offset3 should correspond with i1, i2, and i3, respectively. -template double -axis_aligned_cone_distance(Position r, Direction u, - bool coincident, double offset1, double offset2, double offset3, - double radius_sq) +template +double axis_aligned_cone_distance(Position r, Direction u, bool coincident, + double offset1, double offset2, double offset3, double radius_sq) { const double r1 = r.get() - offset1; const double r2 = r.get() - offset2; @@ -722,8 +725,8 @@ axis_aligned_cone_distance(Position r, Direction u, radius_sq * u.get() * u.get(); const double k = r2 * u.get() + r3 * u.get() - radius_sq * r1 * u.get(); - const double c = r2*r2 + r3*r3 - radius_sq*r1*r1; - double quad = k*k - a*c; + const double c = r2 * r2 + r3 * r3 - radius_sq * r1 * r1; + double quad = k * k - a * c; double d; @@ -749,25 +752,28 @@ axis_aligned_cone_distance(Position r, Direction u, // Determine the smallest positive solution. if (d < 0.0) { - if (b > 0.0) d = b; + if (b > 0.0) + d = b; } else { if (b > 0.0) { - if (b < d) d = b; + if (b < d) + d = b; } } } // If the distance was negative, set boundary distance to infinity. - if (d <= 0.0) return INFTY; + if (d <= 0.0) + return INFTY; return d; } // The first template parameter indicates which axis the cone is aligned to. // The other two parameters indicate the other two axes. offset1, offset2, // and offset3 should correspond with i1, i2, and i3, respectively. -template Direction -axis_aligned_cone_normal(Position r, double offset1, double offset2, - double offset3, double radius_sq) +template +Direction axis_aligned_cone_normal( + Position r, double offset1, double offset2, double offset3, double radius_sq) { Direction u; u.get() = -2.0 * radius_sq * (r.get() - offset1); @@ -780,8 +786,7 @@ axis_aligned_cone_normal(Position r, double offset1, double offset2, // SurfaceXCone implementation //============================================================================== -SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, x0_, y0_, z0_, radius_sq_); } @@ -793,8 +798,8 @@ double SurfaceXCone::evaluate(Position r) const double SurfaceXCone::distance(Position r, Direction u, bool coincident) const { - return axis_aligned_cone_distance<0, 1, 2>(r, u, coincident, x0_, y0_, z0_, - radius_sq_); + return axis_aligned_cone_distance<0, 1, 2>( + r, u, coincident, x0_, y0_, z0_, radius_sq_); } Direction SurfaceXCone::normal(Position r) const @@ -813,8 +818,7 @@ void SurfaceXCone::to_hdf5_inner(hid_t group_id) const // SurfaceYCone implementation //============================================================================== -SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, x0_, y0_, z0_, radius_sq_); } @@ -826,8 +830,8 @@ double SurfaceYCone::evaluate(Position r) const double SurfaceYCone::distance(Position r, Direction u, bool coincident) const { - return axis_aligned_cone_distance<1, 0, 2>(r, u, coincident, y0_, x0_, z0_, - radius_sq_); + return axis_aligned_cone_distance<1, 0, 2>( + r, u, coincident, y0_, x0_, z0_, radius_sq_); } Direction SurfaceYCone::normal(Position r) const @@ -846,8 +850,7 @@ void SurfaceYCone::to_hdf5_inner(hid_t group_id) const // SurfaceZCone implementation //============================================================================== -SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, x0_, y0_, z0_, radius_sq_); } @@ -859,8 +862,8 @@ double SurfaceZCone::evaluate(Position r) const double SurfaceZCone::distance(Position r, Direction u, bool coincident) const { - return axis_aligned_cone_distance<2, 0, 1>(r, u, coincident, z0_, x0_, y0_, - radius_sq_); + return axis_aligned_cone_distance<2, 0, 1>( + r, u, coincident, z0_, x0_, y0_, radius_sq_); } Direction SurfaceZCone::normal(Position r) const @@ -879,39 +882,38 @@ void SurfaceZCone::to_hdf5_inner(hid_t group_id) const // SurfaceQuadric implementation //============================================================================== -SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) - : CSGSurface(surf_node) +SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) : CSGSurface(surf_node) { read_coeffs(surf_node, id_, A_, B_, C_, D_, E_, F_, G_, H_, J_, K_); } -double -SurfaceQuadric::evaluate(Position r) const +double SurfaceQuadric::evaluate(Position r) const { const double x = r.x; const double y = r.y; const double z = r.z; - return x*(A_*x + D_*y + G_) + - y*(B_*y + E_*z + H_) + - z*(C_*z + F_*x + J_) + K_; + return x * (A_ * x + D_ * y + G_) + y * (B_ * y + E_ * z + H_) + + z * (C_ * z + F_ * x + J_) + K_; } -double -SurfaceQuadric::distance(Position r, Direction ang, bool coincident) const +double SurfaceQuadric::distance( + Position r, Direction ang, bool coincident) const { - const double &x = r.x; - const double &y = r.y; - const double &z = r.z; - const double &u = ang.x; - const double &v = ang.y; - const double &w = ang.z; + const double& x = r.x; + const double& y = r.y; + const double& z = r.z; + const double& u = ang.x; + const double& v = ang.y; + const double& w = ang.z; - const double a = A_*u*u + B_*v*v + C_*w*w + D_*u*v + E_*v*w + F_*u*w; - const double k = A_*u*x + B_*v*y + C_*w*z + 0.5*(D_*(u*y + v*x) - + E_*(v*z + w*y) + F_*(w*x + u*z) + G_*u + H_*v + J_*w); - const double c = A_*x*x + B_*y*y + C_*z*z + D_*x*y + E_*y*z + F_*x*z + G_*x - + H_*y + J_*z + K_; - double quad = k*k - a*c; + const double a = + A_ * u * u + B_ * v * v + C_ * w * w + D_ * u * v + E_ * v * w + F_ * u * w; + const double k = A_ * u * x + B_ * v * y + C_ * w * z + + 0.5 * (D_ * (u * y + v * x) + E_ * (v * z + w * y) + + F_ * (w * x + u * z) + G_ * u + H_ * v + J_ * w); + const double c = A_ * x * x + B_ * y * y + C_ * z * z + D_ * x * y + + E_ * y * z + F_ * x * z + G_ * x + H_ * y + J_ * z + K_; + double quad = k * k - a * c; double d; @@ -949,28 +951,29 @@ SurfaceQuadric::distance(Position r, Direction ang, bool coincident) const // Determine the smallest positive solution. if (d < 0.0) { - if (b > 0.0) d = b; + if (b > 0.0) + d = b; } else { if (b > 0.0) { - if (b < d) d = b; + if (b < d) + d = b; } } } // If the distance was negative, set boundary distance to infinity. - if (d <= 0.0) return INFTY; + if (d <= 0.0) + return INFTY; return d; } -Direction -SurfaceQuadric::normal(Position r) const +Direction SurfaceQuadric::normal(Position r) const { - const double &x = r.x; - const double &y = r.y; - const double &z = r.z; - return {2.0*A_*x + D_*y + F_*z + G_, - 2.0*B_*y + D_*x + E_*z + H_, - 2.0*C_*z + E_*y + F_*x + J_}; + const double& x = r.x; + const double& y = r.y; + const double& z = r.z; + return {2.0 * A_ * x + D_ * y + F_ * z + G_, + 2.0 * B_ * y + D_ * x + E_ * z + H_, 2.0 * C_ * z + E_ * y + F_ * x + J_}; } void SurfaceQuadric::to_hdf5_inner(hid_t group_id) const @@ -986,7 +989,9 @@ void read_surfaces(pugi::xml_node node) { // Count the number of surfaces int n_surfaces = 0; - for (pugi::xml_node surf_node : node.children("surface")) {n_surfaces++;} + for (pugi::xml_node surf_node : node.children("surface")) { + n_surfaces++; + } // Loop over XML surface elements and populate the array. Keep track of // periodic surfaces. @@ -1046,8 +1051,8 @@ void read_surfaces(pugi::xml_node node) std::string surf_bc = get_node_value(surf_node, "boundary", true, true); if (surf_bc == "periodic") { if (check_for_node(surf_node, "periodic_surface_id")) { - int i_periodic = std::stoi(get_node_value(surf_node, - "periodic_surface_id")); + int i_periodic = + std::stoi(get_node_value(surf_node, "periodic_surface_id")); int lo_id = std::min(model::surfaces.back()->id_, i_periodic); int hi_id = std::max(model::surfaces.back()->id_, i_periodic); periodic_pairs.insert({lo_id, hi_id}); @@ -1066,35 +1071,37 @@ void read_surfaces(pugi::xml_node node) if (in_map == model::surface_map.end()) { model::surface_map[id] = i_surf; } else { - fatal_error(fmt::format( - "Two or more surfaces use the same unique ID: {}", id)); + fatal_error( + fmt::format("Two or more surfaces use the same unique ID: {}", id)); } } // Resolve unpaired periodic surfaces. A lambda function is used with // std::find_if to identify the unpaired surfaces. - auto is_unresolved_pair = - [](const std::pair p){return p.second == -1;}; - auto first_unresolved = std::find_if(periodic_pairs.begin(), - periodic_pairs.end(), is_unresolved_pair); + auto is_unresolved_pair = [](const std::pair p) { + return p.second == -1; + }; + auto first_unresolved = std::find_if( + periodic_pairs.begin(), periodic_pairs.end(), is_unresolved_pair); if (first_unresolved != periodic_pairs.end()) { // Found one unpaired surface; search for a second one auto next_elem = first_unresolved; next_elem++; - auto second_unresolved = std::find_if(next_elem, periodic_pairs.end(), - is_unresolved_pair); + auto second_unresolved = + std::find_if(next_elem, periodic_pairs.end(), is_unresolved_pair); if (second_unresolved == periodic_pairs.end()) { fatal_error("Found only one periodic surface without a specified partner." - " Please specify the partner for each periodic surface."); + " Please specify the partner for each periodic surface."); } // Make sure there isn't a third unpaired surface next_elem = second_unresolved; next_elem++; - auto third_unresolved = std::find_if(next_elem, - periodic_pairs.end(), is_unresolved_pair); + auto third_unresolved = + std::find_if(next_elem, periodic_pairs.end(), is_unresolved_pair); if (third_unresolved != periodic_pairs.end()) { - fatal_error("Found at least three periodic surfaces without a specified " + fatal_error( + "Found at least three periodic surfaces without a specified " "partner. Please specify the partner for each periodic surface."); } diff --git a/src/tallies/derivative.cpp b/src/tallies/derivative.cpp index 41ea57370..57d66db0d 100644 --- a/src/tallies/derivative.cpp +++ b/src/tallies/derivative.cpp @@ -18,9 +18,9 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map tally_deriv_map; - vector tally_derivs; -} +std::unordered_map tally_deriv_map; +vector tally_derivs; +} // namespace model //============================================================================== // TallyDerivative implementation @@ -55,13 +55,14 @@ TallyDerivative::TallyDerivative(pugi::xml_node node) } if (!found) { fatal_error(fmt::format("Could not find the nuclide \"{}\" specified in " - "derivative {} in any material.", nuclide_name, id)); + "derivative {} in any material.", + nuclide_name, id)); } } else if (variable_str == "temperature") { variable = DerivativeVariable::TEMPERATURE; } else { - fatal_error(fmt::format("Unrecognized variable \"{}\" on derivative {}", - variable_str, id)); + fatal_error(fmt::format( + "Unrecognized variable \"{}\" on derivative {}", variable_str, id)); } diff_material = std::stoi(get_node_value(node, "material")); @@ -71,8 +72,7 @@ TallyDerivative::TallyDerivative(pugi::xml_node node) // Non-method functions //============================================================================== -void -read_tally_derivatives(pugi::xml_node node) +void read_tally_derivatives(pugi::xml_node node) { // Populate the derivatives array. for (auto deriv_node : node.children("derivative")) @@ -85,8 +85,8 @@ read_tally_derivatives(pugi::xml_node node) if (search == model::tally_deriv_map.end()) { model::tally_deriv_map[id] = i; } else { - fatal_error("Two or more derivatives use the same unique ID: " - + std::to_string(id)); + fatal_error("Two or more derivatives use the same unique ID: " + + std::to_string(id)); } } @@ -95,13 +95,13 @@ read_tally_derivatives(pugi::xml_node node) fatal_error("Differential tallies not supported in multi-group mode"); } -void -apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, +void apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, double atom_density, int score_bin, double& score) { const Tally& tally {*model::tallies[i_tally]}; - if (score == 0.0) return; + if (score == 0.0) + return; // If our score was previously c then the new score is // c * (1/f * d_f/d_p + 1/c * d_c/d_p) @@ -127,13 +127,13 @@ apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, switch (deriv.variable) { - //============================================================================ - // Density derivative: - // c = Sigma_MT - // c = sigma_MT * N - // c = sigma_MT * rho * const - // d_c / d_rho = sigma_MT * const - // (1 / c) * (d_c / d_rho) = 1 / rho + //============================================================================ + // Density derivative: + // c = Sigma_MT + // c = sigma_MT * N + // c = sigma_MT * rho * const + // d_c / d_rho = sigma_MT * const + // (1 / c) * (d_c / d_rho) = 1 / rho case DerivativeVariable::DENSITY: switch (tally.estimator_) { @@ -151,29 +151,29 @@ apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, break; default: - fatal_error("Tally derivative not defined for a score on tally " - + std::to_string(tally.id_)); + fatal_error("Tally derivative not defined for a score on tally " + + std::to_string(tally.id_)); } break; default: fatal_error("Differential tallies are only implemented for analog and " - "collision estimators."); + "collision estimators."); } break; - //============================================================================ - // Nuclide density derivative: - // If we are scoring a reaction rate for a single nuclide then - // c = Sigma_MT_i - // c = sigma_MT_i * N_i - // d_c / d_N_i = sigma_MT_i - // (1 / c) * (d_c / d_N_i) = 1 / N_i - // If the score is for the total material (i_nuclide = -1) - // c = Sum_i(Sigma_MT_i) - // d_c / d_N_i = sigma_MT_i - // (1 / c) * (d_c / d_N) = sigma_MT_i / Sigma_MT - // where i is the perturbed nuclide. + //============================================================================ + // Nuclide density derivative: + // If we are scoring a reaction rate for a single nuclide then + // c = Sigma_MT_i + // c = sigma_MT_i * N_i + // d_c / d_N_i = sigma_MT_i + // (1 / c) * (d_c / d_N_i) = 1 / N_i + // If the score is for the total material (i_nuclide = -1) + // c = Sum_i(Sigma_MT_i) + // d_c / d_N_i = sigma_MT_i + // (1 / c) * (d_c / d_N) = sigma_MT_i / Sigma_MT + // where i is the perturbed nuclide. case DerivativeVariable::NUCLIDE_DENSITY: switch (tally.estimator_) { @@ -190,19 +190,18 @@ apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, case SCORE_SCATTER: case SCORE_ABSORPTION: case SCORE_FISSION: - case SCORE_NU_FISSION: - { - // Find the index of the perturbed nuclide. - int i; - for (i = 0; i < material.nuclide_.size(); ++i) - if (material.nuclide_[i] == deriv.diff_nuclide) break; - score *= flux_deriv + 1. / material.atom_density_(i); - } - break; + case SCORE_NU_FISSION: { + // Find the index of the perturbed nuclide. + int i; + for (i = 0; i < material.nuclide_.size(); ++i) + if (material.nuclide_[i] == deriv.diff_nuclide) + break; + score *= flux_deriv + 1. / material.atom_density_(i); + } break; default: - fatal_error("Tally derivative not defined for a score on tally " - + std::to_string(tally.id_)); + fatal_error("Tally derivative not defined for a score on tally " + + std::to_string(tally.id_)); } break; @@ -272,120 +271,117 @@ apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, break; default: - fatal_error("Tally derivative not defined for a score on tally " - + std::to_string(tally.id_)); + fatal_error("Tally derivative not defined for a score on tally " + + std::to_string(tally.id_)); } break; default: fatal_error("Differential tallies are only implemented for analog and " - "collision estimators."); + "collision estimators."); } break; - //============================================================================ - // Temperature derivative: - // If we are scoring a reaction rate for a single nuclide then - // c = Sigma_MT_i - // c = sigma_MT_i * N_i - // d_c / d_T = (d_sigma_Mt_i / d_T) * N_i - // (1 / c) * (d_c / d_T) = (d_sigma_MT_i / d_T) / sigma_MT_i - // If the score is for the total material (i_nuclide = -1) - // (1 / c) * (d_c / d_T) = Sum_i((d_sigma_MT_i / d_T) * N_i) / Sigma_MT_i - // where i is the perturbed nuclide. The d_sigma_MT_i / d_T term is - // computed by multipole_deriv_eval. It only works for the resolved - // resonance range and requires multipole data. + //============================================================================ + // Temperature derivative: + // If we are scoring a reaction rate for a single nuclide then + // c = Sigma_MT_i + // c = sigma_MT_i * N_i + // d_c / d_T = (d_sigma_Mt_i / d_T) * N_i + // (1 / c) * (d_c / d_T) = (d_sigma_MT_i / d_T) / sigma_MT_i + // If the score is for the total material (i_nuclide = -1) + // (1 / c) * (d_c / d_T) = Sum_i((d_sigma_MT_i / d_T) * N_i) / Sigma_MT_i + // where i is the perturbed nuclide. The d_sigma_MT_i / d_T term is + // computed by multipole_deriv_eval. It only works for the resolved + // resonance range and requires multipole data. case DerivativeVariable::TEMPERATURE: switch (tally.estimator_) { - case TallyEstimator::ANALOG: - { - // Find the index of the event nuclide. - int i; - for (i = 0; i < material.nuclide_.size(); ++i) - if (material.nuclide_[i] == p.event_nuclide()) - break; - - const auto& nuc {*data::nuclides[p.event_nuclide()]}; - if (!multipole_in_range(nuc, p.E_last())) { - score *= flux_deriv; - break; - } - - switch (score_bin) { - - case SCORE_TOTAL: - if (p.neutron_xs(p.event_nuclide()).total) { - double dsig_s, dsig_a, dsig_f; - std::tie(dsig_s, dsig_a, dsig_f) = - nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); - score *= flux_deriv + (dsig_s + dsig_a) * - material.atom_density_(i) / - p.macro_xs().total; - } else { - score *= flux_deriv; - } + case TallyEstimator::ANALOG: { + // Find the index of the event nuclide. + int i; + for (i = 0; i < material.nuclide_.size(); ++i) + if (material.nuclide_[i] == p.event_nuclide()) break; - case SCORE_SCATTER: - if (p.neutron_xs(p.event_nuclide()).total - - p.neutron_xs(p.event_nuclide()).absorption) { - double dsig_s, dsig_a, dsig_f; - std::tie(dsig_s, dsig_a, dsig_f) = - nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); - score *= - flux_deriv + dsig_s * material.atom_density_(i) / - (p.macro_xs().total - p.macro_xs().absorption); - } else { - score *= flux_deriv; - } - break; - - case SCORE_ABSORPTION: - if (p.neutron_xs(p.event_nuclide()).absorption) { - double dsig_s, dsig_a, dsig_f; - std::tie(dsig_s, dsig_a, dsig_f) = - nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); - score *= flux_deriv + dsig_a * material.atom_density_(i) / - p.macro_xs().absorption; - } else { - score *= flux_deriv; - } - break; - - case SCORE_FISSION: - if (p.neutron_xs(p.event_nuclide()).fission) { - double dsig_s, dsig_a, dsig_f; - std::tie(dsig_s, dsig_a, dsig_f) = - nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); - score *= flux_deriv + - dsig_f * material.atom_density_(i) / p.macro_xs().fission; - } else { - score *= flux_deriv; - } - break; - - case SCORE_NU_FISSION: - if (p.neutron_xs(p.event_nuclide()).fission) { - double nu = p.neutron_xs(p.event_nuclide()).nu_fission / - p.neutron_xs(p.event_nuclide()).fission; - double dsig_s, dsig_a, dsig_f; - std::tie(dsig_s, dsig_a, dsig_f) = - nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); - score *= flux_deriv + nu * dsig_f * material.atom_density_(i) / - p.macro_xs().nu_fission; - } else { - score *= flux_deriv; - } - break; - - default: - fatal_error("Tally derivative not defined for a score on tally " - + std::to_string(tally.id_)); - } + const auto& nuc {*data::nuclides[p.event_nuclide()]}; + if (!multipole_in_range(nuc, p.E_last())) { + score *= flux_deriv; + break; } - break; + + switch (score_bin) { + + case SCORE_TOTAL: + if (p.neutron_xs(p.event_nuclide()).total) { + double dsig_s, dsig_a, dsig_f; + std::tie(dsig_s, dsig_a, dsig_f) = + nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); + score *= flux_deriv + (dsig_s + dsig_a) * material.atom_density_(i) / + p.macro_xs().total; + } else { + score *= flux_deriv; + } + break; + + case SCORE_SCATTER: + if (p.neutron_xs(p.event_nuclide()).total - + p.neutron_xs(p.event_nuclide()).absorption) { + double dsig_s, dsig_a, dsig_f; + std::tie(dsig_s, dsig_a, dsig_f) = + nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); + score *= + flux_deriv + dsig_s * material.atom_density_(i) / + (p.macro_xs().total - p.macro_xs().absorption); + } else { + score *= flux_deriv; + } + break; + + case SCORE_ABSORPTION: + if (p.neutron_xs(p.event_nuclide()).absorption) { + double dsig_s, dsig_a, dsig_f; + std::tie(dsig_s, dsig_a, dsig_f) = + nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); + score *= flux_deriv + + dsig_a * material.atom_density_(i) / p.macro_xs().absorption; + } else { + score *= flux_deriv; + } + break; + + case SCORE_FISSION: + if (p.neutron_xs(p.event_nuclide()).fission) { + double dsig_s, dsig_a, dsig_f; + std::tie(dsig_s, dsig_a, dsig_f) = + nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); + score *= flux_deriv + + dsig_f * material.atom_density_(i) / p.macro_xs().fission; + } else { + score *= flux_deriv; + } + break; + + case SCORE_NU_FISSION: + if (p.neutron_xs(p.event_nuclide()).fission) { + double nu = p.neutron_xs(p.event_nuclide()).nu_fission / + p.neutron_xs(p.event_nuclide()).fission; + double dsig_s, dsig_a, dsig_f; + std::tie(dsig_s, dsig_a, dsig_f) = + nuc.multipole_->evaluate_deriv(p.E_last(), p.sqrtkT()); + score *= flux_deriv + nu * dsig_f * material.atom_density_(i) / + p.macro_xs().nu_fission; + } else { + score *= flux_deriv; + } + break; + + default: + fatal_error("Tally derivative not defined for a score on tally " + + std::to_string(tally.id_)); + } + } break; case TallyEstimator::COLLISION: if (i_nuclide != -1) { @@ -541,14 +537,13 @@ apply_derivative_to_score(const Particle& p, int i_tally, int i_nuclide, default: fatal_error("Differential tallies are only implemented for analog and " - "collision estimators."); + "collision estimators."); } break; } } -void -score_track_derivative(Particle& p, double distance) +void score_track_derivative(Particle& p, double distance) { // A void material cannot be perturbed so it will not affect flux derivatives. if (p.material() == MATERIAL_VOID) @@ -559,7 +554,8 @@ score_track_derivative(Particle& p, double distance) for (auto idx = 0; idx < model::tally_derivs.size(); idx++) { const auto& deriv = model::tally_derivs[idx]; auto& flux_deriv = p.flux_derivs(idx); - if (deriv.diff_material != material.id_) continue; + if (deriv.diff_material != material.id_) + continue; switch (deriv.variable) { @@ -587,8 +583,8 @@ score_track_derivative(Particle& p, double distance) double dsig_s, dsig_a, dsig_f; std::tie(dsig_s, dsig_a, dsig_f) = nuc.multipole_->evaluate_deriv(p.E(), p.sqrtkT()); - flux_deriv -= distance * (dsig_s + dsig_a) - * material.atom_density_(i); + flux_deriv -= + distance * (dsig_s + dsig_a) * material.atom_density_(i); } } break; @@ -608,7 +604,8 @@ void score_collision_derivative(Particle& p) const auto& deriv = model::tally_derivs[idx]; auto& flux_deriv = p.flux_derivs(idx); - if (deriv.diff_material != material.id_) continue; + if (deriv.diff_material != material.id_) + continue; switch (deriv.variable) { @@ -625,7 +622,8 @@ void score_collision_derivative(Particle& p) // Find the index in this material for the diff_nuclide. int i; for (i = 0; i < material.nuclide_.size(); ++i) - if (material.nuclide_[i] == deriv.diff_nuclide) break; + if (material.nuclide_[i] == deriv.diff_nuclide) + break; // Make sure we found the nuclide. if (material.nuclide_[i] != deriv.diff_nuclide) { fatal_error(fmt::format( @@ -666,4 +664,4 @@ void score_collision_derivative(Particle& p) } } -}// namespace openmc +} // namespace openmc diff --git a/src/tallies/filter.cpp b/src/tallies/filter.cpp index 55916401f..e3934d7ea 100644 --- a/src/tallies/filter.cpp +++ b/src/tallies/filter.cpp @@ -1,25 +1,24 @@ #include "openmc/tallies/filter.h" #include // for max -#include // for strcpy +#include // for strcpy #include #include #include "openmc/capi.h" -#include "openmc/constants.h" // for MAX_LINE_LEN; +#include "openmc/constants.h" // for MAX_LINE_LEN; #include "openmc/error.h" -#include "openmc/xml_interface.h" #include "openmc/tallies/filter_azimuthal.h" #include "openmc/tallies/filter_cell.h" +#include "openmc/tallies/filter_cell_instance.h" #include "openmc/tallies/filter_cellborn.h" #include "openmc/tallies/filter_cellfrom.h" -#include "openmc/tallies/filter_cell_instance.h" #include "openmc/tallies/filter_collision.h" #include "openmc/tallies/filter_delayedgroup.h" #include "openmc/tallies/filter_distribcell.h" -#include "openmc/tallies/filter_energyfunc.h" #include "openmc/tallies/filter_energy.h" +#include "openmc/tallies/filter_energyfunc.h" #include "openmc/tallies/filter_legendre.h" #include "openmc/tallies/filter_material.h" #include "openmc/tallies/filter_mesh.h" @@ -32,6 +31,7 @@ #include "openmc/tallies/filter_surface.h" #include "openmc/tallies/filter_universe.h" #include "openmc/tallies/filter_zernike.h" +#include "openmc/xml_interface.h" // explicit template instantiation definition template class openmc::vector; @@ -43,9 +43,9 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map filter_map; - vector> tally_filters; -} +std::unordered_map filter_map; +vector> tally_filters; +} // namespace model //============================================================================== // Non-member functions @@ -71,9 +71,10 @@ Filter::~Filter() } template -T* Filter::create(int32_t id) { +T* Filter::create(int32_t id) +{ static_assert(std::is_base_of::value, - "Type specified is not derived from openmc::Filter"); + "Type specified is not derived from openmc::Filter"); // Create filter and add to filters vector auto filter = make_unique(); auto ptr_out = filter.get(); @@ -157,7 +158,7 @@ Filter* Filter::create(const std::string& type, int32_t id) } else if (type == "zernikeradial") { return Filter::create(id); } else { - throw std::runtime_error{fmt::format("Unknown filter type: {}", type)}; + throw std::runtime_error {fmt::format("Unknown filter type: {}", type)}; } return nullptr; } @@ -174,7 +175,8 @@ void Filter::set_id(int32_t id) // Make sure no other filter has same ID if (model::filter_map.find(id) != model::filter_map.end()) { - throw std::runtime_error{"Two filters have the same ID: " + std::to_string(id)}; + throw std::runtime_error { + "Two filters have the same ID: " + std::to_string(id)}; } // If no ID specified, auto-assign next ID in sequence @@ -204,35 +206,34 @@ int verify_filter(int32_t index) return 0; } -extern "C" int -openmc_filter_get_id(int32_t index, int32_t* id) +extern "C" int openmc_filter_get_id(int32_t index, int32_t* id) { - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; *id = model::tally_filters[index]->id(); return 0; } -extern "C" int -openmc_filter_set_id(int32_t index, int32_t id) +extern "C" int openmc_filter_set_id(int32_t index, int32_t id) { - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; model::tally_filters[index]->set_id(id); return 0; } -extern "C" int -openmc_filter_get_type(int32_t index, char* type) +extern "C" int openmc_filter_get_type(int32_t index, char* type) { - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; std::strcpy(type, model::tally_filters[index]->type().c_str()); return 0; } -extern "C" int -openmc_get_filter_index(int32_t id, int32_t* index) +extern "C" int openmc_get_filter_index(int32_t id, int32_t* index) { auto it = model::filter_map.find(id); if (it == model::filter_map.end()) { @@ -244,8 +245,7 @@ openmc_get_filter_index(int32_t id, int32_t* index) return 0; } -extern "C" void -openmc_get_filter_next_id(int32_t* id) +extern "C" void openmc_get_filter_next_id(int32_t* id) { int32_t largest_filter_id = 0; for (const auto& t : model::tally_filters) { @@ -254,8 +254,7 @@ openmc_get_filter_next_id(int32_t* id) *id = largest_filter_id + 1; } -extern "C" int -openmc_new_filter(const char* type, int32_t* index) +extern "C" int openmc_new_filter(const char* type, int32_t* index) { *index = model::tally_filters.size(); Filter::create(type); diff --git a/src/tallies/filter_azimuthal.cpp b/src/tallies/filter_azimuthal.cpp index 7bf5343b7..e77aa8bdc 100644 --- a/src/tallies/filter_azimuthal.cpp +++ b/src/tallies/filter_azimuthal.cpp @@ -11,8 +11,7 @@ namespace openmc { -void -AzimuthalFilter::from_xml(pugi::xml_node node) +void AzimuthalFilter::from_xml(pugi::xml_node node) { auto bins = get_node_array(node, "bins"); @@ -21,12 +20,14 @@ AzimuthalFilter::from_xml(pugi::xml_node node) // [-pi,pi) evenly with the input being the number of bins int n_angle = bins[0]; - if (n_angle <= 1) throw std::runtime_error{ - "Number of bins for azimuthal filter must be greater than 1."}; + if (n_angle <= 1) + throw std::runtime_error { + "Number of bins for azimuthal filter must be greater than 1."}; double d_angle = 2.0 * PI / n_angle; bins.resize(n_angle + 1); - for (int i = 0; i < n_angle; i++) bins[i] = -PI + i * d_angle; + for (int i = 0; i < n_angle; i++) + bins[i] = -PI + i * d_angle; bins[n_angle] = PI; } @@ -41,8 +42,9 @@ void AzimuthalFilter::set_bins(gsl::span bins) // Copy bins, ensuring they are valid for (gsl::index i = 0; i < bins.size(); ++i) { - if (i > 0 && bins[i] <= bins[i-1]) { - throw std::runtime_error{"Azimuthal bins must be monotonically increasing."}; + if (i > 0 && bins[i] <= bins[i - 1]) { + throw std::runtime_error { + "Azimuthal bins must be monotonically increasing."}; } bins_.push_back(bins[i]); } @@ -50,9 +52,8 @@ void AzimuthalFilter::set_bins(gsl::span bins) n_bins_ = bins_.size() - 1; } -void -AzimuthalFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void AzimuthalFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { Direction u = (estimator == TallyEstimator::TRACKLENGTH) ? p.u() : p.u_last(); double phi = std::atan2(u.y, u.x); @@ -64,17 +65,16 @@ AzimuthalFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -AzimuthalFilter::to_statepoint(hid_t filter_group) const +void AzimuthalFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", bins_); } -std::string -AzimuthalFilter::text_label(int bin) const +std::string AzimuthalFilter::text_label(int bin) const { - return fmt::format("Azimuthal Angle [{}, {})", bins_.at(bin), bins_.at(bin+1)); + return fmt::format( + "Azimuthal Angle [{}, {})", bins_.at(bin), bins_.at(bin + 1)); } } // namespace openmc diff --git a/src/tallies/filter_cell.cpp b/src/tallies/filter_cell.cpp index 10fa0040e..9ccae6b48 100644 --- a/src/tallies/filter_cell.cpp +++ b/src/tallies/filter_cell.cpp @@ -9,16 +9,15 @@ namespace openmc { -void -CellFilter::from_xml(pugi::xml_node node) +void CellFilter::from_xml(pugi::xml_node node) { // Get cell IDs and convert to indices into the global cells vector auto cells = get_node_array(node, "bins"); for (auto& c : cells) { auto search = model::cell_map.find(c); if (search == model::cell_map.end()) { - throw std::runtime_error{fmt::format( - "Could not find cell {} specified on tally filter.", c)}; + throw std::runtime_error { + fmt::format("Could not find cell {} specified on tally filter.", c)}; } c = search->second; } @@ -26,8 +25,7 @@ CellFilter::from_xml(pugi::xml_node node) this->set_cells(cells); } -void -CellFilter::set_cells(gsl::span cells) +void CellFilter::set_cells(gsl::span cells) { // Clear existing cells cells_.clear(); @@ -45,9 +43,8 @@ CellFilter::set_cells(gsl::span cells) n_bins_ = cells_.size(); } -void -CellFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void CellFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { for (int i = 0; i < p.n_coord(); i++) { auto search = map_.find(p.coord(i).cell); @@ -58,17 +55,16 @@ CellFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -CellFilter::to_statepoint(hid_t filter_group) const +void CellFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); vector cell_ids; - for (auto c : cells_) cell_ids.push_back(model::cells[c]->id_); + for (auto c : cells_) + cell_ids.push_back(model::cells[c]->id_); write_dataset(filter_group, "bins", cell_ids); } -std::string -CellFilter::text_label(int bin) const +std::string CellFilter::text_label(int bin) const { return fmt::format("Cell {}", model::cells[cells_[bin]]->id_); } @@ -77,10 +73,11 @@ CellFilter::text_label(int bin) const // C-API functions //============================================================================== -extern "C" int -openmc_cell_filter_get_bins(int32_t index, const int32_t** cells, int32_t* n) +extern "C" int openmc_cell_filter_get_bins( + int32_t index, const int32_t** cells, int32_t* n) { - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; const auto& filt = model::tally_filters[index].get(); if (filt->type() != "cell") { diff --git a/src/tallies/filter_cell_instance.cpp b/src/tallies/filter_cell_instance.cpp index 0dcc4b094..59f28c7d6 100644 --- a/src/tallies/filter_cell_instance.cpp +++ b/src/tallies/filter_cell_instance.cpp @@ -17,8 +17,7 @@ CellInstanceFilter::CellInstanceFilter(gsl::span instances) this->set_cell_instances(instances); } -void -CellInstanceFilter::from_xml(pugi::xml_node node) +void CellInstanceFilter::from_xml(pugi::xml_node node) { // Get cell IDs/instances auto cells = get_node_array(node, "bins"); @@ -27,11 +26,11 @@ CellInstanceFilter::from_xml(pugi::xml_node node) // Convert into vector of CellInstance vector instances; for (gsl::index i = 0; i < cells.size() / 2; ++i) { - int32_t cell_id = cells[2*i]; - gsl::index instance = cells[2*i + 1]; + int32_t cell_id = cells[2 * i]; + gsl::index instance = cells[2 * i + 1]; auto search = model::cell_map.find(cell_id); if (search == model::cell_map.end()) { - throw std::runtime_error{fmt::format( + throw std::runtime_error {fmt::format( "Could not find cell {} specified on tally filter.", cell_id)}; } gsl::index index = search->second; @@ -41,8 +40,7 @@ CellInstanceFilter::from_xml(pugi::xml_node node) this->set_cell_instances(instances); } -void -CellInstanceFilter::set_cell_instances(gsl::span instances) +void CellInstanceFilter::set_cell_instances(gsl::span instances) { // Clear existing cells cell_instances_.clear(); @@ -64,15 +62,15 @@ CellInstanceFilter::set_cell_instances(gsl::span instances) material_cells_only_ = true; for (const auto& cell_inst : cell_instances_) { const auto& c = *model::cells[cell_inst.index_cell]; - if (c.type_ == Fill::MATERIAL) continue; + if (c.type_ == Fill::MATERIAL) + continue; material_cells_only_ = false; break; } } -void -CellInstanceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void CellInstanceFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { gsl::index index_cell = p.coord(p.n_coord() - 1).cell; gsl::index instance = p.cell_instance(); @@ -86,12 +84,14 @@ CellInstanceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } - if (material_cells_only_) return; + if (material_cells_only_) + return; for (int i = 0; i < p.n_coord() - 1; i++) { gsl::index index_cell = p.coord(i).cell; // if this cell isn't used on the filter, move on - if (cells_.count(index_cell) == 0) continue; + if (cells_.count(index_cell) == 0) + continue; // if this cell is used in the filter, check the instance as well gsl::index instance = cell_instance_at_level(p, i); @@ -103,8 +103,7 @@ CellInstanceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -CellInstanceFilter::to_statepoint(hid_t filter_group) const +void CellInstanceFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); size_t n = cell_instances_.size(); @@ -117,13 +116,12 @@ CellInstanceFilter::to_statepoint(hid_t filter_group) const write_dataset(filter_group, "bins", data); } -std::string -CellInstanceFilter::text_label(int bin) const +std::string CellInstanceFilter::text_label(int bin) const { const auto& x = cell_instances_[bin]; auto cell_id = model::cells[x.index_cell]->id_; - return "Cell " + std::to_string(cell_id) + ", Instance " - + std::to_string(x.instance); + return "Cell " + std::to_string(cell_id) + ", Instance " + + std::to_string(x.instance); } } // namespace openmc diff --git a/src/tallies/filter_cellborn.cpp b/src/tallies/filter_cellborn.cpp index ac5b8be9d..d0d25c9a0 100644 --- a/src/tallies/filter_cellborn.cpp +++ b/src/tallies/filter_cellborn.cpp @@ -4,9 +4,8 @@ namespace openmc { -void -CellbornFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void CellbornFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { auto search = map_.find(p.cell_born()); if (search != map_.end()) { @@ -15,8 +14,7 @@ CellbornFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -std::string -CellbornFilter::text_label(int bin) const +std::string CellbornFilter::text_label(int bin) const { return "Birth Cell " + std::to_string(model::cells[cells_[bin]]->id_); } diff --git a/src/tallies/filter_cellfrom.cpp b/src/tallies/filter_cellfrom.cpp index 9d6af07dd..3c2003263 100644 --- a/src/tallies/filter_cellfrom.cpp +++ b/src/tallies/filter_cellfrom.cpp @@ -4,9 +4,8 @@ namespace openmc { -void -CellFromFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void CellFromFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { for (int i = 0; i < p.n_coord_last(); i++) { auto search = map_.find(p.cell_last(i)); @@ -17,8 +16,7 @@ CellFromFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -std::string -CellFromFilter::text_label(int bin) const +std::string CellFromFilter::text_label(int bin) const { return "Cell from " + std::to_string(model::cells[cells_[bin]]->id_); } diff --git a/src/tallies/filter_collision.cpp b/src/tallies/filter_collision.cpp index cf7d98c85..fbb186a23 100644 --- a/src/tallies/filter_collision.cpp +++ b/src/tallies/filter_collision.cpp @@ -43,7 +43,7 @@ void CollisionFilter::get_all_bins( // Bin the collision number. Must fit exactly the desired collision number. auto search = map_.find(n); - if (search != map_.end()){ + if (search != map_.end()) { match.bins_.push_back(search->second); match.weights_.push_back(1.0); } diff --git a/src/tallies/filter_delayedgroup.cpp b/src/tallies/filter_delayedgroup.cpp index 824b2e815..c6ec21766 100644 --- a/src/tallies/filter_delayedgroup.cpp +++ b/src/tallies/filter_delayedgroup.cpp @@ -5,15 +5,13 @@ namespace openmc { -void -DelayedGroupFilter::from_xml(pugi::xml_node node) +void DelayedGroupFilter::from_xml(pugi::xml_node node) { auto groups = get_node_array(node, "bins"); this->set_groups(groups); } -void -DelayedGroupFilter::set_groups(gsl::span groups) +void DelayedGroupFilter::set_groups(gsl::span groups) { // Clear existing groups groups_.clear(); @@ -23,12 +21,14 @@ DelayedGroupFilter::set_groups(gsl::span groups) // TODO: do these need to be decremented for zero-based indexing? for (auto group : groups) { if (group < 1) { - throw std::invalid_argument{"Encountered delayedgroup bin with index " - + std::to_string(group) + " which is less than 1"}; + throw std::invalid_argument {"Encountered delayedgroup bin with index " + + std::to_string(group) + + " which is less than 1"}; } else if (group > MAX_DELAYED_GROUPS) { - throw std::invalid_argument{"Encountered delayedgroup bin with index " - + std::to_string(group) + " which is greater than MAX_DELATED_GROUPS (" - + std::to_string(MAX_DELAYED_GROUPS) + ")"}; + throw std::invalid_argument { + "Encountered delayedgroup bin with index " + std::to_string(group) + + " which is greater than MAX_DELATED_GROUPS (" + + std::to_string(MAX_DELAYED_GROUPS) + ")"}; } groups_.push_back(group); } @@ -36,23 +36,20 @@ DelayedGroupFilter::set_groups(gsl::span groups) n_bins_ = groups_.size(); } -void -DelayedGroupFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void DelayedGroupFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { match.bins_.push_back(0); match.weights_.push_back(1.0); } -void -DelayedGroupFilter::to_statepoint(hid_t filter_group) const +void DelayedGroupFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", groups_); } -std::string -DelayedGroupFilter::text_label(int bin) const +std::string DelayedGroupFilter::text_label(int bin) const { return "Delayed Group " + std::to_string(groups_[bin]); } diff --git a/src/tallies/filter_distribcell.cpp b/src/tallies/filter_distribcell.cpp index c33c88cbc..89349b61f 100644 --- a/src/tallies/filter_distribcell.cpp +++ b/src/tallies/filter_distribcell.cpp @@ -10,8 +10,7 @@ namespace openmc { -void -DistribcellFilter::from_xml(pugi::xml_node node) +void DistribcellFilter::from_xml(pugi::xml_node node) { auto cells = get_node_array(node, "bins"); if (cells.size() != 1) { @@ -21,15 +20,14 @@ DistribcellFilter::from_xml(pugi::xml_node node) // Find index in global cells vector corresponding to cell ID auto search = model::cell_map.find(cells[0]); if (search == model::cell_map.end()) { - throw std::runtime_error{fmt::format( - "Could not find cell {} specified on tally filter.", cell_)}; + throw std::runtime_error { + fmt::format("Could not find cell {} specified on tally filter.", cell_)}; } this->set_cell(search->second); } -void -DistribcellFilter::set_cell(int32_t cell) +void DistribcellFilter::set_cell(int32_t cell) { Expects(cell >= 0); Expects(cell < model::cells.size()); @@ -37,9 +35,8 @@ DistribcellFilter::set_cell(int32_t cell) n_bins_ = model::cells[cell]->n_instances_; } -void -DistribcellFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void DistribcellFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { int offset = 0; auto distribcell_index = model::cells[cell_]->distribcell_index_; @@ -62,15 +59,13 @@ DistribcellFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -DistribcellFilter::to_statepoint(hid_t filter_group) const +void DistribcellFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", model::cells[cell_]->id_); } -std::string -DistribcellFilter::text_label(int bin) const +std::string DistribcellFilter::text_label(int bin) const { auto map = model::cells[cell_]->distribcell_index_; auto path = distribcell_path(cell_, map, bin); diff --git a/src/tallies/filter_energy.cpp b/src/tallies/filter_energy.cpp index 9169c4d85..48448cb1f 100644 --- a/src/tallies/filter_energy.cpp +++ b/src/tallies/filter_energy.cpp @@ -3,7 +3,7 @@ #include #include "openmc/capi.h" -#include "openmc/constants.h" // For F90_NONE +#include "openmc/constants.h" // For F90_NONE #include "openmc/mgxs_interface.h" #include "openmc/search.h" #include "openmc/settings.h" @@ -15,15 +15,13 @@ namespace openmc { // EnergyFilter implementation //============================================================================== -void -EnergyFilter::from_xml(pugi::xml_node node) +void EnergyFilter::from_xml(pugi::xml_node node) { auto bins = get_node_array(node, "bins"); this->set_bins(bins); } -void -EnergyFilter::set_bins(gsl::span bins) +void EnergyFilter::set_bins(gsl::span bins) { // Clear existing bins bins_.clear(); @@ -31,8 +29,9 @@ EnergyFilter::set_bins(gsl::span bins) // Copy bins, ensuring they are valid for (gsl::index i = 0; i < bins.size(); ++i) { - if (i > 0 && bins[i] <= bins[i-1]) { - throw std::runtime_error{"Energy bins must be monotonically increasing."}; + if (i > 0 && bins[i] <= bins[i - 1]) { + throw std::runtime_error { + "Energy bins must be monotonically increasing."}; } bins_.push_back(bins[i]); } @@ -57,9 +56,8 @@ EnergyFilter::set_bins(gsl::span bins) } } -void -EnergyFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) -const +void EnergyFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { if (p.g() != F90_NONE && matches_transport_groups_) { if (estimator == TallyEstimator::TRACKLENGTH) { @@ -82,26 +80,23 @@ const } } -void -EnergyFilter::to_statepoint(hid_t filter_group) const +void EnergyFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", bins_); } -std::string -EnergyFilter::text_label(int bin) const +std::string EnergyFilter::text_label(int bin) const { - return fmt::format("Incoming Energy [{}, {})", bins_[bin], bins_[bin+1]); + return fmt::format("Incoming Energy [{}, {})", bins_[bin], bins_[bin + 1]); } //============================================================================== // EnergyoutFilter implementation //============================================================================== -void -EnergyoutFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void EnergyoutFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { if (p.g() != F90_NONE && matches_transport_groups_) { match.bins_.push_back(data::mg.num_energy_groups_ - p.g() - 1); @@ -116,21 +111,22 @@ EnergyoutFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -std::string -EnergyoutFilter::text_label(int bin) const +std::string EnergyoutFilter::text_label(int bin) const { - return fmt::format("Outgoing Energy [{}, {})", bins_.at(bin), bins_.at(bin+1)); + return fmt::format( + "Outgoing Energy [{}, {})", bins_.at(bin), bins_.at(bin + 1)); } //============================================================================== // C-API functions //============================================================================== -extern"C" int -openmc_energy_filter_get_bins(int32_t index, const double** energies, size_t* n) +extern "C" int openmc_energy_filter_get_bins( + int32_t index, const double** energies, size_t* n) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -148,11 +144,12 @@ openmc_energy_filter_get_bins(int32_t index, const double** energies, size_t* n) return 0; } -extern "C" int -openmc_energy_filter_set_bins(int32_t index, size_t n, const double* energies) +extern "C" int openmc_energy_filter_set_bins( + int32_t index, size_t n, const double* energies) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -169,4 +166,4 @@ openmc_energy_filter_set_bins(int32_t index, size_t n, const double* energies) return 0; } -}// namespace openmc +} // namespace openmc diff --git a/src/tallies/filter_energyfunc.cpp b/src/tallies/filter_energyfunc.cpp index bea35c8e0..fd595e332 100644 --- a/src/tallies/filter_energyfunc.cpp +++ b/src/tallies/filter_energyfunc.cpp @@ -9,8 +9,7 @@ namespace openmc { -void -EnergyFunctionFilter::from_xml(pugi::xml_node node) +void EnergyFunctionFilter::from_xml(pugi::xml_node node) { if (!settings::run_CE) fatal_error("EnergyFunction filters are only supported for " @@ -29,9 +28,8 @@ EnergyFunctionFilter::from_xml(pugi::xml_node node) this->set_data(energy, y); } -void -EnergyFunctionFilter::set_data(gsl::span energy, - gsl::span y) +void EnergyFunctionFilter::set_data( + gsl::span energy, gsl::span y) { // Check for consistent sizes with new data if (energy.size() != y.size()) { @@ -45,16 +43,16 @@ EnergyFunctionFilter::set_data(gsl::span energy, // Copy over energy values, ensuring they are valid for (gsl::index i = 0; i < energy.size(); ++i) { if (i > 0 && energy[i] <= energy[i - 1]) { - throw std::runtime_error{"Energy bins must be monotonically increasing."}; + throw std::runtime_error { + "Energy bins must be monotonically increasing."}; } energy_.push_back(energy[i]); y_.push_back(y[i]); } } -void -EnergyFunctionFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void EnergyFunctionFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { if (p.E_last() >= energy_.front() && p.E_last() <= energy_.back()) { // Search for the incoming energy bin. @@ -65,20 +63,18 @@ EnergyFunctionFilter::get_all_bins(const Particle& p, TallyEstimator estimator, // Interpolate on the lin-lin grid. match.bins_.push_back(0); - match.weights_.push_back((1-f) * y_[i] + f * y_[i+1]); + match.weights_.push_back((1 - f) * y_[i] + f * y_[i + 1]); } } -void -EnergyFunctionFilter::to_statepoint(hid_t filter_group) const +void EnergyFunctionFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "energy", energy_); write_dataset(filter_group, "y", y_); } -std::string -EnergyFunctionFilter::text_label(int bin) const +std::string EnergyFunctionFilter::text_label(int bin) const { return fmt::format( "Energy Function f([{:.1e}, ..., {:.1e}]) = [{:.1e}, ..., {:.1e}]", @@ -89,12 +85,12 @@ EnergyFunctionFilter::text_label(int bin) const // C-API functions //============================================================================== -extern "C" int -openmc_energyfunc_filter_set_data(int32_t index, size_t n, const double* energy, - const double* y) +extern "C" int openmc_energyfunc_filter_set_data( + int32_t index, size_t n, const double* energy, const double* y) { // Ensure this is a valid index to allocated filter - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter const auto& filt_base = model::tally_filters[index].get(); @@ -103,7 +99,8 @@ openmc_energyfunc_filter_set_data(int32_t index, size_t n, const double* energy, // Check if a valid filter was produced if (!filt) { - set_errmsg("Tried to set interpolation data for non-energy function filter."); + set_errmsg( + "Tried to set interpolation data for non-energy function filter."); return OPENMC_E_INVALID_TYPE; } @@ -111,11 +108,12 @@ openmc_energyfunc_filter_set_data(int32_t index, size_t n, const double* energy, return 0; } -extern "C" int -openmc_energyfunc_filter_get_energy(int32_t index, size_t *n, const double** energy) +extern "C" int openmc_energyfunc_filter_get_energy( + int32_t index, size_t* n, const double** energy) { // ensure this is a valid index to allocated filter - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // get a pointer to the filter const auto& filt_base = model::tally_filters[index].get(); @@ -124,7 +122,8 @@ openmc_energyfunc_filter_get_energy(int32_t index, size_t *n, const double** ene // check if a valid filter was produced if (!filt) { - set_errmsg("Tried to set interpolation data for non-energy function filter."); + set_errmsg( + "Tried to set interpolation data for non-energy function filter."); return OPENMC_E_INVALID_TYPE; } *energy = filt->energy().data(); @@ -132,11 +131,12 @@ openmc_energyfunc_filter_get_energy(int32_t index, size_t *n, const double** ene return 0; } -extern "C" int -openmc_energyfunc_filter_get_y(int32_t index, size_t *n, const double** y) +extern "C" int openmc_energyfunc_filter_get_y( + int32_t index, size_t* n, const double** y) { // ensure this is a valid index to allocated filter - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // get a pointer to the filter const auto& filt_base = model::tally_filters[index].get(); @@ -145,7 +145,8 @@ openmc_energyfunc_filter_get_y(int32_t index, size_t *n, const double** y) // check if a valid filter was produced if (!filt) { - set_errmsg("Tried to set interpolation data for non-energy function filter."); + set_errmsg( + "Tried to set interpolation data for non-energy function filter."); return OPENMC_E_INVALID_TYPE; } *y = filt->y().data(); diff --git a/src/tallies/filter_legendre.cpp b/src/tallies/filter_legendre.cpp index 6626f5ea1..36ae0e41a 100644 --- a/src/tallies/filter_legendre.cpp +++ b/src/tallies/filter_legendre.cpp @@ -7,25 +7,22 @@ namespace openmc { -void -LegendreFilter::from_xml(pugi::xml_node node) +void LegendreFilter::from_xml(pugi::xml_node node) { this->set_order(std::stoi(get_node_value(node, "order"))); } -void -LegendreFilter::set_order(int order) +void LegendreFilter::set_order(int order) { if (order < 0) { - throw std::invalid_argument{"Legendre order must be non-negative."}; + throw std::invalid_argument {"Legendre order must be non-negative."}; } order_ = order; n_bins_ = order_ + 1; } -void -LegendreFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void LegendreFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { vector wgt(n_bins_); calc_pn_c(order_, p.mu(), wgt.data()); @@ -35,15 +32,13 @@ LegendreFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -LegendreFilter::to_statepoint(hid_t filter_group) const +void LegendreFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "order", order_); } -std::string -LegendreFilter::text_label(int bin) const +std::string LegendreFilter::text_label(int bin) const { return "Legendre expansion, P" + std::to_string(bin); } @@ -52,11 +47,11 @@ LegendreFilter::text_label(int bin) const // C-API functions //============================================================================== -extern "C" int -openmc_legendre_filter_get_order(int32_t index, int* order) +extern "C" int openmc_legendre_filter_get_order(int32_t index, int* order) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -73,11 +68,11 @@ openmc_legendre_filter_get_order(int32_t index, int* order) return 0; } -extern "C" int -openmc_legendre_filter_set_order(int32_t index, int order) +extern "C" int openmc_legendre_filter_set_order(int32_t index, int order) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); diff --git a/src/tallies/filter_material.cpp b/src/tallies/filter_material.cpp index e9247457f..6669ab2fa 100644 --- a/src/tallies/filter_material.cpp +++ b/src/tallies/filter_material.cpp @@ -8,15 +8,14 @@ namespace openmc { -void -MaterialFilter::from_xml(pugi::xml_node node) +void MaterialFilter::from_xml(pugi::xml_node node) { // Get material IDs and convert to indices in the global materials vector auto mats = get_node_array(node, "bins"); for (auto& m : mats) { auto search = model::material_map.find(m); if (search == model::material_map.end()) { - throw std::runtime_error{fmt::format( + throw std::runtime_error {fmt::format( "Could not find material {} specified on tally filter.", m)}; } m = search->second; @@ -25,8 +24,7 @@ MaterialFilter::from_xml(pugi::xml_node node) this->set_materials(mats); } -void -MaterialFilter::set_materials(gsl::span materials) +void MaterialFilter::set_materials(gsl::span materials) { // Clear existing materials materials_.clear(); @@ -44,9 +42,8 @@ MaterialFilter::set_materials(gsl::span materials) n_bins_ = materials_.size(); } -void -MaterialFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void MaterialFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { auto search = map_.find(p.material()); if (search != map_.end()) { @@ -55,17 +52,16 @@ MaterialFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -MaterialFilter::to_statepoint(hid_t filter_group) const +void MaterialFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); vector material_ids; - for (auto c : materials_) material_ids.push_back(model::materials[c]->id_); + for (auto c : materials_) + material_ids.push_back(model::materials[c]->id_); write_dataset(filter_group, "bins", material_ids); } -std::string -MaterialFilter::text_label(int bin) const +std::string MaterialFilter::text_label(int bin) const { return fmt::format("Material {}", model::materials[materials_[bin]]->id_); } @@ -74,11 +70,12 @@ MaterialFilter::text_label(int bin) const // C-API functions //============================================================================== -extern "C" int -openmc_material_filter_get_bins(int32_t index, const int32_t** bins, size_t* n) +extern "C" int openmc_material_filter_get_bins( + int32_t index, const int32_t** bins, size_t* n) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -96,11 +93,12 @@ openmc_material_filter_get_bins(int32_t index, const int32_t** bins, size_t* n) return 0; } -extern "C" int -openmc_material_filter_set_bins(int32_t index, size_t n, const int32_t* bins) +extern "C" int openmc_material_filter_set_bins( + int32_t index, size_t n, const int32_t* bins) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); diff --git a/src/tallies/filter_mesh.cpp b/src/tallies/filter_mesh.cpp index d36fdb6f7..a5f52e95a 100644 --- a/src/tallies/filter_mesh.cpp +++ b/src/tallies/filter_mesh.cpp @@ -11,33 +11,30 @@ namespace openmc { -void -MeshFilter::from_xml(pugi::xml_node node) +void MeshFilter::from_xml(pugi::xml_node node) { auto bins_ = get_node_array(node, "bins"); if (bins_.size() != 1) { - fatal_error("Only one mesh can be specified per " + type() - + " mesh filter."); + fatal_error( + "Only one mesh can be specified per " + type() + " mesh filter."); } auto id = bins_[0]; auto search = model::mesh_map.find(id); if (search != model::mesh_map.end()) { set_mesh(search->second); - } else{ - fatal_error(fmt::format( - "Could not find mesh {} specified on tally filter.", id)); + } else { + fatal_error( + fmt::format("Could not find mesh {} specified on tally filter.", id)); } if (check_for_node(node, "translation")) { set_translation(get_node_array(node, "translation")); } - } -void -MeshFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) -const +void MeshFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { Position last_r = p.r_last(); @@ -57,12 +54,12 @@ const match.weights_.push_back(1.0); } } else { - model::meshes[mesh_]->bins_crossed(last_r, r, u, match.bins_, match.weights_); + model::meshes[mesh_]->bins_crossed( + last_r, r, u, match.bins_, match.weights_); } } -void -MeshFilter::to_statepoint(hid_t filter_group) const +void MeshFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", model::meshes[mesh_]->id_); @@ -71,16 +68,14 @@ MeshFilter::to_statepoint(hid_t filter_group) const } } -std::string -MeshFilter::text_label(int bin) const +std::string MeshFilter::text_label(int bin) const { auto& mesh = *model::meshes.at(mesh_); std::string label = mesh.bin_label(bin); return label; } -void -MeshFilter::set_mesh(int32_t mesh) +void MeshFilter::set_mesh(int32_t mesh) { mesh_ = mesh; n_bins_ = model::meshes[mesh_]->n_bins(); @@ -101,8 +96,7 @@ void MeshFilter::set_translation(const double translation[3]) // C-API functions //============================================================================== -extern "C" int -openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh) +extern "C" int openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh) { if (!index_mesh) { set_errmsg("Mesh index argument is a null pointer."); @@ -110,7 +104,8 @@ openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh) } // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -127,11 +122,11 @@ openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh) return 0; } -extern "C" int -openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh) +extern "C" int openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh) { // Make sure this is a valid index to an allocated filter. - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Get a pointer to the filter and downcast. const auto& filt_base = model::tally_filters[index].get(); @@ -154,11 +149,12 @@ openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh) return 0; } -extern "C" int -openmc_mesh_filter_get_translation(int32_t index, double translation[3]) +extern "C" int openmc_mesh_filter_get_translation( + int32_t index, double translation[3]) { // Make sure this is a valid index to an allocated filter - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; // Check the filter type const auto& filter = model::tally_filters[index]; @@ -170,16 +166,19 @@ openmc_mesh_filter_get_translation(int32_t index, double translation[3]) // Get translation from the mesh filter and set value auto mesh_filter = dynamic_cast(filter.get()); const auto& t = mesh_filter->translation(); - for (int i = 0; i < 3; i++) { translation[i] = t[i]; } + for (int i = 0; i < 3; i++) { + translation[i] = t[i]; + } return 0; } -extern "C" int -openmc_mesh_filter_set_translation(int32_t index, double translation[3]) +extern "C" int openmc_mesh_filter_set_translation( + int32_t index, double translation[3]) { // Make sure this is a valid index to an allocated filter - if (int err = verify_filter(index)) return err; + if (int err = verify_filter(index)) + return err; const auto& filter = model::tally_filters[index]; // Check the filter type diff --git a/src/tallies/filter_meshsurface.cpp b/src/tallies/filter_meshsurface.cpp index 8f94e5ecb..b22085ebb 100644 --- a/src/tallies/filter_meshsurface.cpp +++ b/src/tallies/filter_meshsurface.cpp @@ -7,9 +7,8 @@ namespace openmc { -void -MeshSurfaceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void MeshSurfaceFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { Position r0 = p.r_last_current(); Position r1 = p.r(); @@ -20,11 +19,11 @@ MeshSurfaceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, Direction u = p.u(); model::meshes[mesh_]->surface_bins_crossed(r0, r1, u, match.bins_); - for (auto b : match.bins_) match.weights_.push_back(1.0); + for (auto b : match.bins_) + match.weights_.push_back(1.0); } -std::string -MeshSurfaceFilter::text_label(int bin) const +std::string MeshSurfaceFilter::text_label(int bin) const { auto& mesh = *model::meshes[mesh_]; int n_dim = mesh.n_dimension_; @@ -38,49 +37,48 @@ MeshSurfaceFilter::text_label(int bin) const // Get surface part of label. switch (surf_dir) { - case MeshDir::OUT_LEFT: - out += " Outgoing, x-min"; - break; - case MeshDir::IN_LEFT: - out += " Incoming, x-min"; - break; - case MeshDir::OUT_RIGHT: - out += " Outgoing, x-max"; - break; - case MeshDir::IN_RIGHT: - out += " Incoming, x-max"; - break; - case MeshDir::OUT_BACK: - out += " Outgoing, y-min"; - break; - case MeshDir::IN_BACK: - out += " Incoming, y-min"; - break; - case MeshDir::OUT_FRONT: - out += " Outgoing, y-max"; - break; - case MeshDir::IN_FRONT: - out += " Incoming, y-max"; - break; - case MeshDir::OUT_BOTTOM: - out += " Outgoing, z-min"; - break; - case MeshDir::IN_BOTTOM: - out += " Incoming, z-min"; - break; - case MeshDir::OUT_TOP: - out += " Outgoing, z-max"; - break; - case MeshDir::IN_TOP: - out += " Incoming, z-max"; - break; + case MeshDir::OUT_LEFT: + out += " Outgoing, x-min"; + break; + case MeshDir::IN_LEFT: + out += " Incoming, x-min"; + break; + case MeshDir::OUT_RIGHT: + out += " Outgoing, x-max"; + break; + case MeshDir::IN_RIGHT: + out += " Incoming, x-max"; + break; + case MeshDir::OUT_BACK: + out += " Outgoing, y-min"; + break; + case MeshDir::IN_BACK: + out += " Incoming, y-min"; + break; + case MeshDir::OUT_FRONT: + out += " Outgoing, y-max"; + break; + case MeshDir::IN_FRONT: + out += " Incoming, y-max"; + break; + case MeshDir::OUT_BOTTOM: + out += " Outgoing, z-min"; + break; + case MeshDir::IN_BOTTOM: + out += " Incoming, z-min"; + break; + case MeshDir::OUT_TOP: + out += " Outgoing, z-max"; + break; + case MeshDir::IN_TOP: + out += " Incoming, z-max"; + break; } return out; } -void -MeshSurfaceFilter::set_mesh(int32_t mesh) +void MeshSurfaceFilter::set_mesh(int32_t mesh) { mesh_ = mesh; n_bins_ = model::meshes[mesh_]->n_surface_bins(); @@ -90,12 +88,16 @@ MeshSurfaceFilter::set_mesh(int32_t mesh) // C-API functions //============================================================================== -extern"C" int -openmc_meshsurface_filter_get_mesh(int32_t index, int32_t* index_mesh) -{return openmc_mesh_filter_get_mesh(index, index_mesh);} +extern "C" int openmc_meshsurface_filter_get_mesh( + int32_t index, int32_t* index_mesh) +{ + return openmc_mesh_filter_get_mesh(index, index_mesh); +} -extern"C" int -openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh) -{return openmc_mesh_filter_set_mesh(index, index_mesh);} +extern "C" int openmc_meshsurface_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/tallies/filter_mu.cpp b/src/tallies/filter_mu.cpp index b157ff2db..95bb3b210 100644 --- a/src/tallies/filter_mu.cpp +++ b/src/tallies/filter_mu.cpp @@ -8,8 +8,7 @@ namespace openmc { -void -MuFilter::from_xml(pugi::xml_node node) +void MuFilter::from_xml(pugi::xml_node node) { auto bins = get_node_array(node, "bins"); @@ -18,20 +17,21 @@ MuFilter::from_xml(pugi::xml_node node) // [-1,1) evenly with the input being the number of bins int n_angle = bins[0]; - if (n_angle <= 1) throw std::runtime_error{ + if (n_angle <= 1) + throw std::runtime_error { "Number of bins for mu filter must be greater than 1."}; double d_angle = 2.0 / n_angle; bins.resize(n_angle + 1); - for (int i = 0; i < n_angle; i++) bins[i] = -1 + i * d_angle; + for (int i = 0; i < n_angle; i++) + bins[i] = -1 + i * d_angle; bins[n_angle] = 1; } this->set_bins(bins); } -void -MuFilter::set_bins(gsl::span bins) +void MuFilter::set_bins(gsl::span bins) { // Clear existing bins bins_.clear(); @@ -39,8 +39,8 @@ MuFilter::set_bins(gsl::span bins) // Copy bins, ensuring they are valid for (gsl::index i = 0; i < bins.size(); ++i) { - if (i > 0 && bins[i] <= bins[i-1]) { - throw std::runtime_error{"Mu bins must be monotonically increasing."}; + if (i > 0 && bins[i] <= bins[i - 1]) { + throw std::runtime_error {"Mu bins must be monotonically increasing."}; } bins_.push_back(bins[i]); } @@ -48,9 +48,8 @@ MuFilter::set_bins(gsl::span bins) n_bins_ = bins_.size() - 1; } -void -MuFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) -const +void MuFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { if (p.mu() >= bins_.front() && p.mu() <= bins_.back()) { auto bin = lower_bound_index(bins_.begin(), bins_.end(), p.mu()); @@ -59,17 +58,15 @@ const } } -void -MuFilter::to_statepoint(hid_t filter_group) const +void MuFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", bins_); } -std::string -MuFilter::text_label(int bin) const +std::string MuFilter::text_label(int bin) const { - return fmt::format("Change-in-Angle [{}, {})", bins_[bin], bins_[bin+1]); + return fmt::format("Change-in-Angle [{}, {})", bins_[bin], bins_[bin + 1]); } } // namespace openmc diff --git a/src/tallies/filter_particle.cpp b/src/tallies/filter_particle.cpp index a9669661e..3865824f6 100644 --- a/src/tallies/filter_particle.cpp +++ b/src/tallies/filter_particle.cpp @@ -6,8 +6,7 @@ namespace openmc { -void -ParticleFilter::from_xml(pugi::xml_node node) +void ParticleFilter::from_xml(pugi::xml_node node) { auto particles = get_node_array(node, "bins"); @@ -32,9 +31,8 @@ void ParticleFilter::set_particles(gsl::span particles) n_bins_ = particles_.size(); } -void -ParticleFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void ParticleFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { for (auto i = 0; i < particles_.size(); i++) { if (particles_[i] == p.type()) { @@ -44,8 +42,7 @@ ParticleFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -ParticleFilter::to_statepoint(hid_t filter_group) const +void ParticleFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); vector particles; @@ -55,8 +52,7 @@ ParticleFilter::to_statepoint(hid_t filter_group) const write_dataset(filter_group, "bins", particles); } -std::string -ParticleFilter::text_label(int bin) const +std::string ParticleFilter::text_label(int bin) const { const auto& p = particles_.at(bin); return fmt::format("Particle: {}", particle_type_to_str(p)); diff --git a/src/tallies/filter_polar.cpp b/src/tallies/filter_polar.cpp index 51ff496cd..d132ccf42 100644 --- a/src/tallies/filter_polar.cpp +++ b/src/tallies/filter_polar.cpp @@ -9,8 +9,7 @@ namespace openmc { -void -PolarFilter::from_xml(pugi::xml_node node) +void PolarFilter::from_xml(pugi::xml_node node) { auto bins = get_node_array(node, "bins"); @@ -19,20 +18,21 @@ PolarFilter::from_xml(pugi::xml_node node) // [0,pi] evenly with the input being the number of bins int n_angle = bins[0]; - if (n_angle <= 1) throw std::runtime_error{ - "Number of bins for polar filter must be greater than 1."}; + if (n_angle <= 1) + throw std::runtime_error { + "Number of bins for polar filter must be greater than 1."}; double d_angle = PI / n_angle; bins.resize(n_angle + 1); - for (int i = 0; i < n_angle; i++) bins[i] = i * d_angle; + for (int i = 0; i < n_angle; i++) + bins[i] = i * d_angle; bins[n_angle] = PI; } this->set_bins(bins); } -void -PolarFilter::set_bins(gsl::span bins) +void PolarFilter::set_bins(gsl::span bins) { // Clear existing bins bins_.clear(); @@ -40,8 +40,8 @@ PolarFilter::set_bins(gsl::span bins) // Copy bins, ensuring they are valid for (gsl::index i = 0; i < bins.size(); ++i) { - if (i > 0 && bins[i] <= bins[i-1]) { - throw std::runtime_error{"Polar bins must be monotonically increasing."}; + if (i > 0 && bins[i] <= bins[i - 1]) { + throw std::runtime_error {"Polar bins must be monotonically increasing."}; } bins_.push_back(bins[i]); } @@ -49,9 +49,8 @@ PolarFilter::set_bins(gsl::span bins) n_bins_ = bins_.size() - 1; } -void -PolarFilter::get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) -const +void PolarFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { double z = (estimator == TallyEstimator::TRACKLENGTH) ? p.u().z : p.u_last().z; @@ -64,17 +63,15 @@ const } } -void -PolarFilter::to_statepoint(hid_t filter_group) const +void PolarFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "bins", bins_); } -std::string -PolarFilter::text_label(int bin) const +std::string PolarFilter::text_label(int bin) const { - return fmt::format("Polar Angle [{}, {})", bins_[bin], bins_[bin+1]); + return fmt::format("Polar Angle [{}, {})", bins_[bin], bins_[bin + 1]); } } // namespace openmc diff --git a/src/tallies/filter_sph_harm.cpp b/src/tallies/filter_sph_harm.cpp index e8f8eed21..29976f3a1 100644 --- a/src/tallies/filter_sph_harm.cpp +++ b/src/tallies/filter_sph_harm.cpp @@ -1,6 +1,6 @@ #include "openmc/tallies/filter_sph_harm.h" -#include // For pair +#include // For pair #include #include @@ -12,8 +12,7 @@ namespace openmc { -void -SphericalHarmonicsFilter::from_xml(pugi::xml_node node) +void SphericalHarmonicsFilter::from_xml(pugi::xml_node node) { this->set_order(std::stoi(get_node_value(node, "order"))); if (check_for_node(node, "cosine")) { @@ -21,32 +20,31 @@ SphericalHarmonicsFilter::from_xml(pugi::xml_node node) } } -void -SphericalHarmonicsFilter::set_order(int order) +void SphericalHarmonicsFilter::set_order(int order) { if (order < 0) { - throw std::invalid_argument{"Spherical harmonics order must be non-negative."}; + throw std::invalid_argument { + "Spherical harmonics order must be non-negative."}; } order_ = order; n_bins_ = (order_ + 1) * (order_ + 1); } -void -SphericalHarmonicsFilter::set_cosine(gsl::cstring_span cosine) +void SphericalHarmonicsFilter::set_cosine(gsl::cstring_span cosine) { if (cosine == "scatter") { cosine_ = SphericalHarmonicsCosine::scatter; } else if (cosine == "particle") { cosine_ = SphericalHarmonicsCosine::particle; } else { - throw std::invalid_argument{fmt::format("Unrecognized cosine type, \"{}\" " - "in spherical harmonics filter", gsl::to_string(cosine))}; + throw std::invalid_argument {fmt::format("Unrecognized cosine type, \"{}\" " + "in spherical harmonics filter", + gsl::to_string(cosine))}; } } -void -SphericalHarmonicsFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void SphericalHarmonicsFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { // Determine cosine term for scatter expansion if necessary vector wgt(order_ + 1); @@ -65,7 +63,7 @@ SphericalHarmonicsFilter::get_all_bins(const Particle& p, TallyEstimator estimat int j = 0; for (int n = 0; n < order_ + 1; n++) { // Calculate n-th order spherical harmonics for (u,v,w) - int num_nm = 2*n + 1; + int num_nm = 2 * n + 1; // Append the matching (bin,weight) for each moment for (int i = 0; i < num_nm; i++) { @@ -76,8 +74,7 @@ SphericalHarmonicsFilter::get_all_bins(const Particle& p, TallyEstimator estimat } } -void -SphericalHarmonicsFilter::to_statepoint(hid_t filter_group) const +void SphericalHarmonicsFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "order", order_); @@ -88,13 +85,12 @@ SphericalHarmonicsFilter::to_statepoint(hid_t filter_group) const } } -std::string -SphericalHarmonicsFilter::text_label(int bin) const +std::string SphericalHarmonicsFilter::text_label(int bin) const { Expects(bin >= 0 && bin < n_bins_); for (int n = 0; n < order_ + 1; n++) { if (bin < (n + 1) * (n + 1)) { - int m = (bin - n*n) - n; + int m = (bin - n * n) - n; return fmt::format("Spherical harmonic expansion, Y{},{}", n, m); } } @@ -105,8 +101,7 @@ SphericalHarmonicsFilter::text_label(int bin) const // C-API functions //============================================================================== -std::pair -check_sphharm_filter(int32_t index) +std::pair check_sphharm_filter(int32_t index) { // Make sure this is a valid index to an allocated filter. int err = verify_filter(index); @@ -126,28 +121,28 @@ check_sphharm_filter(int32_t index) return {err, filt}; } -extern "C" int -openmc_sphharm_filter_get_order(int32_t index, int* order) +extern "C" int openmc_sphharm_filter_get_order(int32_t index, int* order) { // Check the filter. auto check_result = check_sphharm_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the order. *order = filt->order(); return 0; } -extern "C" int -openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]) +extern "C" int openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]) { // Check the filter. auto check_result = check_sphharm_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the cosine. if (filt->cosine() == SphericalHarmonicsCosine::scatter) { @@ -158,28 +153,29 @@ openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]) return 0; } -extern "C" int -openmc_sphharm_filter_set_order(int32_t index, int order) +extern "C" int openmc_sphharm_filter_set_order(int32_t index, int order) { // Check the filter. auto check_result = check_sphharm_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. filt->set_order(order); return 0; } -extern "C" int -openmc_sphharm_filter_set_cosine(int32_t index, const char cosine[]) +extern "C" int openmc_sphharm_filter_set_cosine( + int32_t index, const char cosine[]) { // Check the filter. auto check_result = check_sphharm_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. try { diff --git a/src/tallies/filter_sptl_legendre.cpp b/src/tallies/filter_sptl_legendre.cpp index c835f1dd9..cf5ef2aed 100644 --- a/src/tallies/filter_sptl_legendre.cpp +++ b/src/tallies/filter_sptl_legendre.cpp @@ -1,6 +1,6 @@ #include "openmc/tallies/filter_sptl_legendre.h" -#include // For pair +#include // For pair #include @@ -11,8 +11,7 @@ namespace openmc { -void -SpatialLegendreFilter::from_xml(pugi::xml_node node) +void SpatialLegendreFilter::from_xml(pugi::xml_node node) { this->set_order(std::stoi(get_node_value(node, "order"))); @@ -28,7 +27,8 @@ SpatialLegendreFilter::from_xml(pugi::xml_node node) this->set_axis(LegendreAxis::z); break; default: - throw std::runtime_error{"Axis for SpatialLegendreFilter must be 'x', 'y', or 'z'"}; + throw std::runtime_error { + "Axis for SpatialLegendreFilter must be 'x', 'y', or 'z'"}; } double min = std::stod(get_node_value(node, "min")); @@ -36,35 +36,32 @@ SpatialLegendreFilter::from_xml(pugi::xml_node node) this->set_minmax(min, max); } -void -SpatialLegendreFilter::set_order(int order) +void SpatialLegendreFilter::set_order(int order) { if (order < 0) { - throw std::invalid_argument{"Legendre order must be non-negative."}; + throw std::invalid_argument {"Legendre order must be non-negative."}; } order_ = order; n_bins_ = order_ + 1; } -void -SpatialLegendreFilter::set_axis(LegendreAxis axis) +void SpatialLegendreFilter::set_axis(LegendreAxis axis) { axis_ = axis; } -void -SpatialLegendreFilter::set_minmax(double min, double max) +void SpatialLegendreFilter::set_minmax(double min, double max) { if (max <= min) { - throw std::invalid_argument{"Maximum value must be greater than minimum value"}; + throw std::invalid_argument { + "Maximum value must be greater than minimum value"}; } min_ = min; max_ = max; } -void -SpatialLegendreFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void SpatialLegendreFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { // Get the coordinate along the axis of interest. double x; @@ -78,7 +75,7 @@ SpatialLegendreFilter::get_all_bins(const Particle& p, TallyEstimator estimator, if (x >= min_ && x <= max_) { // Compute the normalized coordinate value. - double x_norm = 2.0*(x - min_) / (max_ - min_) - 1.0; + double x_norm = 2.0 * (x - min_) / (max_ - min_) - 1.0; // Compute and return the Legendre weights. vector wgt(order_ + 1); @@ -90,8 +87,7 @@ SpatialLegendreFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -SpatialLegendreFilter::to_statepoint(hid_t filter_group) const +void SpatialLegendreFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "order", order_); @@ -106,8 +102,7 @@ SpatialLegendreFilter::to_statepoint(hid_t filter_group) const write_dataset(filter_group, "max", max_); } -std::string -SpatialLegendreFilter::text_label(int bin) const +std::string SpatialLegendreFilter::text_label(int bin) const { if (axis_ == LegendreAxis::x) { return fmt::format("Legendre expansion, x axis, P{}", bin); @@ -122,8 +117,7 @@ SpatialLegendreFilter::text_label(int bin) const // C-API functions //============================================================================== -std::pair -check_sptl_legendre_filter(int32_t index) +std::pair check_sptl_legendre_filter(int32_t index) { // Make sure this is a valid index to an allocated filter. int err = verify_filter(index); @@ -143,29 +137,30 @@ check_sptl_legendre_filter(int32_t index) return {err, filt}; } -extern "C" int -openmc_spatial_legendre_filter_get_order(int32_t index, int* order) +extern "C" int openmc_spatial_legendre_filter_get_order( + int32_t index, int* order) { // Check the filter. auto check_result = check_sptl_legendre_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the order. *order = filt->order(); return 0; } -extern "C" int -openmc_spatial_legendre_filter_get_params(int32_t index, int* axis, - double* min, double* max) +extern "C" int openmc_spatial_legendre_filter_get_params( + int32_t index, int* axis, double* min, double* max) { // Check the filter. auto check_result = check_sptl_legendre_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the params. *axis = static_cast(filt->axis()); @@ -174,33 +169,36 @@ openmc_spatial_legendre_filter_get_params(int32_t index, int* axis, return 0; } -extern "C" int -openmc_spatial_legendre_filter_set_order(int32_t index, int order) +extern "C" int openmc_spatial_legendre_filter_set_order( + int32_t index, int order) { // Check the filter. auto check_result = check_sptl_legendre_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. filt->set_order(order); return 0; } -extern "C" int -openmc_spatial_legendre_filter_set_params(int32_t index, const int* axis, - const double* min, const double* max) +extern "C" int openmc_spatial_legendre_filter_set_params( + int32_t index, const int* axis, const double* min, const double* max) { // Check the filter. auto check_result = check_sptl_legendre_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. - if (axis) filt->set_axis(static_cast(*axis)); - if (min && max) filt->set_minmax(*min, *max); + if (axis) + filt->set_axis(static_cast(*axis)); + if (min && max) + filt->set_minmax(*min, *max); return 0; } diff --git a/src/tallies/filter_surface.cpp b/src/tallies/filter_surface.cpp index 53bbf4045..a84d17728 100644 --- a/src/tallies/filter_surface.cpp +++ b/src/tallies/filter_surface.cpp @@ -8,8 +8,7 @@ namespace openmc { -void -SurfaceFilter::from_xml(pugi::xml_node node) +void SurfaceFilter::from_xml(pugi::xml_node node) { auto surfaces = get_node_array(node, "bins"); @@ -17,8 +16,8 @@ SurfaceFilter::from_xml(pugi::xml_node node) for (auto& s : surfaces) { auto search = model::surface_map.find(s); if (search == model::surface_map.end()) { - throw std::runtime_error{fmt::format( - "Could not find surface {} specified on tally filter.", s)}; + throw std::runtime_error { + fmt::format("Could not find surface {} specified on tally filter.", s)}; } s = search->second; @@ -27,8 +26,7 @@ SurfaceFilter::from_xml(pugi::xml_node node) this->set_surfaces(surfaces); } -void -SurfaceFilter::set_surfaces(gsl::span surfaces) +void SurfaceFilter::set_surfaces(gsl::span surfaces) { // Clear existing surfaces surfaces_.clear(); @@ -46,9 +44,8 @@ SurfaceFilter::set_surfaces(gsl::span surfaces) n_bins_ = surfaces_.size(); } -void -SurfaceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void SurfaceFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { auto search = map_.find(std::abs(p.surface()) - 1); if (search != map_.end()) { @@ -61,17 +58,16 @@ SurfaceFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -SurfaceFilter::to_statepoint(hid_t filter_group) const +void SurfaceFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); vector surface_ids; - for (auto c : surfaces_) surface_ids.push_back(model::surfaces[c]->id_); + for (auto c : surfaces_) + surface_ids.push_back(model::surfaces[c]->id_); write_dataset(filter_group, "bins", surface_ids); } -std::string -SurfaceFilter::text_label(int bin) const +std::string SurfaceFilter::text_label(int bin) const { return fmt::format("Surface {}", model::surfaces[surfaces_[bin]]->id_); } diff --git a/src/tallies/filter_universe.cpp b/src/tallies/filter_universe.cpp index 8dbfa6462..96ad0212d 100644 --- a/src/tallies/filter_universe.cpp +++ b/src/tallies/filter_universe.cpp @@ -8,15 +8,14 @@ namespace openmc { -void -UniverseFilter::from_xml(pugi::xml_node node) +void UniverseFilter::from_xml(pugi::xml_node node) { // Get material IDs and convert to indices in the global materials vector auto universes = get_node_array(node, "bins"); for (auto& u : universes) { auto search = model::universe_map.find(u); if (search == model::universe_map.end()) { - throw std::runtime_error{fmt::format( + throw std::runtime_error {fmt::format( "Could not find universe {} specified on tally filter.", u)}; } u = search->second; @@ -25,8 +24,7 @@ UniverseFilter::from_xml(pugi::xml_node node) this->set_universes(universes); } -void -UniverseFilter::set_universes(gsl::span universes) +void UniverseFilter::set_universes(gsl::span universes) { // Clear existing universes universes_.clear(); @@ -44,9 +42,8 @@ UniverseFilter::set_universes(gsl::span universes) n_bins_ = universes_.size(); } -void -UniverseFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void UniverseFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { for (int i = 0; i < p.n_coord(); i++) { auto search = map_.find(p.coord(i).universe); @@ -57,17 +54,16 @@ UniverseFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -UniverseFilter::to_statepoint(hid_t filter_group) const +void UniverseFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); vector universe_ids; - for (auto u : universes_) universe_ids.push_back(model::universes[u]->id_); + for (auto u : universes_) + universe_ids.push_back(model::universes[u]->id_); write_dataset(filter_group, "bins", universe_ids); } -std::string -UniverseFilter::text_label(int bin) const +std::string UniverseFilter::text_label(int bin) const { return fmt::format("Universe {}", model::universes[universes_[bin]]->id_); } diff --git a/src/tallies/filter_zernike.cpp b/src/tallies/filter_zernike.cpp index d86298c45..65004983c 100644 --- a/src/tallies/filter_zernike.cpp +++ b/src/tallies/filter_zernike.cpp @@ -2,7 +2,7 @@ #include #include -#include // For pair +#include // For pair #include #include @@ -18,8 +18,7 @@ namespace openmc { // ZernikeFilter implementation //============================================================================== -void -ZernikeFilter::from_xml(pugi::xml_node node) +void ZernikeFilter::from_xml(pugi::xml_node node) { set_order(std::stoi(get_node_value(node, "order"))); x_ = std::stod(get_node_value(node, "x")); @@ -27,14 +26,13 @@ ZernikeFilter::from_xml(pugi::xml_node node) r_ = std::stod(get_node_value(node, "r")); } -void -ZernikeFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void ZernikeFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { // Determine the normalized (r,theta) coordinates. double x = p.r().x - x_; double y = p.r().y - y_; - double r = std::sqrt(x*x + y*y) / r_; + double r = std::sqrt(x * x + y * y) / r_; double theta = std::atan2(y, x); if (r <= 1.0) { @@ -48,8 +46,7 @@ ZernikeFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -void -ZernikeFilter::to_statepoint(hid_t filter_group) const +void ZernikeFilter::to_statepoint(hid_t filter_group) const { Filter::to_statepoint(filter_group); write_dataset(filter_group, "order", order_); @@ -58,11 +55,10 @@ ZernikeFilter::to_statepoint(hid_t filter_group) const write_dataset(filter_group, "r", r_); } -std::string -ZernikeFilter::text_label(int bin) const +std::string ZernikeFilter::text_label(int bin) const { Expects(bin >= 0 && bin < n_bins_); - for (int n = 0; n < order_+1; n++) { + for (int n = 0; n < order_ + 1; n++) { int last = (n + 1) * (n + 2) / 2; if (bin < last) { int first = last - (n + 1); @@ -73,28 +69,26 @@ ZernikeFilter::text_label(int bin) const UNREACHABLE(); } -void -ZernikeFilter::set_order(int order) +void ZernikeFilter::set_order(int order) { if (order < 0) { - throw std::invalid_argument{"Zernike order must be non-negative."}; + throw std::invalid_argument {"Zernike order must be non-negative."}; } order_ = order; - n_bins_ = ((order+1) * (order+2)) / 2; + n_bins_ = ((order + 1) * (order + 2)) / 2; } //============================================================================== // ZernikeRadialFilter implementation //============================================================================== -void -ZernikeRadialFilter::get_all_bins(const Particle& p, TallyEstimator estimator, - FilterMatch& match) const +void ZernikeRadialFilter::get_all_bins( + const Particle& p, TallyEstimator estimator, FilterMatch& match) const { // Determine the normalized radius coordinate. double x = p.r().x - x_; double y = p.r().y - y_; - double r = std::sqrt(x*x + y*y) / r_; + double r = std::sqrt(x * x + y * y) / r_; if (r <= 1.0) { // Compute and return the Zernike weights. @@ -107,14 +101,12 @@ ZernikeRadialFilter::get_all_bins(const Particle& p, TallyEstimator estimator, } } -std::string -ZernikeRadialFilter::text_label(int bin) const +std::string ZernikeRadialFilter::text_label(int bin) const { - return "Zernike expansion, Z" + std::to_string(2*bin) + ",0"; + return "Zernike expansion, Z" + std::to_string(2 * bin) + ",0"; } -void -ZernikeRadialFilter::set_order(int order) +void ZernikeRadialFilter::set_order(int order) { ZernikeFilter::set_order(order); n_bins_ = order / 2 + 1; @@ -124,8 +116,7 @@ ZernikeRadialFilter::set_order(int order) // C-API functions //============================================================================== -std::pair -check_zernike_filter(int32_t index) +std::pair check_zernike_filter(int32_t index) { // Make sure this is a valid index to an allocated filter. int err = verify_filter(index); @@ -145,29 +136,29 @@ check_zernike_filter(int32_t index) return {err, filt}; } -extern "C" int -openmc_zernike_filter_get_order(int32_t index, int* order) +extern "C" int openmc_zernike_filter_get_order(int32_t index, int* order) { // Check the filter. auto check_result = check_zernike_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the order. *order = filt->order(); return 0; } -extern "C" int -openmc_zernike_filter_get_params(int32_t index, double* x, double* y, - double* r) +extern "C" int openmc_zernike_filter_get_params( + int32_t index, double* x, double* y, double* r) { // Check the filter. auto check_result = check_zernike_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Output the params. *x = filt->x(); @@ -176,34 +167,37 @@ openmc_zernike_filter_get_params(int32_t index, double* x, double* y, return 0; } -extern "C" int -openmc_zernike_filter_set_order(int32_t index, int order) +extern "C" int openmc_zernike_filter_set_order(int32_t index, int order) { // Check the filter. auto check_result = check_zernike_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. filt->set_order(order); return 0; } -extern "C" int -openmc_zernike_filter_set_params(int32_t index, const double* x, - const double* y, const double* r) +extern "C" int openmc_zernike_filter_set_params( + int32_t index, const double* x, const double* y, const double* r) { // Check the filter. auto check_result = check_zernike_filter(index); auto err = check_result.first; auto filt = check_result.second; - if (err) return err; + if (err) + return err; // Update the filter. - if (x) filt->set_x(*x); - if (y) filt->set_y(*y); - if (r) filt->set_r(*r); + if (x) + filt->set_x(*x); + if (y) + filt->set_y(*y); + if (r) + filt->set_r(*r); return 0; } diff --git a/src/tallies/tally.cpp b/src/tallies/tally.cpp index 153440c50..8e8e3126f 100644 --- a/src/tallies/tally.cpp +++ b/src/tallies/tally.cpp @@ -30,13 +30,13 @@ #include "openmc/tallies/filter_surface.h" #include "openmc/xml_interface.h" -#include #include "xtensor/xadapt.hpp" #include "xtensor/xbuilder.hpp" // for empty_like #include "xtensor/xview.hpp" +#include #include // for max -#include // for size_t +#include // for size_t #include namespace openmc { @@ -46,20 +46,20 @@ namespace openmc { //============================================================================== namespace model { - std::unordered_map tally_map; - vector> tallies; - vector active_tallies; - vector active_analog_tallies; - vector active_tracklength_tallies; - vector active_collision_tallies; - vector active_meshsurf_tallies; - vector active_surface_tallies; -} +std::unordered_map tally_map; +vector> tallies; +vector active_tallies; +vector active_analog_tallies; +vector active_tracklength_tallies; +vector active_collision_tallies; +vector active_meshsurf_tallies; +vector active_surface_tallies; +} // namespace model namespace simulation { - xt::xtensor_fixed> global_tallies; - int32_t n_realizations {0}; -} +xt::xtensor_fixed> global_tallies; +int32_t n_realizations {0}; +} // namespace simulation double global_tally_absorption; double global_tally_collision; @@ -83,19 +83,21 @@ Tally::Tally(pugi::xml_node node) // Copy and set tally id if (!check_for_node(node, "id")) { - throw std::runtime_error{"Must specify id for tally in tally XML file."}; + throw std::runtime_error {"Must specify id for tally in tally XML file."}; } int32_t id = std::stoi(get_node_value(node, "id")); this->set_id(id); - if (check_for_node(node, "name")) name_ = get_node_value(node, "name"); + if (check_for_node(node, "name")) + name_ = get_node_value(node, "name"); // ======================================================================= // READ DATA FOR FILTERS // Check if user is using old XML format and throw an error if so if (check_for_node(node, "filter")) { - throw std::runtime_error{"Tally filters must be specified independently of " + throw std::runtime_error { + "Tally filters must be specified independently of " "tallies in a element. The element itself should " "have a list of filters that apply, e.g., 1 2 " "where 1 and 2 are the IDs of filters specified outside of " @@ -114,7 +116,7 @@ Tally::Tally(pugi::xml_node node) // Determine if filter ID is valid auto it = model::filter_map.find(filter_id); if (it == model::filter_map.end()) { - throw std::runtime_error{fmt::format( + throw std::runtime_error {fmt::format( "Could not find filter {} specified on tally {}", filter_id, id_)}; } @@ -133,7 +135,8 @@ Tally::Tally(pugi::xml_node node) const auto& f = model::tally_filters[i_filter].get(); auto pf = dynamic_cast(f); - if (pf) particle_filter_index = i_filter; + if (pf) + particle_filter_index = i_filter; // Change the tally estimator if a filter demands it std::string filt_type = f->type(); @@ -144,8 +147,8 @@ Tally::Tally(pugi::xml_node node) if (sf->cosine() == SphericalHarmonicsCosine::scatter) { estimator_ = TallyEstimator::ANALOG; } - } else if (filt_type == "spatiallegendre" || filt_type == "zernike" - || filt_type == "zernikeradial") { + } else if (filt_type == "spatiallegendre" || filt_type == "zernike" || + filt_type == "zernikeradial") { estimator_ = TallyEstimator::COLLISION; } } @@ -171,7 +174,7 @@ Tally::Tally(pugi::xml_node node) switch (score) { case SCORE_INVERSE_VELOCITY: fatal_error("Particle filter must be used with photon " - "transport on and inverse velocity score"); + "transport on and inverse velocity score"); break; case SCORE_FLUX: case SCORE_TOTAL: @@ -186,7 +189,8 @@ Tally::Tally(pugi::xml_node node) case SCORE_PROMPT_NU_FISSION: case SCORE_DECAY_RATE: warning("Particle filter is not used with photon transport" - " on and " + reaction_name(score) + " score."); + " on and " + + reaction_name(score) + " score."); break; } } @@ -197,9 +201,11 @@ Tally::Tally(pugi::xml_node node) auto pf = dynamic_cast(f); for (auto p : pf->particles()) { if (p != ParticleType::neutron) { - warning(fmt::format("Particle filter other than NEUTRON used with " + warning(fmt::format( + "Particle filter other than NEUTRON used with " "photon transport turned off. All tallies for particle type {}" - " will have no scores", static_cast(p))); + " will have no scores", + static_cast(p))); } } } @@ -225,14 +231,16 @@ Tally::Tally(pugi::xml_node node) } const auto& deriv = model::tally_derivs[deriv_]; - if (deriv.variable == DerivativeVariable::NUCLIDE_DENSITY - || deriv.variable == DerivativeVariable::TEMPERATURE) { + if (deriv.variable == DerivativeVariable::NUCLIDE_DENSITY || + deriv.variable == DerivativeVariable::TEMPERATURE) { for (int i_nuc : nuclides_) { if (has_energyout && i_nuc == -1) { - fatal_error(fmt::format("Error on tally {}: Cannot use a " + fatal_error(fmt::format( + "Error on tally {}: Cannot use a " "'nuclide_density' or 'temperature' derivative on a tally with an " "outgoing energy filter and 'total' nuclide rate. Instead, tally " - "each nuclide in the material individually.", id_)); + "each nuclide in the material individually.", + id_)); // Note that diff tallies with these characteristics would work // correctly if no tally events occur in the perturbed material // (e.g. pertrubing moderator but only tallying fuel), but this @@ -255,13 +263,15 @@ Tally::Tally(pugi::xml_node node) std::string est = get_node_value(node, "estimator"); if (est == "analog") { estimator_ = TallyEstimator::ANALOG; - } else if (est == "tracklength" || est == "track-length" - || est == "pathlength" || est == "path-length") { + } else if (est == "tracklength" || est == "track-length" || + est == "pathlength" || est == "path-length") { // If the estimator was set to an analog estimator, this means the // tally needs post-collision information - if (estimator_ == TallyEstimator::ANALOG || estimator_ == TallyEstimator::COLLISION) { - throw std::runtime_error{fmt::format("Cannot use track-length " - "estimator for tally {}", id_)}; + if (estimator_ == TallyEstimator::ANALOG || + estimator_ == TallyEstimator::COLLISION) { + throw std::runtime_error {fmt::format("Cannot use track-length " + "estimator for tally {}", + id_)}; } // Set estimator to track-length estimator @@ -271,16 +281,17 @@ Tally::Tally(pugi::xml_node node) // If the estimator was set to an analog estimator, this means the // tally needs post-collision information if (estimator_ == TallyEstimator::ANALOG) { - throw std::runtime_error{fmt::format("Cannot use collision estimator " - "for tally ", id_)}; + throw std::runtime_error {fmt::format("Cannot use collision estimator " + "for tally ", + id_)}; } // Set estimator to collision estimator estimator_ = TallyEstimator::COLLISION; } else { - throw std::runtime_error{fmt::format( - "Invalid estimator '{}' on tally {}", est, id_)}; + throw std::runtime_error { + fmt::format("Invalid estimator '{}' on tally {}", est, id_)}; } } @@ -297,7 +308,6 @@ Tally::Tally(pugi::xml_node node) } } #endif - } Tally::~Tally() @@ -305,15 +315,13 @@ Tally::~Tally() model::tally_map.erase(id_); } -Tally* -Tally::create(int32_t id) +Tally* Tally::create(int32_t id) { model::tallies.push_back(make_unique(id)); return model::tallies.back().get(); } -void -Tally::set_id(int32_t id) +void Tally::set_id(int32_t id) { Expects(id >= 0 || id == C_NONE); @@ -325,7 +333,8 @@ Tally::set_id(int32_t id) // Make sure no other tally has the same ID if (model::tally_map.find(id) != model::tally_map.end()) { - throw std::runtime_error{fmt::format("Two tallies have the same ID: {}", id)}; + throw std::runtime_error { + fmt::format("Two tallies have the same ID: {}", id)}; } // If no ID specified, auto-assign next ID in sequence @@ -342,8 +351,7 @@ Tally::set_id(int32_t id) model::tally_map[id] = index_; } -void -Tally::set_filters(gsl::span filters) +void Tally::set_filters(gsl::span filters) { // Clear old data. filters_.clear(); @@ -368,11 +376,9 @@ Tally::set_filters(gsl::span filters) // Set the strides. set_strides(); - } -void -Tally::set_strides() +void Tally::set_strides() { // Set the strides. Filters are traversed in reverse so that the last filter // has the shortest stride in memory and the first filter has the longest @@ -380,15 +386,14 @@ Tally::set_strides() auto n = filters_.size(); strides_.resize(n, 0); int stride = 1; - for (int i = n-1; i >= 0; --i) { + for (int i = n - 1; i >= 0; --i) { strides_[i] = stride; stride *= model::tally_filters[filters_[i]]->n_bins(); } n_filter_bins_ = stride; } -void -Tally::set_scores(pugi::xml_node node) +void Tally::set_scores(pugi::xml_node node) { if (!check_for_node(node, "scores")) fatal_error(fmt::format("No scores specified on tally {}", id_)); @@ -449,8 +454,9 @@ void Tally::set_scores(const vector& scores) case SCORE_ABSORPTION: case SCORE_FISSION: if (energyout_present) - fatal_error("Cannot tally " + score_str + " reaction rate with an " - "outgoing energy filter"); + fatal_error("Cannot tally " + score_str + + " reaction rate with an " + "outgoing energy filter"); break; case SCORE_SCATTER: @@ -477,7 +483,7 @@ void Tally::set_scores(const vector& scores) if (surface_present || cell_present || cellfrom_present) { if (meshsurface_present) fatal_error("Cannot tally mesh surface currents in the same tally as " - "normal surface currents"); + "normal surface currents"); type_ = TallyType::SURFACE; } else if (meshsurface_present) { type_ = TallyType::MESH_SURFACE; @@ -487,7 +493,8 @@ void Tally::set_scores(const vector& scores) break; case HEATING: - if (settings::photon_transport) estimator_ = TallyEstimator::COLLISION; + if (settings::photon_transport) + estimator_ = TallyEstimator::COLLISION; break; } @@ -498,9 +505,9 @@ void Tally::set_scores(const vector& scores) for (auto it1 = scores_.begin(); it1 != scores_.end(); ++it1) { for (auto it2 = it1 + 1; it2 != scores_.end(); ++it2) { if (*it1 == *it2) - fatal_error(fmt::format( - "Duplicate score of type \"{}\" found in tally {}", - reaction_name(*it1), id_)); + fatal_error( + fmt::format("Duplicate score of type \"{}\" found in tally {}", + reaction_name(*it1), id_)); } } @@ -508,23 +515,23 @@ void Tally::set_scores(const vector& scores) if (!settings::run_CE) { for (auto sc : scores_) if (sc > 0) - fatal_error("Cannot tally " + reaction_name(sc) + " reaction rate " - "in multi-group mode"); + fatal_error("Cannot tally " + reaction_name(sc) + + " reaction rate " + "in multi-group mode"); } // Make sure current scores are not mixed in with volumetric scores. if (type_ == TallyType::SURFACE || type_ == TallyType::MESH_SURFACE) { if (scores_.size() != 1) fatal_error("Cannot tally other scores in the same tally as surface " - "currents."); + "currents."); } if ((surface_present || meshsurface_present) && scores_[0] != SCORE_CURRENT) fatal_error("Cannot tally score other than 'current' when using a surface " - "or mesh-surface filter."); + "or mesh-surface filter."); } -void -Tally::set_nuclides(pugi::xml_node node) +void Tally::set_nuclides(pugi::xml_node node) { nuclides_.clear(); @@ -563,16 +570,16 @@ void Tally::set_nuclides(const vector& nuclides) auto search = data::nuclide_map.find(nuc); if (search == data::nuclide_map.end()) fatal_error(fmt::format("Could not find the nuclide {} specified in " - "tally {} in any material", nuc, id_)); + "tally {} in any material", + nuc, id_)); nuclides_.push_back(search->second); } } } -void -Tally::init_triggers(pugi::xml_node node) +void Tally::init_triggers(pugi::xml_node node) { - for (auto trigger_node: node.children("trigger")) { + for (auto trigger_node : node.children("trigger")) { // Read the trigger type. TriggerMetric metric; if (check_for_node(trigger_node, "type")) { @@ -584,8 +591,8 @@ Tally::init_triggers(pugi::xml_node node) } else if (type_str == "rel_err") { metric = TriggerMetric::relative_error; } else { - fatal_error(fmt::format("Unknown trigger type \"{}\" in tally {}", - type_str, id_)); + fatal_error(fmt::format( + "Unknown trigger type \"{}\" in tally {}", type_str, id_)); } } else { fatal_error(fmt::format( @@ -622,11 +629,14 @@ Tally::init_triggers(pugi::xml_node node) } else { int i_score = 0; for (; i_score < this->scores_.size(); ++i_score) { - if (reaction_name(this->scores_[i_score]) == score_str) break; + if (reaction_name(this->scores_[i_score]) == score_str) + break; } if (i_score == this->scores_.size()) { - fatal_error(fmt::format("Could not find the score \"{}\" in tally " - "{} but it was listed in a trigger on that tally", score_str, id_)); + fatal_error( + fmt::format("Could not find the score \"{}\" in tally " + "{} but it was listed in a trigger on that tally", + score_str, id_)); } triggers_.push_back({metric, threshold, i_score}); } @@ -665,37 +675,40 @@ void Tally::accumulate() } // Account for number of source particles in normalization - double norm = total_source / (settings::n_particles * settings::gen_per_batch); + double norm = + total_source / (settings::n_particles * settings::gen_per_batch); - // Accumulate each result - #pragma omp parallel for +// Accumulate each result +#pragma omp parallel for for (int i = 0; i < results_.shape()[0]; ++i) { for (int j = 0; j < results_.shape()[1]; ++j) { double val = results_(i, j, TallyResult::VALUE) * norm; results_(i, j, TallyResult::VALUE) = 0.0; results_(i, j, TallyResult::SUM) += val; - results_(i, j, TallyResult::SUM_SQ) += val*val; + results_(i, j, TallyResult::SUM_SQ) += val * val; } } } } -std::string -Tally::score_name(int score_idx) const { +std::string Tally::score_name(int score_idx) const +{ if (score_idx < 0 || score_idx >= scores_.size()) { fatal_error("Index in scores array is out of bounds."); } return reaction_name(scores_[score_idx]); } -std::string -Tally::nuclide_name(int nuclide_idx) const { +std::string Tally::nuclide_name(int nuclide_idx) const +{ if (nuclide_idx < 0 || nuclide_idx >= nuclides_.size()) { fatal_error("Index in nuclides array is out of bounds"); } int nuclide = nuclides_.at(nuclide_idx); - if (nuclide == -1) { return "total"; } + if (nuclide == -1) { + return "total"; + } return data::nuclides.at(nuclide)->name_; } @@ -707,7 +720,8 @@ void read_tallies_xml() { // Check if tallies.xml exists. If not, just return since it is optional std::string filename = settings::path_input + "tallies.xml"; - if (!file_exists(filename)) return; + if (!file_exists(filename)) + return; write_message("Reading tallies XML file...", 5); @@ -725,7 +739,8 @@ void read_tallies_xml() read_meshes(root); // We only need the mesh info for plotting - if (settings::run_mode == RunMode::PLOTTING) return; + if (settings::run_mode == RunMode::PLOTTING) + return; // Read data for tally derivatives read_tally_derivatives(root); @@ -743,7 +758,8 @@ void read_tallies_xml() // Check for user tallies int n = 0; - for (auto node : root.children("tally")) ++n; + for (auto node : root.children("tally")) + ++n; if (n == 0 && mpi::master) { warning("No tallies present in tallies.xml file."); } @@ -763,7 +779,8 @@ void reduce_tally_results() auto& tally {model::tallies[i_tally]}; // Get view of accumulated tally values - auto values_view = xt::view(tally->results_, xt::all(), xt::all(), static_cast(TallyResult::VALUE)); + auto values_view = xt::view(tally->results_, xt::all(), xt::all(), + static_cast(TallyResult::VALUE)); // Make copy of tally values in contiguous array xt::xtensor values = values_view; @@ -787,7 +804,8 @@ void reduce_tally_results() // Get view of global tally values auto& gt = simulation::global_tallies; - auto gt_values_view = xt::view(gt, xt::all(), static_cast(TallyResult::VALUE)); + auto gt_values_view = + xt::view(gt, xt::all(), static_cast(TallyResult::VALUE)); // Make copy of values in contiguous array xt::xtensor gt_values = gt_values_view; @@ -809,16 +827,17 @@ void reduce_tally_results() double weight_reduced; MPI_Reduce(&simulation::total_weight, &weight_reduced, 1, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm); - if (mpi::master) simulation::total_weight = weight_reduced; + if (mpi::master) + simulation::total_weight = weight_reduced; } #endif -void -accumulate_tallies() +void accumulate_tallies() { #ifdef OPENMC_MPI // Combine tally results onto master process - if (mpi::n_procs > 1) reduce_tally_results(); + if (mpi::n_procs > 1) + reduce_tally_results(); #endif // Increase number of realizations (only used for global tallies) @@ -831,9 +850,12 @@ accumulate_tallies() if (settings::run_mode == RunMode::EIGENVALUE) { if (simulation::current_batch > settings::n_inactive) { // Accumulate products of different estimators of k - double k_col = gt(GlobalTally::K_COLLISION, TallyResult::VALUE) / simulation::total_weight; - double k_abs = gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) / simulation::total_weight; - double k_tra = gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) / simulation::total_weight; + double k_col = gt(GlobalTally::K_COLLISION, TallyResult::VALUE) / + simulation::total_weight; + double k_abs = gt(GlobalTally::K_ABSORPTION, TallyResult::VALUE) / + simulation::total_weight; + double k_tra = gt(GlobalTally::K_TRACKLENGTH, TallyResult::VALUE) / + simulation::total_weight; simulation::k_col_abs += k_col * k_abs; simulation::k_col_tra += k_col * k_tra; simulation::k_abs_tra += k_abs * k_tra; @@ -842,10 +864,10 @@ accumulate_tallies() // Accumulate results for global tallies for (int i = 0; i < N_GLOBAL_TALLIES; ++i) { - double val = gt(i, TallyResult::VALUE)/simulation::total_weight; + double val = gt(i, TallyResult::VALUE) / simulation::total_weight; gt(i, TallyResult::VALUE) = 0.0; gt(i, TallyResult::SUM) += val; - gt(i, TallyResult::SUM_SQ) += val*val; + gt(i, TallyResult::SUM_SQ) += val * val; } } @@ -856,8 +878,7 @@ accumulate_tallies() } } -void -setup_active_tallies() +void setup_active_tallies() { model::active_tallies.clear(); model::active_analog_tallies.clear(); @@ -875,14 +896,14 @@ setup_active_tallies() case TallyType::VOLUME: switch (tally.estimator_) { - case TallyEstimator::ANALOG: - model::active_analog_tallies.push_back(i); - break; - case TallyEstimator::TRACKLENGTH: - model::active_tracklength_tallies.push_back(i); - break; - case TallyEstimator::COLLISION: - model::active_collision_tallies.push_back(i); + case TallyEstimator::ANALOG: + model::active_analog_tallies.push_back(i); + break; + case TallyEstimator::TRACKLENGTH: + model::active_tracklength_tallies.push_back(i); + break; + case TallyEstimator::COLLISION: + model::active_collision_tallies.push_back(i); } break; @@ -897,8 +918,7 @@ setup_active_tallies() } } -void -free_memory_tally() +void free_memory_tally() { model::tally_derivs.clear(); model::tally_deriv_map.clear(); @@ -922,19 +942,20 @@ free_memory_tally() // C-API functions //============================================================================== -extern "C" int -openmc_extend_tallies(int32_t n, int32_t* index_start, int32_t* index_end) +extern "C" int openmc_extend_tallies( + int32_t n, int32_t* index_start, int32_t* index_end) { - if (index_start) *index_start = model::tallies.size(); - if (index_end) *index_end = model::tallies.size() + n - 1; + if (index_start) + *index_start = model::tallies.size(); + if (index_end) + *index_end = model::tallies.size() + n - 1; for (int i = 0; i < n; ++i) { model::tallies.push_back(make_unique(-1)); } return 0; } -extern "C" int -openmc_get_tally_index(int32_t id, int32_t* index) +extern "C" int openmc_get_tally_index(int32_t id, int32_t* index) { auto it = model::tally_map.find(id); if (it == model::tally_map.end()) { @@ -946,8 +967,7 @@ openmc_get_tally_index(int32_t id, int32_t* index) return 0; } -extern "C" void -openmc_get_tally_next_id(int32_t* id) +extern "C" void openmc_get_tally_next_id(int32_t* id) { int32_t largest_tally_id = 0; for (const auto& t : model::tallies) { @@ -956,8 +976,7 @@ openmc_get_tally_next_id(int32_t* id) *id = largest_tally_id + 1; } -extern "C" int -openmc_tally_get_estimator(int32_t index, int* estimator) +extern "C" int openmc_tally_get_estimator(int32_t index, int* estimator) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -968,8 +987,7 @@ openmc_tally_get_estimator(int32_t index, int* estimator) return 0; } -extern "C" int -openmc_tally_set_estimator(int32_t index, const char* estimator) +extern "C" int openmc_tally_set_estimator(int32_t index, const char* estimator) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -992,8 +1010,7 @@ openmc_tally_set_estimator(int32_t index, const char* estimator) return 0; } -extern "C" int -openmc_tally_get_id(int32_t index, int32_t* id) +extern "C" int openmc_tally_get_id(int32_t index, int32_t* id) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1004,8 +1021,7 @@ openmc_tally_get_id(int32_t index, int32_t* id) return 0; } -extern "C" int -openmc_tally_set_id(int32_t index, int32_t id) +extern "C" int openmc_tally_set_id(int32_t index, int32_t id) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1016,8 +1032,7 @@ openmc_tally_set_id(int32_t index, int32_t id) return 0; } -extern "C" int -openmc_tally_get_type(int32_t index, int32_t* type) +extern "C" int openmc_tally_get_type(int32_t index, int32_t* type) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1028,8 +1043,7 @@ openmc_tally_get_type(int32_t index, int32_t* type) return 0; } -extern "C" int -openmc_tally_set_type(int32_t index, const char* type) +extern "C" int openmc_tally_set_type(int32_t index, const char* type) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1049,8 +1063,7 @@ openmc_tally_set_type(int32_t index, const char* type) return 0; } -extern "C" int -openmc_tally_get_active(int32_t index, bool* active) +extern "C" int openmc_tally_get_active(int32_t index, bool* active) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1061,8 +1074,7 @@ openmc_tally_get_active(int32_t index, bool* active) return 0; } -extern "C" int -openmc_tally_set_active(int32_t index, bool active) +extern "C" int openmc_tally_set_active(int32_t index, bool active) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1073,8 +1085,7 @@ openmc_tally_set_active(int32_t index, bool active) return 0; } -extern "C" int -openmc_tally_get_writable(int32_t index, bool* writable) +extern "C" int openmc_tally_get_writable(int32_t index, bool* writable) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1085,8 +1096,7 @@ openmc_tally_get_writable(int32_t index, bool* writable) return 0; } -extern "C" int -openmc_tally_set_writable(int32_t index, bool writable) +extern "C" int openmc_tally_set_writable(int32_t index, bool writable) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1097,8 +1107,7 @@ openmc_tally_set_writable(int32_t index, bool writable) return 0; } -extern "C" int -openmc_tally_get_scores(int32_t index, int** scores, int* n) +extern "C" int openmc_tally_get_scores(int32_t index, int** scores, int* n) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1110,8 +1119,8 @@ openmc_tally_get_scores(int32_t index, int** scores, int* n) return 0; } -extern "C" int -openmc_tally_set_scores(int32_t index, int n, const char** scores) +extern "C" int openmc_tally_set_scores( + int32_t index, int n, const char** scores) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1129,8 +1138,7 @@ openmc_tally_set_scores(int32_t index, int n, const char** scores) return 0; } -extern "C" int -openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n) +extern "C" int openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1144,8 +1152,8 @@ openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n) return 0; } -extern "C" int -openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides) +extern "C" int openmc_tally_set_nuclides( + int32_t index, int n, const char** nuclides) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1155,13 +1163,13 @@ openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides) vector words(nuclides, nuclides + n); vector nucs; - for (auto word : words){ + for (auto word : words) { if (word == "total") { nucs.push_back(-1); } else { auto search = data::nuclide_map.find(word); if (search == data::nuclide_map.end()) { - set_errmsg("Nuclide \"" + word + "\" has not been loaded yet"); + set_errmsg("Nuclide \"" + word + "\" has not been loaded yet"); return OPENMC_E_DATA; } nucs.push_back(search->second); @@ -1173,8 +1181,8 @@ openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides) return 0; } -extern "C" int -openmc_tally_get_filters(int32_t index, const int32_t** indices, size_t* n) +extern "C" int openmc_tally_get_filters( + int32_t index, const int32_t** indices, size_t* n) { if (index < 0 || index >= model::tallies.size()) { set_errmsg("Index in tallies array is out of bounds."); @@ -1186,8 +1194,8 @@ openmc_tally_get_filters(int32_t index, const int32_t** indices, size_t* n) return 0; } -extern "C" int -openmc_tally_set_filters(int32_t index, size_t n, const int32_t* indices) +extern "C" int openmc_tally_set_filters( + int32_t index, size_t n, const int32_t* indices) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1213,8 +1221,7 @@ openmc_tally_set_filters(int32_t index, size_t n, const int32_t* indices) } //! Reset tally results and number of realizations -extern "C" int -openmc_tally_reset(int32_t index) +extern "C" int openmc_tally_reset(int32_t index) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1226,8 +1233,7 @@ openmc_tally_reset(int32_t index) return 0; } -extern "C" int -openmc_tally_get_n_realizations(int32_t index, int32_t* n) +extern "C" int openmc_tally_get_n_realizations(int32_t index, int32_t* n) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1241,8 +1247,8 @@ openmc_tally_get_n_realizations(int32_t index, int32_t* n) //! \brief Returns a pointer to a tally results array along with its shape. This //! allows a user to obtain in-memory tally results from Python directly. -extern "C" int -openmc_tally_results(int32_t index, double** results, size_t* shape) +extern "C" int openmc_tally_results( + int32_t index, double** results, size_t* shape) { // Make sure the index fits in the array bounds. if (index < 0 || index >= model::tallies.size()) { @@ -1265,13 +1271,15 @@ openmc_tally_results(int32_t index, double** results, size_t* shape) return 0; } -extern "C" int -openmc_global_tallies(double** ptr) +extern "C" int openmc_global_tallies(double** ptr) { *ptr = simulation::global_tallies.data(); return 0; } -extern "C" size_t tallies_size() { return model::tallies.size(); } +extern "C" size_t tallies_size() +{ + return model::tallies.size(); +} } // namespace openmc diff --git a/src/tallies/tally_scoring.cpp b/src/tallies/tally_scoring.cpp index 5242db2e3..a0fc79b5b 100644 --- a/src/tallies/tally_scoring.cpp +++ b/src/tallies/tally_scoring.cpp @@ -89,17 +89,16 @@ FilterBinIter::FilterBinIter( this->compute_index_weight(); } -FilterBinIter& -FilterBinIter::operator++() +FilterBinIter& FilterBinIter::operator++() { // Find the next valid combination of filter bins. To do this, we search // backwards through the filters until we find the first filter whose bins // can be incremented. bool visited_all_combinations = true; - for (int i = tally_.filters().size()-1; i >= 0; --i) { + for (int i = tally_.filters().size() - 1; i >= 0; --i) { auto i_filt = tally_.filters(i); auto& match {filter_matches_[i_filt]}; - if (match.i_bin_ < match.bins_.size()-1) { + if (match.i_bin_ < match.bins_.size() - 1) { // The bin for this filter can be incremented. Increment it and do not // touch any of the remaining filters. ++match.i_bin_; @@ -124,8 +123,7 @@ FilterBinIter::operator++() return *this; } -void -FilterBinIter::compute_index_weight() +void FilterBinIter::compute_index_weight() { index_ = 0; weight_ = 1.; @@ -166,9 +164,10 @@ void score_fission_delayed_dg(int i_tally, int d_bin, double score, filter_weight *= match.weights_[i_bin]; } - // Update the tally result - #pragma omp atomic - tally.results_(filter_index, score_index, TallyResult::VALUE) += score*filter_weight; +// Update the tally result +#pragma omp atomic + tally.results_(filter_index, score_index, TallyResult::VALUE) += + score * filter_weight; // Reset the original delayed group bin dg_match.bins_[i_bin] = original_bin; @@ -245,24 +244,27 @@ double score_fission_q(const Particle& p, int score_bin, const Tally& tally, //! Helper function to obtain the kerma coefficient for a given nuclide -double get_nuclide_neutron_heating(const Particle& p, const Nuclide& nuc, - int rxn_index, int i_nuclide) +double get_nuclide_neutron_heating( + const Particle& p, const Nuclide& nuc, int rxn_index, int i_nuclide) { size_t mt = nuc.reaction_index_[rxn_index]; - if (mt == C_NONE) return 0.0; + if (mt == C_NONE) + return 0.0; auto i_temp = p.neutron_xs(i_nuclide).index_temp; - if (i_temp < 0) return 0.0; // Can be true due to multipole + if (i_temp < 0) + return 0.0; // Can be true due to multipole const auto& rxn {*nuc.reactions_[mt]}; const auto& xs {rxn.xs_[i_temp]}; auto i_grid = p.neutron_xs(i_nuclide).index_grid; - if (i_grid < xs.threshold) return 0.0; + if (i_grid < xs.threshold) + return 0.0; // Determine total kerma auto f = p.neutron_xs(i_nuclide).interp_factor; - double kerma = (1.0 - f) * xs.value[i_grid-xs.threshold] - + f * xs.value[i_grid-xs.threshold+1]; + double kerma = (1.0 - f) * xs.value[i_grid - xs.threshold] + + f * xs.value[i_grid - xs.threshold + 1]; if (settings::run_mode == RunMode::EIGENVALUE) { // Determine kerma for fission as (EFR + EB)*sigma_f @@ -287,7 +289,7 @@ double get_nuclide_neutron_heating(const Particle& p, const Nuclide& nuc, //! Helper function to obtain neutron heating [eV] double score_neutron_heating(const Particle& p, const Tally& tally, double flux, - int rxn_bin, int i_nuclide, double atom_density) + int rxn_bin, int i_nuclide, double atom_density) { double score; // Get heating macroscopic "cross section" @@ -304,11 +306,12 @@ double score_neutron_heating(const Particle& p, const Tally& tally, double flux, if (p.material() != MATERIAL_VOID) { heating_xs = 0.0; const Material& material {*model::materials[p.material()]}; - for (auto i = 0; i< material.nuclide_.size(); ++i) { + for (auto i = 0; i < material.nuclide_.size(); ++i) { int j_nuclide = material.nuclide_[i]; double atom_density {material.atom_density_(i)}; const Nuclide& nuc {*data::nuclides[j_nuclide]}; - heating_xs += atom_density * get_nuclide_neutron_heating(p, nuc, rxn_bin, j_nuclide); + heating_xs += atom_density * + get_nuclide_neutron_heating(p, nuc, rxn_bin, j_nuclide); } if (tally.estimator_ == TallyEstimator::ANALOG) { heating_xs /= p.macro_xs().total; @@ -335,16 +338,15 @@ double score_neutron_heating(const Particle& p, const Tally& tally, double flux, //! In this case, we may need to score to multiple bins if there were multiple //! neutrons produced with different energies. -void -score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) +void score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) { auto& tally {*model::tallies[i_tally]}; auto i_eout_filt = tally.filters()[tally.energyout_filter_]; auto i_bin = p.filter_matches(i_eout_filt).i_bin_; auto bin_energyout = p.filter_matches(i_eout_filt).bins_[i_bin]; - const EnergyoutFilter& eo_filt - {*dynamic_cast(model::tally_filters[i_eout_filt].get())}; + const EnergyoutFilter& eo_filt { + *dynamic_cast(model::tally_filters[i_eout_filt].get())}; // Note that the score below is weighted by keff. Since the creation of // fission sites is weighted such that it is expected to create n_particles @@ -392,16 +394,15 @@ score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) if (E_out < eo_filt.bins().front() || E_out > eo_filt.bins().back()) { continue; } else { - auto i_match = lower_bound_index(eo_filt.bins().begin(), - eo_filt.bins().end(), E_out); + auto i_match = lower_bound_index( + eo_filt.bins().begin(), eo_filt.bins().end(), E_out); p.filter_matches(i_eout_filt).bins_[i_bin] = i_match; } - } // Case for tallying prompt neutrons - if (score_bin == SCORE_NU_FISSION - || (score_bin == SCORE_PROMPT_NU_FISSION && g == 0)) { + if (score_bin == SCORE_NU_FISSION || + (score_bin == SCORE_PROMPT_NU_FISSION && g == 0)) { // Find the filter scoring index for this filter combination int filter_index = 0; @@ -414,9 +415,10 @@ score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) filter_weight *= match.weights_[i_bin]; } - // Update tally results - #pragma omp atomic - tally.results_(filter_index, i_score, TallyResult::VALUE) += score*filter_weight; +// Update tally results +#pragma omp atomic + tally.results_(filter_index, i_score, TallyResult::VALUE) += + score * filter_weight; } else if (score_bin == SCORE_DELAYED_NU_FISSION && g != 0) { @@ -447,7 +449,7 @@ score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) } } - // If the delayed group filter is not present, add score to tally + // If the delayed group filter is not present, add score to tally } else { // Find the filter index and weight for this filter combination @@ -461,9 +463,10 @@ score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) filter_weight *= match.weights_[i_bin]; } - // Update tally results - #pragma omp atomic - tally.results_(filter_index, i_score, TallyResult::VALUE) += score*filter_weight; +// Update tally results +#pragma omp atomic + tally.results_(filter_index, i_score, TallyResult::VALUE) += + score * filter_weight; } } } @@ -472,12 +475,14 @@ score_fission_eout(Particle& p, int i_tally, int i_score, int score_bin) p.filter_matches(i_eout_filt).bins_[i_bin] = bin_energyout; } -double get_nuclide_xs(const Particle& p, int i_nuclide, int score_bin) { +double get_nuclide_xs(const Particle& p, int i_nuclide, int score_bin) +{ const auto& nuc {*data::nuclides[i_nuclide]}; // Get reaction object, or return 0 if reaction is not present auto m = nuc.reaction_index_[score_bin]; - if (m == C_NONE) return 0.0; + if (m == C_NONE) + return 0.0; const auto& rxn {*nuc.reactions_[m]}; const auto& micro {p.neutron_xs(i_nuclide)}; @@ -498,13 +503,14 @@ double get_nuclide_xs(const Particle& p, int i_nuclide, int score_bin) { const auto& xs {rxn.xs_[i_temp]}; double value; if (i_grid >= xs.threshold) { - value = ((1.0 - f) * xs.value[i_grid-xs.threshold] - + f * xs.value[i_grid-xs.threshold+1]); + value = ((1.0 - f) * xs.value[i_grid - xs.threshold] + + f * xs.value[i_grid - xs.threshold + 1]); } else { value = 0.0; } - if (settings::run_mode == RunMode::EIGENVALUE && score_bin == HEATING_LOCAL) { + if (settings::run_mode == RunMode::EIGENVALUE && + score_bin == HEATING_LOCAL) { // Determine kerma for fission as (EFR + EGP + EGD + EB)*sigma_f double kerma_fission = nuc.fragments_ @@ -518,8 +524,8 @@ double get_nuclide_xs(const Particle& p, int i_nuclide, int score_bin) { double kerma_non_fission = value - kerma_fission; // Re-weight non-fission kerma by keff to properly balance energy release - // and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H. Stedry, - // "Self-consistent energy normalization for quasistatic reactor + // and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H. + // Stedry, "Self-consistent energy normalization for quasistatic reactor // calculations", Proc. PHYSOR, Cambridge, UK, Mar 29-Apr 2, 2020. value = simulation::keff * kerma_non_fission + kerma_fission; } @@ -537,9 +543,9 @@ double get_nuclide_xs(const Particle& p, int i_nuclide, int score_bin) { //! argument is really just used for filter weights. The atom_density argument //! is not used for analog tallies. -void -score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, - double filter_weight, int i_nuclide, double atom_density, double flux) +void score_general_ce(Particle& p, int i_tally, int start_index, + int filter_index, double filter_weight, int i_nuclide, double atom_density, + double flux) { Tally& tally {*model::tallies[i_tally]}; @@ -577,7 +583,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_TOTAL: if (tally.estimator_ == TallyEstimator::ANALOG) { // All events will score to the total reaction rate. We can just use @@ -603,7 +608,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_INVERSE_VELOCITY: if (p.type() != Type::neutron) continue; @@ -627,7 +631,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, score /= std::sqrt(2. * E / MASS_NEUTRON_EV) * C_LIGHT * 100.; break; - case SCORE_SCATTER: if (p.type() != Type::neutron && p.type() != Type::photon) continue; @@ -658,7 +661,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_NU_SCATTER: if (p.type() != Type::neutron) continue; @@ -684,7 +686,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_ABSORPTION: if (p.type() != Type::neutron && p.type() != Type::photon) continue; @@ -708,7 +709,8 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, score = p.neutron_xs(i_nuclide).absorption * atom_density * flux; } else { const auto& xs = p.photon_xs(i_nuclide); - score = (xs.total - xs.coherent - xs.incoherent) * atom_density * flux; + score = + (xs.total - xs.coherent - xs.incoherent) * atom_density * flux; } } else { if (p.type() == Type::neutron) { @@ -722,7 +724,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_FISSION: if (p.macro_xs().absorption == 0) continue; @@ -756,7 +757,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_NU_FISSION: if (p.macro_xs().absorption == 0) continue; @@ -800,7 +800,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_PROMPT_NU_FISSION: if (p.macro_xs().absorption == 0) continue; @@ -863,7 +862,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_DELAYED_NU_FISSION: if (p.macro_xs().absorption == 0) continue; @@ -884,9 +882,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, data::nuclides[p.event_nuclide()]->fissionable_) { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto dg = filt.groups()[d_bin]; @@ -922,8 +920,7 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // contribution to the fission bank to the score. if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { @@ -946,14 +943,13 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, if (i_nuclide >= 0) { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; - auto yield = data::nuclides[i_nuclide] - ->nu(E, ReactionProduct::EmissionMode::delayed, d); + auto yield = data::nuclides[i_nuclide]->nu( + E, ReactionProduct::EmissionMode::delayed, d); score = p.neutron_xs(i_nuclide).fission * yield * atom_density * flux; score_fission_delayed_dg( @@ -972,8 +968,7 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // Need to add up contributions for each nuclide if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; if (p.material() != MATERIAL_VOID) { const Material& material {*model::materials[p.material()]}; @@ -983,8 +978,8 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; - auto yield = data::nuclides[j_nuclide] - ->nu(E, ReactionProduct::EmissionMode::delayed, d); + auto yield = data::nuclides[j_nuclide]->nu( + E, ReactionProduct::EmissionMode::delayed, d); score = p.neutron_xs(j_nuclide).fission * yield * atom_density * flux; score_fission_delayed_dg( @@ -1011,7 +1006,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_DECAY_RATE: if (p.macro_xs().absorption == 0) continue; @@ -1026,14 +1020,14 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, const auto& rxn {*nuc.fission_rx_[0]}; if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); + auto yield = + nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); auto rate = rxn.products_[d].decay_rate_; score = p.wgt_absorb() * yield * p.neutron_xs(p.event_nuclide()).fission / @@ -1055,9 +1049,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // of this array and not the MAX_DELAYED_GROUPS constant for // this loop. for (auto d = 0; d < rxn.products_.size() - 2; ++d) { - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d+1); - auto rate = rxn.products_[d+1].decay_rate_; + auto yield = + nuc.nu(E, ReactionProduct::EmissionMode::delayed, d + 1); + auto rate = rxn.products_[d + 1].decay_rate_; score += rate * p.wgt_absorb() * p.neutron_xs(p.event_nuclide()).fission * yield / p.neutron_xs(p.event_nuclide()).absorption * flux; @@ -1086,9 +1080,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, score += simulation::keff * bank.wgt * rate * flux; if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Find the corresponding filter bin and then score for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; @@ -1104,18 +1098,17 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } else { if (i_nuclide >= 0) { const auto& nuc {*data::nuclides[i_nuclide]}; - if (!nuc.fissionable_) continue; + if (!nuc.fissionable_) + continue; const auto& rxn {*nuc.fission_rx_[0]}; if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); + auto yield = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); auto rate = rxn.products_[d].decay_rate_; score = p.neutron_xs(i_nuclide).fission * yield * flux * atom_density * rate; @@ -1131,9 +1124,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // of this array and not the MAX_DELAYED_GROUPS constant for // this loop. for (auto d = 0; d < rxn.products_.size() - 2; ++d) { - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d+1); - auto rate = rxn.products_[d+1].decay_rate_; + auto yield = + nuc.nu(E, ReactionProduct::EmissionMode::delayed, d + 1); + auto rate = rxn.products_[d + 1].decay_rate_; score += p.neutron_xs(i_nuclide).fission * flux * yield * atom_density * rate; } @@ -1141,8 +1134,7 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } else { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; if (p.material() != MATERIAL_VOID) { const Material& material {*model::materials[p.material()]}; @@ -1155,8 +1147,8 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin]; - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); + auto yield = + nuc.nu(E, ReactionProduct::EmissionMode::delayed, d); auto rate = rxn.products_[d].decay_rate_; score = p.neutron_xs(j_nuclide).fission * yield * flux * atom_density * rate; @@ -1183,9 +1175,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // of this array and not the MAX_DELAYED_GROUPS constant for // this loop. for (auto d = 0; d < rxn.products_.size() - 2; ++d) { - auto yield - = nuc.nu(E, ReactionProduct::EmissionMode::delayed, d+1); - auto rate = rxn.products_[d+1].decay_rate_; + auto yield = + nuc.nu(E, ReactionProduct::EmissionMode::delayed, d + 1); + auto rate = rxn.products_[d + 1].decay_rate_; score += p.neutron_xs(j_nuclide).fission * yield * atom_density * flux * rate; } @@ -1197,7 +1189,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_KAPPA_FISSION: if (p.macro_xs().absorption == 0.) continue; @@ -1257,14 +1248,12 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_EVENTS: - // Simply count the number of scoring events - #pragma omp atomic +// Simply count the number of scoring events +#pragma omp atomic tally.results_(filter_index, score_index, TallyResult::VALUE) += 1.0; continue; - case ELASTIC: if (p.type() != Type::neutron) continue; @@ -1299,10 +1288,10 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, case SCORE_FISS_Q_RECOV: if (p.macro_xs().absorption == 0.) continue; - score = score_fission_q(p, score_bin, tally, flux, i_nuclide, atom_density); + score = + score_fission_q(p, score_bin, tally, flux, i_nuclide, atom_density); break; - case N_2N: case N_3N: case N_4N: @@ -1312,7 +1301,8 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // This case block only works if cross sections for these reactions have // been precalculated. When they are not, we revert to the default case, // which looks up cross sections - if (!simulation::need_depletion_rx) goto default_case; + if (!simulation::need_depletion_rx) + goto default_case; if (p.type() != Type::neutron) continue; @@ -1325,12 +1315,24 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } else { int m; switch (score_bin) { - case N_GAMMA: m = 0; break; - case N_P: m = 1; break; - case N_A: m = 2; break; - case N_2N: m = 3; break; - case N_3N: m = 4; break; - case N_4N: m = 5; break; + case N_GAMMA: + m = 0; + break; + case N_P: + m = 1; + break; + case N_A: + m = 2; + break; + case N_2N: + m = 3; + break; + case N_3N: + m = 4; + break; + case N_4N: + m = 5; + break; } if (i_nuclide >= 0) { score = p.neutron_xs(i_nuclide).reaction[m] * atom_density * flux; @@ -1349,7 +1351,6 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } break; - case COHERENT: case INCOHERENT: case PHOTOELECTRIC: @@ -1373,28 +1374,30 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, } else { if (i_nuclide >= 0) { const auto& micro = p.photon_xs(i_nuclide); - double xs = - (score_bin == COHERENT) ? micro.coherent : - (score_bin == INCOHERENT) ? micro.incoherent : - (score_bin == PHOTOELECTRIC) ? micro.photoelectric : - micro.pair_production; + double xs = (score_bin == COHERENT) ? micro.coherent + : (score_bin == INCOHERENT) + ? micro.incoherent + : (score_bin == PHOTOELECTRIC) + ? micro.photoelectric + : micro.pair_production; score = xs * atom_density * flux; } else { - double xs = (score_bin == COHERENT) ? p.macro_xs().coherent - : (score_bin == INCOHERENT) ? p.macro_xs().incoherent - : (score_bin == PHOTOELECTRIC) - ? p.macro_xs().photoelectric - : p.macro_xs().pair_production; + double xs = (score_bin == COHERENT) + ? p.macro_xs().coherent + : (score_bin == INCOHERENT) + ? p.macro_xs().incoherent + : (score_bin == PHOTOELECTRIC) + ? p.macro_xs().photoelectric + : p.macro_xs().pair_production; score = xs * flux; } } break; - case HEATING: if (p.type() == Type::neutron) { - score = score_neutron_heating(p, tally, flux, HEATING, - i_nuclide, atom_density); + score = score_neutron_heating( + p, tally, flux, HEATING, i_nuclide, atom_density); } else { // The energy deposited is the difference between the pre-collision and // post-collision energy... @@ -1428,8 +1431,9 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_last() * flux; } else { // Any other cross section has to be calculated on-the-fly - if (score_bin < 2) fatal_error("Invalid score type on tally " - + std::to_string(tally.id_)); + if (score_bin < 2) + fatal_error( + "Invalid score type on tally " + std::to_string(tally.id_)); score = 0.; if (i_nuclide >= 0) { score = get_nuclide_xs(p, i_nuclide, score_bin) * atom_density * flux; @@ -1438,7 +1442,8 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, for (auto i = 0; i < material.nuclide_.size(); ++i) { auto j_nuclide = material.nuclide_[i]; auto atom_density = material.atom_density_(i); - score += get_nuclide_xs(p, j_nuclide, score_bin) * atom_density * flux; + score += + get_nuclide_xs(p, j_nuclide, score_bin) * atom_density * flux; } } } @@ -1446,12 +1451,13 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, // Add derivative information on score for differential tallies. if (tally.deriv_ != C_NONE) - apply_derivative_to_score(p, i_tally, i_nuclide, atom_density, score_bin, - score); + apply_derivative_to_score( + p, i_tally, i_nuclide, atom_density, score_bin, score); - // Update tally results - #pragma omp atomic - tally.results_(filter_index, score_index, TallyResult::VALUE) += score*filter_weight; +// Update tally results +#pragma omp atomic + tally.results_(filter_index, score_index, TallyResult::VALUE) += + score * filter_weight; } } @@ -1460,17 +1466,17 @@ score_general_ce(Particle& p, int i_tally, int start_index, int filter_index, //! For analog tallies, the flux estimate depends on the score type so the flux //! argument is really just used for filter weights. -void -score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, - double filter_weight, int i_nuclide, double atom_density, double flux) +void score_general_mg(Particle& p, int i_tally, int start_index, + int filter_index, double filter_weight, int i_nuclide, double atom_density, + double flux) { auto& tally {*model::tallies[i_tally]}; // Set the direction and group to use with get_xs Direction p_u; int p_g; - if (tally.estimator_ == TallyEstimator::ANALOG - || tally.estimator_ == TallyEstimator::COLLISION) { + if (tally.estimator_ == TallyEstimator::ANALOG || + tally.estimator_ == TallyEstimator::COLLISION) { if (settings::survival_biasing) { @@ -1521,7 +1527,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, switch (score_bin) { - case SCORE_FLUX: if (tally.estimator_ == TallyEstimator::ANALOG) { // All events score to a flux bin. We actually use a collision estimator @@ -1540,7 +1545,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_TOTAL: if (tally.estimator_ == TallyEstimator::ANALOG) { // All events will score to the total reaction rate. We can just use @@ -1552,10 +1556,10 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } else { score = p.wgt_last(); } - //TODO: should flux be multiplied in above instead of below? + // TODO: should flux be multiplied in above instead of below? if (i_nuclide >= 0) { - score *= flux * atom_density * nuc_xs.get_xs(MgxsType::TOTAL, p_g) - / macro_xs.get_xs(MgxsType::TOTAL, p_g); + score *= flux * atom_density * nuc_xs.get_xs(MgxsType::TOTAL, p_g) / + macro_xs.get_xs(MgxsType::TOTAL, p_g); } } else { if (i_nuclide >= 0) { @@ -1566,10 +1570,9 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_INVERSE_VELOCITY: - if (tally.estimator_ == TallyEstimator::ANALOG - || tally.estimator_ == TallyEstimator::COLLISION) { + if (tally.estimator_ == TallyEstimator::ANALOG || + tally.estimator_ == TallyEstimator::COLLISION) { // All events score to an inverse velocity bin. We actually use a // collision estimator in place of an analog one since there is no way // to count 'events' exactly for the inverse velocity @@ -1581,11 +1584,11 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_last(); } if (i_nuclide >= 0) { - score *= flux * nuc_xs.get_xs(MgxsType::INVERSE_VELOCITY, p_g) - / macro_xs.get_xs(MgxsType::TOTAL, p_g); + score *= flux * nuc_xs.get_xs(MgxsType::INVERSE_VELOCITY, p_g) / + macro_xs.get_xs(MgxsType::TOTAL, p_g); } else { - score *= flux * macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, p_g) - / macro_xs.get_xs(MgxsType::TOTAL, p_g); + score *= flux * macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, p_g) / + macro_xs.get_xs(MgxsType::TOTAL, p_g); } } else { if (i_nuclide >= 0) { @@ -1596,7 +1599,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_SCATTER: if (tally.estimator_ == TallyEstimator::ANALOG) { // Skip any event where the particle didn't scatter @@ -1624,7 +1626,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_NU_SCATTER: if (tally.estimator_ == TallyEstimator::ANALOG) { // Skip any event where the particle didn't scatter @@ -1646,14 +1647,14 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } } else { if (i_nuclide >= 0) { - score = atom_density * flux * nuc_xs.get_xs(MgxsType::NU_SCATTER, p_g); + score = + atom_density * flux * nuc_xs.get_xs(MgxsType::NU_SCATTER, p_g); } else { score = flux * macro_xs.get_xs(MgxsType::NU_SCATTER, p_g); } } break; - case SCORE_ABSORPTION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing) { @@ -1669,20 +1670,19 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_last() * flux; } if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::ABSORPTION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::ABSORPTION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } } else { if (i_nuclide >= 0) { - score = atom_density * flux - * nuc_xs.get_xs(MgxsType::ABSORPTION, p_g); + score = + atom_density * flux * nuc_xs.get_xs(MgxsType::ABSORPTION, p_g); } else { score = p.macro_xs().absorption * flux; } } break; - case SCORE_FISSION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing) { @@ -1700,11 +1700,11 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_last() * flux; } if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } else { - score *= macro_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= macro_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } } else { if (i_nuclide >= 0) { @@ -1715,7 +1715,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_NU_FISSION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing || p.fission()) { @@ -1732,11 +1731,11 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, // nu-fission score = p.wgt_absorb() * flux; if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::NU_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::NU_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } else { - score *= macro_xs.get_xs(MgxsType::NU_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= macro_xs.get_xs(MgxsType::NU_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } } else { // Skip any non-fission events @@ -1749,21 +1748,20 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, // score. score = simulation::keff * p.wgt_bank() * flux; if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::FISSION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::FISSION, p_g); } } } else { if (i_nuclide >= 0) { - score = atom_density * flux - * nuc_xs.get_xs(MgxsType::NU_FISSION, p_g); + score = + atom_density * flux * nuc_xs.get_xs(MgxsType::NU_FISSION, p_g); } else { score = flux * macro_xs.get_xs(MgxsType::NU_FISSION, p_g); } } break; - case SCORE_PROMPT_NU_FISSION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing || p.fission()) { @@ -1781,11 +1779,11 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_absorb() * flux; if (i_nuclide >= 0) { score *= atom_density * - nuc_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + nuc_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } else { - score *= macro_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= macro_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } } else { // Skip any non-fission events @@ -1801,21 +1799,20 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, auto prompt_frac = 1. - n_delayed / static_cast(p.n_bank()); score = simulation::keff * p.wgt_bank() * prompt_frac * flux; if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::FISSION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::FISSION, p_g); } } } else { if (i_nuclide >= 0) { score = atom_density * flux * - nuc_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g); + nuc_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g); } else { score = flux * macro_xs.get_xs(MgxsType::PROMPT_NU_FISSION, p_g); } } break; - case SCORE_DELAYED_NU_FISSION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing || p.fission()) { @@ -1834,21 +1831,21 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, if (abs_xs > 0.) { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin] - 1; score = p.wgt_absorb() * flux; if (i_nuclide >= 0) { score *= nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, - nullptr, nullptr, &d) - / abs_xs; + nullptr, nullptr, &d) / + abs_xs; } else { score *= macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, - nullptr, nullptr, &d) - / abs_xs; + nullptr, nullptr, &d) / + abs_xs; } score_fission_delayed_dg( i_tally, d_bin, score, score_index, p.filter_matches()); @@ -1860,11 +1857,11 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, // delayed-nu-fission xs to the absorption xs score = p.wgt_absorb() * flux; if (i_nuclide >= 0) { - score *= nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g) - / abs_xs; + score *= + nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g) / abs_xs; } else { - score *= macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g) - / abs_xs; + score *= + macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g) / abs_xs; } } } @@ -1881,8 +1878,7 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, // contribution to the fission bank to the score. if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { @@ -1890,8 +1886,8 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = simulation::keff * p.wgt_bank() / p.n_bank() * p.n_delayed_bank(d - 1) * flux; if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::FISSION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::FISSION, p_g); } score_fission_delayed_dg( i_tally, d_bin, score, score_index, p.filter_matches()); @@ -1904,26 +1900,26 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = simulation::keff * p.wgt_bank() / p.n_bank() * n_delayed * flux; if (i_nuclide >= 0) { - score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::FISSION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::FISSION, p_g); } } } } else { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin] - 1; if (i_nuclide >= 0) { - score = flux * atom_density * nuc_xs.get_xs( - MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); + score = flux * atom_density * + nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, nullptr, + nullptr, &d); } else { - score = flux * macro_xs.get_xs( - MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); + score = flux * macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, + nullptr, nullptr, &d); } score_fission_delayed_dg( i_tally, d_bin, score, score_index, p.filter_matches()); @@ -1932,7 +1928,7 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } else { if (i_nuclide >= 0) { score = flux * atom_density * - nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g); + nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g); } else { score = flux * macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g); } @@ -1940,7 +1936,6 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } break; - case SCORE_DECAY_RATE: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing) { @@ -1951,23 +1946,25 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, if (abs_xs > 0) { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin] - 1; score = p.wgt_absorb() * flux; if (i_nuclide >= 0) { - score *= nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, - nullptr, nullptr, &d) - * nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, - nullptr, nullptr, &d) / abs_xs; + score *= nuc_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, + nullptr, nullptr, &d) / + abs_xs; } else { - score *= macro_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, - nullptr, &d) - * macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, - nullptr, nullptr, &d) / abs_xs; + score *= macro_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, + nullptr, nullptr, &d) / + abs_xs; } score_fission_delayed_dg( i_tally, d_bin, score, score_index, p.filter_matches()); @@ -2015,19 +2012,21 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, auto d = bank.delayed_group - 1; if (d != -1) { if (i_nuclide >= 0) { - score += simulation::keff * atom_density * bank.wgt * flux - * nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) - * nuc_xs.get_xs(MgxsType::FISSION, p_g) - / macro_xs.get_xs(MgxsType::FISSION, p_g); + score += simulation::keff * atom_density * bank.wgt * flux * + nuc_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + nuc_xs.get_xs(MgxsType::FISSION, p_g) / + macro_xs.get_xs(MgxsType::FISSION, p_g); } else { - score += simulation::keff * bank.wgt * flux - * macro_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d); + score += simulation::keff * bank.wgt * flux * + macro_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d); } if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( - model::tally_filters[i_dg_filt].get())}; + const DelayedGroupFilter& filt { + *dynamic_cast( + model::tally_filters[i_dg_filt].get())}; // Find the corresponding filter bin and then score for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto dg = filt.groups()[d_bin]; @@ -2039,29 +2038,29 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, } } } - if (tally.delayedgroup_filter_ != C_NONE) continue; + if (tally.delayedgroup_filter_ != C_NONE) + continue; } } else { if (tally.delayedgroup_filter_ != C_NONE) { auto i_dg_filt = tally.filters()[tally.delayedgroup_filter_]; - const DelayedGroupFilter& filt - {*dynamic_cast( + const DelayedGroupFilter& filt {*dynamic_cast( model::tally_filters[i_dg_filt].get())}; // Tally each delayed group bin individually for (auto d_bin = 0; d_bin < filt.n_bins(); ++d_bin) { auto d = filt.groups()[d_bin] - 1; if (i_nuclide >= 0) { - score = atom_density * flux - * nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, - nullptr, &d) - * nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, nullptr, - nullptr, &d); + score = + atom_density * flux * + nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + nuc_xs.get_xs( + MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); } else { - score = flux - * macro_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, - nullptr, &d) - * macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, nullptr, - nullptr, &d); + score = flux * + macro_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, + nullptr, nullptr, &d); } score_fission_delayed_dg( i_tally, d_bin, score, score_index, p.filter_matches()); @@ -2071,20 +2070,23 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = 0.; for (auto d = 0; d < data::mg.num_delayed_groups_; ++d) { if (i_nuclide >= 0) { - score += atom_density * flux - * nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) - * nuc_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); + score += + atom_density * flux * + nuc_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + nuc_xs.get_xs( + MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); } else { - score += flux - * macro_xs.get_xs(MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) - * macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, nullptr, nullptr, &d); + score += flux * + macro_xs.get_xs( + MgxsType::DECAY_RATE, p_g, nullptr, nullptr, &d) * + macro_xs.get_xs(MgxsType::DELAYED_NU_FISSION, p_g, + nullptr, nullptr, &d); } } } } break; - case SCORE_KAPPA_FISSION: if (tally.estimator_ == TallyEstimator::ANALOG) { if (settings::survival_biasing) { @@ -2102,17 +2104,16 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, score = p.wgt_last() * flux; } if (i_nuclide >= 0) { - score *= atom_density - * nuc_xs.get_xs(MgxsType::KAPPA_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= atom_density * nuc_xs.get_xs(MgxsType::KAPPA_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } else { - score *= - macro_xs.get_xs(MgxsType::KAPPA_FISSION, p_g) - / macro_xs.get_xs(MgxsType::ABSORPTION, p_g); + score *= macro_xs.get_xs(MgxsType::KAPPA_FISSION, p_g) / + macro_xs.get_xs(MgxsType::ABSORPTION, p_g); } } else { if (i_nuclide >= 0) { - score = atom_density * flux * nuc_xs.get_xs(MgxsType::KAPPA_FISSION, p_g); + score = + atom_density * flux * nuc_xs.get_xs(MgxsType::KAPPA_FISSION, p_g); } else { score = flux * macro_xs.get_xs(MgxsType::KAPPA_FISSION, p_g); } @@ -2120,27 +2121,26 @@ score_general_mg(Particle& p, int i_tally, int start_index, int filter_index, break; case SCORE_EVENTS: - // Simply count the number of scoring events - #pragma omp atomic +// Simply count the number of scoring events +#pragma omp atomic tally.results_(filter_index, score_index, TallyResult::VALUE) += 1.0; continue; - default: continue; } - // Update tally results - #pragma omp atomic - tally.results_(filter_index, score_index, TallyResult::VALUE) += score*filter_weight; +// Update tally results +#pragma omp atomic + tally.results_(filter_index, score_index, TallyResult::VALUE) += + score * filter_weight; } } //! Tally rates for when the user requests a tally on all nuclides. -void -score_all_nuclides(Particle& p, int i_tally, double flux, - int filter_index, double filter_weight) +void score_all_nuclides( + Particle& p, int i_tally, double flux, int filter_index, double filter_weight) { const Tally& tally {*model::tallies[i_tally]}; const Material& material {*model::materials[p.material()]}; @@ -2150,13 +2150,13 @@ score_all_nuclides(Particle& p, int i_tally, double flux, auto i_nuclide = material.nuclide_[i]; auto atom_density = material.atom_density_(i); - //TODO: consider replacing this "if" with pointers or templates + // TODO: consider replacing this "if" with pointers or templates if (settings::run_CE) { - score_general_ce(p, i_tally, i_nuclide*tally.scores_.size(), filter_index, - filter_weight, i_nuclide, atom_density, flux); + score_general_ce(p, i_tally, i_nuclide * tally.scores_.size(), + filter_index, filter_weight, i_nuclide, atom_density, flux); } else { - score_general_mg(p, i_tally, i_nuclide*tally.scores_.size(), filter_index, - filter_weight, i_nuclide, atom_density, flux); + score_general_mg(p, i_tally, i_nuclide * tally.scores_.size(), + filter_index, filter_weight, i_nuclide, atom_density, flux); } } @@ -2164,13 +2164,13 @@ score_all_nuclides(Particle& p, int i_tally, double flux, int i_nuclide = -1; double atom_density = 0.; auto n_nuclides = data::nuclides.size(); - //TODO: consider replacing this "if" with pointers or templates + // TODO: consider replacing this "if" with pointers or templates if (settings::run_CE) { - score_general_ce(p, i_tally, n_nuclides*tally.scores_.size(), filter_index, - filter_weight, i_nuclide, atom_density, flux); + score_general_ce(p, i_tally, n_nuclides * tally.scores_.size(), + filter_index, filter_weight, i_nuclide, atom_density, flux); } else { - score_general_mg(p, i_tally, n_nuclides*tally.scores_.size(), filter_index, - filter_weight, i_nuclide, atom_density, flux); + score_general_mg(p, i_tally, n_nuclides * tally.scores_.size(), + filter_index, filter_weight, i_nuclide, atom_density, flux); } } @@ -2192,7 +2192,8 @@ void score_analog_tally_ce(Particle& p) // assume_separate break below. auto filter_iter = FilterBinIter(tally, p); auto end = FilterBinIter(tally, true, &p.filter_matches()); - if (filter_iter == end) continue; + if (filter_iter == end) + continue; // Loop over filter bins. for (; filter_iter != end; ++filter_iter) { @@ -2208,7 +2209,7 @@ void score_analog_tally_ce(Particle& p) // the event nuclide or the total material. Note that the atomic // density argument for score_general is not used for analog tallies. if (i_nuclide == p.event_nuclide() || i_nuclide == -1) - score_general_ce(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_ce(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, -1.0, flux); } @@ -2217,12 +2218,12 @@ void score_analog_tally_ce(Particle& p) // can take advantage of the fact that we know exactly how nuclide // bins correspond to nuclide indices. First, tally the nuclide. auto i = p.event_nuclide(); - score_general_ce(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_ce(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, -1, -1.0, flux); // Now tally the total material. i = tally.nuclides_.size(); - score_general_ce(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_ce(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, -1, -1.0, flux); } } @@ -2231,7 +2232,8 @@ void score_analog_tally_ce(Particle& p) // separate, this implies that once a tally has been scored to, we needn't // check the others. This cuts down on overhead when there are many // tallies specified - if (settings::assume_separate) break; + if (settings::assume_separate) + break; } // Reset all the filter matches for the next tally event. @@ -2249,7 +2251,8 @@ void score_analog_tally_mg(Particle& p) // assume_separate break below. auto filter_iter = FilterBinIter(tally, p); auto end = FilterBinIter(tally, true, &p.filter_matches()); - if (filter_iter == end) continue; + if (filter_iter == end) + continue; // Loop over filter bins. for (; filter_iter != end; ++filter_iter) { @@ -2264,11 +2267,12 @@ void score_analog_tally_mg(Particle& p) if (i_nuclide >= 0) { auto j = model::materials[p.material()]->mat_nuclide_index_[i_nuclide]; - if (j == C_NONE) continue; + if (j == C_NONE) + continue; atom_density = model::materials[p.material()]->atom_density_(j); } - score_general_mg(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_mg(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, atom_density, 1.0); } } @@ -2277,7 +2281,8 @@ void score_analog_tally_mg(Particle& p) // separate, this implies that once a tally has been scored to, we needn't // check the others. This cuts down on overhead when there are many // tallies specified - if (settings::assume_separate) break; + if (settings::assume_separate) + break; } // Reset all the filter matches for the next tally event. @@ -2285,8 +2290,7 @@ void score_analog_tally_mg(Particle& p) match.bins_present_ = false; } -void -score_tracklength_tally(Particle& p, double distance) +void score_tracklength_tally(Particle& p, double distance) { // Determine the tracklength estimate of the flux double flux = p.wgt() * distance; @@ -2299,7 +2303,8 @@ score_tracklength_tally(Particle& p, double distance) // assume_separate break below. auto filter_iter = FilterBinIter(tally, p); auto end = FilterBinIter(tally, true, &p.filter_matches()); - if (filter_iter == end) continue; + if (filter_iter == end) + continue; // Loop over filter bins. for (; filter_iter != end; ++filter_iter) { @@ -2309,8 +2314,8 @@ score_tracklength_tally(Particle& p, double distance) // Loop over nuclide bins. if (tally.all_nuclides_) { if (p.material() != MATERIAL_VOID) - score_all_nuclides(p, i_tally, flux*filter_weight, filter_index, - filter_weight); + score_all_nuclides( + p, i_tally, flux * filter_weight, filter_index, filter_weight); } else { for (auto i = 0; i < tally.nuclides_.size(); ++i) { @@ -2321,29 +2326,30 @@ score_tracklength_tally(Particle& p, double distance) if (p.material() != MATERIAL_VOID) { auto j = model::materials[p.material()]->mat_nuclide_index_[i_nuclide]; - if (j == C_NONE) continue; + if (j == C_NONE) + continue; atom_density = model::materials[p.material()]->atom_density_(j); } } - //TODO: consider replacing this "if" with pointers or templates + // TODO: consider replacing this "if" with pointers or templates if (settings::run_CE) { - score_general_ce(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_ce(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, atom_density, flux); } else { - score_general_mg(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_mg(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, atom_density, flux); } } } - } // If the user has specified that we can assume all tallies are spatially // separate, this implies that once a tally has been scored to, we needn't // check the others. This cuts down on overhead when there are many // tallies specified - if (settings::assume_separate) break; + if (settings::assume_separate) + break; } // Reset all the filter matches for the next tally event. @@ -2371,7 +2377,8 @@ void score_collision_tally(Particle& p) // assume_separate break below. auto filter_iter = FilterBinIter(tally, p); auto end = FilterBinIter(tally, true, &p.filter_matches()); - if (filter_iter == end) continue; + if (filter_iter == end) + continue; // Loop over filter bins. for (; filter_iter != end; ++filter_iter) { @@ -2380,8 +2387,8 @@ void score_collision_tally(Particle& p) // Loop over nuclide bins. if (tally.all_nuclides_) { - score_all_nuclides(p, i_tally, flux*filter_weight, filter_index, - filter_weight); + score_all_nuclides( + p, i_tally, flux * filter_weight, filter_index, filter_weight); } else { for (auto i = 0; i < tally.nuclides_.size(); ++i) { @@ -2391,16 +2398,17 @@ void score_collision_tally(Particle& p) if (i_nuclide >= 0) { auto j = model::materials[p.material()]->mat_nuclide_index_[i_nuclide]; - if (j == C_NONE) continue; + if (j == C_NONE) + continue; atom_density = model::materials[p.material()]->atom_density_(j); } - //TODO: consider replacing this "if" with pointers or templates + // TODO: consider replacing this "if" with pointers or templates if (settings::run_CE) { - score_general_ce(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_ce(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, atom_density, flux); } else { - score_general_mg(p, i_tally, i*tally.scores_.size(), filter_index, + score_general_mg(p, i_tally, i * tally.scores_.size(), filter_index, filter_weight, i_nuclide, atom_density, flux); } } @@ -2411,7 +2419,8 @@ void score_collision_tally(Particle& p) // separate, this implies that once a tally has been scored to, we needn't // check the others. This cuts down on overhead when there are many // tallies specified - if (settings::assume_separate) break; + if (settings::assume_separate) + break; } // Reset all the filter matches for the next tally event. @@ -2432,7 +2441,8 @@ void score_surface_tally(Particle& p, const vector& tallies) // assume_separate break below. auto filter_iter = FilterBinIter(tally, p); auto end = FilterBinIter(tally, true, &p.filter_matches()); - if (filter_iter == end) continue; + if (filter_iter == end) + continue; // Loop over filter bins. for (; filter_iter != end; ++filter_iter) { @@ -2445,7 +2455,7 @@ void score_surface_tally(Particle& p, const vector& tallies) double score = flux * filter_weight; for (auto score_index = 0; score_index < tally.scores_.size(); ++score_index) { - #pragma omp atomic +#pragma omp atomic tally.results_(filter_index, score_index, TallyResult::VALUE) += score; } } @@ -2454,7 +2464,8 @@ void score_surface_tally(Particle& p, const vector& tallies) // separate, this implies that once a tally has been scored to, we needn't // check the others. This cuts down on overhead when there are many // tallies specified - if (settings::assume_separate) break; + if (settings::assume_separate) + break; } // Reset all the filter matches for the next tally event. diff --git a/src/tallies/trigger.cpp b/src/tallies/trigger.cpp index 40eb3290f..2c155980e 100644 --- a/src/tallies/trigger.cpp +++ b/src/tallies/trigger.cpp @@ -20,15 +20,15 @@ namespace openmc { //============================================================================== namespace settings { - KTrigger keff_trigger; +KTrigger keff_trigger; } //============================================================================== // Non-member functions //============================================================================== -std::pair -get_tally_uncertainty(int i_tally, int score_index, int filter_index) +std::pair get_tally_uncertainty( + int i_tally, int score_index, int filter_index) { const auto& tally {model::tallies[i_tally]}; @@ -37,7 +37,7 @@ get_tally_uncertainty(int i_tally, int score_index, int filter_index) int n = tally->n_realizations_; auto mean = sum / n; - double std_dev = std::sqrt((sum_sq/n - mean*mean) / (n-1)); + double std_dev = std::sqrt((sum_sq / n - mean * mean) / (n - 1)); double rel_err = (mean != 0.) ? std_dev / std::abs(mean) : 0.; return {std_dev, rel_err}; @@ -50,19 +50,20 @@ get_tally_uncertainty(int i_tally, int score_index, int filter_index) //! param[out] tally_id The ID number of the most limiting tally //! param[out] score The most limiting tally score bin -void -check_tally_triggers(double& ratio, int& tally_id, int& score) +void check_tally_triggers(double& ratio, int& tally_id, int& score) { ratio = 0.; for (auto i_tally = 0; i_tally < model::tallies.size(); ++i_tally) { const Tally& t {*model::tallies[i_tally]}; // Ignore tallies with less than two realizations. - if (t.n_realizations_ < 2) continue; + if (t.n_realizations_ < 2) + continue; for (const auto& trigger : t.triggers_) { // Skip trigger if it is not active - if (trigger.metric == TriggerMetric::not_active) continue; + if (trigger.metric == TriggerMetric::not_active) + continue; const auto& results = t.results_; for (auto filter_index = 0; filter_index < results.shape()[0]; @@ -70,25 +71,25 @@ check_tally_triggers(double& ratio, int& tally_id, int& score) for (auto score_index = 0; score_index < results.shape()[1]; ++score_index) { // Compute the tally uncertainty metrics. - auto uncert_pair = get_tally_uncertainty(i_tally, score_index, - filter_index); + auto uncert_pair = + get_tally_uncertainty(i_tally, score_index, filter_index); double std_dev = uncert_pair.first; double rel_err = uncert_pair.second; // Pick out the relevant uncertainty metric for this trigger. double uncertainty; switch (trigger.metric) { - case TriggerMetric::variance: - uncertainty = std_dev * std_dev; - break; - case TriggerMetric::standard_deviation: - uncertainty = std_dev; - break; - case TriggerMetric::relative_error: - uncertainty = rel_err; - break; - case TriggerMetric::not_active: - UNREACHABLE(); + case TriggerMetric::variance: + uncertainty = std_dev * std_dev; + break; + case TriggerMetric::standard_deviation: + uncertainty = std_dev; + break; + case TriggerMetric::relative_error: + uncertainty = rel_err; + break; + case TriggerMetric::not_active: + UNREACHABLE(); } // Compute the uncertainty / threshold ratio. @@ -111,10 +112,10 @@ check_tally_triggers(double& ratio, int& tally_id, int& score) //! Compute the uncertainty/threshold ratio for the eigenvalue trigger. -double -check_keff_trigger() +double check_keff_trigger() { - if (settings::run_mode != RunMode::EIGENVALUE) return 0.0; + if (settings::run_mode != RunMode::EIGENVALUE) + return 0.0; double k_combined[2]; openmc_get_keff(k_combined); @@ -144,8 +145,7 @@ check_keff_trigger() //! See if tally and eigenvalue uncertainties are under trigger thresholds. -void -check_triggers() +void check_triggers() { // Make some aliases. const auto current_batch {simulation::current_batch}; @@ -153,9 +153,12 @@ check_triggers() const auto interval {settings::trigger_batch_interval}; // See if the current batch is one for which the triggers must be checked. - if (!settings::trigger_on) return; - if (current_batch < n_batches) return; - if (((current_batch - n_batches) % interval) != 0) return; + if (!settings::trigger_on) + return; + if (current_batch < n_batches) + return; + if (((current_batch - n_batches) % interval) != 0) + return; // Check the eigenvalue and tally triggers. double keff_ratio = check_keff_trigger(); @@ -175,7 +178,8 @@ check_triggers() std::string msg; if (keff_ratio >= tally_ratio) { msg = fmt::format("Triggers unsatisfied, max unc./thresh. is {} for " - "eigenvalue", keff_ratio); + "eigenvalue", + keff_ratio); } else { msg = fmt::format( "Triggers unsatisfied, max unc./thresh. is {} for {} in tally {}", @@ -189,11 +193,11 @@ check_triggers() // the number of batches. auto max_ratio = std::max(keff_ratio, tally_ratio); auto n_active = current_batch - settings::n_inactive; - auto n_pred_batches = static_cast(n_active * max_ratio * max_ratio) - + settings::n_inactive + 1; + auto n_pred_batches = static_cast(n_active * max_ratio * max_ratio) + + settings::n_inactive + 1; - std::string msg = fmt::format("The estimated number of batches is {}", - n_pred_batches); + std::string msg = + fmt::format("The estimated number of batches is {}", n_pred_batches); if (n_pred_batches > settings::n_max_batches) { msg.append(" --- greater than max batches"); warning(msg); diff --git a/src/thermal.cpp b/src/thermal.cpp index 5e3c6d6bb..1101d5485 100644 --- a/src/thermal.cpp +++ b/src/thermal.cpp @@ -3,13 +3,13 @@ #include // for sort, move, min, max, find #include // for round, sqrt, abs -#include #include "xtensor/xarray.hpp" #include "xtensor/xbuilder.hpp" #include "xtensor/xmath.hpp" #include "xtensor/xsort.hpp" #include "xtensor/xtensor.hpp" #include "xtensor/xview.hpp" +#include #include "openmc/constants.h" #include "openmc/endf.h" @@ -29,7 +29,7 @@ namespace openmc { namespace data { std::unordered_map thermal_scatt_map; vector> thermal_scatt; -} +} // namespace data //============================================================================== // ThermalScattering implementation @@ -84,13 +84,14 @@ ThermalScattering::ThermalScattering( auto i_closest = xt::argmin(xt::abs(temps_available - T))[0]; auto temp_actual = temps_available[i_closest]; if (std::abs(temp_actual - T) < settings::temperature_tolerance) { - if (std::find(temps_to_read.begin(), temps_to_read.end(), std::round(temp_actual)) - == temps_to_read.end()) { + if (std::find(temps_to_read.begin(), temps_to_read.end(), + std::round(temp_actual)) == temps_to_read.end()) { temps_to_read.push_back(std::round(temp_actual)); } } else { fatal_error(fmt::format("Nuclear data library does not contain cross " - "sections for {} at or near {} K.", name_, std::round(T))); + "sections for {} at or near {} K.", + name_, std::round(T))); } } break; @@ -104,18 +105,22 @@ ThermalScattering::ThermalScattering( if (temps_available[j] <= T && T < temps_available[j + 1]) { int T_j = std::round(temps_available[j]); int T_j1 = std::round(temps_available[j + 1]); - if (std::find(temps_to_read.begin(), temps_to_read.end(), T_j) == temps_to_read.end()) { + if (std::find(temps_to_read.begin(), temps_to_read.end(), T_j) == + temps_to_read.end()) { temps_to_read.push_back(T_j); } - if (std::find(temps_to_read.begin(), temps_to_read.end(), T_j1) == temps_to_read.end()) { + if (std::find(temps_to_read.begin(), temps_to_read.end(), T_j1) == + temps_to_read.end()) { temps_to_read.push_back(T_j1); } found = true; } } if (!found) { - fatal_error(fmt::format("Nuclear data library does not contain cross " - "sections for {} at temperatures that bound {} K.", name_, std::round(T))); + fatal_error( + fmt::format("Nuclear data library does not contain cross " + "sections for {} at temperatures that bound {} K.", + name_, std::round(T))); } } } @@ -145,28 +150,29 @@ ThermalScattering::ThermalScattering( close_group(kT_group); } -void -ThermalScattering::calculate_xs(double E, double sqrtkT, int* i_temp, - double* elastic, double* inelastic, - uint64_t* seed) const +void ThermalScattering::calculate_xs(double E, double sqrtkT, int* i_temp, + double* elastic, double* inelastic, uint64_t* seed) const { // Determine temperature for S(a,b) table - double kT = sqrtkT*sqrtkT; + double kT = sqrtkT * sqrtkT; int i = 0; auto n = kTs_.size(); if (n > 1) { // Find temperatures that bound the actual temperature - while (kTs_[i+1] < kT && i + 1 < n - 1) ++i; + while (kTs_[i + 1] < kT && i + 1 < n - 1) + ++i; if (settings::temperature_method == TemperatureMethod::NEAREST) { // Pick closer of two bounding temperatures - if (kT - kTs_[i] > kTs_[i+1] - kT) ++i; + if (kT - kTs_[i] > kTs_[i + 1] - kT) + ++i; } else { // Randomly sample between temperature i and i+1 - double f = (kT - kTs_[i]) / (kTs_[i+1] - kTs_[i]); - if (f > prn(seed)) ++i; + double f = (kT - kTs_[i]) / (kTs_[i + 1] - kTs_[i]); + if (f > prn(seed)) + ++i; } } @@ -177,8 +183,7 @@ ThermalScattering::calculate_xs(double E, double sqrtkT, int* i_temp, data_[i].calculate_xs(E, elastic, inelastic); } -bool -ThermalScattering::has_nuclide(const char* name) const +bool ThermalScattering::has_nuclide(const char* name) const { std::string nuc {name}; return std::find(nuclides_.begin(), nuclides_.end(), nuc) != nuclides_.end(); @@ -242,8 +247,8 @@ ThermalData::ThermalData(hid_t group) } } -void -ThermalData::calculate_xs(double E, double* elastic, double* inelastic) const +void ThermalData::calculate_xs( + double E, double* elastic, double* inelastic) const { // Calculate thermal elastic scattering cross section if (elastic_.xs) { @@ -256,9 +261,8 @@ ThermalData::calculate_xs(double E, double* elastic, double* inelastic) const *inelastic = (*inelastic_.xs)(E); } -void -ThermalData::sample(const NuclideMicroXS& micro_xs, double E, - double* E_out, double* mu, uint64_t* seed) +void ThermalData::sample(const NuclideMicroXS& micro_xs, double E, + double* E_out, double* mu, uint64_t* seed) { // Determine whether inelastic or elastic scattering will occur if (prn(seed) < micro_xs.thermal_elastic / micro_xs.thermal) { @@ -270,7 +274,8 @@ ThermalData::sample(const NuclideMicroXS& micro_xs, double E, // Because of floating-point roundoff, it may be possible for mu to be // outside of the range [-1,1). In these cases, we just set mu to exactly // -1 or 1 - if (std::abs(*mu) > 1.0) *mu = std::copysign(1.0, *mu); + if (std::abs(*mu) > 1.0) + *mu = std::copysign(1.0, *mu); } void free_memory_thermal() diff --git a/src/timer.cpp b/src/timer.cpp index 395fa0988..86436758a 100644 --- a/src/timer.cpp +++ b/src/timer.cpp @@ -33,7 +33,7 @@ Timer time_event_death; // Timer implementation //============================================================================== -void Timer::start () +void Timer::start() { running_ = true; start_ = clock::now(); diff --git a/src/track_output.cpp b/src/track_output.cpp index ed20b057b..065c2d465 100644 --- a/src/track_output.cpp +++ b/src/track_output.cpp @@ -7,8 +7,8 @@ #include "openmc/simulation.h" #include "openmc/vector.h" -#include #include "xtensor/xtensor.hpp" +#include #include // for size_t #include @@ -45,7 +45,7 @@ void finalize_particle_track(Particle& p) n_coords.push_back(coords.size()); } -#pragma omp critical (FinalizeParticleTrack) +#pragma omp critical(FinalizeParticleTrack) { hid_t file_id = file_open(filename, 'w'); write_attribute(file_id, "filetype", "track"); @@ -55,7 +55,7 @@ void finalize_particle_track(Particle& p) for (auto i = 1; i <= p.tracks().size(); ++i) { const auto& t {p.tracks()[i - 1]}; size_t n = t.size(); - xt::xtensor data({n,3}); + xt::xtensor data({n, 3}); for (int j = 0; j < n; ++j) { data(j, 0) = t[j].x; data(j, 1) = t[j].y; diff --git a/src/urr.cpp b/src/urr.cpp index 28ad2505f..280fb01ef 100644 --- a/src/urr.cpp +++ b/src/urr.cpp @@ -28,4 +28,4 @@ UrrData::UrrData(hid_t group_id) read_dataset(group_id, "table", prob_); } -} \ No newline at end of file +} // namespace openmc \ No newline at end of file diff --git a/src/volume_calc.cpp b/src/volume_calc.cpp index 33c788358..ae738d6bb 100644 --- a/src/volume_calc.cpp +++ b/src/volume_calc.cpp @@ -23,7 +23,7 @@ #include "xtensor/xview.hpp" #include // for copy -#include // for pow, sqrt +#include // for pow, sqrt #include namespace openmc { @@ -52,7 +52,8 @@ VolumeCalculation::VolumeCalculation(pugi::xml_node node) domain_type_ = TallyDomain::UNIVERSE; } else { fatal_error(std::string("Unrecognized domain type for stochastic " - "volume calculation: " + domain_type)); + "volume calculation: " + + domain_type)); } // Read domain IDs, bounding corodinates and number of samples @@ -67,7 +68,8 @@ VolumeCalculation::VolumeCalculation(pugi::xml_node node) threshold_ = std::stod(get_node_value(threshold_node, "threshold")); if (threshold_ <= 0.0) { fatal_error(fmt::format("Invalid error threshold {} provided for a " - "volume calculation.", threshold_)); + "volume calculation.", + threshold_)); } std::string tmp = get_node_value(threshold_node, "type"); @@ -75,23 +77,21 @@ VolumeCalculation::VolumeCalculation(pugi::xml_node node) trigger_type_ = TriggerMetric::variance; } else if (tmp == "std_dev") { trigger_type_ = TriggerMetric::standard_deviation; - } else if ( tmp == "rel_err") { + } else if (tmp == "rel_err") { trigger_type_ = TriggerMetric::relative_error; } else { fatal_error(fmt::format( "Invalid volume calculation trigger type '{}' provided.", tmp)); } - } // Ensure there are no duplicates by copying elements to a set and then // comparing the length with the original vector std::unordered_set unique_ids(domain_ids_.cbegin(), domain_ids_.cend()); if (unique_ids.size() != domain_ids_.size()) { - throw std::runtime_error{"Domain IDs for a volume calculation " - "must be unique."}; + throw std::runtime_error {"Domain IDs for a volume calculation " + "must be unique."}; } - } vector VolumeCalculation::execute() const @@ -109,31 +109,32 @@ vector VolumeCalculation::execute() const size_t remainder = n_samples_ % mpi::n_procs; size_t i_start, i_end; if (mpi::rank < remainder) { - i_start = (min_samples + 1)*mpi::rank; + i_start = (min_samples + 1) * mpi::rank; i_end = i_start + min_samples + 1; } else { - i_start = (min_samples + 1)*remainder + (mpi::rank - remainder)*min_samples; + i_start = + (min_samples + 1) * remainder + (mpi::rank - remainder) * min_samples; i_end = i_start + min_samples; } while (true) { - #pragma omp parallel +#pragma omp parallel { // Variables that are private to each thread vector> indices(n); vector> hits(n); Particle p; - // Sample locations and count hits - #pragma omp for +// Sample locations and count hits +#pragma omp for for (size_t i = i_start; i < i_end; i++) { int64_t id = iterations * n_samples_ + i; uint64_t seed = init_seed(id, STREAM_VOLUME); p.n_coord() = 1; Position xi {prn(&seed), prn(&seed), prn(&seed)}; - p.r() = lower_left_ + xi*(upper_right_ - lower_left_); + p.r() = lower_left_ + xi * (upper_right_ - lower_left_); p.u() = {0.5, 0.5, 0.5}; // If this location is not in the geometry at all, move on to next block @@ -153,7 +154,7 @@ vector VolumeCalculation::execute() const } } else if (domain_type_ == TallyDomain::CELL) { for (int level = 0; level < p.n_coord(); ++level) { - for (int i_domain=0; i_domain < n; i_domain++) { + for (int i_domain = 0; i_domain < n; i_domain++) { if (model::cells[p.coord(level).cell]->id_ == domain_ids_[i_domain]) { this->check_hit( @@ -175,23 +176,23 @@ vector VolumeCalculation::execute() const } } - // At this point, each thread has its own pair of index/hits lists and we now - // need to reduce them. OpenMP is not nearly smart enough to do this on its own, - // so we have to manually reduce them + // At this point, each thread has its own pair of index/hits lists and we + // now need to reduce them. OpenMP is not nearly smart enough to do this + // on its own, so we have to manually reduce them - #ifdef _OPENMP +#ifdef _OPENMP int n_threads = omp_get_num_threads(); - #else +#else int n_threads = 1; - #endif +#endif - #pragma omp for ordered schedule(static) +#pragma omp for ordered schedule(static) for (int i = 0; i < n_threads; ++i) { - #pragma omp ordered +#pragma omp ordered for (int i_domain = 0; i_domain < n; ++i_domain) { for (int j = 0; j < indices[i_domain].size(); ++j) { - // Check if this material has been added to the master list and if so, - // accumulate the number of hits + // Check if this material has been added to the master list and if + // so, accumulate the number of hits bool already_added = false; for (int k = 0; k < master_indices[i_domain].size(); k++) { if (indices[i_domain][j] == master_indices[i_domain][k]) { @@ -201,8 +202,9 @@ vector VolumeCalculation::execute() const } } if (!already_added) { - // If we made it here, the material hasn't yet been added to the master - // list, so add entries to the master indices and master hits lists + // If we made it here, the material hasn't yet been added to the + // master list, so add entries to the master indices and master + // hits lists master_indices[i_domain].push_back(indices[i_domain][j]); master_hits[i_domain].push_back(hits[i_domain][j]); } @@ -215,7 +217,7 @@ vector VolumeCalculation::execute() const // Determine volume of bounding box Position d {upper_right_ - lower_left_}; - double volume_sample = d.x*d.y*d.z; + double volume_sample = d.x * d.y * d.z; // bump iteration counter and get total number // of samples at this point @@ -233,7 +235,8 @@ vector VolumeCalculation::execute() const auto& result {results[i_domain]}; // Create 2D array to store atoms/uncertainty for each nuclide. Later this - // is compressed into vectors storing only those nuclides that are non-zero + // is compressed into vectors storing only those nuclides that are + // non-zero auto n_nuc = data::nuclides.size(); xt::xtensor atoms({n_nuc, 2}, 0.0); @@ -241,21 +244,23 @@ vector VolumeCalculation::execute() const if (mpi::master) { for (int j = 1; j < mpi::n_procs; j++) { int q; - MPI_Recv(&q, 1, MPI_INTEGER, j, 2*j, mpi::intracomm, MPI_STATUS_IGNORE); + MPI_Recv( + &q, 1, MPI_INTEGER, j, 2 * j, mpi::intracomm, MPI_STATUS_IGNORE); vector buffer(2 * q); - MPI_Recv(buffer.data(), 2*q, MPI_INTEGER, j, 2*j + 1, mpi::intracomm, MPI_STATUS_IGNORE); + MPI_Recv(buffer.data(), 2 * q, MPI_INTEGER, j, 2 * j + 1, + mpi::intracomm, MPI_STATUS_IGNORE); for (int k = 0; k < q; ++k) { bool already_added = false; for (int m = 0; m < master_indices[i_domain].size(); ++m) { - if (buffer[2*k] == master_indices[i_domain][m]) { - master_hits[i_domain][m] += buffer[2*k + 1]; + if (buffer[2 * k] == master_indices[i_domain][m]) { + master_hits[i_domain][m] += buffer[2 * k + 1]; already_added = true; break; } } if (!already_added) { - master_indices[i_domain].push_back(buffer[2*k]); - master_hits[i_domain].push_back(buffer[2*k + 1]); + master_indices[i_domain].push_back(buffer[2 * k]); + master_hits[i_domain].push_back(buffer[2 * k + 1]); } } } @@ -263,12 +268,13 @@ vector VolumeCalculation::execute() const int q = master_indices[i_domain].size(); vector buffer(2 * q); for (int k = 0; k < q; ++k) { - buffer[2*k] = master_indices[i_domain][k]; - buffer[2*k + 1] = master_hits[i_domain][k]; + buffer[2 * k] = master_indices[i_domain][k]; + buffer[2 * k + 1] = master_hits[i_domain][k]; } - MPI_Send(&q, 1, MPI_INTEGER, 0, 2*mpi::rank, mpi::intracomm); - MPI_Send(buffer.data(), 2*q, MPI_INTEGER, 0, 2*mpi::rank + 1, mpi::intracomm); + MPI_Send(&q, 1, MPI_INTEGER, 0, 2 * mpi::rank, mpi::intracomm); + MPI_Send(buffer.data(), 2 * q, MPI_INTEGER, 0, 2 * mpi::rank + 1, + mpi::intracomm); } #endif @@ -276,11 +282,13 @@ vector VolumeCalculation::execute() const int total_hits = 0; for (int j = 0; j < master_indices[i_domain].size(); ++j) { total_hits += master_hits[i_domain][j]; - double f = static_cast(master_hits[i_domain][j]) / total_samples; - double var_f = f*(1.0 - f) / total_samples; + double f = + static_cast(master_hits[i_domain][j]) / total_samples; + double var_f = f * (1.0 - f) / total_samples; int i_material = master_indices[i_domain][j]; - if (i_material == MATERIAL_VOID) continue; + if (i_material == MATERIAL_VOID) + continue; const auto& mat = model::materials[i_material]; for (int k = 0; k < mat->nuclide_.size(); ++k) { @@ -292,29 +300,34 @@ vector VolumeCalculation::execute() const } // Determine volume - result.volume[0] = static_cast(total_hits) / total_samples * volume_sample; - result.volume[1] = std::sqrt(result.volume[0] - * (volume_sample - result.volume[0]) / total_samples); + result.volume[0] = + static_cast(total_hits) / total_samples * volume_sample; + result.volume[1] = + std::sqrt(result.volume[0] * (volume_sample - result.volume[0]) / + total_samples); result.iterations = iterations; // update threshold value if needed if (trigger_type_ != TriggerMetric::not_active) { double val = 0.0; switch (trigger_type_) { - case TriggerMetric::standard_deviation: - val = result.volume[1]; - break; - case TriggerMetric::relative_error: - val = result.volume[0] == 0.0 ? INFTY : result.volume[1] / result.volume[0]; - break; - case TriggerMetric::variance: - val = result.volume[1] * result.volume[1]; - break; - default: - break; + case TriggerMetric::standard_deviation: + val = result.volume[1]; + break; + case TriggerMetric::relative_error: + val = result.volume[0] == 0.0 ? INFTY + : result.volume[1] / result.volume[0]; + break; + case TriggerMetric::variance: + val = result.volume[1] * result.volume[1]; + break; + default: + break; } // update max if entry is valid - if (val > 0.0) { trigger_val = std::max(trigger_val, val); } + if (val > 0.0) { + trigger_val = std::max(trigger_val, val); + } } for (int j = 0; j < n_nuc; ++j) { @@ -334,7 +347,9 @@ vector VolumeCalculation::execute() const } // end domain loop // if no trigger is applied, we're done - if (trigger_type_ == TriggerMetric::not_active) { return results; } + if (trigger_type_ == TriggerMetric::not_active) { + return results; + } #ifdef OPENMC_MPI // update maximum error value on all processes @@ -342,13 +357,20 @@ vector VolumeCalculation::execute() const #endif // return results of the calculation - if (trigger_val < threshold_) { return results; } + if (trigger_val < threshold_) { + return results; + } #ifdef OPENMC_MPI - // if iterating in an MPI run, need to zero indices and hits so they aren't counted twice + // if iterating in an MPI run, need to zero indices and hits so they aren't + // counted twice if (!mpi::master) { - for (auto& v : master_indices) { std::fill(v.begin(), v.end(), 0); } - for (auto& v : master_hits) { std::fill(v.begin(), v.end(), 0); } + for (auto& v : master_indices) { + std::fill(v.begin(), v.end(), 0); + } + for (auto& v : master_hits) { + std::fill(v.begin(), v.end(), 0); + } } #endif @@ -381,18 +403,18 @@ void VolumeCalculation::to_hdf5( write_attribute(file_id, "iterations", results[0].iterations); write_attribute(file_id, "threshold", threshold_); std::string trigger_str; - switch(trigger_type_) { - case TriggerMetric::variance: - trigger_str = "variance"; - break; - case TriggerMetric::standard_deviation: - trigger_str = "std_dev"; - break; - case TriggerMetric::relative_error: - trigger_str = "rel_err"; - break; - default: - break; + switch (trigger_type_) { + case TriggerMetric::variance: + trigger_str = "variance"; + break; + case TriggerMetric::standard_deviation: + trigger_str = "std_dev"; + break; + case TriggerMetric::relative_error: + trigger_str = "rel_err"; + break; + default: + break; } write_attribute(file_id, "trigger_type", trigger_str); } else { @@ -401,17 +423,15 @@ void VolumeCalculation::to_hdf5( if (domain_type_ == TallyDomain::CELL) { write_attribute(file_id, "domain_type", "cell"); - } - else if (domain_type_ == TallyDomain::MATERIAL) { + } else if (domain_type_ == TallyDomain::MATERIAL) { write_attribute(file_id, "domain_type", "material"); - } - else if (domain_type_ == TallyDomain::UNIVERSE) { + } else if (domain_type_ == TallyDomain::UNIVERSE) { write_attribute(file_id, "domain_type", "universe"); } - for (int i = 0; i < domain_ids_.size(); ++i) - { - hid_t group_id = create_group(file_id, fmt::format("domain_{}", domain_ids_[i])); + for (int i = 0; i < domain_ids_.size(); ++i) { + hid_t group_id = + create_group(file_id, fmt::format("domain_{}", domain_ids_[i])); // Write volume for domain const auto& result {results[i]}; @@ -473,7 +493,8 @@ void free_memory_volume() // that the user has specified and writes results to HDF5 files //============================================================================== -int openmc_calculate_volumes() { +int openmc_calculate_volumes() +{ using namespace openmc; if (mpi::master) { @@ -483,7 +504,7 @@ int openmc_calculate_volumes() { time_volume.start(); for (int i = 0; i < model::volume_calcs.size(); ++i) { - write_message(4, "Running volume calculation {}", i+1); + write_message(4, "Running volume calculation {}", i + 1); // Run volume calculation const auto& vol_calc {model::volume_calcs[i]}; @@ -493,7 +514,8 @@ int openmc_calculate_volumes() { std::string domain_type; if (vol_calc.domain_type_ == VolumeCalculation::TallyDomain::CELL) { domain_type = " Cell "; - } else if (vol_calc.domain_type_ == VolumeCalculation::TallyDomain::MATERIAL) { + } else if (vol_calc.domain_type_ == + VolumeCalculation::TallyDomain::MATERIAL) { domain_type = " Material "; } else { domain_type = " Universe "; @@ -506,11 +528,10 @@ int openmc_calculate_volumes() { } // Write volumes to HDF5 file - std::string filename = fmt::format("{}volume_{}.h5", - settings::path_output, i + 1); + std::string filename = + fmt::format("{}volume_{}.h5", settings::path_output, i + 1); vol_calc.to_hdf5(filename, results); } - } // Show elapsed time diff --git a/src/wmp.cpp b/src/wmp.cpp index 4299b9400..e9c4fb5e3 100644 --- a/src/wmp.cpp +++ b/src/wmp.cpp @@ -2,15 +2,15 @@ #include "openmc/constants.h" #include "openmc/cross_sections.h" +#include "openmc/error.h" // for writing messages #include "openmc/hdf5_interface.h" #include "openmc/math_functions.h" #include "openmc/nuclide.h" -#include "openmc/error.h" // for writing messages #include -#include #include // for min +#include namespace openmc { @@ -50,14 +50,16 @@ WindowedMultipole::WindowedMultipole(hid_t group) read_dataset(group, "broaden_poly", broaden_poly); if (n_windows != broaden_poly.shape()[0]) { fatal_error("broaden_poly array shape is not consistent with the windows " - "array shape in WMP library for " + name_ + "."); + "array shape in WMP library for " + + name_ + "."); } // Read the "curvefit" array. read_dataset(group, "curvefit", curvefit_); if (n_windows != curvefit_.shape()[0]) { fatal_error("curvefit array shape is not consistent with the windows " - "array shape in WMP library for " + name_ + "."); + "array shape in WMP library for " + + name_ + "."); } fit_order_ = curvefit_.shape()[1] - 1; @@ -77,8 +79,8 @@ WindowedMultipole::WindowedMultipole(hid_t group) } } -std::tuple -WindowedMultipole::evaluate(double E, double sqrtkT) const +std::tuple WindowedMultipole::evaluate( + double E, double sqrtkT) const { using namespace std::complex_literals; @@ -106,12 +108,16 @@ WindowedMultipole::evaluate(double E, double sqrtkT) const // Broaden the curvefit. double dopp = sqrt_awr_ / sqrtkT; array broadened_polynomials; - broaden_wmp_polynomials(E, dopp, fit_order_ + 1, broadened_polynomials.data()); + broaden_wmp_polynomials( + E, dopp, fit_order_ + 1, broadened_polynomials.data()); for (int i_poly = 0; i_poly < fit_order_ + 1; ++i_poly) { - sig_s += curvefit_(i_window, i_poly, FIT_S) * broadened_polynomials[i_poly]; - sig_a += curvefit_(i_window, i_poly, FIT_A) * broadened_polynomials[i_poly]; + sig_s += + curvefit_(i_window, i_poly, FIT_S) * broadened_polynomials[i_poly]; + sig_a += + curvefit_(i_window, i_poly, FIT_A) * broadened_polynomials[i_poly]; if (fissionable_) { - sig_f += curvefit_(i_window, i_poly, FIT_F) * broadened_polynomials[i_poly]; + sig_f += + curvefit_(i_window, i_poly, FIT_F) * broadened_polynomials[i_poly]; } } } else { @@ -132,7 +138,8 @@ WindowedMultipole::evaluate(double E, double sqrtkT) const if (sqrtkT == 0.0) { // If at 0K, use asymptotic form. - for (int i_pole = window.index_start; i_pole <= window.index_end; ++i_pole) { + for (int i_pole = window.index_start; i_pole <= window.index_end; + ++i_pole) { std::complex psi_chi = -1.0i / (data_(i_pole, MP_EA) - sqrtE); std::complex c_temp = psi_chi * invE; sig_s += (data_(i_pole, MP_RS) * c_temp).real(); @@ -144,7 +151,8 @@ WindowedMultipole::evaluate(double E, double sqrtkT) const } else { // At temperature, use Faddeeva function-based form. double dopp = sqrt_awr_ / sqrtkT; - for (int i_pole = window.index_start; i_pole <= window.index_end; ++i_pole) { + for (int i_pole = window.index_start; i_pole <= window.index_end; + ++i_pole) { std::complex z = (sqrtE - data_(i_pole, MP_EA)) * dopp; std::complex w_val = faddeeva(z) * dopp * invE * SQRT_PI; sig_s += (data_(i_pole, MP_RS) * w_val).real(); @@ -158,8 +166,8 @@ WindowedMultipole::evaluate(double E, double sqrtkT) const return std::make_tuple(sig_s, sig_a, sig_f); } -std::tuple -WindowedMultipole::evaluate_deriv(double E, double sqrtkT) const +std::tuple WindowedMultipole::evaluate_deriv( + double E, double sqrtkT) const { // ========================================================================== // Bookkeeping @@ -167,11 +175,11 @@ WindowedMultipole::evaluate_deriv(double E, double sqrtkT) const // Define some frequently used variables. double sqrtE = std::sqrt(E); double invE = 1.0 / E; - double T = sqrtkT*sqrtkT / K_BOLTZMANN; + double T = sqrtkT * sqrtkT / K_BOLTZMANN; if (sqrtkT == 0.0) { fatal_error("Windowed multipole temperature derivatives are not implemented" - " for 0 Kelvin cross sections."); + " for 0 Kelvin cross sections."); } // Locate us @@ -201,7 +209,7 @@ WindowedMultipole::evaluate_deriv(double E, double sqrtkT) const sig_f += (data_(i_pole, MP_RF) * w_val).real(); } } - double norm = -0.5*sqrt_awr_ / std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5); + double norm = -0.5 * sqrt_awr_ / std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5); sig_s *= norm; sig_a *= norm; sig_f *= norm; @@ -226,7 +234,8 @@ void check_wmp_version(hid_t file) } } else { fatal_error(fmt::format("WMP data does not indicate a version. Your " - "installation of OpenMC expects version {}x data.", WMP_VERSION[0])); + "installation of OpenMC expects version {}x data.", + WMP_VERSION[0])); } } @@ -237,7 +246,8 @@ void read_multipole_data(int i_nuclide) auto it = data::library_map.find({Library::Type::wmp, nuc->name_}); // If no WMP library for this nuclide, just return - if (it == data::library_map.end()) return; + if (it == data::library_map.end()) + return; // Check if WMP library exists int idx = it->second; @@ -286,16 +296,17 @@ void broaden_wmp_polynomials(double E, double dopp, int n, double factors[]) // fit, and no less. factors[0] = erf_beta / E; factors[1] = 1. / sqrtE; - factors[2] = factors[0] * (half_inv_dopp2 + E) + exp_m_beta2 / - (beta * SQRT_PI); - if (n > 3) factors[3] = factors[1] * (E + 3.0 * half_inv_dopp2); + factors[2] = + factors[0] * (half_inv_dopp2 + E) + exp_m_beta2 / (beta * SQRT_PI); + if (n > 3) + factors[3] = factors[1] * (E + 3.0 * half_inv_dopp2); // Perform recursive broadening of high order components (Eq. 16) for (int i = 1; i < n - 3; i++) { double ip1_dbl = i + 1; - factors[i + 3] = -factors[i - 1] * (ip1_dbl - 1.) * ip1_dbl * - quarter_inv_dopp4 + factors[i + 1] * - (E + (1. + 2. * ip1_dbl) * half_inv_dopp2); + factors[i + 3] = + -factors[i - 1] * (ip1_dbl - 1.) * ip1_dbl * quarter_inv_dopp4 + + factors[i + 1] * (E + (1. + 2. * ip1_dbl) * half_inv_dopp2); } } diff --git a/src/xml_interface.cpp b/src/xml_interface.cpp index a715dfae2..cf3b981e5 100644 --- a/src/xml_interface.cpp +++ b/src/xml_interface.cpp @@ -7,9 +7,8 @@ namespace openmc { -std::string -get_node_value(pugi::xml_node node, const char* name, bool lowercase, - bool strip) +std::string get_node_value( + pugi::xml_node node, const char* name, bool lowercase, bool strip) { // Search for either an attribute or child tag and get the data as a char*. const pugi::char_t* value_char; @@ -24,7 +23,8 @@ get_node_value(pugi::xml_node node, const char* name, bool lowercase, std::string value {value_char}; // Convert to lower-case if needed - if (lowercase) to_lower(value); + if (lowercase) + to_lower(value); // Strip leading/trailing whitespace if needed if (strip) { @@ -35,8 +35,7 @@ get_node_value(pugi::xml_node node, const char* name, bool lowercase, return value; } -bool -get_node_value_bool(pugi::xml_node node, const char* name) +bool get_node_value_bool(pugi::xml_node node, const char* name) { if (node.attribute(name)) { return node.attribute(name).as_bool(); diff --git a/src/xsdata.cpp b/src/xsdata.cpp index 4cfc0b85a..1929f51e6 100644 --- a/src/xsdata.cpp +++ b/src/xsdata.cpp @@ -1,14 +1,14 @@ #include "openmc/xsdata.h" +#include #include #include -#include #include -#include "xtensor/xview.hpp" +#include "xtensor/xbuilder.hpp" #include "xtensor/xindex_view.hpp" #include "xtensor/xmath.hpp" -#include "xtensor/xbuilder.hpp" +#include "xtensor/xview.hpp" #include "openmc/constants.h" #include "openmc/error.h" @@ -17,22 +17,21 @@ #include "openmc/random_lcg.h" #include "openmc/settings.h" - namespace openmc { //============================================================================== // XsData class methods //============================================================================== -XsData::XsData(bool fissionable, AngleDistributionType scatter_format, int n_pol, int n_azi, - size_t n_groups, size_t n_d_groups) : - n_g_(n_groups), - n_dg_(n_d_groups) +XsData::XsData(bool fissionable, AngleDistributionType scatter_format, + int n_pol, int n_azi, size_t n_groups, size_t n_d_groups) + : n_g_(n_groups), n_dg_(n_d_groups) { size_t n_ang = n_pol * n_azi; // check to make sure scatter format is OK before we allocate - if (scatter_format != AngleDistributionType::HISTOGRAM && scatter_format != AngleDistributionType::TABULAR && + if (scatter_format != AngleDistributionType::HISTOGRAM && + scatter_format != AngleDistributionType::TABULAR && scatter_format != AngleDistributionType::LEGENDRE) { fatal_error("Invalid scatter_format!"); } @@ -66,7 +65,6 @@ XsData::XsData(bool fissionable, AngleDistributionType scatter_format, int n_pol chi_delayed = xt::zeros(shape); } - for (int a = 0; a < n_ang; a++) { if (scatter_format == AngleDistributionType::HISTOGRAM) { scatter.emplace_back(new ScattDataHistogram); @@ -80,9 +78,10 @@ XsData::XsData(bool fissionable, AngleDistributionType scatter_format, int n_pol //============================================================================== -void -XsData::from_hdf5(hid_t xsdata_grp, bool fissionable, AngleDistributionType scatter_format, - AngleDistributionType final_scatter_format, int order_data, bool is_isotropic, int n_pol, int n_azi) +void XsData::from_hdf5(hid_t xsdata_grp, bool fissionable, + AngleDistributionType scatter_format, + AngleDistributionType final_scatter_format, int order_data, bool is_isotropic, + int n_pol, int n_azi) { // Reconstruct the dimension information so it doesn't need to be passed size_t n_ang = n_pol * n_azi; @@ -98,8 +97,8 @@ XsData::from_hdf5(hid_t xsdata_grp, bool fissionable, AngleDistributionType scat read_nd_vector(xsdata_grp, "inverse-velocity", inverse_velocity); // Get scattering data - scatter_from_hdf5(xsdata_grp, n_ang, scatter_format, - final_scatter_format, order_data); + scatter_from_hdf5( + xsdata_grp, n_ang, scatter_format, final_scatter_format, order_data); // Check absorption to ensure it is not 0 since it is often the // denominator in tally methods @@ -122,9 +121,8 @@ XsData::from_hdf5(hid_t xsdata_grp, bool fissionable, AngleDistributionType scat //============================================================================== -void -XsData::fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, - bool is_isotropic) +void XsData::fission_vector_beta_from_hdf5( + hid_t xsdata_grp, size_t n_ang, bool is_isotropic) { // Data is provided as nu-fission and chi with a beta for delayed info @@ -138,8 +136,8 @@ XsData::fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, // Now every incoming group in prompt_chi and delayed_chi is the normalized // chi we just made chi_prompt = xt::view(temp_chi, xt::all(), xt::newaxis(), xt::all()); - chi_delayed = xt::view(temp_chi, xt::all(), xt::newaxis(), xt::newaxis(), - xt::all()); + chi_delayed = + xt::view(temp_chi, xt::all(), xt::newaxis(), xt::newaxis(), xt::all()); // Get nu-fission xt::xtensor temp_nufiss({n_ang, n_g_}, 0.); @@ -150,7 +148,8 @@ XsData::fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, int beta_ndims = dataset_ndims(beta_dset); close_dataset(beta_dset); int ndim_target = 1; - if (!is_isotropic) ndim_target += 2; + if (!is_isotropic) + ndim_target += 2; if (beta_ndims == ndim_target) { xt::xtensor temp_beta({n_ang, n_dg_}, 0.); read_nd_vector(xsdata_grp, "beta", temp_beta, true); @@ -160,8 +159,8 @@ XsData::fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, // Set delayed_nu_fission as beta * nu_fission delayed_nu_fission = - xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis()) * - xt::view(temp_nufiss, xt::all(), xt::newaxis(), xt::all()); + xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis()) * + xt::view(temp_nufiss, xt::all(), xt::newaxis(), xt::all()); } else if (beta_ndims == ndim_target + 1) { xt::xtensor temp_beta({n_ang, n_dg_, n_g_}, 0.); read_nd_vector(xsdata_grp, "beta", temp_beta, true); @@ -170,13 +169,12 @@ XsData::fission_vector_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, prompt_nu_fission = temp_nufiss * (1. - xt::sum(temp_beta, {1})); // Set delayed_nu_fission as beta * nu_fission - delayed_nu_fission = temp_beta * - xt::view(temp_nufiss, xt::all(), xt::newaxis(), xt::all()); + delayed_nu_fission = + temp_beta * xt::view(temp_nufiss, xt::all(), xt::newaxis(), xt::all()); } } -void -XsData::fission_vector_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) +void XsData::fission_vector_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) { // Data is provided separately as prompt + delayed nu-fission and chi @@ -192,23 +190,21 @@ XsData::fission_vector_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) read_nd_vector(xsdata_grp, "chi-delayed", temp_chi_d, true); // Normalize chi by summing over the outgoing groups for each incoming angle - temp_chi_d /= xt::view(xt::sum(temp_chi_d, {2}), - xt::all(), xt::all(), xt::newaxis()); + temp_chi_d /= + xt::view(xt::sum(temp_chi_d, {2}), xt::all(), xt::all(), xt::newaxis()); - // Now assign the prompt and delayed chis by replicating for each incoming group + // Now assign the prompt and delayed chis by replicating for each incoming + // group chi_prompt = xt::view(temp_chi_p, xt::all(), xt::newaxis(), xt::all()); - chi_delayed = xt::view(temp_chi_d, xt::all(), xt::all(), xt::newaxis(), - xt::all()); + chi_delayed = + xt::view(temp_chi_d, xt::all(), xt::all(), xt::newaxis(), xt::all()); // Get prompt and delayed nu-fission directly - read_nd_vector(xsdata_grp, "prompt-nu-fission", prompt_nu_fission, - true); - read_nd_vector(xsdata_grp, "delayed-nu-fission", - delayed_nu_fission, true); + read_nd_vector(xsdata_grp, "prompt-nu-fission", prompt_nu_fission, true); + read_nd_vector(xsdata_grp, "delayed-nu-fission", delayed_nu_fission, true); } -void -XsData::fission_vector_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) +void XsData::fission_vector_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) { // No beta is provided and there is no prompt/delay distinction. // Therefore, the code only considers the data as prompt. @@ -229,8 +225,8 @@ XsData::fission_vector_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) //============================================================================== -void -XsData::fission_matrix_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic) +void XsData::fission_matrix_beta_from_hdf5( + hid_t xsdata_grp, size_t n_ang, bool is_isotropic) { // Data is provided as nu-fission and chi with a beta for delayed info @@ -243,7 +239,8 @@ XsData::fission_matrix_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_is int beta_ndims = dataset_ndims(beta_dset); close_dataset(beta_dset); int ndim_target = 1; - if (!is_isotropic) ndim_target += 2; + if (!is_isotropic) + ndim_target += 2; if (beta_ndims == ndim_target) { xt::xtensor temp_beta({n_ang, n_dg_}, 0.); read_nd_vector(xsdata_grp, "beta", temp_beta, true); @@ -256,19 +253,20 @@ XsData::fission_matrix_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_is prompt_nu_fission = xt::sum(temp_matrix, {2}) * (1. - temp_beta_sum); // Store chi-prompt - chi_prompt = xt::view(1.0 - temp_beta_sum, xt::all(), xt::newaxis(), - xt::newaxis()) * temp_matrix; + chi_prompt = + xt::view(1.0 - temp_beta_sum, xt::all(), xt::newaxis(), xt::newaxis()) * + temp_matrix; // delayed_nu_fission is the sum of this matrix over outgoing groups and // multiplied by beta delayed_nu_fission = - xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis()) * - xt::view(xt::sum(temp_matrix, {2}), xt::all(), xt::newaxis(), xt::all()); + xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis()) * + xt::view(xt::sum(temp_matrix, {2}), xt::all(), xt::newaxis(), xt::all()); // Store chi-delayed chi_delayed = - xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis(), xt::newaxis()) * - xt::view(temp_matrix, xt::all(), xt::newaxis(), xt::all(), xt::all()); + xt::view(temp_beta, xt::all(), xt::all(), xt::newaxis(), xt::newaxis()) * + xt::view(temp_matrix, xt::all(), xt::newaxis(), xt::all(), xt::all()); } else if (beta_ndims == ndim_target + 1) { xt::xtensor temp_beta({n_ang, n_dg_, n_g_}, 0.); @@ -282,30 +280,30 @@ XsData::fission_matrix_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_is prompt_nu_fission = xt::sum(temp_matrix, {2}) * (1. - temp_beta_sum); // Store chi-prompt - chi_prompt = xt::view(1.0 - temp_beta_sum, xt::all(), xt::all(), - xt::newaxis()) * temp_matrix; + chi_prompt = + xt::view(1.0 - temp_beta_sum, xt::all(), xt::all(), xt::newaxis()) * + temp_matrix; // delayed_nu_fission is the sum of this matrix over outgoing groups and // multiplied by beta - delayed_nu_fission = temp_beta * - xt::view(xt::sum(temp_matrix, {2}), xt::all(), xt::newaxis(), xt::all()); + delayed_nu_fission = temp_beta * xt::view(xt::sum(temp_matrix, {2}), + xt::all(), xt::newaxis(), xt::all()); // Store chi-delayed chi_delayed = - xt::view(temp_beta, xt::all(), xt::all(), xt::all(), xt::newaxis()) * - xt::view(temp_matrix, xt::all(), xt::newaxis(), xt::all(), xt::all()); + xt::view(temp_beta, xt::all(), xt::all(), xt::all(), xt::newaxis()) * + xt::view(temp_matrix, xt::all(), xt::newaxis(), xt::all(), xt::all()); } - //Normalize both chis - chi_prompt /= xt::view(xt::sum(chi_prompt, {2}), - xt::all(), xt::all(), xt::newaxis()); + // Normalize both chis + chi_prompt /= + xt::view(xt::sum(chi_prompt, {2}), xt::all(), xt::all(), xt::newaxis()); - chi_delayed /= xt::view(xt::sum(chi_delayed, {3}), - xt::all(), xt::all(), xt::all(), xt::newaxis()); + chi_delayed /= xt::view( + xt::sum(chi_delayed, {3}), xt::all(), xt::all(), xt::all(), xt::newaxis()); } -void -XsData::fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) +void XsData::fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) { // Data is provided separately as prompt + delayed nu-fission and chi @@ -319,7 +317,7 @@ XsData::fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) // chi_prompt is this matrix but normalized over outgoing groups, which we // have already stored in prompt_nu_fission chi_prompt = temp_matrix_p / - xt::view(prompt_nu_fission, xt::all(), xt::all(), xt::newaxis()); + xt::view(prompt_nu_fission, xt::all(), xt::all(), xt::newaxis()); // Get the delayed nu-fission matrix xt::xtensor temp_matrix_d({n_ang, n_dg_, n_g_, n_g_}, 0.); @@ -330,12 +328,11 @@ XsData::fission_matrix_no_beta_from_hdf5(hid_t xsdata_grp, size_t n_ang) // chi_prompt is this matrix but normalized over outgoing groups, which we // have already stored in prompt_nu_fission - chi_delayed = temp_matrix_d / - xt::view(delayed_nu_fission, xt::all(), xt::all(), xt::all(), xt::newaxis()); + chi_delayed = temp_matrix_d / xt::view(delayed_nu_fission, xt::all(), + xt::all(), xt::all(), xt::newaxis()); } -void -XsData::fission_matrix_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) +void XsData::fission_matrix_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) { // No beta is provided and there is no prompt/delay distinction. // Therefore, the code only considers the data as prompt. @@ -349,14 +346,14 @@ XsData::fission_matrix_no_delayed_from_hdf5(hid_t xsdata_grp, size_t n_ang) // chi_prompt is this matrix but normalized over outgoing groups, which we // have already stored in prompt_nu_fission - chi_prompt = temp_matrix / xt::view(prompt_nu_fission, xt::all(), xt::all(), - xt::newaxis()); + chi_prompt = temp_matrix / + xt::view(prompt_nu_fission, xt::all(), xt::all(), xt::newaxis()); } //============================================================================== -void -XsData::fission_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic) +void XsData::fission_from_hdf5( + hid_t xsdata_grp, size_t n_ang, bool is_isotropic) { // Get the fission and kappa_fission data xs; these are optional read_nd_vector(xsdata_grp, "fission", fission); @@ -397,9 +394,9 @@ XsData::fission_from_hdf5(hid_t xsdata_grp, size_t n_ang, bool is_isotropic) //============================================================================== -void -XsData::scatter_from_hdf5(hid_t xsdata_grp, size_t n_ang, AngleDistributionType scatter_format, - AngleDistributionType final_scatter_format, int order_data) +void XsData::scatter_from_hdf5(hid_t xsdata_grp, size_t n_ang, + AngleDistributionType scatter_format, + AngleDistributionType final_scatter_format, int order_data) { if (!object_exists(xsdata_grp, "scatter_data")) { fatal_error("Must provide scatter_data group!"); @@ -487,12 +484,11 @@ XsData::scatter_from_hdf5(hid_t xsdata_grp, size_t n_ang, AngleDistributionType xt::xtensor in_gmin = xt::view(gmin, a, xt::all()); xt::xtensor in_gmax = xt::view(gmax, a, xt::all()); - legendre_scatt.init(in_gmin, in_gmax, - temp_mult[a], input_scatt[a]); + legendre_scatt.init(in_gmin, in_gmax, temp_mult[a], input_scatt[a]); // Now create a tabular version of legendre_scatt - convert_legendre_to_tabular(legendre_scatt, - *static_cast(scatter[a].get())); + convert_legendre_to_tabular( + legendre_scatt, *static_cast(scatter[a].get())); scatter_format = final_scatter_format; } @@ -515,7 +511,8 @@ void XsData::combine( // Combine the non-scattering data for (size_t i = 0; i < those_xs.size(); i++) { XsData* that = those_xs[i]; - if (!equiv(*that)) fatal_error("Cannot combine the XsData objects!"); + if (!equiv(*that)) + fatal_error("Cannot combine the XsData objects!"); double scalar = scalars[i]; total += scalar * that->total; absorption += scalar * that->absorption; @@ -529,13 +526,13 @@ void XsData::combine( fission += scalar * that->fission; delayed_nu_fission += scalar * that->delayed_nu_fission; chi_prompt += scalar * - xt::view(xt::sum(that->prompt_nu_fission, {1}), - xt::all(), xt::newaxis(), xt::newaxis()) * - that->chi_prompt; + xt::view(xt::sum(that->prompt_nu_fission, {1}), xt::all(), + xt::newaxis(), xt::newaxis()) * + that->chi_prompt; chi_delayed += scalar * - xt::view(xt::sum(that->delayed_nu_fission, {2}), - xt::all(), xt::all(), xt::newaxis(), xt::newaxis()) * - that->chi_delayed; + xt::view(xt::sum(that->delayed_nu_fission, {2}), xt::all(), + xt::all(), xt::newaxis(), xt::newaxis()) * + that->chi_delayed; } decay_rate += scalar * that->decay_rate; } @@ -544,8 +541,8 @@ void XsData::combine( // azimuthal angle and delayed group (for chi_delayed) chi_prompt /= xt::view(xt::sum(chi_prompt, {2}), xt::all(), xt::all(), xt::newaxis()); - chi_delayed /= xt::view(xt::sum(chi_delayed, {3}), xt::all(), xt::all(), - xt::all(), xt::newaxis()); + chi_delayed /= xt::view( + xt::sum(chi_delayed, {3}), xt::all(), xt::all(), xt::all(), xt::newaxis()); // Allow the ScattData object to combine itself for (size_t a = 0; a < total.shape()[0]; a++) { @@ -562,10 +559,9 @@ void XsData::combine( //============================================================================== -bool -XsData::equiv(const XsData& that) +bool XsData::equiv(const XsData& that) { return (absorption.shape() == that.absorption.shape()); } -} //namespace openmc +} // namespace openmc