Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small fixes and improvements / sparse coefficient matrices #1088

Merged
merged 28 commits into from
Sep 17, 2021
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
a83c4ca
[SCons] Update docstring
ischoegl Aug 20, 2021
b9a7eb8
[UnitTest] Fix true_divide RuntimeWarning in test_kinetics.py
ischoegl Aug 4, 2021
2091536
Allow for custom NotImplementedError messages
ischoegl Aug 17, 2021
5e94f54
[Thermo] Fix compilation warning in MixtureFugacityTP.cpp
ischoegl Aug 20, 2021
3d03164
[Unittests] Resolve unused variable warning in test-surfSolver2
ischoegl Aug 20, 2021
d6afa44
[Numerics] Update eigen_dense.h and introduce eigen_sparse.h
ischoegl Aug 2, 2021
3fcbc13
[Kinetics] Update ChebyshevRate interface
ischoegl Aug 20, 2021
ef7c81b
[Kinetics] Remove unused functions from internal StoichManager.h classes
ischoegl Aug 22, 2021
c409e25
[Kinetics] Add sparse stoichiometric coefficients in StoichManager.h
ischoegl Aug 23, 2021
b9a4eea
[Kinetics] Implement mechanism for Kinetics::finalizeSetup
ischoegl Aug 23, 2021
3f2dc1e
[Kinetics] Merge irreversible and reversible product StoichManagerN
ischoegl Aug 23, 2021
9e31a12
[Kinetics] Use sparse stoichcoeff matrices for internal calculations
ischoegl Aug 23, 2021
de3158b
[Python] Enable optional scipy.sparse output
ischoegl Aug 23, 2021
31b08de
[Python] Create sparse stoichCoeff API
ischoegl Aug 23, 2021
67cd2e3
[GH] Add scipy to coverage tests
ischoegl Aug 24, 2021
6cd9e31
[Unittest] Skip some tests if h5py is not installed
ischoegl Aug 27, 2021
b492434
[Kinetics] Streamline Chebyshev interface
ischoegl Sep 4, 2021
2ac8e8c
[Unittest] Update Chebyshev tests
ischoegl Sep 4, 2021
d9a446b
[Python] Make sparse API more efficient and deprecate *stoich methods
ischoegl Aug 23, 2021
5ff68c3
[Unittest] Add test for sparse matrix output
ischoegl Aug 24, 2021
79e62d8
[Kinetics] Standardize Plog rates access
ischoegl Sep 5, 2021
463598a
[Kinetics] Access Chebyshev coefficients as 'data'
ischoegl Sep 5, 2021
031a7e9
[Kinetics] Use compressed sparse matrix format
ischoegl Sep 14, 2021
5394540
[Python] Switch sparse matrix output to CSC (from COO) format
ischoegl Sep 14, 2021
a9901f5
Update formatting
ischoegl Sep 16, 2021
202c2bf
[Kinetics] Partially roll back changes to Chebyshev
ischoegl Sep 16, 2021
5a2999f
[Kinetics] Ensure member variables are reset when calling Plog::setRates
ischoegl Sep 16, 2021
c4e4a7b
[Kinetics] Improve nomenclature for final step of Kinetics setup
ischoegl Sep 17, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ jobs:
- name: Upgrade pip
run: python3 -m pip install -U pip setuptools wheel
- name: Install Python dependencies
run: python3 -m pip install ruamel.yaml scons numpy cython h5py pandas pytest
run: python3 -m pip install ruamel.yaml scons numpy cython h5py pandas scipy pytest
pytest-github-actions-annotate-failures
- name: Build Cantera
run: |
Expand Down
13 changes: 7 additions & 6 deletions SConstruct
Original file line number Diff line number Diff line change
Expand Up @@ -680,12 +680,13 @@ config_options = [
False),
BoolVariable(
"legacy_rate_constants",
"""If set to 'false', rate constant calculations will will no longer include
third-body concentrations for ThreeBodyReaction objects. For Cantera 2.6, the
default is set to 'true' (no change of previous behavior). After Cantera 2.6,
the default will be changed to 'false', and rate constant calculations will be
consistent with conventional definitions (see Eq. 9.75 in Kee, Coltrin and
Glarborg, 'Chemically Reacting Flow', Wiley Interscience, 2003).""",
"""If enabled, rate constant calculations include third-body concentrations
for three-body reactions, which corresponds to the legacy implementation.
For Cantera 2.6, the option remains enabled (no change compared to past
behavior). After Cantera 2.6, the default will be to disable this option,
and rate constant calculations will be consistent with conventional
definitions (see Eq. 9.75 in Kee, Coltrin and Glarborg, 'Chemically Reacting
Flow', Wiley Interscience, 2003).""",
True),
]

Expand Down
6 changes: 6 additions & 0 deletions include/cantera/base/ctexceptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ class NotImplementedError : public CanteraError
NotImplementedError(const std::string& func) :
CanteraError(func, "Not implemented.") {}

//! Alternative constructor taking same arguments as @see CanteraError
template <typename... Args>
NotImplementedError(const std::string& func, const std::string& msg,
const Args&... args) :
CanteraError(func, msg, args...) {}

