GridFire v0.7.1_rc2
General Purpose Nuclear Network
Loading...
Searching...
No Matches
gridfire::solver::CVODESolverStrategy Class Referencefinal

Stiff ODE integrator backed by SUNDIALS CVODE (BDF) for network + energy. More...

#include <CVODE_solver_strategy.h>

Inheritance diagram for gridfire::solver::CVODESolverStrategy:
[legend]
Collaboration diagram for gridfire::solver::CVODESolverStrategy:
[legend]

Classes

struct  CVODERHSOutputData
 
struct  CVODEUserData
 A helper struct to pass C++ context to C-style CVODE callbacks. More...
 
struct  TimestepContext
 Immutable view of the current integration state passed to callbacks. More...
 

Public Types

using TimestepCallback = std::function< void(const TimestepContext &context)>
 Type alias for a timestep callback function.
 

Public Member Functions

 CVODESolverStrategy (engine::DynamicEngine &engine)
 Construct the CVODE strategy and create a SUNDIALS context.
 
 ~CVODESolverStrategy () override
 Destructor: cleans CVODE/SUNDIALS resources and frees SUNContext.
 
 CVODESolverStrategy (const CVODESolverStrategy &)=delete
 
CVODESolverStrategyoperator= (const CVODESolverStrategy &)=delete
 
 CVODESolverStrategy (CVODESolverStrategy &&)=delete
 
CVODESolverStrategyoperator= (CVODESolverStrategy &&)=delete
 
NetOut evaluate (const NetIn &netIn) override
 Integrate from t=0 to netIn.tMax and return final composition and energy.
 
NetOut evaluate (const NetIn &netIn, bool displayTrigger)
 Call to evaluate which will let the user control if the trigger reasoning is displayed.
 
void set_callback (const std::any &callback) override
 Install a timestep callback.
 
bool get_stdout_logging_enabled () const
 Whether per-step logs are printed to stdout and CVode is stepped with CV_ONE_STEP.
 
void set_stdout_logging_enabled (bool logging_enabled)
 Enable/disable per-step stdout logging.
 
void set_absTol (double absTol)
 
void set_relTol (double relTol)
 
double get_absTol () const
 
double get_relTol () const
 
std::vector< std::tuple< std::string, std::string > > describe_callback_context () const override
 Schema of fields exposed to the timestep callback context.
 
- Public Member Functions inherited from gridfire::solver::NetworkSolverStrategy< EngineT >
 NetworkSolverStrategy (EngineT &engine)
 Constructor for the NetworkSolverStrategy.
 
virtual ~NetworkSolverStrategy ()=default
 Virtual destructor.
 

Private Member Functions

CVODERHSOutputData calculate_rhs (sunrealtype t, N_Vector y, N_Vector ydot, const CVODEUserData *data) const
 Compute RHS into ydot at time t from the engine and current state y.
 
void initialize_cvode_integration_resources (uint64_t N, size_t numSpecies, double current_time, const fourdst::composition::Composition &composition, double absTol, double relTol, double accumulatedEnergy)
 Allocate and initialize CVODE vectors, linear algebra, tolerances, and constraints.
 
void cleanup_cvode_resources (bool memFree)
 Destroy CVODE vectors/linear algebra and optionally the CVODE memory block.
 
void set_detailed_step_logging (bool enabled)
 
void log_step_diagnostics (const CVODEUserData &user_data, bool displayJacobianStiffness, bool displaySpeciesBalance, bool to_file, std::optional< std::string > filename) const
 Compute and print per-component error ratios; run diagnostic helpers.
 

Static Private Member Functions

static int cvode_rhs_wrapper (sunrealtype t, N_Vector y, N_Vector ydot, void *user_data)
 CVODE RHS C-wrapper that delegates to calculate_rhs and captures exceptions.
 
