From CHEMKIN to OpenFOAM: How chemkin2foam Works
Contents
Most reaction mechanisms used in combustion CFD are distributed in CHEMKIN format, while OpenFOAM reads its own dictionary format. chemkin2foam is a Python tool I wrote to convert the three CHEMKIN files (mechanism, thermodynamic data and transport data) into chemistry files that OpenFOAM 8–13 can read directly. Besides the format conversion, the program uses Cantera to compute the viscosity of each species and fits the As and Ts parameters required by the OpenFOAM sutherland transport model. It can also fit species diffusion coefficients and write a thermophysicalTransport dictionary for either the Fickian (mixture-averaged) or the Maxwell–Stefan (multicomponent) model. Both tasks are tedious and error-prone when done by hand.
The sections below follow the order in which the program runs and explain the theory and formulas behind each step.
Overall workflow
chem.inp ─┐
therm.dat ├─ ck2yaml ─→ chem.yaml ─→ ct.Solution(gas) ─┬─→ thermos (NASA polynomials + Sutherland + elements)
tran.dat ─┘ ├─→ reactions (reaction rates)
├─→ elements
├─→ transportProperties (As / Ts)
└─→ thermophysicalTransport (optional, diffusion coefficients)The program relies on Cantera to parse the CHEMKIN input and to evaluate all properties, so it contains no CHEMKIN parser of its own. It first calls Cantera’s ck2yaml to convert the three CHEMKIN files into a Cantera YAML mechanism, then loads the YAML file with ct.Solution. The resulting gas object holds all species, reactions and transport parameters, and every output file is written from data read from gas or properties computed with it.
Comments, continuation lines, duplicate reactions, specific collision partners and the other variations found in CHEMKIN files are all handled by ck2yaml. A further advantage is that the properties used in OpenFOAM come from the same models that Cantera uses in one-dimensional flame calculations, so results from the two codes can be compared directly.
Step 1: CHEMKIN to Cantera YAML
The three input files
The example shipped with the repository is a reduced version of GRI-Mech 1.2 with 21 species and 84 reactions.
The mechanism file chem.inp lists the elements, the species and the reactions. Each reaction takes one line ending with the Arrhenius parameters
,
and
, in cm–mol–s and cal/mol units:
O+H+M<=>OH+M 5.000E+17 -1.000 0.00
H2/2.00/ H2O/6.00/ CH4/2.00/ CO/1.50/ CO2/2.00/ C2H6/3.00/ AR/0.70/The second line gives the third-body efficiencies. Pressure-dependent reactions carry additional keywords such as LOW, TROE and PLOG.
In the thermodynamic file therm.dat, each species takes four lines giving its temperature ranges and the coefficients of two NASA 7-coefficient polynomials, one for the high-temperature range and one for the low-temperature range.
The transport file tran.dat gives the Lennard-Jones parameters of each species on a single line:
CH4 2 141.400 3.746 0.000 2.600 13.000The six columns are the molecular geometry (0 for atoms, 1 for linear and 2 for nonlinear molecules), the well depth in K, the collision diameter in Å, the dipole moment in Debye, the polarizability in ų, and the rotational relaxation collision number at 298 K.
Running ck2yaml
The program uses the ck2yaml command if it is on the path and falls back to python -m cantera.ck2yaml otherwise:
base = "ck2yaml" if shutil.which("ck2yaml") else "python -m cantera.ck2yaml"
cmd = base.split() + [f"--input={ck_mech}", f"--thermo={ck_thermo}",
f"--transport={ck_transport}", f"--output={yaml_path}"]
subprocess.run(cmd, check=True)The generated chem.yaml is kept in the output directory. It is useful for checking the conversion and can be used as is for one-dimensional flame calculations in Cantera.
Unit conversion
Once the YAML file is loaded, Cantera works internally in kmol–m–s–J units. OpenFOAM’s chemistry library uses the same system, so values read from gas can be written to OpenFOAM without further conversion. For the three-body reaction above,
The activation energy has to be converted to the activation temperature used by OpenFOAM:
def _ap(rate):
return rate.pre_exponential_factor, rate.temperature_exponent, rate.activation_energy / ct.gas_constantOne of the LOW entries in the example has
, which gives
, matching the value Ta 618.960026 in the generated reactions file.
Thermodynamics: NASA polynomials to janafThermo
CHEMKIN thermodynamic data are NASA 7-coefficient polynomials with a high-temperature and a low-temperature range joined at , which is usually 1000 K:
OpenFOAM’s janafThermo uses exactly the same form, so this step is a change of format only. Cantera stores spec.thermo.coeffs as [T_mid, 7 high-range coefficients, 7 low-range coefficients], and the program splits this array into highCpCoeffs and lowCpCoeffs. The output for CH4 is:
CH4
{
specie
{
molWeight 16.043;
}
thermodynamics
{
Tlow 200;
Thigh 3500;
Tcommon 1000;
highCpCoeffs ( 0.074851495 0.0133909467 -5.73285809e-06 1.22292535e-09 -1.0181523e-13 -9468.34459 18.437318 );
lowCpCoeffs ( 5.14987613 -0.0136709788 4.91800599e-05 -4.84743026e-08 1.66693956e-11 -10246.6476 -4.64130376 );
}
transport
{
As 1.07892393e-06;
Ts 218.711397;
}
elements
{
C 1;
H 4;
}
}The program also handles one edge case. When a species is given with a single polynomial, Cantera reads it with identical high- and low-range coefficients and with
equal to the upper temperature limit. In that case the program resets Tcommon to 1000 K so that OpenFOAM does not receive a degenerate temperature range.
About the 300 K warning. Many thermodynamic files use 300 K as the lower temperature limit (N2 and AR in the example are two such species). If a case starts at exactly 300 K, round-off can push the temperature slightly below the limit, and OpenFOAM reports
attempt to use janafThermo out of temperature range. LoweringTlowinthermosby hand (to 250 K, for example) or starting the case at 301 K avoids the problem.
Transport: fitting the Sutherland parameters
Why a fit is needed
The transport model most often used with OpenFOAM’s combustion solvers is sutherland, which needs only two parameters per species:
The CHEMKIN file tran.dat contains Lennard-Jones parameters and no values of
or
. From the Lennard-Jones parameters, Cantera computes the viscosity of a pure species with the Chapman–Enskog kinetic theory:
Here is the reduced collision integral, a function of , and a correction based on the dipole moment is applied to polar molecules such as H2O. The Sutherland formula can be regarded as a two-parameter approximation of this result, so the program computes the viscosity curve with Cantera and fits and to it by least squares.
Implementation
def _sutherland(T, As, Ts):
return As * T ** 1.5 / (Ts + T)
Temp = np.arange(200, 2501, 1) # 200–2500 K in 1 K steps
for sp in gas.species_names:
gas.X = f"{sp}:1" # pure species
muy = [gas.viscosity for gas.TP in ((t, ct.one_atm) for t in Temp)]
(As, Ts), _ = curve_fit(_sutherland, Temp, muy, p0=(1.0e-6, 120.0), maxfev=10000)Setting gas.X = f"{sp}:1" makes the gas a pure species, so gas.viscosity returns the viscosity of that species alone. The loop variable in for gas.TP in ... assigns each (T, 1 atm) pair directly to gas.TP, which updates the state before the viscosity is read. Gas viscosity does not depend on pressure at low pressure, so a fixed value of 1 atm is sufficient. If the fit fails for a species, the program prints a warning and uses the default values
. The original state of gas is restored after the loop so that later steps are not affected.
For CH4 the fit gives and . At 300 K the formula then gives , which is of the expected order for methane.
Thermal conductivity
The sutherland model has no separate input for thermal conductivity. OpenFOAM derives it from the viscosity with a modified Eucken relation:
The accuracy of and therefore affects both momentum and heat transport.
The fitted parameters are written to the transport sub-dictionary of each species in thermos, and a separate transportProperties file is written for reference. The Sutherland form has its own limits: for strongly polar molecules or over a wide temperature range, two parameters cannot reproduce the Chapman–Enskog curve exactly. OpenFOAM also computes the mixture viscosity as a mass-fraction-weighted average of the species values, whereas Cantera uses the Wilke mixing rule by default, so the mixture viscosities from the two codes differ somewhat.
Reactions: from Cantera reaction objects to OpenFOAM dictionaries
The program loops over gas.reactions() and handles each reaction according to its reaction_type. OpenFOAM builds the reaction type name from a prefix and a rate type, and the prefix depends on whether the reaction is reversible:
prefix = "reversible" if rxn.reversible else "irreversible"For a reversible reaction, OpenFOAM computes the equilibrium constant from the thermodynamic data and obtains the reverse rate from it:
The NASA coefficients in thermos thus determine the reverse rates of all reversible reactions as well as the heat release.
Reaction equations
Cantera’s equation strings are rewritten in the form OpenFOAM expects. Both <=> and => become =, (+M) and + M are removed, and 2 H is written as 2H. A reaction with non-stoichiometric orders (orders) is written in the form CH4^0.7.
Arrhenius reactions
The basic rate expression is
which maps to reversibleArrhenius or irreversibleArrhenius with the entries A, beta and Ta.
Three-body reactions
The rate of a three-body reaction is multiplied by the effective concentration of the collision partner:
The efficiencies
are those listed in chem.inp, for example H2/2.00/ H2O/6.00/ .... OpenFOAM’s thirdBodyArrhenius requires an efficiency for every species, so the program assigns the default value of 1 to species the mechanism does not mention. The example reaction O+H+M<=>OH+M becomes:
un-named-reaction-0
{
type reversibleThirdBodyArrhenius;
reaction "H + O = OH";
A 5e+11;
beta -1;
Ta 0;
coeffs
21
(
(H2 2)
(H 1)
...
(H2O 6)
...
(AR 0.7)
)
;
}When the collision partner is a specific species, as in (+AR), only that species acts as a third body and the default efficiency of all other species must be 0. The function _is_one_third_body() detects this case and the default value is changed accordingly.
Pressure-dependent reactions: Lindemann and Troe
A falloff reaction has two sets of Arrhenius parameters, one for the low-pressure limit
(given with the LOW keyword) and one for the high-pressure limit
. The two limits are joined through the reduced pressure:
The Lindemann form sets . The Troe form uses a temperature-dependent broadening factor:
with , and .
The four values in CHEMKIN’s TROE/ α T*** T* T** / line map to the OpenFOAM entries alpha, Tsss, Ts and Tss, in that order. The last value
is optional, and omitting it removes the third term of
. OpenFOAM, however, requires all four entries, so when only three are given the program sets Tss = 4.5036e15. With this value
, which is mathematically the same as leaving the term out.
The example reaction H+CH2(+M)<=>CH3(+M) becomes:
type reversibleArrheniusTroeFallOff;
reaction "CH2 + H = CH3";
k0 { A 3.2e+21; beta -3.14; Ta 618.960026; }
kInf { A 2.5e+13; beta -0.8; Ta 0; }
F { alpha 0.68; Tsss 78; Ts 1995; Tss 5590; }
thirdBodyEfficiencies { coeffs 21 ( (H2 2) ... ); }(Each sub-dictionary has been collapsed onto one line here to save space.) Because includes an extra factor of , its units differ from those of by one volume factor. This is why becomes while becomes .
PLOG reactions
A PLOG reaction gives one set of Arrhenius parameters at each of several pressures
. If the pressure prompt is left empty, the program writes an ArrheniusPLOG reaction with all
listed in ArrheniusData, and OpenFOAM interpolates at run time. When the pressure in a case is nearly constant, as in an atmospheric flame, the user can enter that pressure instead. The program then computes equivalent Arrhenius parameters at that pressure and writes an ordinary reaction, which is cheaper to evaluate.
For a fixed pressure, the standard PLOG treatment interpolates linearly in :
Since is linear in , interpolating each of the three parameters separately gives a that agrees with the direct interpolation of at every temperature:
k = (math.log(p) - math.log(pi)) / (math.log(pj) - math.log(pi))
return Ai * (Aj/Ai)**k, bi + k*(bj-bi), Tai + k*(Taj-Tai)The result is still a standard Arrhenius expression and can be passed to OpenFOAM as is. If the requested pressure lies outside the PLOG range, the program prints a warning and uses the parameters of the nearest pressure point.
Non-equilibrium reversible reactions
Some mechanisms write the forward and reverse directions as two separate irreversible reactions (=>) with their own rate parameters, so that the reverse rate does not come from the equilibrium constant. The program checks each pair of adjacent reactions, and if both are irreversible and the reactants of one are the products of the other, it merges them into OpenFOAM’s nonEquilibriumReversibleArrhenius (or its three-body variant), with the two parameter sets written to the forward and reverse sub-dictionaries.
Unsupported types
Chebyshev and other rate forms are not supported at present. For such a reaction the program raises NotImplementedError, catches it, prints a warning and skips the reaction without stopping the conversion. It is a good idea to check the terminal output afterwards for any skipped reactions.
Diffusion models: thermophysicalTransport
This part matters for laminar flames, particularly for hydrogen-containing fuels or stratified combustion, where differential diffusion has a clear effect. The program offers three options.
Option 1: unity Lewis number (default)
No thermophysicalTransport file is written, and OpenFOAM uses its default unity Lewis number assumption, in which the diffusivity of every species equals the thermal diffusivity:
This is usually acceptable for turbulent flames. Light species such as H and H2 diffuse considerably faster than heat, however, and a unity Lewis number model cannot capture effects such as thermo-diffusive instability.
Binary diffusion coefficients and the fitted form
Both diffusion models are built on the binary diffusion coefficients . The Chapman–Enskog theory gives
where is the reduced mass, and and are combined from the Lennard-Jones parameters of the two species. is proportional to , and the remaining temperature dependence is contained in the collision integral .
OpenFOAM’s binaryDiffusionCoefficient function uses this structure and represents the remaining part as a fourth-order polynomial in
:
The fit divides out first, and what remains is an ordinary polynomial fit in :
def _fit_D_polynomial(D_vals, T_array, p_ref):
lnT = np.log(T_array)
y = D_vals * p_ref / (T_array ** 1.5) # remove T^1.5/p
coeffs = np.polyfit(lnT, y, 4)[::-1] # reorder to c0..c4
...The samples cover 300–3000 K with 60 points at a reference pressure of 1 atm (set by the DIFFUSION_FIT_* constants at the top of the script). After fitting, the program prints the five entries with the largest error together with the maximum and mean relative errors, so the quality of the fit can be checked.
Option 2: Fickian (mixture-averaged)
FickianFourier assigns one mixture-averaged diffusion coefficient
to each species, and the diffusive flux is approximated as
Cantera computes the mixture-averaged coefficient from the binary coefficients:
depends on the local composition
, while the Dm entries in the OpenFOAM dictionary are functions of
only. The program therefore evaluates
at a reference composition. By default this is an equimolar mixture of all species, and the user can enter a different one, such as CH4:1,O2:2,N2:7.52 for a stoichiometric methane/air mixture. In combustion problems dominated by nitrogen, a composition close to the actual conditions is usually more appropriate than an equimolar mixture. If the composition varies strongly across the domain, as in a strongly non-premixed flame, the Maxwell–Stefan model described below is the better choice.
The generated dictionary looks roughly like this, where mixtureDiffusionCoefficients yes indicates that the entries are per-species Dm values:
simulationType laminar;
laminar
{
model FickianFourier;
mixtureDiffusionCoefficients yes;
Dm
{
CH4
{
type binaryDiffusionCoefficient;
coeffs (c0 c1 c2 c3 c4);
}
...
}
}For RAS or LES the model becomes FickianEddyDiffusivity, which adds turbulent diffusion to the laminar part. The program then asks for the turbulent Prandtl number
(default 0.85) and the turbulent Schmidt number
(default 0.7):
Option 3: Maxwell–Stefan (multicomponent)
MaxwellStefanFourier solves the Stefan–Maxwell equations for multicomponent diffusion directly, neglecting pressure diffusion and the Soret effect:
This model needs the full matrix of binary diffusion coefficients
. Binary coefficients do not depend on composition, so no reference composition is needed. At each sample temperature the program reads Cantera’s gas.binary_diff_coeffs and fits every pair with
, self-diffusion
included. With 21 species the example has
sets of coefficients:
// 21 species, 231 entries, fit 300-3000 K
simulationType laminar;
laminar
{
model MaxwellStefanFourier;
D
{
H2-H2
{
type binaryDiffusionCoefficient;
coeffs (-7.21875541e-03 4.74027262e-03 -9.13003819e-04 8.46482801e-05 -2.81247635e-06);
}
H2-H
{
...
}
}
}The Maxwell–Stefan model is more accurate but also more expensive, since a linear system has to be solved in every cell at every time step. OpenFOAM provides it for laminar flow only, so the program does not ask for a simulation type when this option is chosen and always writes a laminar dictionary.
Version requirements
FickianFourier, FickianEddyDiffusivity and MaxwellStefanFourier were introduced in OpenFOAM 9. If the target version is 8 and a diffusion model is selected, the program prints a warning and skips thermophysicalTransport, while all other files are written as usual.
Usage
conda install -c conda-forge cantera numpy scipy
python chemkin2foam.pyThe program prompts for the CHEMKIN directory and file names, the output directory, the PLOG pressure (leave it empty to keep the PLOG form), the target OpenFOAM version and the diffusion model, and starts the conversion after confirmation. The generated files go into the constant directory of the case and are referenced in the way required by the OpenFOAM version in use.
Summary and limitations
chemkin2foam uses Cantera as an intermediate layer and rewrites the thermodynamic, kinetic and transport information of a CHEMKIN mechanism in the forms that OpenFOAM’s models expect. The thermodynamic data and reaction rates only change format and units, so no information is lost there. The transport data (Sutherland parameters and diffusion coefficients) come from fitting Cantera’s kinetic-theory results to the functional forms OpenFOAM supports, which introduces some approximation error.
Several limitations remain. Chebyshev and other unsupported rate forms are skipped during conversion. The two-parameter Sutherland formula is only an approximation for strongly polar molecules and over wide temperature ranges. The Dm values of the Fickian model depend on a fixed reference composition. Thermal diffusion (the Soret effect) is not included, which may matter for hydrogen flames. The temperature range for the diffusion fits is also a constant in the script and has to be edited by hand if a different range is needed.
The code is on GitHub at Fkstone/chemkin2foam under GPL-3.0. The Cantera-to-OpenFOAM part was developed with reference to canteraToFoam from Lund University. Issues and questions are welcome.