virtual std::string getClass() const {
return "NotImplementedError";
}
Expand Down
60 changes: 60 additions & 0 deletions include/cantera/cython/wrappers.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// at https://cantera.org/license.txt for license and copyright information.

#include "cantera/base/logger.h"
#include "cantera/numerics/eigen_sparse.h"
#include "cantera/thermo/ThermoPhase.h"
#include "cantera/transport/TransportBase.h"
#include "cantera/kinetics/Kinetics.h"
Expand Down Expand Up @@ -49,6 +50,60 @@ void CxxArray2D_set(Cantera::Array2D& array, size_t i, size_t j, double value)
array(i,j) = value;
}

// Service function to pass index/value triplets describing sparse matrix
size_t sparseTriplets(const Eigen::SparseMatrix<double>& mat,
int* rows, int* cols, double* data, size_t length)
{
size_t count = 0;
for (int i = 0; i < mat.outerSize(); i++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(mat, i); it; ++it) {
if (count < length) {
rows[count] = it.row();
cols[count] = it.col();
data[count] = it.value();
}
count++;
}
}
if (count > length) {
throw Cantera::CanteraError("sparseComponents",
"Output arrays have insufficient length. Required size is {}, "
"while provided length is {}.", count, length);
}
return count;
}

// Service function to pass CSC data describing sparse matrix
void sparseCscData(const Eigen::SparseMatrix<double>& mat,
double* value, int* inner, int* outer)
{
if (!mat.isCompressed()) {
throw Cantera::CanteraError("sparseCscData",
"Invalid input: Eigen matrix is not compressed.");
}
if (mat.IsRowMajor) {
throw Cantera::CanteraError("sparseCscData",
"Invalid input: Eigen matrix is not in column major format.");
}
ischoegl marked this conversation as resolved.
Show resolved Hide resolved

const double* valuePtr = mat.valuePtr();
const int* innerPtr = mat.innerIndexPtr();
for (size_t i = 0; i < mat.nonZeros(); ++i) {
value[i] = valuePtr[i];
inner[i] = innerPtr[i];
}

const int* outerPtr = mat.outerIndexPtr();
for (size_t i = 0; i < mat.outerSize() + 1; ++i) {
outer[i] = outerPtr[i];
}
}

// Function which passes sparse matrix
#define SPARSE_MATRIX(PREFIX, CLASS_NAME, FUNC_NAME) \
Eigen::SparseMatrix<double> PREFIX ## _ ## FUNC_NAME(Cantera::CLASS_NAME* object) \
{ return object->FUNC_NAME(); }

// Function which populates a 1D array
#define ARRAY_FUNC(PREFIX, CLASS_NAME, FUNC_NAME) \
void PREFIX ## _ ## FUNC_NAME(Cantera::CLASS_NAME* object, double* data) \
Expand All @@ -62,6 +117,7 @@ void CxxArray2D_set(Cantera::Array2D& array, size_t i, size_t j, double value)

#define THERMO_1D(FUNC_NAME) ARRAY_FUNC(thermo, ThermoPhase, FUNC_NAME)
#define KIN_1D(FUNC_NAME) ARRAY_FUNC(kin, Kinetics, FUNC_NAME)
#define KIN_SPARSE_MATRIX(FUNC_NAME) SPARSE_MATRIX(kin, Kinetics, FUNC_NAME)
#define TRANSPORT_1D(FUNC_NAME) ARRAY_FUNC(tran, Transport, FUNC_NAME)
#define TRANSPORT_2D(FUNC_NAME) ARRAY_FUNC2(tran, Transport, FUNC_NAME)

Expand Down Expand Up @@ -89,6 +145,10 @@ THERMO_1D(getCp_R)
THERMO_1D(getActivities)
THERMO_1D(getActivityCoefficients)

KIN_SPARSE_MATRIX(reactantStoichCoeffs)
KIN_SPARSE_MATRIX(productStoichCoeffs)
KIN_SPARSE_MATRIX(revProductStoichCoeffs)

KIN_1D(getFwdRatesOfProgress)
KIN_1D(getRevRatesOfProgress)
KIN_1D(getNetRatesOfProgress)
Expand Down
2 changes: 1 addition & 1 deletion include/cantera/kinetics/BulkKinetics.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class BulkKinetics : public Kinetics
virtual void getRevRateConstants(double* krev,
bool doIrreversible = false);

virtual bool addReaction(shared_ptr<Reaction> r);
virtual bool addReaction(shared_ptr<Reaction> r, bool finalize=true);
virtual void modifyReaction(size_t i, shared_ptr<Reaction> rNew);

virtual void resizeSpecies();
Expand Down
2 changes: 1 addition & 1 deletion include/cantera/kinetics/GasKinetics.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class GasKinetics : public BulkKinetics
//! @name Reaction Mechanism Setup Routines
//! @{
virtual void init();
virtual bool addReaction(shared_ptr<Reaction> r);
virtual bool addReaction(shared_ptr<Reaction> r, bool finalize=true);
virtual void modifyReaction(size_t i, shared_ptr<Reaction> rNew);
virtual void invalidateCache();
//@}
Expand Down
2 changes: 1 addition & 1 deletion include/cantera/kinetics/InterfaceKinetics.h
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ class InterfaceKinetics : public Kinetics

