refactor(reaction): refactored to an abstract reaction class in prep for weak reactions

This commit is contained in:
2025-08-14 13:33:46 -04:00
parent d920a55ba6
commit 0b77f2e269
81 changed files with 1050041 additions and 913 deletions

View File

@@ -215,9 +215,9 @@ namespace gridfire {
*
* @return Reference to the LogicalReactionSet containing all reactions.
*/
[[nodiscard]] virtual const reaction::LogicalReactionSet& getNetworkReactions() const = 0;
[[nodiscard]] virtual const reaction::ReactionSet& getNetworkReactions() const = 0;
virtual void setNetworkReactions(const reaction::LogicalReactionSet& reactions) = 0;
virtual void setNetworkReactions(const reaction::ReactionSet& reactions) = 0;
/**
* @brief Compute timescales for all species in the network.
@@ -305,7 +305,7 @@ namespace gridfire {
* engine's internal representation. It is useful for accessing species
* data efficiently.
*/
[[nodiscard]] virtual int getSpeciesIndex(const fourdst::atomic::Species &species) const = 0;
[[nodiscard]] virtual size_t getSpeciesIndex(const fourdst::atomic::Species &species) const = 0;
/**
* @brief Map a NetIn object to a vector of molar abundances.
@@ -357,6 +357,7 @@ namespace gridfire {
*/
virtual void rebuild(const fourdst::composition::Composition& comp, BuildDepthType depth) {
throw std::logic_error("Setting network depth not supported by this engine.");
// ReSharper disable once CppDFAUnreachableCode
}
};

View File

