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"
9#include "gridfire/reaction/reaction.h"
10#include "gridfire/engine/engine_abstract.h"
11#include "gridfire/screening/screening_abstract.h"
12#include "gridfire/screening/screening_types.h"
13#include "gridfire/partition/partition_abstract.h"
14#include "gridfire/engine/procedures/construction.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;
38 namespace gridfire {
44 typedef CppAD::AD<double> ADDouble;
45
46 using fourdst::config::Config;
47 using fourdst::logging::LogManager;
48 using fourdst::constant::Constants;
49
57 static constexpr double MIN_DENSITY_THRESHOLD = 1e-18;
58
66 static constexpr double MIN_ABUNDANCE_THRESHOLD = 1e-18;
67
74 static constexpr double MIN_JACOBIAN_THRESHOLD = 1e-24;
75
76
100 class GraphEngine final : public DynamicEngine{
101 public:
112 explicit GraphEngine(
113 const fourdst::composition::Composition &composition,
114 const BuildDepthType = NetworkBuildDepth::Full
115 );
116
117 explicit GraphEngine(
118 const fourdst::composition::Composition &composition,
119 const partition::PartitionFunction& partitionFunction,
120 const BuildDepthType buildDepth = NetworkBuildDepth::Full
121 );
122
131 explicit GraphEngine(const reaction::LogicalReactionSet &reactions);
132
146 [[nodiscard]] std::expected<StepDerivatives<double>, expectations::StaleEngineError> calculateRHSAndEnergy(
147 const std::vector<double>& Y,
148 const double T9,
149 const double rho
150 ) const override;
151
165 void generateJacobianMatrix(
166 const std::vector<double>& Y_dynamic,
167 const double T9,
168 const double rho
169 ) const override;
170
171 void generateJacobianMatrix(
172 const std::vector<double> &Y_dynamic,
173 double T9,
174 double rho,
175 const SparsityPattern &sparsityPattern
176 ) const override;
177
184 void generateStoichiometryMatrix() override;
185
198 [[nodiscard]] double calculateMolarReactionFlow(
199 const reaction::Reaction& reaction,
200 const std::vector<double>&Y,
201 const double T9,
202 const double rho
203 ) const override;
204
209 [[nodiscard]] const std::vector<fourdst::atomic::Species>& getNetworkSpecies() const override;
210
215 [[nodiscard]] const reaction::LogicalReactionSet& getNetworkReactions() const override;
216
217 void setNetworkReactions(const reaction::LogicalReactionSet& reactions) override;
218
230 [[nodiscard]] double getJacobianMatrixEntry(
231 const int i,
232 const int j
233 ) const override;
234
241 [[nodiscard]] static std::unordered_map<fourdst::atomic::Species, int> getNetReactionStoichiometry(
242 const reaction::Reaction& reaction
243 );
244
256 [[nodiscard]] int getStoichiometryMatrixEntry(
257 const int speciesIndex,
258 const int reactionIndex
259 ) const override;
260
272 [[nodiscard]] std::expected<std::unordered_map<fourdst::atomic::Species, double>, expectations::StaleEngineError> getSpeciesTimescales(
273 const std::vector<double>& Y,
274 double T9,
275 double rho
276 ) const override;
277
278 [[nodiscard]] std::expected<std::unordered_map<fourdst::atomic::Species, double>, expectations::StaleEngineError> getSpeciesDestructionTimescales(
279 const std::vector<double>& Y,
280 double T9,
281 double rho
282 ) const override;
283
284 fourdst::composition::Composition update(const NetIn &netIn) override;
285
286 bool isStale(const NetIn &netIn) override;
287
294 [[nodiscard]] bool involvesSpecies(
295 const fourdst::atomic::Species& species
296 ) const;
297
314 void exportToDot(
315 const std::string& filename
316 ) const;
317
334 void exportToCSV(
335 const std::string& filename
336 ) const;
337
338 void setScreeningModel(screening::ScreeningType) override;
339
340 [[nodiscard]] screening::ScreeningType getScreeningModel() const override;
341
342 void setPrecomputation(bool precompute);
343
344 [[nodiscard]] bool isPrecomputationEnabled() const;
345
346 [[nodiscard]] const partition::PartitionFunction& getPartitionFunction() const;
347
348 [[nodiscard]] double calculateReverseRate(
349 const reaction::Reaction &reaction,
350 double T9
351 ) const;
352
353 [[nodiscard]] double calculateReverseRateTwoBody(
354 const reaction::Reaction &reaction,
355 const double T9,
356 const double forwardRate,
357 const double expFactor
358 ) const;
359
360 [[nodiscard]] double calculateReverseRateTwoBodyDerivative(
361 const reaction::Reaction &reaction,
362 const double T9,
363 const double reverseRate
364 ) const;
365
366 [[nodiscard]] bool isUsingReverseReactions() const;
367
368 void setUseReverseReactions(bool useReverse);
369
370 [[nodiscard]] int getSpeciesIndex(
371 const fourdst::atomic::Species& species
372 ) const override;
373
374 [[nodiscard]] std::vector<double> mapNetInToMolarAbundanceVector(const NetIn &netIn) const override;
375
376 [[nodiscard]] PrimingReport primeEngine(const NetIn &netIn) override;
377
378 [[nodiscard]] BuildDepthType getDepth() const override;
379
380 void rebuild(const fourdst::composition::Composition& comp, const BuildDepthType depth) override;
381
382
383 private:
384 struct PrecomputedReaction {
385 // Forward cacheing
386 size_t reaction_index;
387 std::vector<size_t> unique_reactant_indices;
388 std::vector<int> reactant_powers;
389 double symmetry_factor;
390 std::vector<size_t> affected_species_indices;
391 std::vector<int> stoichiometric_coefficients;
392
393 // Reverse cacheing
394 std::vector<size_t> unique_product_indices;
395 std::vector<int> product_powers;
396 double reverse_symmetry_factor;
397 };
398
399 struct constants {
400 const double u = Constants::getInstance().get("u").value;
401 const double Na = Constants::getInstance().get("N_a").value;
402 const double c = Constants::getInstance().get("c").value;
403 const double kB = Constants::getInstance().get("kB").value;
404 };
405 private:
406 class AtomicReverseRate final : public CppAD::atomic_base<double> {
407 public:
408 AtomicReverseRate(
409 const reaction::Reaction& reaction,
410 const GraphEngine& engine
411 ):
412 atomic_base<double>("AtomicReverseRate"),
413 m_reaction(reaction),
414 m_engine(engine) {}
415
416 bool forward(
417 size_t p,
418 size_t q,
419 const CppAD::vector<bool>& vx,
420 CppAD::vector<bool>& vy,
421 const CppAD::vector<double>& tx,
422 CppAD::vector<double>& ty
423 ) override;
424 bool reverse(
425 size_t q,
426 const CppAD::vector<double>& tx,
427 const CppAD::vector<double>& ty,
428 CppAD::vector<double>& px,
429 const CppAD::vector<double>& py
430 ) override;
431 bool for_sparse_jac(
432 size_t q,
433 const CppAD::vector<std::set<size_t>>&r,
434 CppAD::vector<std::set<size_t>>& s
435 ) override;
436 bool rev_sparse_jac(
437 size_t q,
438 const CppAD::vector<std::set<size_t>>&rt,
439 CppAD::vector<std::set<size_t>>& st
440 ) override;
441
442 private:
443 const reaction::Reaction& m_reaction;
444 const GraphEngine& m_engine;
445 };
446 private:
447 Config& m_config = Config::getInstance();
448 quill::Logger* m_logger = LogManager::getInstance().getLogger("log");
449
450 constants m_constants;
451
452 reaction::LogicalReactionSet m_reactions;
453 std::unordered_map<std::string_view, reaction::Reaction*> m_reactionIDMap;
454
455 std::vector<fourdst::atomic::Species> m_networkSpecies;
456 std::unordered_map<std::string_view, fourdst::atomic::Species> m_networkSpeciesMap;
457 std::unordered_map<fourdst::atomic::Species, size_t> m_speciesToIndexMap;
458
459 boost::numeric::ublas::compressed_matrix<int> m_stoichiometryMatrix;
460
461 mutable boost::numeric::ublas::compressed_matrix<double> m_jacobianMatrix;
462 mutable CppAD::ADFun<double> m_rhsADFun;
463 mutable CppAD::sparse_jac_work m_jac_work;
464 CppAD::sparse_rc<std::vector<size_t>> m_full_jacobian_sparsity_pattern;
465
466 std::vector<std::unique_ptr<AtomicReverseRate>> m_atomicReverseRates;
467
468 screening::ScreeningType m_screeningType = screening::ScreeningType::BARE;
469 std::unique_ptr<screening::ScreeningModel> m_screeningModel = screening::selectScreeningModel(m_screeningType);
470
471 bool m_usePrecomputation = true;
472
473 bool m_useReverseReactions = true;
474
475 BuildDepthType m_depth;
476
477 std::vector<PrecomputedReaction> m_precomputedReactions;
478 std::unique_ptr<partition::PartitionFunction> m_partitionFunction;
479
480 private:
488 void syncInternalMaps();
489
496 void collectNetworkSpecies();
497
504 void populateReactionIDMap();
505
512 void populateSpeciesToIndexMap();
513
521 void reserveJacobianMatrix() const;
522
532 void recordADTape();
533
534 void collectAtomicReverseRateAtomicBases();
535
536 void precomputeNetwork();
537
538
548 [[nodiscard]] bool validateConservation() const;
549
550
551 [[nodiscard]] StepDerivatives<double> calculateAllDerivativesUsingPrecomputation(
552 const std::vector<double> &Y_in,
553 const std::vector<double>& bare_rates,
554 const std::vector<double> &bare_reverse_rates,
555 double T9, double rho
556 ) const;
557
571 template <IsArithmeticOrAD T>
572 T calculateMolarReactionFlow(
573 const reaction::Reaction &reaction,
574 const std::vector<T> &Y,
575 const T T9,
576 const T rho
577 ) const;
578
579 template<IsArithmeticOrAD T>
580 T calculateReverseMolarReactionFlow(
581 T T9,
582 T rho,
583 std::vector<T> screeningFactors,
584 std::vector<T> Y,
585 size_t reactionIndex,
586 const reaction::LogicalReaction &reaction
587 ) const;
588
601 template<IsArithmeticOrAD T>
602 [[nodiscard]] StepDerivatives<T> calculateAllDerivatives(
603 const std::vector<T> &Y_in,
604 T T9,
605 T rho
606 ) const;
607
620 [[nodiscard]] StepDerivatives<double> calculateAllDerivatives(
621 const std::vector<double>& Y_in,
622 const double T9,
623 const double rho
624 ) const;
625
638 [[nodiscard]] StepDerivatives<ADDouble> calculateAllDerivatives(
639 const std::vector<ADDouble>& Y_in,
640 const ADDouble &T9,
641 const ADDouble &rho
642 ) const;
643 };
644
645
646
647 template <IsArithmeticOrAD T>
648 T GraphEngine::calculateReverseMolarReactionFlow(
649 T T9,
650 T rho,
651 std::vector<T> screeningFactors,
652 std::vector<T> Y,
653 size_t reactionIndex,
654 const reaction::LogicalReaction &reaction
655 ) const {
656 if (!m_useReverseReactions) {
657 return static_cast<T>(0.0); // If reverse reactions are not used, return zero
658 }
659 T reverseMolarFlow = static_cast<T>(0.0);
660
661 if (reaction.qValue() != 0.0) {
662 T reverseRateConstant = static_cast<T>(0.0);
663 if constexpr (std::is_same_v<T, ADDouble>) { // Check if T is an AD type at compile time
664 const auto& atomic_func_ptr = m_atomicReverseRates[reactionIndex];
665 if (atomic_func_ptr != nullptr) {
666 // A. Instantiate the atomic operator for the specific reaction
667 // B. Marshal the input vector
668 std::vector<T> ax = { T9 };
669
670 std::vector<T> ay(1);
671 (*atomic_func_ptr)(ax, ay);
672 reverseRateConstant = static_cast<T>(ay[0]);
673 } else {
674 return reverseMolarFlow; // If no atomic function is available, return zero
675 }
676 } else {
677 // A,B If not calling with an AD type, calculate the reverse rate directly
678 reverseRateConstant = calculateReverseRate(reaction, T9);
679 }
680
681 // C. Get product multiplicities
682 std::unordered_map<fourdst::atomic::Species, int> productCounts;
683 for (const auto& product : reaction.products()) {
684 productCounts[product]++;
685 }
686
687 // D. Calculate the symmetry factor
688 T reverseSymmetryFactor = static_cast<T>(1.0);
689 for (const auto &count: productCounts | std::views::values) {
690 reverseSymmetryFactor /= static_cast<T>(std::tgamma(static_cast<double>(count + 1))); // Gamma function for factorial
691 }
692
693 // E. Calculate the abundance term
694 T productAbundanceTerm = static_cast<T>(1.0);
695 for (const auto& [species, count] : productCounts) {
696 const unsigned long speciesIndex = m_speciesToIndexMap.at(species);
697 productAbundanceTerm *= CppAD::pow(Y[speciesIndex], count);
698 }
699
700 // F. Determine the power for the density term
701 const size_t num_products = reaction.products().size();
702 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
703
704 // G. Assemble the reverse molar flow rate
705 reverseMolarFlow = screeningFactors[reactionIndex] *
706 reverseRateConstant *
707 productAbundanceTerm *
708 reverseSymmetryFactor *
709 rho_power;
710 }
711 return reverseMolarFlow;
712 }
713
714 template<IsArithmeticOrAD T>
715 StepDerivatives<T> GraphEngine::calculateAllDerivatives(
716 const std::vector<T> &Y_in, T T9, T rho) const {
717 std::vector<T> screeningFactors = m_screeningModel->calculateScreeningFactors(
718 m_reactions,
719 m_networkSpecies,
720 Y_in,
721 T9,
722 rho
723 );
724
725 // --- Setup output derivatives structure ---
726 StepDerivatives<T> result;
727 result.dydt.resize(m_networkSpecies.size(), static_cast<T>(0.0));
728
729 // --- AD Pre-setup (flags to control conditionals in an AD safe / branch aware manner) ---
730 // ----- Constants for AD safe calculations ---
731 const T zero = static_cast<T>(0.0);
732 const T one = static_cast<T>(1.0);
733
734 // ----- Initialize variables for molar concentration product and thresholds ---
735 // Note: the logic here is that we use CppAD::CondExprLt to test thresholds and if they are less we set the flag
736 // to zero so that the final returned reaction flow is 0. This is as opposed to standard if statements
737 // which create branches that break the AD tape.
738 const T rho_threshold = static_cast<T>(MIN_DENSITY_THRESHOLD);
739
740 // --- Check if the density is below the threshold where we ignore reactions ---
741 T threshold_flag = CppAD::CondExpLt(rho, rho_threshold, zero, one); // If rho < threshold, set flag to 0
742
743 std::vector<T> Y = Y_in;
744 for (size_t i = 0; i < m_networkSpecies.size(); ++i) {
745 // We use CppAD::CondExpLt to handle AD taping and prevent branching
746 // Note that while this is syntactically more complex this is equivalent to
747 // if (Y[i] < 0) {Y[i] = 0;}
748 // The issue is that this would introduce a branch which would require the auto diff tape to be re-recorded
749 // each timestep, which is very inefficient.
750 Y[i] = CppAD::CondExpLt(Y[i], zero, zero, Y[i]); // Ensure no negative abundances
751 }
752
753 const T u = static_cast<T>(m_constants.u); // Atomic mass unit in grams
754 const T N_A = static_cast<T>(m_constants.Na); // Avogadro's number in mol^-1
755 const T c = static_cast<T>(m_constants.c); // Speed of light in cm/s
756
757 // --- SINGLE LOOP OVER ALL REACTIONS ---
758 for (size_t reactionIndex = 0; reactionIndex < m_reactions.size(); ++reactionIndex) {
759 const auto& reaction = m_reactions[reactionIndex];
760
761 // 1. Calculate forward reaction rate
762 const T forwardMolarReactionFlow = screeningFactors[reactionIndex] *
763 calculateMolarReactionFlow<T>(reaction, Y, T9, rho);
764
765 // 2. Calculate reverse reaction rate
766 T reverseMolarFlow = calculateReverseMolarReactionFlow<T>(
767 T9,
768 rho,
769 screeningFactors,
770 Y,
771 reactionIndex,
772 reaction
773 );
774
775 const T molarReactionFlow = forwardMolarReactionFlow - reverseMolarFlow; // Net molar reaction flow
776
777 // 3. Use the rate to update all relevant species derivatives (dY/dt)
778 for (size_t speciesIndex = 0; speciesIndex < m_networkSpecies.size(); ++speciesIndex) {
779 const T nu_ij = static_cast<T>(m_stoichiometryMatrix(speciesIndex, reactionIndex));
780 result.dydt[speciesIndex] += threshold_flag * nu_ij * molarReactionFlow;
781 }
782 }
783
784 T massProductionRate = static_cast<T>(0.0); // [mol][s^-1]
785 for (const auto& [species, index] : m_speciesToIndexMap) {
786 massProductionRate += result.dydt[index] * species.mass() * u;
787 }
788
789 result.nuclearEnergyGenerationRate = -massProductionRate * N_A * c * c; // [cm^2][s^-3] = [erg][s^-1][g^-1]
790
791 return result;
792 }
793
794
795 template <IsArithmeticOrAD T>
796 T GraphEngine::calculateMolarReactionFlow(
797 const reaction::Reaction &reaction,
798 const std::vector<T> &Y,
799 const T T9,
800 const T rho
801 ) const {
802
803 // --- Pre-setup (flags to control conditionals in an AD safe / branch aware manner) ---
804 // ----- Constants for AD safe calculations ---
805 const T zero = static_cast<T>(0.0);
806
807 // --- Calculate the molar reaction rate (in units of [s^-1][cm^3(N-1)][mol^(1-N)] for N reactants) ---
808 const T k_reaction = reaction.calculate_rate(T9);
809
810 // --- Cound the number of each reactant species to account for species multiplicity ---
811 std::unordered_map<std::string, int> reactant_counts;
812 reactant_counts.reserve(reaction.reactants().size());
813 for (const auto& reactant : reaction.reactants()) {
814 reactant_counts[std::string(reactant.name())]++;
815 }
816 const int totalReactants = static_cast<int>(reaction.reactants().size());
817
818 // --- Accumulator for the molar concentration ---
819 auto molar_concentration_product = static_cast<T>(1.0);
820
821 // --- Loop through each unique reactant species and calculate the molar concentration for that species then multiply that into the accumulator ---
822 for (const auto& [species_name, count] : reactant_counts) {
823 // --- Resolve species to molar abundance ---
824 // PERF: Could probably optimize out this lookup
825 const auto species_it = m_speciesToIndexMap.find(m_networkSpeciesMap.at(species_name));
826 const size_t species_index = species_it->second;
827 const T Yi = Y[species_index];
828
829 // --- 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 ---
830 molar_concentration_product *= CppAD::pow(Yi, static_cast<T>(count)); // ni^count
831
832 // --- Apply factorial correction for identical reactions ---
833 if (count > 1) {
834 molar_concentration_product /= static_cast<T>(std::tgamma(static_cast<double>(count + 1))); // Gamma function for factorial
835 }
836 }
837 // --- Final reaction flow calculation [mol][s^-1][g^-1] ---
838 // Note: If the threshold flag ever gets set to zero this will return zero.
839 // This will result basically in multiple branches being written to the AD tape, which will make
840 // the tape more expensive to record, but it will also mean that we only need to record it once for
841 // the entire network.
842 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
843 return molar_concentration_product * k_reaction * densityTerm;
844 }
845
846};
gridfire::DynamicEngine
Abstract class for engines supporting Jacobian and stoichiometry operations.
Definition engine_abstract.h:130
gridfire::GraphEngine::AtomicReverseRate::AtomicReverseRate
AtomicReverseRate(const reaction::Reaction &reaction, const GraphEngine &engine)
Definition engine_graph.h:408
gridfire::GraphEngine::AtomicReverseRate::reverse
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
Definition engine_graph.cpp:1051
gridfire::GraphEngine::AtomicReverseRate::m_engine
const GraphEngine & m_engine
Definition engine_graph.h:444
gridfire::GraphEngine::AtomicReverseRate::rev_sparse_jac
bool rev_sparse_jac(size_t q, const CppAD::vector< std::set< size_t > > &rt, CppAD::vector< std::set< size_t > > &st) override
Definition engine_graph.cpp:1078
gridfire::GraphEngine::AtomicReverseRate::m_reaction
const reaction::Reaction & m_reaction
Definition engine_graph.h:443
gridfire::GraphEngine::AtomicReverseRate::forward
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
Definition engine_graph.cpp:1029
gridfire::GraphEngine::AtomicReverseRate::for_sparse_jac
bool for_sparse_jac(size_t q, const CppAD::vector< std::set< size_t > > &r, CppAD::vector< std::set< size_t > > &s) override
Definition engine_graph.cpp:1069
gridfire::GraphEngine::isPrecomputationEnabled
bool isPrecomputationEnabled() const
Definition engine_graph.cpp:615
gridfire::GraphEngine::calculateReverseRateTwoBody
double calculateReverseRateTwoBody(const reaction::Reaction &reaction, const double T9, const double forwardRate, const double expFactor) const
Definition engine_graph.cpp:269
gridfire::GraphEngine::calculateReverseRate
double calculateReverseRate(const reaction::Reaction &reaction, double T9) const
Definition engine_graph.cpp:242
gridfire::GraphEngine::getNetworkSpecies
const std::vector< fourdst::atomic::Species > & getNetworkSpecies() const override
Gets the list of species in the network.
Definition engine_graph.cpp:162
gridfire::GraphEngine::m_constants
constants m_constants
Definition engine_graph.h:450
gridfire::GraphEngine::getDepth
BuildDepthType getDepth() const override
Definition engine_graph.cpp:434
gridfire::GraphEngine::calculateReverseMolarReactionFlow
T calculateReverseMolarReactionFlow(T T9, T rho, std::vector< T > screeningFactors, std::vector< T > Y, size_t reactionIndex, const reaction::LogicalReaction &reaction) const
Definition engine_graph.h:648
gridfire::GraphEngine::m_usePrecomputation
bool m_usePrecomputation
Flag to enable or disable using precomputed reactions for efficiency. Mathematically,...
Definition engine_graph.h:471
gridfire::GraphEngine::m_full_jacobian_sparsity_pattern
CppAD::sparse_rc< std::vector< size_t > > m_full_jacobian_sparsity_pattern
Full sparsity pattern for the Jacobian matrix.
Definition engine_graph.h:464
gridfire::GraphEngine::m_jac_work
CppAD::sparse_jac_work m_jac_work
Work object for sparse Jacobian calculations.
Definition engine_graph.h:463
gridfire::GraphEngine::populateReactionIDMap
void populateReactionIDMap()
Populates the reaction ID map.
Definition engine_graph.cpp:135
gridfire::GraphEngine::mapNetInToMolarAbundanceVector
std::vector< double > mapNetInToMolarAbundanceVector(const NetIn &netIn) const override
Definition engine_graph.cpp:399
gridfire::GraphEngine::collectAtomicReverseRateAtomicBases
void collectAtomicReverseRateAtomicBases()
Definition engine_graph.cpp:947
gridfire::GraphEngine::m_rhsADFun
CppAD::ADFun< double > m_rhsADFun
CppAD function for the right-hand side of the ODE.
Definition engine_graph.h:462
gridfire::GraphEngine::m_jacobianMatrix
boost::numeric::ublas::compressed_matrix< double > m_jacobianMatrix
Jacobian matrix (species x species).
Definition engine_graph.h:461
gridfire::GraphEngine::getJacobianMatrixEntry
double getJacobianMatrixEntry(const int i, const int j) const override
Gets an entry from the previously generated Jacobian matrix.
Definition engine_graph.cpp:722
gridfire::GraphEngine::m_networkSpeciesMap
std::unordered_map< std::string_view, fourdst::atomic::Species > m_networkSpeciesMap
Map from species name to Species object.
Definition engine_graph.h:456
gridfire::GraphEngine::m_useReverseReactions
bool m_useReverseReactions
Flag to enable or disable reverse reactions. If false, only forward reactions are considered.
Definition engine_graph.h:473
gridfire::GraphEngine::m_partitionFunction
std::unique_ptr< partition::PartitionFunction > m_partitionFunction
Partition function for the network.
Definition engine_graph.h:478
gridfire::GraphEngine::setNetworkReactions
void setNetworkReactions(const reaction::LogicalReactionSet &reactions) override
Definition engine_graph.cpp:174
gridfire::GraphEngine::m_config
Config & m_config
Definition engine_graph.h:447
gridfire::GraphEngine::setUseReverseReactions
void setUseReverseReactions(bool useReverse)
Definition engine_graph.cpp:391
gridfire::GraphEngine::populateSpeciesToIndexMap
void populateSpeciesToIndexMap()
Populates the species-to-index map.
Definition engine_graph.cpp:144
gridfire::GraphEngine::m_logger
quill::Logger * m_logger
Definition engine_graph.h:448
gridfire::GraphEngine::m_screeningType
screening::ScreeningType m_screeningType
Screening type for the reaction network. Default to no screening.
Definition engine_graph.h:468
gridfire::GraphEngine::update
fourdst::composition::Composition update(const NetIn &netIn) override
Update the internal state of the engine.
Definition engine_graph.cpp:886
gridfire::GraphEngine::m_precomputedReactions
std::vector< PrecomputedReaction > m_precomputedReactions
Precomputed reactions for efficiency.
Definition engine_graph.h:477
gridfire::GraphEngine::m_reactionIDMap
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 ...
Definition engine_graph.h:453
gridfire::GraphEngine::getSpeciesTimescales
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.
Definition engine_graph.cpp:842
gridfire::GraphEngine::getScreeningModel
screening::ScreeningType getScreeningModel() const override
Get the current electron screening model.
Definition engine_graph.cpp:607
gridfire::GraphEngine::getStoichiometryMatrixEntry
int getStoichiometryMatrixEntry(const int speciesIndex, const int reactionIndex) const override
Gets an entry from the stoichiometry matrix.
Definition engine_graph.cpp:733
gridfire::GraphEngine::setPrecomputation
void setPrecomputation(bool precompute)
Definition engine_graph.cpp:611
gridfire::GraphEngine::m_depth
BuildDepthType m_depth
Definition engine_graph.h:475
gridfire::GraphEngine::setScreeningModel
void setScreeningModel(screening::ScreeningType) override
Set the electron screening model.
Definition engine_graph.cpp:602
gridfire::GraphEngine::m_atomicReverseRates
std::vector< std::unique_ptr< AtomicReverseRate > > m_atomicReverseRates
Definition engine_graph.h:466
gridfire::GraphEngine::exportToCSV
void exportToCSV(const std::string &filename) const
Exports the network to a CSV file for analysis.
Definition engine_graph.cpp:788
gridfire::GraphEngine::getNetReactionStoichiometry
static std::unordered_map< fourdst::atomic::Species, int > getNetReactionStoichiometry(const reaction::Reaction &reaction)
Gets the net stoichiometry for a given reaction.
Definition engine_graph.cpp:727
gridfire::GraphEngine::reserveJacobianMatrix
void reserveJacobianMatrix() const
Reserves space for the Jacobian matrix.
Definition engine_graph.cpp:151
gridfire::GraphEngine::getSpeciesIndex
int getSpeciesIndex(const fourdst::atomic::Species &species) const override
Definition engine_graph.cpp:395
gridfire::GraphEngine::calculateMolarReactionFlow
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.
Definition engine_graph.cpp:623
gridfire::GraphEngine::precomputeNetwork
void precomputeNetwork()
Definition engine_graph.cpp:960
gridfire::GraphEngine::m_networkSpecies
std::vector< fourdst::atomic::Species > m_networkSpecies
Vector of unique species in the network.
Definition engine_graph.h:455
gridfire::GraphEngine::recordADTape
void recordADTape()
Records the AD tape for the right-hand side of the ODE.
Definition engine_graph.cpp:902
gridfire::GraphEngine::calculateAllDerivativesUsingPrecomputation
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
Definition engine_graph.cpp:448
gridfire::GraphEngine::involvesSpecies
bool involvesSpecies(const fourdst::atomic::Species &species) const
Checks if a given species is involved in the network.
Definition engine_graph.cpp:179
gridfire::GraphEngine::calculateRHSAndEnergy
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.
Definition engine_graph.cpp:57
gridfire::GraphEngine::m_reactions
reaction::LogicalReactionSet m_reactions
Set of REACLIB reactions in the network.
Definition engine_graph.h:452
gridfire::GraphEngine::syncInternalMaps
void syncInternalMaps()
Synchronizes the internal maps.
Definition engine_graph.cpp:81
gridfire::GraphEngine::validateConservation
bool validateConservation() const
Validates mass and charge conservation across all reactions.
Definition engine_graph.cpp:187
gridfire::GraphEngine::generateJacobianMatrix
void generateJacobianMatrix(const std::vector< double > &Y_dynamic, const double T9, const double rho) const override
Generates the Jacobian matrix for the current state.
Definition engine_graph.cpp:632
gridfire::GraphEngine::m_stoichiometryMatrix
boost::numeric::ublas::compressed_matrix< int > m_stoichiometryMatrix
Stoichiometry matrix (species x reactions).
Definition engine_graph.h:459
gridfire::GraphEngine::getNetworkReactions
const reaction::LogicalReactionSet & getNetworkReactions() const override
Gets the set of logical reactions in the network.
Definition engine_graph.cpp:168
gridfire::GraphEngine::m_speciesToIndexMap
std::unordered_map< fourdst::atomic::Species, size_t > m_speciesToIndexMap
Map from species to their index in the stoichiometry matrix.
Definition engine_graph.h:457
gridfire::GraphEngine::rebuild
void rebuild(const fourdst::composition::Composition &comp, const BuildDepthType depth) override
Definition engine_graph.cpp:438
gridfire::GraphEngine::exportToDot
void exportToDot(const std::string &filename) const
Exports the network to a DOT file for visualization.
Definition engine_graph.cpp:740
gridfire::GraphEngine::getPartitionFunction
const partition::PartitionFunction & getPartitionFunction() const
Definition engine_graph.cpp:619
gridfire::GraphEngine::isUsingReverseReactions
bool isUsingReverseReactions() const
Definition engine_graph.cpp:387
gridfire::GraphEngine::primeEngine
PrimingReport primeEngine(const NetIn &netIn) override
Definition engine_graph.cpp:407
gridfire::GraphEngine::generateStoichiometryMatrix
void generateStoichiometryMatrix() override
Generates the stoichiometry matrix for the network.
Definition engine_graph.cpp:545
gridfire::GraphEngine::collectNetworkSpecies
void collectNetworkSpecies()
Collects the unique species in the network.
Definition engine_graph.cpp:106
gridfire::GraphEngine::getSpeciesDestructionTimescales
std::expected< std::unordered_map< fourdst::atomic::Species, double >, expectations::StaleEngineError > getSpeciesDestructionTimescales(const std::vector< double > &Y, double T9, double rho) const override
Definition engine_graph.cpp:861
gridfire::GraphEngine::isStale
bool isStale(const NetIn &netIn) override
Definition engine_graph.cpp:898
gridfire::GraphEngine::m_screeningModel
std::unique_ptr< screening::ScreeningModel > m_screeningModel
Definition engine_graph.h:469
gridfire::GraphEngine::calculateReverseRateTwoBodyDerivative
double calculateReverseRateTwoBodyDerivative(const reaction::Reaction &reaction, const double T9, const double reverseRate) const
Definition engine_graph.cpp:346
gridfire::GraphEngine::calculateAllDerivatives
StepDerivatives< T > calculateAllDerivatives(const std::vector< T > &Y_in, T T9, T rho) const
Calculates all derivatives (dY/dt) and the energy generation rate.
Definition engine_graph.h:715
gridfire::GraphEngine::GraphEngine
GraphEngine(const fourdst::composition::Composition &composition, const BuildDepthType=NetworkBuildDepth::Full)
Constructs a GraphEngine from a composition.
Definition engine_graph.cpp:34
gridfire::partition::PartitionFunction
Abstract interface for evaluating nuclear partition functions.
Definition partition_abstract.h:17
gridfire::reaction::LogicalReaction
Represents a "logical" reaction that aggregates rates from multiple sources.
Definition reaction.h:310
gridfire::reaction::Reaction
Represents a single nuclear reaction from a specific data source.
Definition reaction.h:72
construction.h
engine_abstract.h
Abstract interfaces for reaction network engines in GridFire.
gridfire::reaction
Definition reaction.h:25
gridfire::reaction::LogicalReactionSet
TemplatedReactionSet< LogicalReaction > LogicalReactionSet
A set of logical reactions.
Definition reaction.h:563
gridfire::screening::selectScreeningModel
std::unique_ptr< ScreeningModel > selectScreeningModel(ScreeningType type)
A factory function to select and create a screening model.
Definition screening_types.cpp:9
gridfire::screening::ScreeningType
ScreeningType
Enumerates the available plasma screening models.
Definition screening_types.h:15
gridfire::screening::ScreeningType::BARE
@ BARE
No screening applied. The screening factor is always 1.0.
Definition screening_types.h:16
gridfire
Definition engine_abstract.h:31
gridfire::NetworkBuildDepth::Full
@ Full
Definition building.h:22
gridfire::ADDouble
CppAD::AD< double > ADDouble
Alias for CppAD AD type for double precision.
Definition engine_graph.h:44
gridfire::BuildDepthType
std::variant< NetworkBuildDepth, int > BuildDepthType
Variant specifying either a predefined NetworkBuildDepth or a custom integer depth.
Definition building.h:37
gridfire::SparsityPattern
std::vector< std::pair< size_t, size_t > > SparsityPattern
Definition engine_abstract.h:65
gridfire::MIN_ABUNDANCE_THRESHOLD
static constexpr double MIN_ABUNDANCE_THRESHOLD
Minimum abundance threshold below which species are ignored.
Definition engine_graph.h:66
gridfire::MIN_DENSITY_THRESHOLD
static constexpr double MIN_DENSITY_THRESHOLD
Minimum density threshold below which reactions are ignored.
Definition engine_graph.h:57
gridfire::MIN_JACOBIAN_THRESHOLD
static constexpr double MIN_JACOBIAN_THRESHOLD
Minimum value for Jacobian matrix entries.
Definition engine_graph.h:74
network.h
partition_abstract.h
priming.h
reaction.h
Defines classes for representing and managing nuclear reactions.
screening_abstract.h
screening_types.h
gridfire::GraphEngine::PrecomputedReaction
Definition engine_graph.h:384
gridfire::GraphEngine::PrecomputedReaction::reactant_powers
std::vector< int > reactant_powers
Definition engine_graph.h:388
gridfire::GraphEngine::PrecomputedReaction::product_powers
std::vector< int > product_powers
Powers of each unique product in the reverse reaction.
Definition engine_graph.h:395
gridfire::GraphEngine::PrecomputedReaction::affected_species_indices
std::vector< size_t > affected_species_indices
Definition engine_graph.h:390
gridfire::GraphEngine::PrecomputedReaction::unique_reactant_indices
std::vector< size_t > unique_reactant_indices
Definition engine_graph.h:387
gridfire::GraphEngine::PrecomputedReaction::reverse_symmetry_factor
double reverse_symmetry_factor
Symmetry factor for reverse reactions.
Definition engine_graph.h:396
gridfire::GraphEngine::PrecomputedReaction::stoichiometric_coefficients
std::vector< int > stoichiometric_coefficients
Definition engine_graph.h:391
gridfire::GraphEngine::PrecomputedReaction::reaction_index
size_t reaction_index
Definition engine_graph.h:386
gridfire::GraphEngine::PrecomputedReaction::unique_product_indices
std::vector< size_t > unique_product_indices
Unique product indices for reverse reactions.
Definition engine_graph.h:394
gridfire::GraphEngine::PrecomputedReaction::symmetry_factor
double symmetry_factor
Definition engine_graph.h:389
gridfire::GraphEngine::constants
Definition engine_graph.h:399
gridfire::GraphEngine::constants::kB
const double kB
Boltzmann constant in erg/K.
Definition engine_graph.h:403
gridfire::GraphEngine::constants::u
const double u
Atomic mass unit in g.
Definition engine_graph.h:400
gridfire::GraphEngine::constants::Na
const double Na
Avogadro's number.
Definition engine_graph.h:401
gridfire::GraphEngine::constants::c
const double c
Speed of light in cm/s.
Definition engine_graph.h:402
gridfire::NetIn
Definition network.h:53
gridfire::PrimingReport
Captures the result of a network priming operation.
Definition reporting.h:67
gridfire::StepDerivatives
Structure holding derivatives and energy generation for a network step.
Definition engine_abstract.h:60
gridfire::StepDerivatives::nuclearEnergyGenerationRate
T nuclearEnergyGenerationRate
Specific energy generation rate (e.g., erg/g/s).
Definition engine_abstract.h:62
gridfire::StepDerivatives::dydt
std::vector< T > dydt
Derivatives of abundances (dY/dt for each species).
Definition engine_abstract.h:61
gridfire::expectations::StaleEngineError
Definition expected_engine.h:44