virtual void init();
virtual void resizeSpecies();
virtual bool addReaction(shared_ptr<Reaction> r);
virtual bool addReaction(shared_ptr<Reaction> r, bool finalize=true);
virtual void modifyReaction(size_t i, shared_ptr<Reaction> rNew);
//! @}

Expand Down
40 changes: 36 additions & 4 deletions include/cantera/kinetics/Kinetics.h
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ class Kinetics
return "Kinetics";
}

//! Finalize Kinetics object and associated objects
virtual void finalizeSetup();
ischoegl marked this conversation as resolved.
Show resolved Hide resolved

//! Number of reactions in the reaction mechanism.
size_t nReactions() const {
return m_reactions.size();
Expand Down Expand Up @@ -555,6 +558,15 @@ class Kinetics
* @param i reaction index
*/
virtual double reactantStoichCoeff(size_t k, size_t i) const;

/**
* Stoichiometric coefficient matrix for reactants.
*/
Eigen::SparseMatrix<double> reactantStoichCoeffs() const
{
return m_reactantStoich.stoichCoeffs();
}
ischoegl marked this conversation as resolved.
Show resolved Hide resolved

/**
* Stoichiometric coefficient of species k as a product in reaction i.
*
Expand All @@ -563,6 +575,22 @@ class Kinetics
*/
virtual double productStoichCoeff(size_t k, size_t i) const;

/**
* Stoichiometric coefficient matrix for products.
*/
Eigen::SparseMatrix<double> productStoichCoeffs() const
{
return m_productStoich.stoichCoeffs();
}

/**
* Stoichiometric coefficient matrix for products of reversible reactions.
*/
Eigen::SparseMatrix<double> revProductStoichCoeffs() const
{
return m_revProductStoich.stoichCoeffs();
}

//! Reactant order of species k in reaction i.
/*!
* This is the nominal order of the activity concentration in
Expand Down Expand Up @@ -738,9 +766,10 @@ class Kinetics
* base class method in addition to handling their own specialized behavior.
*
* @param r Pointer to the Reaction object to be added.
* @param finalize If `true`, finalize Kinetics object.
* @return `true` if the reaction is added or `false` if it was skipped
*/
virtual bool addReaction(shared_ptr<Reaction> r);
virtual bool addReaction(shared_ptr<Reaction> r, bool finalize=true);

/**
* Modify the rate expression associated with a reaction. The
Expand Down Expand Up @@ -892,13 +921,16 @@ class Kinetics
//! Stoichiometry manager for the reactants for each reaction
StoichManagerN m_reactantStoich;

//! Stoichiometry manager for the products for each reaction
StoichManagerN m_productStoich;

//! Stoichiometry manager for the products of reversible reactions
StoichManagerN m_revProductStoich;

//! Stoichiometry manager for the products of irreversible reactions
StoichManagerN m_irrevProductStoich;
//@}

//! Boolean indicating whether Kinetics object setup is finalized
bool m_finalized;

//! The number of species in all of the phases
//! that participate in this kinetics mechanism.
size_t m_kk;
Expand Down
21 changes: 12 additions & 9 deletions include/cantera/kinetics/ReactionRate.h
Original file line number Diff line number Diff line change
Expand Up @@ -379,25 +379,28 @@ class PlogRate final : public ReactionRate<PlogData>, public Plog
* Chebyshev polynomials are not defined outside the interval (-1,1), and
* therefore extrapolation of rates outside the range of temperatures and
* pressures for which they are defined is strongly discouraged.
*
* @TODO rename to ChebyshevRate when the legacy ChebyshevRate class is removed
* from RxnRates.h after Cantera 2.6.
*/
class ChebyshevRate3 final : public ReactionRate<ChebyshevData>, public Chebyshev
{
public:
//! Default constructor.
ChebyshevRate3() {}

//! Constructor directly from coefficient array
/*
* @param Tmin Minimum temperature [K]
* @param Tmax Maximum temperature [K]
* @param Pmin Minimum pressure [Pa]
* @param Pmax Maximum pressure [Pa]
* @param coeffs Coefficient array dimensioned `nT` by `nP` where `nT` and
//! Constructor using coefficient array
/*!
* @param Trange Valid temperature range (min, max) [K]
* @param Prange Valid pressure range (min, max) [Pa]
* @param coeffs Coefficient array dimensioned `nT` by `nP` where `nT` and
* `nP` are the number of temperatures and pressures used in the fit,
* respectively.
*/
ChebyshevRate3(double Tmin, double Tmax, double Pmin, double Pmax,
const Array2D& coeffs);
ChebyshevRate3(
const std::pair<double, double> Trange,
const std::pair<double, double> Prange,
const Array2D& coeffs);

//! Constructor using AnyMap content
//! @param node AnyMap containing rate information
Expand Down
Loading