static int cvode_jac_wrapper (sunrealtype t, N_Vector y, N_Vector ydot, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
 CVODE dense Jacobian C-wrapper that fills SUNDenseMatrix using the engine.
 

Private Attributes

fourdst::config::Config & m_config = fourdst::config::Config::getInstance()
 
quill::Logger * m_logger = fourdst::logging::LogManager::getInstance().getLogger("log")
 
SUNContext m_sun_ctx = nullptr
 SUNDIALS context (lifetime of the solver).
 
void * m_cvode_mem = nullptr
 CVODE memory block.
 
N_Vector m_Y = nullptr
 CVODE state vector (species + energy accumulator).
 
N_Vector m_YErr = nullptr
 Estimated local errors.
 
SUNMatrix m_J = nullptr
 Dense Jacobian matrix.
 
SUNLinearSolver m_LS = nullptr
 Dense linear solver.
 
std::optional< TimestepCallbackm_callback
 Optional per-step callback.
 
int m_num_steps = 0
 CVODE step counter (used for diagnostics and triggers).
 
bool m_stdout_logging_enabled = true
 If true, print per-step logs and use CV_ONE_STEP.
 
N_Vector m_constraints = nullptr
 CVODE constraints vector (>= 0 for species entries).
 
std::optional< double > m_absTol
 User-specified absolute tolerance.
 
std::optional< double > m_relTol
 User-specified relative tolerance.
 
bool m_detailed_step_logging = false
 If true, log detailed step diagnostics (error ratios, Jacobian, species balance).
 

Additional Inherited Members

- Protected Attributes inherited from gridfire::solver::NetworkSolverStrategy< EngineT >
EngineT & m_engine
 The engine used by this solver strategy.
 

Detailed Description

Stiff ODE integrator backed by SUNDIALS CVODE (BDF) for network + energy.

Integrates the nuclear network abundances along with a final accumulator entry for specific energy using CVODE's BDF method and a dense linear solver. The state vector layout is: [y_0, y_1, ..., y_{N-1}, eps], where eps is the accumulated specific energy (erg/g).

Implementation summary:

  • Creates a SUNContext and CVODE memory; initializes the state from a Composition.
  • Enforces non-negativity on species via CVodeSetConstraints (>= 0 for all species slots).
  • Uses a user-provided DynamicEngine to compute RHS and to fill the dense Jacobian.
  • The Jacobian is assembled column-major into a SUNDenseMatrix; the energy row/column is currently set to zero (decoupled from abundances in the linearization).
  • An internal trigger can rebuild the engine/network; when triggered, CVODE resources are torn down and recreated with the new network size, preserving the energy accumulator.
  • The CVODE RHS wrapper captures exceptions::StaleEngineTrigger from the engine evaluation path as recoverable (return code 1) and stores a copy in user-data for the driver loop.
Example
using gridfire::solver::NetIn;
CVODESolverStrategy solver(engine);
NetIn in;
in.temperature = 1.0e9; // K
in.density = 1.0e6; // g/cm^3
in.tMax = 1.0; // s
in.composition = initialComposition;
auto out = solver.evaluate(in);
std::cout << "Final energy: " << out.energy << " erg/g\n";
Stiff ODE integrator backed by SUNDIALS CVODE (BDF) for network + energy.
Definition CVODE_solver_strategy.h:81
Definition types.h:27
double density
Density in g/cm^3.
Definition types.h:32
double tMax
Maximum time.
Definition types.h:29
fourdst::composition::Composition composition
Composition of the network.
Definition types.h:28
double temperature
Temperature in Kelvin.
Definition types.h:31

Member Typedef Documentation

◆ TimestepCallback

using gridfire::solver::CVODESolverStrategy::TimestepCallback = std::function<void(const TimestepContext& context)>

Type alias for a timestep callback function.

Constructor & Destructor Documentation

◆ CVODESolverStrategy() [1/3]

gridfire::solver::CVODESolverStrategy::CVODESolverStrategy ( engine::DynamicEngine engine)
explicit

Construct the CVODE strategy and create a SUNDIALS context.

Parameters
engineDynamicEngine used for RHS/Jacobian evaluation and network access.
Exceptions
std::runtime_errorIf SUNContext_Create fails.

◆ ~CVODESolverStrategy()

gridfire::solver::CVODESolverStrategy::~CVODESolverStrategy ( )
override

Destructor: cleans CVODE/SUNDIALS resources and frees SUNContext.

◆ CVODESolverStrategy() [2/3]

gridfire::solver::CVODESolverStrategy::CVODESolverStrategy ( const CVODESolverStrategy )
delete

◆ CVODESolverStrategy() [3/3]

gridfire::solver::CVODESolverStrategy::CVODESolverStrategy ( CVODESolverStrategy &&  )
delete

Member Function Documentation

◆ calculate_rhs()

CVODESolverStrategy::CVODERHSOutputData gridfire::solver::CVODESolverStrategy::calculate_rhs ( sunrealtype  t,
N_Vector  y,
N_Vector  ydot,
const CVODEUserData data 
) const
private

Compute RHS into ydot at time t from the engine and current state y.

Converts the CVODE state to a Composition (mass fractions) and calls engine.calculateRHSAndEnergy(T9, rho). Negative small abundances are clamped to zero before constructing Composition. On stale engine, throws exceptions::StaleEngineTrigger.

◆ cleanup_cvode_resources()

void gridfire::solver::CVODESolverStrategy::cleanup_cvode_resources ( bool  memFree)
private

Destroy CVODE vectors/linear algebra and optionally the CVODE memory block.

Parameters
memFreeIf true, also calls CVodeFree on m_cvode_mem.

◆ cvode_jac_wrapper()

int gridfire::solver::CVODESolverStrategy::cvode_jac_wrapper ( sunrealtype  t,
N_Vector  y,
N_Vector  ydot,
SUNMatrix  J,
void *  user_data,
N_Vector  tmp1,
N_Vector  tmp2,
N_Vector  tmp3 
)
staticprivate

CVODE dense Jacobian C-wrapper that fills SUNDenseMatrix using the engine.

Assembles J(i,j) = d(f_i)/d(y_j) for all species using engine->getJacobianMatrixEntry, then zeros the last row and column corresponding to the energy variable.

◆ cvode_rhs_wrapper()

int gridfire::solver::CVODESolverStrategy::cvode_rhs_wrapper ( sunrealtype  t,
N_Vector  y,
N_Vector  ydot,
void *  user_data 
)
staticprivate

CVODE RHS C-wrapper that delegates to calculate_rhs and captures exceptions.

Returns
0 on success; 1 on recoverable StaleEngineTrigger; -1 on other failures.

◆ describe_callback_context()

std::vector< std::tuple< std::string, std::string > > gridfire::solver::CVODESolverStrategy::describe_callback_context ( ) const
overridevirtual

Schema of fields exposed to the timestep callback context.

Implements gridfire::solver::NetworkSolverStrategy< EngineT >.

◆ evaluate() [1/2]

NetOut gridfire::solver::CVODESolverStrategy::evaluate ( const NetIn netIn)
overridevirtual

Integrate from t=0 to netIn.tMax and return final composition and energy.

Implementation summary:

  • Converts temperature to T9, initializes CVODE memory and state (size = numSpecies + 1).
  • Repeatedly calls CVode in single-step or normal mode depending on stdout logging.
  • Wraps RHS to capture exceptions::StaleEngineTrigger as a recoverable step failure; if present after a step, it is rethrown for upstream handling.
  • Prints/collects diagnostics per step (step size, energy, solver iterations).
  • On trigger activation, rebuilds CVODE resources to reflect a changed network and reinitialized the state using the latest engine composition, preserving energy.
  • At the end, converts molar abundances to mass fractions and assembles NetOut, including derivatives of energy w.r.t. T and rho from the engine.
Parameters
netInInputs: temperature [K], density [g cm^-3], tMax [s], composition.
Returns
NetOut containing final Composition, accumulated energy [erg/g], step count, and dEps/dT, dEps/dRho.
Exceptions
std::runtime_errorIf any CVODE or SUNDIALS call fails (negative return codes), or if internal consistency checks fail during engine updates.
exceptions::StaleEngineTriggerPropagated if the engine signals a stale state during RHS evaluation (captured in the wrapper then rethrown here).

Implements gridfire::solver::NetworkSolverStrategy< EngineT >.

◆ evaluate() [2/2]

NetOut gridfire::solver::CVODESolverStrategy::evaluate ( const NetIn netIn,
bool  displayTrigger 
)

Call to evaluate which will let the user control if the trigger reasoning is displayed.

Parameters
netInInputs: temperature [K], density [g cm^-3], tMax [s], composition.
displayTriggerBoolean flag to control if trigger reasoning is displayed
Returns
NetOut containing final Composition, accumulated energy [erg/g], step count, and dEps/dT, dEps/dRho.
Exceptions
std::runtime_errorIf any CVODE or SUNDIALS call fails (negative return codes), or if internal consistency checks fail during engine updates.
exceptions::StaleEngineTriggerPropagated if the engine signals a stale state during RHS evaluation (captured in the wrapper then rethrown here).

◆ get_absTol()

double gridfire::solver::CVODESolverStrategy::get_absTol ( ) const

◆ get_relTol()

double gridfire::solver::CVODESolverStrategy::get_relTol ( ) const

◆ get_stdout_logging_enabled()

bool gridfire::solver::CVODESolverStrategy::get_stdout_logging_enabled ( ) const

Whether per-step logs are printed to stdout and CVode is stepped with CV_ONE_STEP.

◆ initialize_cvode_integration_resources()

void gridfire::solver::CVODESolverStrategy::initialize_cvode_integration_resources ( uint64_t  N,
size_t  numSpecies,
double  current_time,
const fourdst::composition::Composition &  composition,
double  absTol,
double  relTol,
double  accumulatedEnergy 
)
private

Allocate and initialize CVODE vectors, linear algebra, tolerances, and constraints.

State vector m_Y is sized to N (numSpecies + 1). Species slots are initialized from Composition molar abundances when present, otherwise a tiny positive value; the last slot is set to accumulatedEnergy. Sets scalar tolerances, non-negativity constraints for species, maximum step size, creates a dense matrix and dense linear solver, and registers the Jacobian.

◆ log_step_diagnostics()

void gridfire::solver::CVODESolverStrategy::log_step_diagnostics ( const CVODEUserData user_data,
bool  displayJacobianStiffness,
bool  displaySpeciesBalance,
bool  to_file,
std::optional< std::string >  filename 
) const
private

Compute and print per-component error ratios; run diagnostic helpers.

Gathers CVODE's estimated local errors, converts the state to a Composition, and prints a sorted table of species with the highest error ratios; then invokes diagnostic routines to inspect Jacobian stiffness and species balance.

◆ operator=() [1/2]

CVODESolverStrategy & gridfire::solver::CVODESolverStrategy::operator= ( const CVODESolverStrategy )
delete

◆ operator=() [2/2]

CVODESolverStrategy & gridfire::solver::CVODESolverStrategy::operator= ( CVODESolverStrategy &&  )
delete

◆ set_absTol()

void gridfire::solver::CVODESolverStrategy::set_absTol ( double  absTol)

◆ set_callback()

void gridfire::solver::CVODESolverStrategy::set_callback ( const std::any &  callback)
overridevirtual

Install a timestep callback.

Parameters
callbackstd::any containing TimestepCallback (std::function<void(const TimestepContext&)>).
Exceptions
std::bad_any_castIf callback is not of the expected type.

Implements gridfire::solver::NetworkSolverStrategy< EngineT >.

◆ set_detailed_step_logging()

void gridfire::solver::CVODESolverStrategy::set_detailed_step_logging ( bool  enabled)
private

◆ set_relTol()

void gridfire::solver::CVODESolverStrategy::set_relTol ( double  relTol)

◆ set_stdout_logging_enabled()

void gridfire::solver::CVODESolverStrategy::set_stdout_logging_enabled ( bool  logging_enabled)

Enable/disable per-step stdout logging.

Parameters
logging_enabledFlag to control if a timestep summary is written to standard output or not

Member Data Documentation

◆ m_absTol

std::optional<double> gridfire::solver::CVODESolverStrategy::m_absTol
private

User-specified absolute tolerance.

◆ m_callback

std::optional<TimestepCallback> gridfire::solver::CVODESolverStrategy::m_callback
private

Optional per-step callback.

◆ m_config

fourdst::config::Config& gridfire::solver::CVODESolverStrategy::m_config = fourdst::config::Config::getInstance()
private

◆ m_constraints

N_Vector gridfire::solver::CVODESolverStrategy::m_constraints = nullptr
private

CVODE constraints vector (>= 0 for species entries).

◆ m_cvode_mem

void* gridfire::solver::CVODESolverStrategy::m_cvode_mem = nullptr
private

CVODE memory block.

◆ m_detailed_step_logging

bool gridfire::solver::CVODESolverStrategy::m_detailed_step_logging = false
private

If true, log detailed step diagnostics (error ratios, Jacobian, species balance).

◆ m_J

SUNMatrix gridfire::solver::CVODESolverStrategy::m_J = nullptr
private

Dense Jacobian matrix.

◆ m_logger

quill::Logger* gridfire::solver::CVODESolverStrategy::m_logger = fourdst::logging::LogManager::getInstance().getLogger("log")
private

◆ m_LS

SUNLinearSolver gridfire::solver::CVODESolverStrategy::m_LS = nullptr
private

Dense linear solver.

◆ m_num_steps

int gridfire::solver::CVODESolverStrategy::m_num_steps = 0
private

CVODE step counter (used for diagnostics and triggers).

◆ m_relTol

std::optional<double> gridfire::solver::CVODESolverStrategy::m_relTol
private

User-specified relative tolerance.

◆ m_stdout_logging_enabled

bool gridfire::solver::CVODESolverStrategy::m_stdout_logging_enabled = true
private

If true, print per-step logs and use CV_ONE_STEP.

◆ m_sun_ctx

SUNContext gridfire::solver::CVODESolverStrategy::m_sun_ctx = nullptr
private

SUNDIALS context (lifetime of the solver).

◆ m_Y

N_Vector gridfire::solver::CVODESolverStrategy::m_Y = nullptr
private

CVODE state vector (species + energy accumulator).

◆ m_YErr

N_Vector gridfire::solver::CVODESolverStrategy::m_YErr = nullptr
private

Estimated local errors.


The documentation for this class was generated from the following files: