GridFire 0.0.1a
General Purpose Nuclear Network
Loading...
Searching...
No Matches
engine_graph.h
Go to the documentation of this file.
1#pragma once
2
3#include "fourdst/composition/atomicSpecies.h"
4#include "fourdst/composition/composition.h"
5#include "fourdst/logging/logging.h"
6#include "fourdst/config/config.h"
7
8#include "gridfire/network.h"
15
16#include <string>
17#include <unordered_map>
18#include <vector>
19#include <memory>
20#include <ranges>
21
22#include <boost/numeric/ublas/matrix_sparse.hpp>
23
24#include "cppad/cppad.hpp"
25#include "cppad/utility/sparse_rc.hpp"
26#include "cppad/speed/sparse_jac_fun.hpp"
27
28#include "procedures/priming.h"
29
30
31#include "quill/LogMacros.h"
32
33// PERF: The function getNetReactionStoichiometry returns a map of species to their stoichiometric coefficients for a given reaction.
34// this makes extra copies of the species, which is not ideal and could be optimized further.
35// Even more relevant is the member m_reactionIDMap which makes copies of a REACLIBReaction for each reaction ID.
36// REACLIBReactions are quite large data structures, so this could be a performance bottleneck.
37// static bool isF17 = false;
38namespace gridfire {
39 static bool s_debug = false; // Global debug flag for the GraphEngine
45 typedef CppAD::AD<double> ADDouble;
46
47 using fourdst::config::Config;
48 using fourdst::logging::LogManager;
49 using fourdst::constant::Constants;
50
58 static constexpr double MIN_DENSITY_THRESHOLD = 1e-18;
59
67 static constexpr double MIN_ABUNDANCE_THRESHOLD = 1e-18;
68
75 static constexpr double MIN_JACOBIAN_THRESHOLD = 1e-24;
76
77
101 class GraphEngine final : public DynamicEngine{
102 public:
113 explicit GraphEngine(
114 const fourdst::composition::Composition &composition,
116 );
117
118 explicit GraphEngine(
119 const fourdst::composition::Composition &composition,
120 const partition::PartitionFunction& partitionFunction,
121 const BuildDepthType buildDepth = NetworkBuildDepth::Full
122 );
123
132 explicit GraphEngine(const reaction::LogicalReactionSet &reactions);
133
147 [[nodiscard]] std::expected<StepDerivatives<double>, expectations::StaleEngineError> calculateRHSAndEnergy(
148 const std::vector<double>& Y,
149 const double T9,
150 const double rho
151 ) const override;
152
167 const std::vector<double>& Y_dynamic,
168 const double T9,
169 const double rho
170 ) const override;
171
173 const std::vector<double> &Y_dynamic,
174 double T9,
175 double rho,
176 const SparsityPattern &sparsityPattern
177 ) const override;
178
185 void generateStoichiometryMatrix() override;
186
199 [[nodiscard]] double calculateMolarReactionFlow(
201 const std::vector<double>&Y,
202 const double T9,
203 const double rho
204 ) const override;
205
210 [[nodiscard]] const std::vector<fourdst::atomic::Species>& getNetworkSpecies() const override;
211
216 [[nodiscard]] const reaction::LogicalReactionSet& getNetworkReactions() const override;
217
218 void setNetworkReactions(const reaction::LogicalReactionSet& reactions) override;
219
231 [[nodiscard]] double getJacobianMatrixEntry(
232 const int i,
233 const int j
234 ) const override;
235
242 [[nodiscard]] static std::unordered_map<fourdst::atomic::Species, int> getNetReactionStoichiometry(
244 );
245
257 [[nodiscard]] int getStoichiometryMatrixEntry(
258 const int speciesIndex,
259 const int reactionIndex
260 ) const override;
261
273 [[nodiscard]] std::expected<std::unordered_map<fourdst::atomic::Species, double>, expectations::StaleEngineError> getSpeciesTimescales(
274 const std::vector<double>& Y,
275 double T9,
276 double rho
277 ) const override;
278
279 [[nodiscard]] std::expected<std::unordered_map<fourdst::atomic::Species, double>, expectations::StaleEngineError> getSpeciesDestructionTimescales(
280 const std::vector<double>& Y,
281 double T9,
282 double rho
283 ) const override;
284
285 fourdst::composition::Composition update(const NetIn &netIn) override;
286
287 bool isStale(const NetIn &netIn) override;
288
295 [[nodiscard]] bool involvesSpecies(
296 const fourdst::atomic::Species& species
297 ) const;
298
315 void exportToDot(
316 const std::string& filename
317 ) const;
318
335 void exportToCSV(
336 const std::string& filename
337 ) const;
338
340
341 [[nodiscard]] screening::ScreeningType getScreeningModel() const override;
342
343 void setPrecomputation(bool precompute);
344
345 [[nodiscard]] bool isPrecomputationEnabled() const;
346
347 [[nodiscard]] const partition::PartitionFunction& getPartitionFunction() const;
348
349 [[nodiscard]] double calculateReverseRate(
351 double T9
352 ) const;
353
354 [[nodiscard]] double calculateReverseRateTwoBody(
356 const double T9,
357 const double forwardRate,
358 const double expFactor
359 ) const;
360
361 [[nodiscard]] double calculateReverseRateTwoBodyDerivative(
363 const double T9,
364 const double reverseRate
365 ) const;
366
367 [[nodiscard]] bool isUsingReverseReactions() const;
368
369 void setUseReverseReactions(bool useReverse);
370
371 [[nodiscard]] int getSpeciesIndex(
372 const fourdst::atomic::Species& species
373 ) const override;
374
375 [[nodiscard]] std::vector<double> mapNetInToMolarAbundanceVector(const NetIn &netIn) const override;
376
377 [[nodiscard]] PrimingReport primeEngine(const NetIn &netIn) override;
378
379 [[nodiscard]] BuildDepthType getDepth() const override;
380
381 void rebuild(const fourdst::composition::Composition& comp, const BuildDepthType depth) override;
382
383
384 private:
386 // Forward cacheing
388 std::vector<size_t> unique_reactant_indices;
389 std::vector<int> reactant_powers;
391 std::vector<size_t> affected_species_indices;
393
394 // Reverse cacheing
395 std::vector<size_t> unique_product_indices;
396 std::vector<int> product_powers;
398 };
399
400 struct constants {
401 const double u = Constants::getInstance().get("u").value;
402 const double Na = Constants::getInstance().get("N_a").value;
403 const double c = Constants::getInstance().get("c").value;
404 const double kB = Constants::getInstance().get("kB").value;
405 };
406 private:
407 class AtomicReverseRate final : public CppAD::atomic_base<double> {
408 public:
411 const GraphEngine& engine
412 ):
413 atomic_base<double>("AtomicReverseRate"),
415 m_engine(engine) {}
416
417 bool forward(
418 size_t p,
419 size_t q,
420 const CppAD::vector<bool>& vx,
421 CppAD::vector<bool>& vy,
422 const CppAD::vector<double>& tx,
423 CppAD::vector<double>& ty
424 ) override;
425 bool reverse(
426 size_t q,
427 const CppAD::vector<double>& tx,
428 const CppAD::vector<double>& ty,
429 CppAD::vector<double>& px,
430 const CppAD::vector<double>& py
431 ) override;
432 bool for_sparse_jac(
433 size_t q,
434 const CppAD::vector<std::set<size_t>>&r,
435 CppAD::vector<std::set<size_t>>& s
436 ) override;
437 bool rev_sparse_jac(
438 size_t q,
439 const CppAD::vector<std::set<size_t>>&rt,
440 CppAD::vector<std::set<size_t>>& st
441 ) override;
442
443 private:
446 };
447 private:
448 Config& m_config = Config::getInstance();
449 quill::Logger* m_logger = LogManager::getInstance().getLogger("log");
450
452
454 std::unordered_map<std::string_view, reaction::Reaction*> m_reactionIDMap;
455
456 std::vector<fourdst::atomic::Species> m_networkSpecies;
457 std::unordered_map<std::string_view, fourdst::atomic::Species> m_networkSpeciesMap;
458 std::unordered_map<fourdst::atomic::Species, size_t> m_speciesToIndexMap;
459
460 boost::numeric::ublas::compressed_matrix<int> m_stoichiometryMatrix;
461
462 mutable boost::numeric::ublas::compressed_matrix<double> m_jacobianMatrix;
463 mutable CppAD::ADFun<double> m_rhsADFun;
464 mutable CppAD::sparse_jac_work m_jac_work;
465 CppAD::sparse_rc<std::vector<size_t>> m_full_jacobian_sparsity_pattern;
466
467 std::vector<std::unique_ptr<AtomicReverseRate>> m_atomicReverseRates;
468
470 std::unique_ptr<screening::ScreeningModel> m_screeningModel = screening::selectScreeningModel(m_screeningType);
471
473
475
477
478 std::vector<PrecomputedReaction> m_precomputedReactions;
479 std::unique_ptr<partition::PartitionFunction> m_partitionFunction;
480
481 private:
489 void syncInternalMaps();
490
498
506
514
522 void reserveJacobianMatrix() const;
523
533 void recordADTape();
534
536
537 void precomputeNetwork();
538
539
549 [[nodiscard]] bool validateConservation() const;
550
563 const fourdst::composition::Composition &composition,
564 double culling,
565 double T9
566 );
567
568
569
571 const std::vector<double> &Y_in,
572 const std::vector<double>& bare_rates,
573 const std::vector<double> &bare_reverse_rates,
574 double T9, double rho
575 ) const;
576
590 template <IsArithmeticOrAD T>
593 const std::vector<T> &Y,
594 const T T9,
595 const T rho
596 ) const;
597
598 template<IsArithmeticOrAD T>
600 T T9,
601 T rho,
602 std::vector<T> screeningFactors,
603 std::vector<T> Y,
604 size_t reactionIndex,
606 ) const;
607
620 template<IsArithmeticOrAD T>
622 const std::vector<T> &Y_in,
623 T T9,
624 T rho
625 ) const;
626
640 const std::vector<double>& Y_in,
641 const double T9,
642 const double rho
643 ) const;
644
658 const std::vector<ADDouble>& Y_in,
659 const ADDouble &T9,
660 const ADDouble &rho
661 ) const;
662 };
663
664
665
666 template <IsArithmeticOrAD T>
668 T T9,
669 T rho,
670 std::vector<T> screeningFactors,
671 std::vector<T> Y,
672 size_t reactionIndex,
674 ) const {
676 return static_cast<T>(0.0); // If reverse reactions are not used, return zero
677 }
678 s_debug = false;
679 if (reaction.peName() == "p(p,e+)d" || reaction.peName() =="d(d,n)he3" || reaction.peName() == "c12(p,g)n13") {
680 if constexpr (!std::is_same_v<T, ADDouble>) {
681 s_debug = true;
682 std::cout << "Calculating reverse molar flow for reaction: " << reaction.peName() << std::endl;
683 std::cout << "\tT9: " << T9 << ", rho: " << rho << std::endl;
684 }
685 }
686 T reverseMolarFlow = static_cast<T>(0.0);
687
688 if (reaction.qValue() != 0.0) {
689 T reverseRateConstant = static_cast<T>(0.0);
690 if constexpr (std::is_same_v<T, ADDouble>) { // Check if T is an AD type at compile time
691 const auto& atomic_func_ptr = m_atomicReverseRates[reactionIndex];
692 if (atomic_func_ptr != nullptr) {
693 // A. Instantiate the atomic operator for the specific reaction
694 // B. Marshal the input vector
695 std::vector<T> ax = { T9 };
696
697 std::vector<T> ay(1);
698 (*atomic_func_ptr)(ax, ay);
699 reverseRateConstant = static_cast<T>(ay[0]);
700 } else {
701 return reverseMolarFlow; // If no atomic function is available, return zero
702 }
703 } else {
704 // A,B If not calling with an AD type, calculate the reverse rate directly
705 if (s_debug) {
706 std::cout << "\tUsing double overload\n";
707 }
708 reverseRateConstant = calculateReverseRate(reaction, T9);
709 }
710
711 // C. Get product multiplicities
712 std::unordered_map<fourdst::atomic::Species, int> productCounts;
713 for (const auto& product : reaction.products()) {
714 productCounts[product]++;
715 }
716
717 // D. Calculate the symmetry factor
718 T reverseSymmetryFactor = static_cast<T>(1.0);
719 for (const auto &count: productCounts | std::views::values) {
720 reverseSymmetryFactor /= static_cast<T>(std::tgamma(static_cast<double>(count + 1))); // Gamma function for factorial
721 }
722
723 // E. Calculate the abundance term
724 T productAbundanceTerm = static_cast<T>(1.0);
725 for (const auto& [species, count] : productCounts) {
726 const unsigned long speciesIndex = m_speciesToIndexMap.at(species);
727 productAbundanceTerm *= CppAD::pow(Y[speciesIndex], count);
728 }
729
730 // F. Determine the power for the density term
731 const size_t num_products = reaction.products().size();
732 const T rho_power = CppAD::pow(rho, static_cast<T>(num_products > 1 ? num_products - 1 : 0)); // Density raised to the power of (N-1) for N products
733
734 // G. Assemble the reverse molar flow rate
735 reverseMolarFlow = screeningFactors[reactionIndex] *
736 reverseRateConstant *
737 productAbundanceTerm *
738 reverseSymmetryFactor *
739 rho_power;
740 }
741 return reverseMolarFlow;
742 }
743
744 template<IsArithmeticOrAD T>
746 const std::vector<T> &Y_in, T T9, T rho) const {
747 std::vector<T> screeningFactors = m_screeningModel->calculateScreeningFactors(
750 Y_in,
751 T9,
752 rho
753 );
754
755 // --- Setup output derivatives structure ---
756 StepDerivatives<T> result;
757 result.dydt.resize(m_networkSpecies.size(), static_cast<T>(0.0));
758
759 // --- AD Pre-setup (flags to control conditionals in an AD safe / branch aware manner) ---
760 // ----- Constants for AD safe calculations ---
761 const T zero = static_cast<T>(0.0);
762 const T one = static_cast<T>(1.0);
763
764 // ----- Initialize variables for molar concentration product and thresholds ---
765 // Note: the logic here is that we use CppAD::CondExprLt to test thresholds and if they are less we set the flag
766 // to zero so that the final returned reaction flow is 0. This is as opposed to standard if statements
767 // which create branches that break the AD tape.
768 const T rho_threshold = static_cast<T>(MIN_DENSITY_THRESHOLD);
769
770 // --- Check if the density is below the threshold where we ignore reactions ---
771 T threshold_flag = CppAD::CondExpLt(rho, rho_threshold, zero, one); // If rho < threshold, set flag to 0
772
773 std::vector<T> Y = Y_in;
774 for (size_t i = 0; i < m_networkSpecies.size(); ++i) {
775 // We use CppAD::CondExpLt to handle AD taping and prevent branching
776 // Note that while this is syntactically more complex this is equivalent to
777 // if (Y[i] < 0) {Y[i] = 0;}
778 // The issue is that this would introduce a branch which would require the auto diff tape to be re-recorded
779 // each timestep, which is very inefficient.
780 Y[i] = CppAD::CondExpLt(Y[i], zero, zero, Y[i]); // Ensure no negative abundances
781 }
782
783 const T u = static_cast<T>(m_constants.u); // Atomic mass unit in grams
784 const T N_A = static_cast<T>(m_constants.Na); // Avogadro's number in mol^-1
785 const T c = static_cast<T>(m_constants.c); // Speed of light in cm/s
786
787 // --- SINGLE LOOP OVER ALL REACTIONS ---
788 for (size_t reactionIndex = 0; reactionIndex < m_reactions.size(); ++reactionIndex) {
789 const auto& reaction = m_reactions[reactionIndex];
790
791 // 1. Calculate forward reaction rate
792 const T forwardMolarReactionFlow = screeningFactors[reactionIndex] *
794
795 // 2. Calculate reverse reaction rate
796 T reverseMolarFlow = calculateReverseMolarReactionFlow<T>(
797 T9,
798 rho,
799 screeningFactors,
800 Y,
801 reactionIndex,
803 );
804
805 const T molarReactionFlow = forwardMolarReactionFlow - reverseMolarFlow; // Net molar reaction flow
806
807 // 3. Use the rate to update all relevant species derivatives (dY/dt)
808 for (size_t speciesIndex = 0; speciesIndex < m_networkSpecies.size(); ++speciesIndex) {
809 const T nu_ij = static_cast<T>(m_stoichiometryMatrix(speciesIndex, reactionIndex));
810 result.dydt[speciesIndex] += threshold_flag * nu_ij * molarReactionFlow;
811 }
812 }
813
814 T massProductionRate = static_cast<T>(0.0); // [mol][s^-1]
815 for (const auto& [species, index] : m_speciesToIndexMap) {
816 massProductionRate += result.dydt[index] * species.mass() * u;
817 }
818
819 result.nuclearEnergyGenerationRate = -massProductionRate * N_A * c * c; // [cm^2][s^-3] = [erg][s^-1][g^-1]
820
821 return result;
822 }
823
824
825 template <IsArithmeticOrAD T>
828 const std::vector<T> &Y,
829 const T T9,
830 const T rho
831 ) const {
832
833 // --- Pre-setup (flags to control conditionals in an AD safe / branch aware manner) ---
834 // ----- Constants for AD safe calculations ---
835 const T zero = static_cast<T>(0.0);
836
837 // --- Calculate the molar reaction rate (in units of [s^-1][cm^3(N-1)][mol^(1-N)] for N reactants) ---
838 const T k_reaction = reaction.calculate_rate(T9);
839
840 // --- Cound the number of each reactant species to account for species multiplicity ---
841 std::unordered_map<std::string, int> reactant_counts;
842 reactant_counts.reserve(reaction.reactants().size());
843 for (const auto& reactant : reaction.reactants()) {
844 reactant_counts[std::string(reactant.name())]++;
845 }
846 const int totalReactants = static_cast<int>(reaction.reactants().size());
847
848 // --- Accumulator for the molar concentration ---
849 auto molar_concentration_product = static_cast<T>(1.0);
850
851 // --- Loop through each unique reactant species and calculate the molar concentration for that species then multiply that into the accumulator ---
852 for (const auto& [species_name, count] : reactant_counts) {
853 // --- Resolve species to molar abundance ---
854 // PERF: Could probably optimize out this lookup
855 const auto species_it = m_speciesToIndexMap.find(m_networkSpeciesMap.at(species_name));
856 const size_t species_index = species_it->second;
857 const T Yi = Y[species_index];
858
859 // --- If count is > 1 , we need to raise the molar concentration to the power of count since there are really count bodies in that reaction ---
860 molar_concentration_product *= CppAD::pow(Yi, static_cast<T>(count)); // ni^count
861
862 // --- Apply factorial correction for identical reactions ---
863 if (count > 1) {
864 molar_concentration_product /= static_cast<T>(std::tgamma(static_cast<double>(count + 1))); // Gamma function for factorial
865 }
866 }
867 // --- Final reaction flow calculation [mol][s^-1][g^-1] ---
868 // Note: If the threshold flag ever gets set to zero this will return zero.
869 // This will result basically in multiple branches being written to the AD tape, which will make
870 // the tape more expensive to record, but it will also mean that we only need to record it once for
871 // the entire network.
872 const T densityTerm = CppAD::pow(rho, totalReactants > 1 ? static_cast<T>(totalReactants - 1) : zero); // Density raised to the power of (N-1) for N reactants
873 return molar_concentration_product * k_reaction * densityTerm;
874 }
875
876};
Abstract class for engines supporting Jacobian and stoichiometry operations.
AtomicReverseRate(const reaction::Reaction &reaction, const GraphEngine &engine)
bool reverse(size_t q, const CppAD::vector< double > &tx, const CppAD::vector< double > &ty, CppAD::vector< double > &px, const CppAD::vector< double > &py) override
bool rev_sparse_jac(size_t q, const CppAD::vector< std::set< size_t > > &rt, CppAD::vector< std::set< size_t > > &st) override
const reaction::Reaction & m_reaction
bool forward(size_t p, size_t q, const CppAD::vector< bool > &vx, CppAD::vector< bool > &vy, const CppAD::vector< double > &tx, CppAD::vector< double > &ty) override
bool for_sparse_jac(size_t q, const CppAD::vector< std::set< size_t > > &r, CppAD::vector< std::set< size_t > > &s) override
bool isPrecomputationEnabled() const
double calculateReverseRateTwoBody(const reaction::Reaction &reaction, const double T9, const double forwardRate, const double expFactor) const
double calculateReverseRate(const reaction::Reaction &reaction, double T9) const
const std::vector< fourdst::atomic::Species > & getNetworkSpecies() const override
Gets the list of species in the network.
BuildDepthType getDepth() const override
T calculateReverseMolarReactionFlow(T T9, T rho, std::vector< T > screeningFactors, std::vector< T > Y, size_t reactionIndex, const reaction::LogicalReaction &reaction) const
bool m_usePrecomputation
Flag to enable or disable using precomputed reactions for efficiency. Mathematically,...
CppAD::sparse_rc< std::vector< size_t > > m_full_jacobian_sparsity_pattern
Full sparsity pattern for the Jacobian matrix.
CppAD::sparse_jac_work m_jac_work
Work object for sparse Jacobian calculations.
void populateReactionIDMap()
Populates the reaction ID map.
std::vector< double > mapNetInToMolarAbundanceVector(const NetIn &netIn) const override
void collectAtomicReverseRateAtomicBases()
CppAD::ADFun< double > m_rhsADFun
CppAD function for the right-hand side of the ODE.
boost::numeric::ublas::compressed_matrix< double > m_jacobianMatrix
Jacobian matrix (species x species).
double getJacobianMatrixEntry(const int i, const int j) const override
Gets an entry from the previously generated Jacobian matrix.
std::unordered_map< std::string_view, fourdst::atomic::Species > m_networkSpeciesMap
Map from species name to Species object.
bool m_useReverseReactions
Flag to enable or disable reverse reactions. If false, only forward reactions are considered.
std::unique_ptr< partition::PartitionFunction > m_partitionFunction
Partition function for the network.
void setNetworkReactions(const reaction::LogicalReactionSet &reactions) override
void setUseReverseReactions(bool useReverse)
void populateSpeciesToIndexMap()
Populates the species-to-index map.
quill::Logger * m_logger
screening::ScreeningType m_screeningType
Screening type for the reaction network. Default to no screening.
fourdst::composition::Composition update(const NetIn &netIn) override
Update the internal state of the engine.
std::vector< PrecomputedReaction > m_precomputedReactions
Precomputed reactions for efficiency.
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 ...
std::expected< std::unordered_map< fourdst::atomic::Species, double >, expectations::StaleEngineError > getSpeciesTimescales(const std::vector< double > &Y, double T9, double rho) const override
Computes timescales for all species in the network.
screening::ScreeningType getScreeningModel() const override
Get the current electron screening model.
int getStoichiometryMatrixEntry(const int speciesIndex, const int reactionIndex) const override
Gets an entry from the stoichiometry matrix.
void setPrecomputation(bool precompute)
BuildDepthType m_depth
void setScreeningModel(screening::ScreeningType) override
Set the electron screening model.
std::vector< std::unique_ptr< AtomicReverseRate > > m_atomicReverseRates
void exportToCSV(const std::string &filename) const
Exports the network to a CSV file for analysis.
static std::unordered_map< fourdst::atomic::Species, int > getNetReactionStoichiometry(const reaction::Reaction &reaction)
Gets the net stoichiometry for a given reaction.
void reserveJacobianMatrix() const
Reserves space for the Jacobian matrix.
int getSpeciesIndex(const fourdst::atomic::Species &species) const override
double calculateMolarReactionFlow(const reaction::Reaction &reaction, const std::vector< double > &Y, const double T9, const double rho) const override
Calculates the molar reaction flow for a given reaction.
std::vector< fourdst::atomic::Species > m_networkSpecies
Vector of unique species in the network.
void recordADTape()
Records the AD tape for the right-hand side of the ODE.
StepDerivatives< double > calculateAllDerivativesUsingPrecomputation(const std::vector< double > &Y_in, const std::vector< double > &bare_rates, const std::vector< double > &bare_reverse_rates, double T9, double rho) const
bool involvesSpecies(const fourdst::atomic::Species &species) const
Checks if a given species is involved in the network.
std::expected< StepDerivatives< double >, expectations::StaleEngineError > calculateRHSAndEnergy(const std::vector< double > &Y, const double T9, const double rho) const override
Calculates the right-hand side (dY/dt) and energy generation rate.
reaction::LogicalReactionSet m_reactions
Set of REACLIB reactions in the network.
void syncInternalMaps()
Synchronizes the internal maps.
bool validateConservation() const
Validates mass and charge conservation across all reactions.
void generateJacobianMatrix(const std::vector< double > &Y_dynamic, const double T9, const double rho) const override
Generates the Jacobian matrix for the current state.
boost::numeric::ublas::compressed_matrix< int > m_stoichiometryMatrix
Stoichiometry matrix (species x reactions).
const reaction::LogicalReactionSet & getNetworkReactions() const override
Gets the set of logical reactions in the network.
std::unordered_map< fourdst::atomic::Species, size_t > m_speciesToIndexMap
Map from species to their index in the stoichiometry matrix.
void rebuild(const fourdst::composition::Composition &comp, const BuildDepthType depth) override
void exportToDot(const std::string &filename) const
Exports the network to a DOT file for visualization.
const partition::PartitionFunction & getPartitionFunction() const
bool isUsingReverseReactions() const
PrimingReport primeEngine(const NetIn &netIn) override
void generateStoichiometryMatrix() override
Generates the stoichiometry matrix for the network.
void collectNetworkSpecies()
Collects the unique species in the network.
void validateComposition(const fourdst::composition::Composition &composition, double culling, double T9)
Validates the composition against the current reaction set.
std::expected< std::unordered_map< fourdst::atomic::Species, double >, expectations::StaleEngineError > getSpeciesDestructionTimescales(const std::vector< double > &Y, double T9, double rho) const override
bool isStale(const NetIn &netIn) override
std::unique_ptr< screening::ScreeningModel > m_screeningModel
double calculateReverseRateTwoBodyDerivative(const reaction::Reaction &reaction, const double T9, const double reverseRate) const
StepDerivatives< T > calculateAllDerivatives(const std::vector< T > &Y_in, T T9, T rho) const
Calculates all derivatives (dY/dt) and the energy generation rate.
GraphEngine(const fourdst::composition::Composition &composition, const BuildDepthType=NetworkBuildDepth::Full)
Constructs a GraphEngine from a composition.
Abstract interface for evaluating nuclear partition functions.
Represents a "logical" reaction that aggregates rates from multiple sources.
Definition reaction.h:310
Represents a single nuclear reaction from a specific data source.
Definition reaction.h:72
Abstract interfaces for reaction network engines in GridFire.
TemplatedReactionSet< LogicalReaction > LogicalReactionSet
A set of logical reactions.
Definition reaction.h:563
std::unique_ptr< ScreeningModel > selectScreeningModel(ScreeningType type)
A factory function to select and create a screening model.
ScreeningType
Enumerates the available plasma screening models.
@ BARE
No screening applied. The screening factor is always 1.0.
CppAD::AD< double > ADDouble
Alias for CppAD AD type for double precision.
std::variant< NetworkBuildDepth, int > BuildDepthType
Variant specifying either a predefined NetworkBuildDepth or a custom integer depth.
Definition building.h:37
std::vector< std::pair< size_t, size_t > > SparsityPattern
static constexpr double MIN_ABUNDANCE_THRESHOLD
Minimum abundance threshold below which species are ignored.
static constexpr double MIN_DENSITY_THRESHOLD
Minimum density threshold below which reactions are ignored.
static constexpr double MIN_JACOBIAN_THRESHOLD
Minimum value for Jacobian matrix entries.
static bool s_debug
Defines classes for representing and managing nuclear reactions.
std::vector< int > product_powers
Powers of each unique product in the reverse reaction.
double reverse_symmetry_factor
Symmetry factor for reverse reactions.
std::vector< size_t > unique_product_indices
Unique product indices for reverse reactions.
const double kB
Boltzmann constant in erg/K.
const double u
Atomic mass unit in g.
const double Na
Avogadro's number.
const double c
Speed of light in cm/s.
Captures the result of a network priming operation.
Definition reporting.h:67
Structure holding derivatives and energy generation for a network step.
T nuclearEnergyGenerationRate
Specific energy generation rate (e.g., erg/g/s).
std::vector< T > dydt
Derivatives of abundances (dY/dt for each species).