@@ -25,16 +25,10 @@
#include "cppad/utility/sparse_rc.hpp"
#include "cppad/speed/sparse_jac_fun.hpp"
#include "procedures/priming.h"
#include "quill/LogMacros.h"
// PERF: The function getNetReactionStoichiometry returns a map of species to their stoichiometric coefficients for a given reaction.
// this makes extra copies of the species, which is not ideal and could be optimized further.
// Even more relevant is the member m_reactionIDMap which makes copies of a REACLIBReaction for each reaction ID.
// REACLIBReactions are quite large data structures, so this could be a performance bottleneck.
// static bool isF17 = false;
namespace gridfire {
/**
* @brief Alias for CppAD AD type for double precision.
@@ -128,7 +122,7 @@ namespace gridfire {
* This constructor uses the given set of reactions to construct the
* reaction network.
*/
explicit GraphEngine(const reaction::LogicalReactionSet &reactions);
explicit GraphEngine(const reaction::ReactionSet &reactions);
/**
* @brief Calculates the right-hand side (dY/dt) and energy generation rate.
@@ -212,9 +206,9 @@ namespace gridfire {
* @brief Gets the set of logical reactions in the network.
* @return Reference to the LogicalReactionSet containing all reactions.
*/
[[nodiscard]] const reaction::LogicalReactionSet& getNetworkReactions() const override;
[[nodiscard]] const reaction::ReactionSet& getNetworkReactions() const override;
void setNetworkReactions(const reaction::LogicalReactionSet& reactions) override;
void setNetworkReactions(const reaction::ReactionSet& reactions) override;
/**
* @brief Gets an entry from the previously generated Jacobian matrix.
@@ -394,6 +388,8 @@ namespace gridfire {
*
* @param reaction The reaction for which to calculate the reverse rate.
* @param T9 Temperature in units of 10^9 K.
* @param rho
* @param Y
* @return Reverse rate for the reaction (e.g., mol/g/s).
*
* This method computes the reverse rate based on the forward rate and
@@ -401,7 +397,7 @@ namespace gridfire {
*/
[[nodiscard]] double calculateReverseRate(
const reaction::Reaction &reaction,
double T9
double T9, double rho, const std::vector<double> &Y
) const;
/**
@@ -426,7 +422,7 @@ namespace gridfire {
[[nodiscard]] double calculateReverseRateTwoBodyDerivative(
const reaction::Reaction &reaction,
const double T9,
const double reverseRate
double rho, const std::vector<double> &Y, const double reverseRate
) const;
/**
@@ -458,8 +454,8 @@ namespace gridfire {
* This method returns the index of the given species in the network's
* species vector. If the species is not found, it returns -1.
*/
[[nodiscard]] int getSpeciesIndex(
const fourdst::atomic::Species& species
[[nodiscard]] size_t getSpeciesIndex(
const fourdst::atomic::Species &species
) const override;
/**
@@ -574,7 +570,7 @@ namespace gridfire {
constants m_constants;
reaction::LogicalReactionSet m_reactions; ///< Set of REACLIB reactions in the network.
reaction::ReactionSet m_reactions; ///< Set of REACLIB reactions in the network.
std::unordered_map<std::string_view, reaction::Reaction*> m_reactionIDMap; ///< Map from reaction ID to REACLIBReaction. //PERF: This makes copies of REACLIBReaction and could be a performance bottleneck.
std::vector<fourdst::atomic::Species> m_networkSpecies; ///< Vector of unique species in the network.
@@ -654,7 +650,7 @@ namespace gridfire {
*
* @throws std::runtime_error If there are no species in the network.
*/
void recordADTape();
void recordADTape() const;
void collectAtomicReverseRateAtomicBases();
@@ -708,7 +704,7 @@ namespace gridfire {
std::vector<T> screeningFactors,
std::vector<T> Y,
size_t reactionIndex,
const reaction::LogicalReaction &reaction
const reaction::Reaction &reaction
) const;
/**
@@ -776,7 +772,7 @@ namespace gridfire {
std::vector<T> screeningFactors,
std::vector<T> Y,
size_t reactionIndex,
const reaction::LogicalReaction &reaction
const reaction::Reaction &reaction
) const {
if (!m_useReverseReactions) {
return static_cast<T>(0.0); // If reverse reactions are not used, return zero
@@ -800,7 +796,7 @@ namespace gridfire {
}
} else {
// A,B If not calling with an AD type, calculate the reverse rate directly
reverseRateConstant = calculateReverseRate(reaction, T9);
reverseRateConstant = calculateReverseRate(reaction, T9, 0, {});
}
// C. Get product multiplicities
@@ -888,14 +884,18 @@ namespace gridfire {
calculateMolarReactionFlow<T>(reaction, Y, T9, rho);
// 2. Calculate reverse reaction rate
T reverseMolarFlow = calculateReverseMolarReactionFlow<T>(
T9,
rho,
screeningFactors,
Y,
reactionIndex,
reaction
);
T reverseMolarFlow = static_cast<T>(0.0);
// Do not calculate reverse flow for weak reactions
if (reaction.type() == reaction::ReactionType::LOGICAL_REACLIB || reaction.type() == reaction::ReactionType::REACLIB) {
reverseMolarFlow = calculateReverseMolarReactionFlow<T>(
T9,
rho,
screeningFactors,
Y,
reactionIndex,
reaction
);
}
const T molarReactionFlow = forwardMolarReactionFlow - reverseMolarFlow; // Net molar reaction flow
@@ -930,7 +930,7 @@ namespace gridfire {
const T zero = static_cast<T>(0.0);
// --- Calculate the molar reaction rate (in units of [s^-1][cm^3(N-1)][mol^(1-N)] for N reactants) ---
const T k_reaction = reaction.calculate_rate(T9);
const T k_reaction = reaction.calculate_rate(T9, rho, Y);
// --- Cound the number of each reactant species to account for species multiplicity ---
std::unordered_map<std::string, int> reactant_counts;

View File

@@ -30,7 +30,7 @@ namespace gridfire {
* @return A LogicalReactionSet encapsulating the collected reactions for graph-based engines.
* @throws std::logic_error If the resolved network depth is zero (no reactions can be collected).
*/
reaction::LogicalReactionSet build_reaclib_nuclear_network(
reaction::ReactionSet build_reaclib_nuclear_network(
const fourdst::composition::Composition &composition,
BuildDepthType maxLayers = NetworkBuildDepth::Full,
bool reverse = false

View File

@@ -3,13 +3,8 @@
#include "gridfire/engine/engine_abstract.h"
#include "gridfire/network.h"
#include "fourdst/composition/composition.h"
#include "fourdst/composition/atomicSpecies.h"
#include <map>
#include <ranges>
#include <sstream>
namespace gridfire {
@@ -30,7 +25,7 @@ namespace gridfire {
* @return PrimingReport encapsulating the results of the priming operation.
*/
PrimingReport primeNetwork(
const NetIn&,
const NetIn& netIn,
DynamicEngine& engine
);

View File

@@ -9,7 +9,6 @@
#include "fourdst/config/config.h"
#include "fourdst/logging/logging.h"
#include "gridfire/engine/procedures/priming.h"
#include "gridfire/engine/procedures/construction.h"
#include "quill/Logger.h"
@@ -203,9 +202,9 @@ namespace gridfire {
*
* @return Reference to the LogicalReactionSet containing all active reactions.
*/
[[nodiscard]] const reaction::LogicalReactionSet& getNetworkReactions() const override;
[[nodiscard]] const reaction::ReactionSet& getNetworkReactions() const override;
void setNetworkReactions(const reaction::LogicalReactionSet& reactions) override;
void setNetworkReactions(const reaction::ReactionSet& reactions) override;
/**
* @brief Computes timescales for all active species in the network.
@@ -270,7 +269,7 @@ namespace gridfire {
*/
[[nodiscard]] screening::ScreeningType getScreeningModel() const override;
[[nodiscard]] int getSpeciesIndex(const fourdst::atomic::Species &species) const override;
[[nodiscard]] size_t getSpeciesIndex(const fourdst::atomic::Species &species) const override;
[[nodiscard]] std::vector<double> mapNetInToMolarAbundanceVector(const NetIn &netIn) const override;
@@ -289,7 +288,7 @@ namespace gridfire {
/** @brief The set of species that are currently active in the network. */
std::vector<fourdst::atomic::Species> m_activeSpecies;
/** @brief The set of reactions that are currently active in the network. */
reaction::LogicalReactionSet m_activeReactions;
reaction::ReactionSet m_activeReactions;
/** @brief A map from the indices of the active species to the indices of the corresponding species in the full network. */
std::vector<size_t> m_speciesIndexMap;
@@ -304,7 +303,7 @@ namespace gridfire {
* @brief A struct to hold a reaction and its flow rate.
*/
struct ReactionFlow {
const reaction::LogicalReaction* reactionPtr;
const reaction::Reaction* reactionPtr;
double flowRate;
};
private:
@@ -442,20 +441,20 @@ namespace gridfire {
* 4. A reaction is kept if its `flowRate` is greater than the `absoluteCullingThreshold`.
* 5. The pointers to the kept reactions are stored in a vector and returned.
*/
[[nodiscard]] std::vector<const reaction::LogicalReaction*> cullReactionsByFlow(
[[nodiscard]] std::vector<const reaction::Reaction*> cullReactionsByFlow(
const std::vector<ReactionFlow>& allFlows,
const std::unordered_set<fourdst::atomic::Species>& reachableSpecies,
const std::vector<double>& Y_full,
double maxFlow
) const;
typedef std::pair<std::unordered_set<const reaction::LogicalReaction*>, std::unordered_set<fourdst::atomic::Species>> RescueSet;
typedef std::pair<std::unordered_set<const reaction::Reaction*>, std::unordered_set<fourdst::atomic::Species>> RescueSet;
[[nodiscard]] RescueSet rescueEdgeSpeciesDestructionChannel(
const std::vector<double>& Y_full,
const double T9,
const double rho,
const std::vector<fourdst::atomic::Species>& activeSpecies,
const reaction::LogicalReactionSet& activeReactions
const reaction::ReactionSet& activeReactions
) const;
/**
* @brief Finalizes the set of active species and reactions.
@@ -473,7 +472,7 @@ namespace gridfire {
* - `m_activeSpecies` is sorted by atomic mass.
*/
void finalizeActiveSet(
const std::vector<const reaction::LogicalReaction*>& finalReactions
const std::vector<const reaction::Reaction*>& finalReactions
);
};
}

View File

@@ -16,14 +16,14 @@ namespace gridfire{
class DefinedEngineView : public DynamicEngine, public EngineView<DynamicEngine> {
public:
DefinedEngineView(const std::vector<std::string>& peNames, DynamicEngine& baseEngine);
const DynamicEngine& getBaseEngine() const override;
[[nodiscard]] const DynamicEngine& getBaseEngine() const override;
// --- Engine Interface ---
/**
* @brief Gets the list of active species in the network defined by the file.
* @return A const reference to the vector of active species.
*/
const std::vector<fourdst::atomic::Species>& getNetworkSpecies() const override;
[[nodiscard]] const std::vector<fourdst::atomic::Species>& getNetworkSpecies() const override;
// --- DynamicEngine Interface ---
/**
@@ -37,7 +37,7 @@ namespace gridfire{
*
* @throws std::runtime_error If the view is stale (i.e., `update()` has not been called after `setNetworkFile()`).
*/
std::expected<StepDerivatives<double>, expectations::StaleEngineError> calculateRHSAndEnergy(
[[nodiscard]] std::expected<StepDerivatives<double>, expectations::StaleEngineError> calculateRHSAndEnergy(
const std::vector<double>& Y_defined,
const double T9,
const double rho
@@ -66,7 +66,7 @@ namespace gridfire{
* @throws std::runtime_error If the view is stale.
* @throws std::out_of_range If an index is out of bounds.
*/
double getJacobianMatrixEntry(
[[nodiscard]] double getJacobianMatrixEntry(
const int i_defined,
const int j_defined
) const override;
@@ -86,7 +86,7 @@ namespace gridfire{
* @throws std::runtime_error If the view is stale.
* @throws std::out_of_range If an index is out of bounds.
*/
int getStoichiometryMatrixEntry(
[[nodiscard]] int getStoichiometryMatrixEntry(
const int speciesIndex_defined,
const int reactionIndex_defined
) const override;
@@ -101,7 +101,7 @@ namespace gridfire{
*
* @throws std::runtime_error If the view is stale or if the reaction is not in the active set.
*/
double calculateMolarReactionFlow(
[[nodiscard]] double calculateMolarReactionFlow(
const reaction::Reaction& reaction,
const std::vector<double>& Y_defined,
const double T9,
@@ -114,9 +114,9 @@ namespace gridfire{
*
* @throws std::runtime_error If the view is stale.
*/
const reaction::LogicalReactionSet& getNetworkReactions() const override;
[[nodiscard]] const reaction::ReactionSet& getNetworkReactions() const override;
void setNetworkReactions(const reaction::LogicalReactionSet& reactions) override;
void setNetworkReactions(const reaction::ReactionSet& reactions) override;
/**
* @brief Computes timescales for all active species in the network.
*
@@ -168,7 +168,7 @@ namespace gridfire{
*/
[[nodiscard]] screening::ScreeningType getScreeningModel() const override;
[[nodiscard]] int getSpeciesIndex(const fourdst::atomic::Species &species) const override;
[[nodiscard]] size_t getSpeciesIndex(const fourdst::atomic::Species &species) const override;
[[nodiscard]] std::vector<double> mapNetInToMolarAbundanceVector(const NetIn &netIn) const override;
@@ -181,7 +181,7 @@ namespace gridfire{
///< Active species in the defined engine.
std::vector<fourdst::atomic::Species> m_activeSpecies;
///< Active reactions in the defined engine.
reaction::LogicalReactionSet m_activeReactions;
reaction::ReactionSet m_activeReactions;
///< Maps indices of active species to indices in the full network.
std::vector<size_t> m_speciesIndexMap;
@@ -198,7 +198,7 @@ namespace gridfire{
*
* @throws std::runtime_error If an active species is not found in the base engine's species list.
*/
std::vector<size_t> constructSpeciesIndexMap() const;
[[nodiscard]] std::vector<size_t> constructSpeciesIndexMap() const;
/**
* @brief Constructs the reaction index map.
@@ -210,7 +210,7 @@ namespace gridfire{
*
* @throws std::runtime_error If an active reaction is not found in the base engine's reaction list.
*/
std::vector<size_t> constructReactionIndexMap() const;
[[nodiscard]] std::vector<size_t> constructReactionIndexMap() const;
/**
* @brief Maps a vector of culled abundances to a vector of full abundances.
@@ -219,7 +219,7 @@ namespace gridfire{
* @return A vector of abundances for the full network, with the abundances of the active
* species copied from the defined vector.
*/
std::vector<double> mapViewToFull(const std::vector<double>& defined) const;
[[nodiscard]] std::vector<double> mapViewToFull(const std::vector<double>& defined) const;
/**
* @brief Maps a vector of full abundances to a vector of culled abundances.
@@ -228,7 +228,7 @@ namespace gridfire{
* @return A vector of abundances for the active species, with the abundances of the active
* species copied from the full vector.
*/
std::vector<double> mapFullToView(const std::vector<double>& full) const;
[[nodiscard]] std::vector<double> mapFullToView(const std::vector<double>& full) const;
/**
* @brief Maps a culled species index to a full species index.
@@ -238,7 +238,7 @@ namespace gridfire{
*
* @throws std::out_of_range If the defined index is out of bounds for the species index map.
*/
size_t mapViewToFullSpeciesIndex(size_t definedSpeciesIndex) const;
[[nodiscard]] size_t mapViewToFullSpeciesIndex(size_t definedSpeciesIndex) const;
/**
* @brief Maps a culled reaction index to a full reaction index.
@@ -248,7 +248,7 @@ namespace gridfire{
*
* @throws std::out_of_range If the defined index is out of bounds for the reaction index map.
*/
size_t mapViewToFullReactionIndex(size_t definedReactionIndex) const;
[[nodiscard]] size_t mapViewToFullReactionIndex(size_t definedReactionIndex) const;
void validateNetworkState() const;
@@ -263,8 +263,8 @@ namespace gridfire{
const std::string& fileName,
const io::NetworkFileParser& parser
);
std::string getNetworkFile() const { return m_fileName; }
const io::NetworkFileParser& getParser() const { return m_parser; }
[[nodiscard]] std::string getNetworkFile() const { return m_fileName; }
[[nodiscard]] const io::NetworkFileParser& getParser() const { return m_parser; }
private:
using Config = fourdst::config::Config;
using LogManager = fourdst::logging::LogManager;

View File

@@ -86,7 +86,7 @@ namespace gridfire {
* This method combines the hashes of the binned temperature, density, and
* each species abundance. The `bin()` static method is used for discretization.
*/
size_t hash() const;
[[nodiscard]] size_t hash() const;
/**
* @brief Converts a value to a discrete bin based on a tolerance.
@@ -110,20 +110,18 @@ namespace gridfire {
}
// Needs to be in this order (splitting gridfire namespace up) to avoid some issues with forward declarations and the () operator.
namespace std {
template <>
struct hash<gridfire::QSECacheKey> {
/**
template <>
struct std::hash<gridfire::QSECacheKey> {
/**
* @brief Computes the hash of a QSECacheKey for use in `std::unordered_map`.
* @param key The QSECacheKey to hash.
* @return The pre-computed hash value of the key.
*/
size_t operator()(const gridfire::QSECacheKey& key) const noexcept {
// The hash is pre-computed, so we just return it.
return key.m_hash;
}
};
} // namespace std
size_t operator()(const gridfire::QSECacheKey& key) const noexcept {
// The hash is pre-computed, so we just return it.
return key.m_hash;
}
}; // namespace std
namespace gridfire {
/**
@@ -356,7 +354,7 @@ namespace gridfire {
* @return A const reference to the `LogicalReactionSet` from the base engine,
* containing all reactions in the full network.
*/
[[nodiscard]] const reaction::LogicalReactionSet & getNetworkReactions() const override;
[[nodiscard]] const reaction::ReactionSet & getNetworkReactions() const override;
/**
* @brief Sets the set of logical reactions in the network.
@@ -375,7 +373,7 @@ namespace gridfire {
* @throws exceptions::UnableToSetNetworkReactionsError Always.
*/
void setNetworkReactions(
const reaction::LogicalReactionSet &reactions
const reaction::ReactionSet &reactions
) override;
/**
@@ -615,7 +613,7 @@ namespace gridfire {
* @par How
* This method delegates directly to the base engine's `getSpeciesIndex()`.
*/
[[nodiscard]] int getSpeciesIndex(const fourdst::atomic::Species &species) const override;
[[nodiscard]] size_t getSpeciesIndex(const fourdst::atomic::Species &species) const override;
/**
* @brief Maps a `NetIn` struct to a molar abundance vector for the full network.
@@ -841,12 +839,12 @@ namespace gridfire {
* @brief Gets the number of output values from the functor (size of the residual vector).
* @return The number of algebraic species being solved.
*/
[[nodiscard]] int values() const { return m_qse_solve_indices.size(); }
[[nodiscard]] size_t values() const { return m_qse_solve_indices.size(); }
/**
* @brief Gets the number of input values to the functor (size of the variable vector).
* @return The number of algebraic species being solved.
*/
[[nodiscard]] int inputs() const { return m_qse_solve_indices.size(); }
[[nodiscard]] size_t inputs() const { return m_qse_solve_indices.size(); }
/**
* @brief Evaluates the functor's residual vector `f_qse = dY_alg/dt`.
@@ -1038,25 +1036,6 @@ namespace gridfire {
double rho
) const;
/**
* @brief Builds a connectivity graph from a set of fast reaction indices.
*
* @param fast_reaction_indices A set of indices for reactions considered "fast".
* @return An unordered map representing the adjacency list of the connectivity graph,
* where keys are species indices and values are vectors of connected species indices.
*
* @par Purpose
* To represent the reaction pathways among a subset of reactions.
*
* @par How
* It iterates through the specified fast reactions. For each reaction, it creates
* a two-way edge in the graph between every reactant and every product, signifying
* that mass can flow between them.
*/
std::unordered_map<size_t, std::vector<size_t>> buildConnectivityGraph(
const std::unordered_set<size_t> &fast_reaction_indices
) const;
/**
* @brief Validates candidate QSE groups using flux analysis.
*

View File

@@ -3,11 +3,9 @@
#include "gridfire/engine/engine_abstract.h"
#include "gridfire/engine/views/engine_defined.h"
#include "gridfire/network.h"
#include "fourdst/logging/logging.h"
#include "fourdst/composition/atomicSpecies.h"
#include "fourdst/composition/composition.h"
#include "quill/Logger.h"
@@ -66,7 +64,7 @@ namespace gridfire {
* @return Vector of reaction name strings containing the priming species.
* @throws std::runtime_error If no reactions involve the priming species.
*/
std::vector<std::string> constructPrimingReactionSet(
[[nodiscard]] std::vector<std::string> constructPrimingReactionSet(
const fourdst::atomic::Species& primingSpecies,
const DynamicEngine& baseEngine
) const;

View File

@@ -0,0 +1,11 @@
#pragma once
#include "fourdst/plugin/plugin.h"
class SolverPluginInterface : public fourdst::plugin::PluginBase {
public:
using PluginBase::PluginBase;
~SolverPluginInterface() override = default;
virtual void log_time(double t, double dt) = 0;
};

View File

@@ -28,8 +28,6 @@
#include "fourdst/composition/composition.h"
#include "fourdst/constants/const.h"
#include "gridfire/reaction/reaction.h"
#include "quill/Logger.h"
#include <unordered_map>

View File

@@ -40,7 +40,7 @@ namespace gridfire::partition {
* @return Dimensionless partition function value = 2*spin + 1.
* @throws std::out_of_range If the isotope key is not found in m_ground_state_spin.
+ */
double evaluate(
[[nodiscard]] double evaluate(
const int z,
const int a,
const double T9
@@ -57,7 +57,7 @@ namespace gridfire::partition {
* @return Zero.
* @throws std::out_of_range If the isotope key is not found.
+ */
double evaluateDerivative(
[[nodiscard]] double evaluateDerivative(
const int z,
const int a,
const double T9
@@ -70,7 +70,7 @@ namespace gridfire::partition {
* @return True if m_ground_state_spin contains the key; false otherwise.
* @post No side effects.
+ */
bool supports(
[[nodiscard]] bool supports(
const int z,
const int a
) const override;
@@ -79,13 +79,13 @@ namespace gridfire::partition {
* @return The string literal "GroundState".
* @post No side effects.
+ */
std::string type() const override { return "GroundState"; }
[[nodiscard]] std::string type() const override { return "GroundState"; }
/**
* @brief Create a deep copy of this partition function.
* @return Unique_ptr to a new GroundStatePartitionFunction cloned from this object.
* @post Caller owns the returned instance.
+ */
std::unique_ptr<PartitionFunction> clone() const override {
[[nodiscard]] std::unique_ptr<PartitionFunction> clone() const override {
return std::make_unique<GroundStatePartitionFunction>(*this);
}
private:
@@ -94,15 +94,13 @@ namespace gridfire::partition {
/**
* @brief Generate a unique lookup key for an isotope.
+ *
* Combines atomic number z and mass number a into a single integer.
* Combines atomic number z and mass number an into a single integer.
* @param z Proton number of the isotope.
* @param a Mass number of the isotope; should be < 1000 to avoid collisions.
* @pre a < 1000.
* @return Integer key = z * 1000 + a.
+ */
static constexpr int make_key(
const int z,
const int a);
static constexpr int make_key(int z, int a);
};
}

View File

@@ -5,10 +5,8 @@
#include "fourdst/logging/logging.h"
#include <string>
#include <vector>
#include <unordered_map>
#include <array>
#include <utility>
#include <memory>
namespace gridfire::partition {
@@ -45,7 +43,7 @@ namespace gridfire::partition {
* @post No side effects.
* @throws std::out_of_range If isotope key not found in m_partitionData.
*/
double evaluate(int z, int a, double T9) const override;
[[nodiscard]] double evaluate(int z, int a, double T9) const override;
/**
* @brief Evaluate temperature derivative of partition function.
*
@@ -58,7 +56,7 @@ namespace gridfire::partition {
* @post No side effects.
* @throws std::out_of_range If isotope data is missing.
*/
double evaluateDerivative(int z, int a, double T9) const override;
[[nodiscard]] double evaluateDerivative(int z, int a, double T9) const override;
/**
* @brief Check if partition data exists for given isotope.
* @param z Atomic number.
@@ -66,19 +64,19 @@ namespace gridfire::partition {
* @return true if data available; false otherwise.
* @post No side effects.
*/
bool supports(int z, int a) const override;
[[nodiscard]] bool supports(int z, int a) const override;
/**
* @brief Get type identifier for this partition function.
* @return Literal string "RauscherThielemann".
* @post No side effects.
*/
std::string type() const override { return "RauscherThielemann"; }
[[nodiscard]] std::string type() const override { return "RauscherThielemann"; }
/**
* @brief Clone this partition function instance.
* @return Unique pointer to a copy of this object.
* @post Caller owns the returned object.
*/
std::unique_ptr<PartitionFunction> clone() const override {
[[nodiscard]] std::unique_ptr<PartitionFunction> clone() const override {
return std::make_unique<RauscherThielemannPartitionFunction>(*this);
}
private:
@@ -132,7 +130,7 @@ namespace gridfire::partition {
* @return IdentifiedIsotope with data reference and indices.
* @throws std::out_of_range If isotope not found in m_partitionData.
*/
IdentifiedIsotope find(int z, int a, double T9) const;
[[nodiscard]] IdentifiedIsotope find(int z, int a, double T9) const;
/**
* @brief Generate integer key for isotope (z,a).
* @param z Atomic number.

View File

@@ -1,5 +1,6 @@
#pragma once
// ReSharper disable once CppUnusedIncludeDirective
#include <cstdint>
namespace gridfire::partition::record {

View File

@@ -14,6 +14,6 @@ namespace gridfire::reaclib {
*
* @return A constant reference to the application-wide reaction set.
*/
const reaction::LogicalReactionSet& get_all_reactions();
const reaction::ReactionSet &get_all_reaclib_reactions();
} // namespace gridfire::reaclib
} // namespace gridfire::reaclib

View File

@@ -11,7 +11,6 @@
#include "cppad/cppad.hpp"
#include "xxhash64.h"
/**
* @file reaction.h
@@ -20,9 +19,14 @@
* This file contains the core data structures for handling nuclear reactions,
* including individual reactions from specific sources (`Reaction`), collections
* of reactions (`ReactionSet`), and logical reactions that aggregate rates from
* multiple sources (`LogicalReaction`, `LogicalReactionSet`).
* multiple sources (`LogicalReaclibReaction`, `LogicalReactionSet`).
*/
namespace gridfire::reaction {
enum class ReactionType {
WEAK,
REACLIB,
LOGICAL_REACLIB,
};
/**
* @struct RateCoefficientSet
* @brief Holds the seven coefficients for the REACLIB rate equation.
@@ -69,13 +73,51 @@ namespace gridfire::reaction {
* double rate = p_gamma_d.calculate_rate(0.1); // T9 = 0.1
* @endcode
*/
class Reaction {
public:
/**
* @brief Virtual destructor.
*/
virtual ~Reaction() = default;
[[nodiscard]] virtual double calculate_rate(double T9, double rho, const std::vector<double>& Y) const = 0;
[[nodiscard]] virtual CppAD::AD<double> calculate_rate(CppAD::AD<double> T9, CppAD::AD<double> rho, const std::vector<CppAD::AD<double>>& Y) const = 0;
[[nodiscard]] virtual std::string_view id() const = 0;
[[nodiscard]] virtual const std::vector<fourdst::atomic::Species>& reactants() const = 0;
[[nodiscard]] virtual const std::vector<fourdst::atomic::Species>& products() const = 0;
[[nodiscard]] virtual bool contains(const fourdst::atomic::Species& species) const = 0;
[[nodiscard]] virtual bool contains_reactant(const fourdst::atomic::Species& species) const = 0;
[[nodiscard]] virtual bool contains_product(const fourdst::atomic::Species& species) const = 0;
[[nodiscard]] virtual bool is_reverse() const = 0;
[[nodiscard]] virtual std::unordered_set<fourdst::atomic::Species> all_species() const = 0;
[[nodiscard]] virtual std::unordered_set<fourdst::atomic::Species> reactant_species() const = 0;
[[nodiscard]] virtual std::unordered_set<fourdst::atomic::Species> product_species() const = 0;
[[nodiscard]] virtual size_t num_species() const = 0;
[[nodiscard]] virtual std::unordered_map<fourdst::atomic::Species, int> stoichiometry() const = 0;
[[nodiscard]] virtual int stoichiometry(const fourdst::atomic::Species& species) const = 0;
[[nodiscard]] virtual uint64_t hash(uint64_t seed) const = 0;
[[nodiscard]] virtual double qValue() const = 0;
[[nodiscard]] virtual double calculate_forward_rate_log_derivative(double T9, double rho, const std::vector<double>& Y) const = 0;
[[nodiscard]] virtual ReactionType type() const = 0;
[[nodiscard]] virtual std::unique_ptr<Reaction> clone() const = 0;
friend std::ostream& operator<<(std::ostream& os, const Reaction& r) {
os << "Reaction(ID: " << r.id() << ")";
return os;
}
};
class ReaclibReaction : public Reaction {
public:
~ReaclibReaction() override = default;
/**
* @brief Constructs a Reaction object.
* @param id A unique identifier for the reaction.
@@ -88,7 +130,7 @@ namespace gridfire::reaction {
* @param sets The set of rate coefficients.
* @param reverse True if this is a reverse reaction rate.
*/
Reaction(
ReaclibReaction(
const std::string_view id,
const std::string_view peName,
const int chapter,
@@ -102,18 +144,22 @@ namespace gridfire::reaction {
/**
* @brief Calculates the reaction rate for a given temperature.
* @param T9 The temperature in units of 10^9 K.
* @param rho Density [Not used in this implementation].
* @param Y Molar abundances of species [Not used in this implementation].
* @return The calculated reaction rate.
*/
[[nodiscard]] virtual double calculate_rate(const double T9) const;
[[nodiscard]] double calculate_rate(double T9, double rho, const std::vector<double>& Y) const override;
/**
* @brief Calculates the reaction rate for a given temperature using CppAD types.
* @param T9 The temperature in units of 10^9 K, as a CppAD::AD<double>.
* @param rho Density, as a CppAD::AD<double> [Not used in this implementation].
* @param Y Molar abundances of species, as a vector of CppAD::AD<double> [Not used in this implementation].
* @return The calculated reaction rate, as a CppAD::AD<double>.
*/
[[nodiscard]] virtual CppAD::AD<double> calculate_rate(const CppAD::AD<double> T9) const;
[[nodiscard]] CppAD::AD<double> calculate_rate(CppAD::AD<double> T9, CppAD::AD<double> rho, const std::vector<CppAD::AD<double>>& Y) const override;
[[nodiscard]] virtual double calculate_forward_rate_log_derivative(const double T9) const;
[[nodiscard]] double calculate_forward_rate_log_derivative(double T9, double rho, const std::vector<double>& Y) const override;
/**
* @brief Gets the reaction name in (projectile, ejectile) notation.
@@ -133,6 +179,8 @@ namespace gridfire::reaction {
*/
[[nodiscard]] std::string_view sourceLabel() const { return m_sourceLabel; }
[[nodiscard]] ReactionType type() const override { return ReactionType::REACLIB; }
/**
* @brief Gets the set of rate coefficients.
* @return A const reference to the RateCoefficientSet.
@@ -144,88 +192,88 @@ namespace gridfire::reaction {
* @param species The species to check for.
* @return True if the species is involved, false otherwise.
*/
[[nodiscard]] bool contains(const fourdst::atomic::Species& species) const;
[[nodiscard]] bool contains(const fourdst::atomic::Species& species) const override;
/**
* @brief Checks if the reaction involves a given species as a reactant.
* @param species The species to check for.
* @return True if the species is a reactant, false otherwise.
*/
[[nodiscard]] bool contains_reactant(const fourdst::atomic::Species& species) const;
[[nodiscard]] bool contains_reactant(const fourdst::atomic::Species& species) const override;
/**
* @brief Checks if the reaction involves a given species as a product.
* @param species The species to check for.
* @return True if the species is a product, false otherwise.
*/
[[nodiscard]] bool contains_product(const fourdst::atomic::Species& species) const;
[[nodiscard]] bool contains_product(const fourdst::atomic::Species& species) const override;
/**
* @brief Gets a set of all unique species involved in the reaction.
* @return An unordered_set of all reactant and product species.
*/
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> all_species() const;
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> all_species() const override;
/**
* @brief Gets a set of all unique reactant species.
* @return An unordered_set of reactant species.
*/
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> reactant_species() const;
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> reactant_species() const override;
/**
* @brief Gets a set of all unique product species.
* @return An unordered_set of product species.
*/
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> product_species() const;
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> product_species() const override;
/**
* @brief Gets the number of unique species involved in the reaction.
* @return The count of unique species.
*/
[[nodiscard]] size_t num_species() const;
[[nodiscard]] size_t num_species() const override;
/**
* @brief Calculates the stoichiometric coefficient for a given species.
* @param species The species for which to find the coefficient.
* @return The stoichiometric coefficient (negative for reactants, positive for products).
*/
[[nodiscard]] int stoichiometry(const fourdst::atomic::Species& species) const;
[[nodiscard]] int stoichiometry(const fourdst::atomic::Species& species) const override;
/**
* @brief Gets a map of all species to their stoichiometric coefficients.
* @return An unordered_map from species to their integer coefficients.
*/
[[nodiscard]] std::unordered_map<fourdst::atomic::Species, int> stoichiometry() const;
[[nodiscard]] std::unordered_map<fourdst::atomic::Species, int> stoichiometry() const override;
/**
* @brief Gets the unique identifier of the reaction.
* @return The reaction ID.
*/
[[nodiscard]] std::string_view id() const { return m_id; }
[[nodiscard]] std::string_view id() const override { return m_id; }
/**
* @brief Gets the Q-value of the reaction.
* @return The Q-value in whatever units the reaction was defined in (usually MeV).
*/
[[nodiscard]] double qValue() const { return m_qValue; }
[[nodiscard]] double qValue() const override { return m_qValue; }
/**
* @brief Gets the vector of reactant species.
* @return A const reference to the vector of reactants.
*/
[[nodiscard]] const std::vector<fourdst::atomic::Species>& reactants() const { return m_reactants; }
[[nodiscard]] const std::vector<fourdst::atomic::Species>& reactants() const override { return m_reactants; }
/**
* @brief Gets the vector of product species.
* @return A const reference to the vector of products.
*/
[[nodiscard]] const std::vector<fourdst::atomic::Species>& products() const { return m_products; }
[[nodiscard]] const std::vector<fourdst::atomic::Species>& products() const override { return m_products; }
/**
* @brief Checks if this is a reverse reaction rate.
* @return True if it is a reverse rate, false otherwise.
*/
[[nodiscard]] bool is_reverse() const { return m_reverse; }
[[nodiscard]] bool is_reverse() const override { return m_reverse; }
/**
* @brief Calculates the excess energy from the mass difference of reactants and products.
@@ -238,14 +286,14 @@ namespace gridfire::reaction {
* @param other The other Reaction to compare with.
* @return True if the reaction IDs are the same.
*/
bool operator==(const Reaction& other) const { return m_id == other.m_id; }
bool operator==(const ReaclibReaction& other) const { return m_id == other.m_id; }
/**
* @brief Compares this reaction with another for inequality.
* @param other The other Reaction to compare with.
* @return True if the reactions are not equal.
*/
bool operator!=(const Reaction& other) const { return !(*this == other); }
bool operator!=(const ReaclibReaction& other) const { return !(*this == other); }
/**
* @brief Computes a hash for the reaction based on its ID.
@@ -253,10 +301,12 @@ namespace gridfire::reaction {
* @return A 64-bit hash value.
* @details Uses the XXHash64 algorithm on the reaction's ID string.
*/
[[nodiscard]] uint64_t hash(uint64_t seed = 0) const;
[[nodiscard]] uint64_t hash(uint64_t seed) const override;
friend std::ostream& operator<<(std::ostream& os, const Reaction& r) {
return os << "(Reaction:" << r.m_id << ")";
[[nodiscard]] std::unique_ptr<Reaction> clone() const override;
friend std::ostream& operator<<(std::ostream& os, const ReaclibReaction& r) {
return os << "(ReaclibReaction:" << r.m_id << ")";
}
protected:
@@ -296,25 +346,24 @@ namespace gridfire::reaction {
};
/**
* @class LogicalReaction
* @class LogicalReaclibReaction
* @brief Represents a "logical" reaction that aggregates rates from multiple sources.
*
* A LogicalReaction shares the same reactants and products but combines rates
* A LogicalReaclibReaction shares the same reactants and products but combines rates
* from different evaluations (e.g., "wc12" and "st08" for the same physical
* reaction). The total rate is the sum of the individual rates.
* It inherits from Reaction, using the properties of the first provided reaction
* as its base properties (reactants, products, Q-value, etc.).
*/
class LogicalReaction final : public Reaction {
class LogicalReaclibReaction final : public ReaclibReaction {
public:
/**
* @brief Constructs a LogicalReaction from a vector of `Reaction` objects.
* @param reactions A vector of reactions that represent the same logical process.
* @throws std::runtime_error if the provided reactions have inconsistent Q-values.
*/
explicit LogicalReaction(const std::vector<Reaction> &reactions);
explicit LogicalReaclibReaction(const std::vector<ReaclibReaction> &reactions);
/**
* @brief Adds another `Reaction` source to this logical reaction.
@@ -322,7 +371,7 @@ namespace gridfire::reaction {
* @throws std::runtime_error if the reaction has a different `peName`, a duplicate
* source label, or an inconsistent Q-value.
*/
void add_reaction(const Reaction& reaction);
void add_reaction(const ReaclibReaction& reaction);
/**
* @brief Gets the number of source rates contributing to this logical reaction.
@@ -339,18 +388,26 @@ namespace gridfire::reaction {
/**
* @brief Calculates the total reaction rate by summing all source rates.
* @param T9 The temperature in units of 10^9 K.
* @param rho
* @param Y
* @return The total calculated reaction rate.
*/
[[nodiscard]] double calculate_rate(const double T9) const override;
[[nodiscard]] double calculate_rate(double T9, double rho, const std::vector<double>& Y) const override;
[[nodiscard]] virtual double calculate_forward_rate_log_derivative(const double T9) const override;
[[nodiscard]] double calculate_forward_rate_log_derivative(double T9, double rho, const std::vector<double>& Y) const override;
[[nodiscard]] ReactionType type() const override { return ReactionType::LOGICAL_REACLIB; }
[[nodiscard]] std::unique_ptr<Reaction> clone() const override;
/**
* @brief Calculates the total reaction rate using CppAD types.
* @param T9 The temperature in units of 10^9 K, as a CppAD::AD<double>.
* @param rho
* @param Y
* @return The total calculated reaction rate, as a CppAD::AD<double>.
*/
[[nodiscard]] CppAD::AD<double> calculate_rate(const CppAD::AD<double> T9) const override;
[[nodiscard]] CppAD::AD<double> calculate_rate(CppAD::AD<double> T9, CppAD::AD<double> rho, const std::vector<CppAD::AD<double>>& Y) const override;
/** @name Iterators
* Provides iterators to loop over the rate coefficient sets.
@@ -363,8 +420,8 @@ namespace gridfire::reaction {
///@}
///
friend std::ostream& operator<<(std::ostream& os, const LogicalReaction& r) {
os << "(LogicalReaction: " << r.id() << ", reverse: " << r.is_reverse() << ")";
friend std::ostream& operator<<(std::ostream& os, const LogicalReaclibReaction& r) {
os << "(LogicalReaclibReaction: " << r.id() << ", reverse: " << r.is_reverse() << ")";
return os;
}
@@ -402,41 +459,44 @@ namespace gridfire::reaction {
}
};
template <typename ReactionT>
class TemplatedReactionSet final {
class ReactionSet final {
public:
/**
* @brief Constructs a ReactionSet from a vector of reactions.
* @param reactions The initial vector of Reaction objects.
*/
explicit TemplatedReactionSet(std::vector<ReactionT> reactions);
explicit ReactionSet(std::vector<std::unique_ptr<Reaction>>&& reactions);
TemplatedReactionSet();
explicit ReactionSet(const std::vector<Reaction*>& reactions);
ReactionSet();
/**
* @brief Copy constructor.
* @param other The ReactionSet to copy.
*/
TemplatedReactionSet(const TemplatedReactionSet<ReactionT>& other);
ReactionSet(const ReactionSet& other);
/**
* @brief Copy assignment operator.
* @param other The ReactionSet to assign from.
* @return A reference to this ReactionSet.
*/
TemplatedReactionSet<ReactionT>& operator=(const TemplatedReactionSet<ReactionT>& other);
ReactionSet& operator=(const ReactionSet& other);
/**
* @brief Adds a reaction to the set.
* @param reaction The Reaction to add.
*/
void add_reaction(ReactionT reaction);
void add_reaction(const Reaction& reaction);
void add_reaction(std::unique_ptr<Reaction>&& reaction);
/**
* @brief Removes a reaction from the set.
* @param reaction The Reaction to remove.
*/
void remove_reaction(const ReactionT& reaction);
void remove_reaction(const Reaction& reaction);
/**
* @brief Checks if the set contains a reaction with the given ID.
@@ -490,7 +550,7 @@ namespace gridfire::reaction {
* @return A const reference to the Reaction.
* @throws std::out_of_range if the index is out of bounds.
*/
[[nodiscard]] const ReactionT& operator[](size_t index) const;
[[nodiscard]] const Reaction& operator[](size_t index) const;
/**
* @brief Accesses a reaction by its ID.
@@ -498,21 +558,21 @@ namespace gridfire::reaction {
* @return A const reference to the Reaction.
* @throws std::out_of_range if no reaction with the given ID exists.
*/
[[nodiscard]] const ReactionT& operator[](const std::string_view& id) const;
[[nodiscard]] const Reaction& operator[](const std::string_view& id) const;
/**
* @brief Compares this set with another for equality.
* @param other The other ReactionSet to compare with.
* @return True if the sets are equal (same size and hash).
*/
bool operator==(const TemplatedReactionSet& other) const;
bool operator==(const ReactionSet& other) const;
/**
* @brief Compares this set with another for inequality.
* @param other The other ReactionSet to compare with.
* @return True if the sets are not equal.
*/
bool operator!=(const TemplatedReactionSet& other) const;
bool operator!=(const ReactionSet& other) const;
/**
* @brief Computes a hash for the entire set.
@@ -522,7 +582,7 @@ namespace gridfire::reaction {
* sorts the hashes, and then computes a final hash over the sorted list
* of hashes. This ensures the hash is order-independent.
*/
[[nodiscard]] uint64_t hash(uint64_t seed = 0) const;
[[nodiscard]] uint64_t hash(uint64_t seed) const;
/** @name Iterators
* Provides iterators to loop over the reactions in the set.
@@ -534,210 +594,30 @@ namespace gridfire::reaction {
[[nodiscard]] auto end() const { return m_reactions.cend(); }
///@}
///
friend std::ostream& operator<<(std::ostream& os, const TemplatedReactionSet<ReactionT>& r) {
os << "(ReactionSet: [";
size_t counter = 0;
for (const auto& reaction : r.m_reactions) {
os << reaction;
if (counter < r.m_reactions.size() - 2) {
os << ", ";
} else if (counter == r.m_reactions.size() - 2) {
os << " and ";
}
++counter;
}
os << "])";
return os;
}
[[nodiscard]] std::unordered_set<fourdst::atomic::Species> getReactionSetSpecies() const;
friend std::ostream& operator<<(std::ostream& os, const ReactionSet& rs) {
os << "(ReactionSet: {";
int i = 0;
for (const auto& reaction : rs.m_reactions) {
os << *reaction;
if (i < rs.m_reactions.size() - 1) {
os << ", ";
}
}
os << "})";
return os;
}
private:
quill::Logger* m_logger = fourdst::logging::LogManager::getInstance().getLogger("log");
std::vector<ReactionT> m_reactions;
std::vector<std::unique_ptr<Reaction>> m_reactions;
std::string m_id;
std::unordered_map<std::string, ReactionT> m_reactionNameMap; ///< Maps reaction IDs to Reaction objects for quick lookup.
std::unordered_map<std::string, size_t> m_reactionNameMap; ///< Maps reaction IDs to Reaction objects for quick lookup.
};
using ReactionSet = TemplatedReactionSet<Reaction>; ///< A set of reactions, typically from a single source like REACLIB.
using LogicalReactionSet = TemplatedReactionSet<LogicalReaction>; ///< A set of logical reactions.
ReactionSet packReactionSet(const ReactionSet& reactionSet);
LogicalReactionSet packReactionSetToLogicalReactionSet(const ReactionSet& reactionSet);
template <typename ReactionT>
TemplatedReactionSet<ReactionT>::TemplatedReactionSet(
std::vector<ReactionT> reactions
) :
m_reactions(std::move(reactions)) {
if (m_reactions.empty()) {
return; // Case where the reactions will be added later.
}
m_reactionNameMap.reserve(reactions.size());
for (const auto& reaction : m_reactions) {
m_id += reaction.id();
m_reactionNameMap.emplace(reaction.id(), reaction);
}
}
template<typename ReactionT>
TemplatedReactionSet<ReactionT>::TemplatedReactionSet() {}
template <typename ReactionT>
TemplatedReactionSet<ReactionT>::TemplatedReactionSet(const TemplatedReactionSet<ReactionT> &other) {
m_reactions.reserve(other.m_reactions.size());
for (const auto& reaction_ptr: other.m_reactions) {
m_reactions.push_back(reaction_ptr);
}
m_reactionNameMap.reserve(other.m_reactionNameMap.size());
for (const auto& reaction_ptr : m_reactions) {
m_reactionNameMap.emplace(reaction_ptr.id(), reaction_ptr);
}
}
template <typename ReactionT>
TemplatedReactionSet<ReactionT>& TemplatedReactionSet<ReactionT>::operator=(const TemplatedReactionSet<ReactionT> &other) {
if (this != &other) {
TemplatedReactionSet temp(other);
std::swap(m_reactions, temp.m_reactions);
std::swap(m_reactionNameMap, temp.m_reactionNameMap);
}
return *this;
}
template <typename ReactionT>
void TemplatedReactionSet<ReactionT>::add_reaction(ReactionT reaction) {
m_reactions.emplace_back(reaction);
m_id += m_reactions.back().id();
m_reactionNameMap.emplace(m_reactions.back().id(), m_reactions.back());
}
template <typename ReactionT>
void TemplatedReactionSet<ReactionT>::remove_reaction(const ReactionT& reaction) {
if (!m_reactionNameMap.contains(std::string(reaction.id()))) {
return;
}
m_reactionNameMap.erase(std::string(reaction.id()));
std::erase_if(m_reactions, [&reaction](const Reaction& r) {
return r == reaction;
});
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::contains(const std::string_view& id) const {
for (const auto& reaction : m_reactions) {
if (reaction.id() == id) {
return true;
}
}
return false;
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::contains(const Reaction& reaction) const {
for (const auto& r : m_reactions) {
if (r == reaction) {
return true;
}
}
return false;
}
template <typename ReactionT>
void TemplatedReactionSet<ReactionT>::clear() {
m_reactions.clear();
m_reactionNameMap.clear();
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::contains_species(const fourdst::atomic::Species& species) const {
for (const auto& reaction : m_reactions) {
if (reaction.contains(species)) {
return true;
}
}
return false;
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::contains_reactant(const fourdst::atomic::Species& species) const {
for (const auto& r : m_reactions) {
if (r.contains_reactant(species)) {
return true;
}
}
return false;
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::contains_product(const fourdst::atomic::Species& species) const {
for (const auto& r : m_reactions) {
if (r.contains_product(species)) {
return true;
}
}
return false;
}
template <typename ReactionT>
const ReactionT& TemplatedReactionSet<ReactionT>::operator[](const size_t index) const {
if (index >= m_reactions.size()) {
m_logger -> flush_log();
throw std::out_of_range("Index" + std::to_string(index) + " out of range for ReactionSet of size " + std::to_string(m_reactions.size()) + ".");
}
return m_reactions[index];
}
template <typename ReactionT>
const ReactionT& TemplatedReactionSet<ReactionT>::operator[](const std::string_view& id) const {
if (auto it = m_reactionNameMap.find(std::string(id)); it != m_reactionNameMap.end()) {
return it->second;
}
m_logger -> flush_log();
throw std::out_of_range("Species " + std::string(id) + " does not exist in ReactionSet.");
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::operator==(const TemplatedReactionSet<ReactionT>& other) const {
if (size() != other.size()) {
return false;
}
return hash() == other.hash();
}
template <typename ReactionT>
bool TemplatedReactionSet<ReactionT>::operator!=(const TemplatedReactionSet<ReactionT>& other) const {
return !(*this == other);
}
template <typename ReactionT>
uint64_t TemplatedReactionSet<ReactionT>::hash(uint64_t seed) const {
if (m_reactions.empty()) {
return XXHash64::hash(nullptr, 0, seed);
}
std::vector<uint64_t> individualReactionHashes;
individualReactionHashes.reserve(m_reactions.size());
for (const auto& reaction : m_reactions) {
individualReactionHashes.push_back(reaction.hash(seed));
}
std::ranges::sort(individualReactionHashes);
const auto data = static_cast<const void*>(individualReactionHashes.data());
const size_t sizeInBytes = individualReactionHashes.size() * sizeof(uint64_t);
return XXHash64::hash(data, sizeInBytes, seed);
}
template<typename ReactionT>
std::unordered_set<fourdst::atomic::Species> TemplatedReactionSet<ReactionT>::getReactionSetSpecies() const {
std::unordered_set<fourdst::atomic::Species> species;
for (const auto& reaction : m_reactions) {
const auto reactionSpecies = reaction.all_species();
species.insert(reactionSpecies.begin(), reactionSpecies.end());
}
return species;
}
}

View File

@@ -0,0 +1,58 @@
#pragma once
#include "fourdst/composition/atomicSpecies.h"
#include <unordered_map>
#include <expected>
namespace gridfire::rates::weak {
enum class WeakReactionType {
BETA_PLUS_DECAY,
BETA_MINUS_DECAY,
ELECTRON_CAPTURE,
POSITRON_CAPTURE,
};
inline std::unordered_map<WeakReactionType, std::string> WeakReactionTypeNames = {
{WeakReactionType::BETA_PLUS_DECAY, "β+ Decay"},
{WeakReactionType::BETA_MINUS_DECAY, "β- Decay"},
{WeakReactionType::ELECTRON_CAPTURE, "e- Capture"},
{WeakReactionType::POSITRON_CAPTURE, "e+ Capture"},
};
struct WeakReaction {
WeakReactionType type;
float T9;
float log_rhoYe;
float mu_e;
float log_rate;
float log_neutrino_loss;
friend std::ostream& operator<<(std::ostream& os, const WeakReaction& reaction) {
os << "WeakReaction(type=" << WeakReactionTypeNames[reaction.type]
<< ", T9=" << reaction.T9
<< ", log_rhoYe=" << reaction.log_rhoYe
<< ", mu_e=" << reaction.mu_e
<< ", log_rate=" << reaction.log_rate
<< ", log_neutrino_loss=" << reaction.log_neutrino_loss
<< ")";
return os;
}
};
class WeakReactionMap {
public:
WeakReactionMap();
~WeakReactionMap() = default;
std::vector<WeakReaction> get_all_reactions() const;
std::expected<std::vector<WeakReaction>, bool> get_species_reactions(const fourdst::atomic::Species &species) const;
std::expected<std::vector<WeakReaction>, bool> get_species_reactions(const std::string& species_name) const;
private:
std::unordered_map<fourdst::atomic::Species, std::vector<WeakReaction>> m_weak_network;
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -70,8 +70,8 @@ namespace gridfire::screening {
* }
* @endcode
*/
virtual std::vector<double> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
[[nodiscard]] virtual std::vector<double> calculateScreeningFactors(
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<double>& Y,
const double T9,
@@ -97,8 +97,8 @@ namespace gridfire::screening {
* This method is essential for including the effects of screening in the
* Jacobian matrix of the reaction network.
*/
virtual std::vector<ADDouble> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
[[nodiscard]] virtual std::vector<ADDouble> calculateScreeningFactors(
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<ADDouble>& Y,
const ADDouble T9,

View File

@@ -52,7 +52,7 @@ namespace gridfire::screening {
* @endcode
*/
[[nodiscard]] std::vector<double> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<double>& Y,
const double T9,
@@ -75,7 +75,7 @@ namespace gridfire::screening {
* size as the `reactions` set.
*/
[[nodiscard]] std::vector<ADDouble> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<ADDouble>& Y,
const ADDouble T9,
@@ -99,7 +99,7 @@ namespace gridfire::screening {
*/
template <typename T>
[[nodiscard]] std::vector<T> calculateFactors_impl(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<T>& Y,
const T T9,
@@ -124,7 +124,7 @@ namespace gridfire::screening {
*/
template<typename T>
std::vector<T> BareScreeningModel::calculateFactors_impl(
const reaction::LogicalReactionSet &reactions,
const reaction::ReactionSet &reactions,
const std::vector<fourdst::atomic::Species> &species,
const std::vector<T> &Y,
const T T9,

View File

@@ -0,0 +1,49 @@
#pragma once
#include "gridfire/screening/screening_abstract.h"
#include "gridfire/reaction/reaction.h"
#include "cppad/cppad.hpp"
namespace gridfire::screening {
class IntermediateScreeningModel final : public ScreeningModel {
public:
std::vector<double> calculateScreeningFactors(
const reaction::ReactionSet &reactions,
const std::vector<fourdst::atomic::Species> &species,
const std::vector<double> &Y,
double T9,
double rho
) const override;
std::vector<ADDouble> calculateScreeningFactors(
const reaction::ReactionSet &reactions,
const std::vector<fourdst::atomic::Species> &species,
const std::vector<ADDouble> &Y,
ADDouble T9,
ADDouble rho
) const override;
private:
template<typename T>
[[nodiscard]] std::vector<T> calculateFactors_impl(
const reaction::ReactionSet &reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<T>& Y,
T T9,
T rho
) const;
};
template<typename T>
std::vector<T> IntermediateScreeningModel::calculateFactors_impl(
const reaction::ReactionSet &reactions,
const std::vector<fourdst::atomic::Species> &species,
const std::vector<T> &Y,
const T T9,
const T rho
) const {
// TODO: Implement the intermediate screening model logic here. Follow the prescription from Graboske et al. (1973)
return std::vector<T>(species.size(), 0);
}
}

View File

@@ -48,7 +48,7 @@ namespace gridfire::screening {
* @endcode
*/
[[nodiscard]] std::vector<double> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<double>& Y,
const double T9,
@@ -70,7 +70,7 @@ namespace gridfire::screening {
* @return A vector of screening factors as AD types.
*/
[[nodiscard]] std::vector<CppAD::AD<double>> calculateScreeningFactors(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<CppAD::AD<double>>& Y,
const CppAD::AD<double> T9,
@@ -98,7 +98,7 @@ namespace gridfire::screening {
*/
template <typename T>
[[nodiscard]] std::vector<T> calculateFactors_impl(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<T>& Y,
const T T9,
@@ -139,7 +139,7 @@ namespace gridfire::screening {
*/
template <typename T>
std::vector<T> WeakScreeningModel::calculateFactors_impl(
const reaction::LogicalReactionSet& reactions,
const reaction::ReactionSet& reactions,
const std::vector<fourdst::atomic::Species>& species,
const std::vector<T>& Y,
const T T9,
@@ -177,7 +177,7 @@ namespace gridfire::screening {
factors.reserve(reactions.size());
for (const auto& reaction : reactions) {
T H_12(0.0); // screening abundance term
const auto& reactants = reaction.reactants();
const auto& reactants = reaction->reactants();
const bool isTripleAlpha = (
reactants.size() == 3 &&
reactants[0].m_z == 2 &&

View File

@@ -36,7 +36,7 @@ namespace gridfire::solver {
* the context that will be passed to the callback function, and use this information to craft their own
* callback function.
*/
virtual std::vector<std::tuple<std::string, std::string>> describe() const = 0;
[[nodiscard]] virtual std::vector<std::tuple<std::string, std::string>> describe() const = 0;
};
/**
* @class NetworkSolverStrategy
@@ -92,7 +92,7 @@ namespace gridfire::solver {
* the context that will be passed to the callback function, and use this information to craft their own
* callback function.
*/
virtual std::vector<std::tuple<std::string, std::string>> describe_callback_context() const = 0;
[[nodiscard]] virtual std::vector<std::tuple<std::string, std::string>> describe_callback_context() const = 0;
protected:
EngineT& m_engine; ///< The engine used by this solver strategy.
};
@@ -191,7 +191,7 @@ namespace gridfire::solver {
*
* @implements SolverContextBase::describe
*/
std::vector<std::tuple<std::string, std::string>> describe() const override;
[[nodiscard]] std::vector<std::tuple<std::string, std::string>> describe() const override;
};
/**
@@ -228,7 +228,7 @@ namespace gridfire::solver {
*
* @implements SolverContextBase::describe
*/
std::vector<std::tuple<std::string, std::string>> describe_callback_context() const override;
[[nodiscard]] std::vector<std::tuple<std::string, std::string>> describe_callback_context() const override;
private: