betaFeedback

WorksComputer Science

equilibrium-c: A Lightweight Modern Equilibrium Chemistry Calculator for Hypersonic Flow Applications

Abstract

equilibrium-c (eqc) is a program for computing the composition of gas mixtures in chemical equilibrium. In typical usage, the program is given a known thermodynamic state, such as fixed temperature and pressure, as well as an initial composition of gaseous species, and computes the final composition in the limit of a large amount of time relative to the reaction speeds. eqc includes a database of thermodynamic properties taken from the literature, a set of core routines written the C programming language to solve the equilibrium problems, and a Python wrapper layer to organise the solution process and interface with user code. Dependencies are extremely minimal, and the API is designed to be easily embedded in multi-physics codes that solve problems in fluid dynamics, combustion, and chemical processing. In this paper, I first introduce the equations of chemical equilibrium, then spend some time discussing their numerical solution, and finally present a series of example problems, with an emphasis on verification and validation of the solver.

Program Summary

Program Title: equilibrium-c

CPC Library link to program files: (to be added by Technical Editor)

Developer’s repository link:

github.com/uqngibbo/equilibrium-c

Code Ocean capsule: (to be added by Technical Editor)

Licensing provisions: MIT

Programming language: C, Python

Nature of problem:

equilibrium-c solves the reacting thermochemistry equations to find the equilibrium composition for a given thermodynamic state. The code is open-source and has been developed with a minimal dependencies philosophy. equilibrium-c be used on its own via a python interface or embedded into a more elaborate multi-physics code that may require chemical equilibrium as a submodule.

Solution method:

The equations are solved using a modified Newton’s method for multidimensional nonlinear equations, with analytic derivatives for the Jacobian. These modifications consist of an underrelaxation factor for each update, as well as careful handling of small species and a novel convergence metric.

Additional comments:

Emphasis is placed, in the paper, on reacting supersonic flow, owing to the nature of the author’s primary research interest. However, the code is applicable to a diverse range of applications in research and beyond. Readers who are interested in pursuing these applications are encouraged to contact the author via the corresponding email address.

E-mail address: [email protected]

Introduction

Many research problems involving rockets, high-speed aeroplanes, and spacecraft reentering the atmosphere encounter fluid flows with chemical reactions. These reactions affect the dynamics and thermochemistry of the flow, and must be considered in modelling calculations in order to compute accurate values of drag, heat transfer, or radiation that are needed for engineering design. In some situations, considerable time and complexity may be saved in these calculations by assuming the gas is in chemical equilibrium: The state that the gas would reach in the limit of a large time relative to the reaction time constants, as in figure 1.

Figure 1. Chemically reacting flow passing through a shockwave.

The equilibrium composition of a gas depends only on its thermodynamic state, which means a dedicated computer program for computing it would be valuable across a wide range of applications, from hypersonic wind-tunnel design to research in combustion and surface chemistry. In addition, computer programs designed for scientific research have a range of desiderata beyond their functional capabilities: they should be open source and freely available, have good documentation that explains their structure and algorithmic design, they should be verified and validated, preferably using automated tests that can be run by a user, and they should be easy to install and have minimal dependencies. One of the earliest efforts to provide a program for equilibrium calculations was STANJAN [1], a Fortran-77 code that introduced the Method of Element Potentials. This method considers the equilibrium calculation as a constrained non-linear optimisation problem using Lagrange multipliers, a formulation that can handle complex mixtures and a wide range of initial conditions, and for these reasons it was adopted by most subsequent programs. Some further development of the method was introduced in Steven Pope’s ceq [2], written in Fortran-90, which implemented a procedure

called “Gibbs function continuation” that aimed to improve convergence in the case of linear constraints on the final species composition. Element potentials were also adopted in NASA’s Chemical Equilibrium with Applications (CEA) [3], a widely used Fortran-77 code and associated database developed at NASA’s Lewis Research Centre, with a most recent release (CEAv2) from 2002. CEA has found widespread use in the aerospace research community, as in addition to solving chemical equilibrium problems, it also provides a range of application modes for solving problems such as rocket nozzles or shockwaves. More recent work in this space includes the equilibrium solver in the C++ combustion toolkit Cantera [4], and a Python toolkit called EQTK [5] which was developed for dilute liquid phase calculations needed for DNA and RNA research.

This brief review demonstrates that there is a broad interest in chemical equilibrium solvers for enabling various fields of applied research, but also serves to highlight some of the problems with the existing programs. STANJAN, ceq, and CEA are essentially un-maintained, and their use of old-school FORTRAN and text-based input files make them difficult for modern programs to interface with. Cantera is modern and reasonably well maintained, though its large size and project complexity means that linking it to existing code is also difficult. EQTK is lighter in weight and has good design and documentation, though its intended field of application is dilute liquid chemistry, and thus it does not use the Element Potential method that was developed to handle the very hot gas phase flows encountered in hypersonics.

To try and address these shortcomings, this paper introduces a new program for the calculation of chemical equilibrium problems, called equilibrium-c or eqc for short. eqc is a re-implementation of the same equations solved by CEA, using an updated numerical method and a focus on the non-functional desiderata of a good research code. The program is open-sourced under the permissive MIT license and can be freely downloaded from the project’s github page. It requires minimal dependencies (basic development libraries, a C compiler, and python3-numpy), works on both Linux and Windows, and can be compiled into a dynamic library for easy embedding in high performance multiphysics codes. It comes with a dozen unit tests which are continuously integrated whenever new changes are made, but can also be run by any user to verify that the implementation is functioning as advertised. Finally, it is documented in this paper and in a number of example scripts, some of which serve to verify the code against experimental data.

Thermodynamics of Chemical Equilibrium

The program described in this paper follows the element potential method by Gordon and McBride [3], in which we seek an equilibrium state by minimising the value of a certain thermodynamic potential. For a problem at fixed temperature and pressure, the relevant potential would be the Gibbs energy G=U+pV−TSG = U + pV - TS, or for a fixed internal energy and volume problem, the potential would be the Helmholtz energy F=U−TSF = U - TS. These potentials change as the composition of the gas is varied, even if the rest of the thermodynamic state is kept fixed, which allows the equilibrium state to be obtained via constrained minimisation, with the constraints provided by the initial composition and the requirement of elemental conservation.

The basic theory of this process is presented in many textbooks, which would ordinarily preclude a derivation in a publication such as this one; however, the author has found that almost always this material is presented in a way that is hand-wavy or otherwise unsatisfying. Gordon and McBride [3], for example, offer no explanation whatsoever for their formulation. Turns and Haworth [6], one of the best selling undergraduate textbooks on combustion theory, merely introduce the derivatives of the Gibbs energy as a mysterious “chemical potential”, as if such a definition were an explanation for why the method works. A slightly better approach is given Anderson [7], who introduces an analytic form of the second law of thermodynamics that includes a term for non-equilibrium or irreversible entropy change.

dS=p dV+dET+dSirrev(1)dS = \frac{p\,dV + dE}{T} + dS_{\mathrm{irrev}} \tag*{(1)}

Putting aside, for the moment, any curiosity about where this equation comes from, we can proceed to rearrange it to isolate the irreversible entropy change, and then introduce differential changes in the pressure VdpVdp and S dTS\,dT.

T dS−p dV−dE=dSirrevT\,dS - p\,dV - dE = dS_{\mathrm{irrev}}
T dS+S dT−S dT−p dV+V dp−V dp−dE=dSirrevT\,dS + S\,dT - S\,dT - p\,dV + V\,dp - V\,dp - dE = dS_{\mathrm{irrev}}
d(TS)+S dT−d(pV)−V dp−dE=dSirrevd(TS) + S\,dT - d(pV) - V\,dp - dE = dS_{\mathrm{irrev}}
d(TS−pV−E)+S dT−V dp=dSirrevd(TS - pV - E) + S\,dT - V\,dp = dS_{\mathrm{irrev}}

The differential term in brackets is minus the Gibbs energy, and assuming a constant pressure and temperature process, we seem to be entitled to assume dpdp and dTdT are equal to zero. These simplifications lead to the final expression as follows.

−dG=dSirrev(2)-dG = dS_{\mathrm{irrev}} \tag*{(2)}

This derivation appears to show that the change in the Gibbs energy for a gas mixture at constant pressure and temperature is equal to the change in irreversible entropy. Anderson asserts that these irreversibilities “are caused chemical nonequilibrium during the process”, but “irreversible” is just thermodynamics jargon for “non-equilibrium”, so this explanation offers no insight into why this is the case or where equation 1 actually comes from.

To understand why minimising the Gibbs energy results in chemical equilibrium, or indeed why chemistry has to do with thermodynamics in the first place, we must start with the principles of statistical mechanics that underpin the more familiar laws of classical thermodynamics. To begin with, we follow chapter 11 of Anderson [7] and consider a box of uniform gas molecules with volume VV, without the complexity of reactions for the moment. This gas will consist of a large number of individual particles with different energies, which are constantly colliding with each other and exchanging energy through various means, though these energies can be added up to get a total energy EE which is conserved in the melee of collisions.

To develop a statistical model for the distribution of particle energies, we need one major starting assumption, which is that the energy states available to the particles are quantized. This means that there are a finite (but very large) number of different energy states, and that these states are occupied by individual particles for brief moments of time as they rattle around the box. A schematic depiction of this is shown in Figure 2.

Illustration of particles and energy levels in an ideal gas

Figure 2. Illustration of particles and energy levels in an ideal gas.

In this figure, the energy levels are shown with a certain number of particles occupying them, for example there are three particles occupying the 5th energy level (N5=3N_5 = 3). The complete distribution of these occupation numbers NjN_j is of interest to us for many reasons, since they can be summed over to give the total number of particles, as well as the total energy.

N=∑jNjE=∑jεjNjN = \sum_j N_j \qquad E = \sum_j \varepsilon_j N_j

Where εj\varepsilon_j is the amount of energy in the jth energy level. A given distribution of NjN_j is called a macrostate, for example, the macrostate shown in figure 2 is N=[0,0,1,1,0,3,1,2,0,…]N = [0, 0, 1, 1, 0, 3, 1, 2, 0, \ldots]. If we were to take particle 4 and move it down one energy level we would get a different macrostate, namely N=[0,0,1,1,1,2,1,2,0,…]N = [0, 0, 1, 1, 1, 2, 1, 2, 0, \ldots]. Importantly, if we were to take particle 4 and swap it with particle 3, we would not change the overall set of occupation numbers, meaning that the macrostate would be the same. This implies that there may be multiple ways of arranging a set of particles into a given macrostate. Indeed, a quick calculation shows that there are 8!/3!/2!=33608!/3!/2!=3360 ways of arranging the 8 particles into the macrostate in figure 2. These individual arrangements are called microstates, and though they are physically identical in terms of energy, the number of available microstates affect the probability of each macrostate showing up the random dance of molecular collisions.

To further understand this point, an analogy may be helpful. Consider rolling a pair of six-sided dice and adding the results together, as is done in many board games. A pair of 1s gives a total of two, and a pair of 6s gives a total of twelve, the two rarest totals, each with only one permutation of individual rolls that can make it. A total of three however, can be achieved with a 1 and a 2, or a 2 and a 1, making it twice as likely. The number of permutations increases as the totals increase up to seven, which can be made with 1&6, 2&5, 3&4, 4&3, 5&2, 6&1, making it much more likely to appear than the one or the twelve, as can be seen in table 2.

Roll 1
Roll 2123456
1234567
2345678
3456789
45678910
567891011
6789101112

Table 1. Totals (macrostates) resulting from a pair of six-sided dice rolls.

In this analogy, the totals are the macrostates, and the individual dice roll combinations are the microstates. Since the seven has the most microstates it is the most likely total to appear in a random pair of rolls, and we might say it is the most probable macrostate.

This analogy extends to the particles of gas in the box. Some sets of occupation numbers will have more microstates associated with them than others, and the most likely macrostate is of interest for predicting the behaviour of the collective. Anderson [7] provides an expression for the number of microstates WW involved in any given macrostate or set of occupation numbers NjN_j.

W=∏j(Nj+gj−1)!(gj−1)!Nj!(3)W = \prod_j \frac{(N_j+g_j-1)!}{(g_j-1)!N_j!} \tag*{(3)}

This equation introduces the degeneracy, or statistical weight of an energy level gjg_j. Degeneracies arise due to the fact that multiple distinct quantum states may have the same energy, such as the angular momentum of a particle in different directions. To extend our analogy from before, imagine instead of rolling a pair of six-sided dice with exactly one of each number on the faces, we were instead to roll a pair of twenty sided dice with some duplicates of the numerals 1-6 on them. When counting the microstates then, we would have to account for the number of duplicates to determine the most likely total.

Equation 3 can be used to determine the most likely macrostate via mathematical optimisation. First, we choose to work with the logarithm of WW rather than the actual value, as its maximum will occur at the same place, and the corresponding sum of terms is easier to deal with than a product.

ln⁡(W)=∑jln⁡(Nj+gj−1)!−ln⁡(gj−1)!−ln⁡(Nj)!\ln(W) = \sum_j \ln(N_j+g_j-1)! - \ln(g_j-1)! - \ln(N_j)!

Next we assume that the energy levels can be lumped into a succession of quasi-levels with similar energy levels. This leads to each state having a large number of occupying particles and a large number of degeneracies, Nj≫1N_j \gg1 and gj≫1g_j \gg1.

ln⁡(W)=∑jln⁡(Nj+gj)!−ln⁡(gj)!−ln⁡(Nj)!\ln(W) = \sum_j \ln(N_j+g_j)! - \ln(g_j)! - \ln(N_j)!

We can then employ Stirling’s approximation to remove the factorials: ln⁡(a!)=aln⁡(a)−a\ln(a!) = a\ln(a) - a.

ln⁡(W)=∑j[Njln⁡(1+gjNj)+gjln⁡(Njgj+1)]\ln(W) = \sum_j \left[N_j\ln\left(1+\frac{g_j}{N_j}\right) + g_j\ln\left(\frac{N_j}{g_j}+1\right)\right]

This equation can be maximised to determine the most probable macrostate, the set of NjN_j’s with the most number of microstates. To do this we again follow Anderson [7], who employs the method of Lagrange multipliers to maximise subject to a constrained number of total particles NN and total energy EE.

N=∑jNjN = \sum_j N_j
E=∑jεjNjE = \sum_j \varepsilon_j N_j

Skipping the intermediate steps, the result of the minimisation is as follows, introducing Lagrange multipliers α\alpha and β\beta.

Nj∗=gjeαeβεjN_j^* = \frac{g_j}{e^{\alpha}e^{\beta\varepsilon_j}}

α\alpha can be removed from this expression by introducing the constraint of total NN, and it can be shown that β\beta is the inverse of the quantity normally referred to as the temperature (or in physical units, the Boltzmann constant kk times the temperature). This leads to an expression for the most probable macrostate Nj∗N_j^*:

Nj∗=Ngje−εj/kT∑igie−εi/kT(4)N_j^* = N \frac{g_j e^{-\varepsilon_j/kT}}{\sum_i g_i e^{-\varepsilon_i/kT}} \tag*{(4)}

This is the famous Boltzmann distribution. The Boltzmann distribution is interesting because although it underpins much of classical thermodynamics, there is no fundamental law of physics that compels a system to exist or remain in it. As we have seen it is simply one configuration out of countless others, though it is the one with the most microstates that can manifest it.

In order to understand why this distribution is so important, consider again the rolling of a pair of six-sided dice, but this time we should think of the average of the two rolls, which is merely the total divided by two. The most likely average of a given pair is three-and-a-half, corresponding to the sum of seven discussed earlier, though a circumspect gambler would not be terribly surprised to find either a one (from a pair of 1’s) or a six (from a pair of 6’s) should arise from time to time.

Consider however, what happens to the average as the number of dice rolls increases. With three dice there are now 63=2166^3 = 216 total permutations, but still only one way of rolling an average of one, i.e. three 1’s, so extreme values have become less likely, and for the same reason, the intermediate values have become more likely. The general formula for the number of permutations associated with a given total when rolling nn six sided dice is given in Appendix A, which has been used to generate Figure 3, in which the discrete probability functions of different nn values are plotted with both axes normalised.

Figure 3. Discrete PDFs of multiple dice rolls, normalised across domain and range.

This figure demonstrates an important property of additive probabilistic systems that is related to the Law of Large Numbers. This property is that, as the number of degrees of freedom (dice, in this example) increases, the PDF contracts about the mean value, making extreme values less and less likely and the near-mean values more and more likely. With one thousand dice, the chances of getting the most probable macrostate (a total of exactly 3500 for a mean of 3.5) is 0.738 %, but the chances of getting approximately the macrostate, say 3.5 ±\pm 0.1 is ≈\approx 93.6 %. With a million dice rolls, the chances of being within half a percent of the mean are 99.99997 %.

The number of particles making up a hot gas is, of course, much larger even than this. And so when we do thermodynamics, we can bet that the gas will be in the mostly likely macrostate, or any of the huge number of nearly identical nearby ones. Thanks to the astronomical number of particles in the system, and Law of Large numbers, this bet will be right every time.

Having understood why the most probable macrostate is so important, we now want to connect the statistical mechanics expressions considered so far into the more familiar ones of classical thermodynamics. To compute the properties of a system at the most probable macrostate (i.e. the thermodynamic equilibrium), we must evaluate ln⁡(W)\ln(W) using the expression for Nj∗N_j^*. (Recall that Nj∗N_j^* is the set of occupation numbers that define the most probable macrostate). This results in ln⁡(Wmax)\ln(W^{max}), the log of the number of microstates included with the most probable macrostate. ln⁡(Wmax)\ln(W^{max}) is a number which has a very special place in thermodynamics, we call it the entropy.

S=kBln⁡(Wmax⁡)(5)S = k_B \ln\left(W^{\max}\right) \tag*{(5)}

Combining equations 4 and 3 gives the following expression for ln⁡(Wmax⁡)\ln\left(W^{\max}\right).

ln⁡(Wmax⁡)=∑jNj∗[ln⁡gjNj+1]\ln\left(W^{\max}\right) = \sum_j N_j^* \left[\ln\frac{g_j}{N_j} + 1\right]

Substituting equation 4 results in a simple expression with the summation over states removed.

ln⁡(Wmax⁡)=N[ln⁡QN+1]+EkT(6)\ln\left(W^{\max}\right) = N\left[\ln\frac{Q}{N} + 1\right] + \frac{E}{kT} \tag*{(6)}

This introduces the partition function QQ, which is defined as Q=∑jgje−εj/kTQ = \sum_j g_j e^{-\varepsilon_j/kT}. The specifics of the partition function are important for actually evaluating a statistical mechanics problem, but for the purposes of this derivation we can just note that QQ is a function of both the volume and the temperature Q(V,T)Q(V,T). Simplifying equation 6 further, we can swap Wmax⁡W^{\max} for SS and get an expression that is very close to the standard thermodynamics-style definition of entropy.

S=kN[ln⁡Q(V,T)N+1]+E(V,T)T(7)S = kN\left[\ln\frac{Q(V,T)}{N} + 1\right] + \frac{E(V,T)}{T} \tag*{(7)}

This expression is a function of two independent variables, though exactly which two can be chosen for convenience. In the following section, we will be interested in the derivative of this expression, which will allow us to track the entropy as the properties of the system change. Considering TT and VV as independent variables, the infinitesimal difference in entropy is:

dS=∂S∂T∣VdT+∂S∂V∣TdVdS = \left.\frac{\partial S}{\partial T}\right|_V dT + \left.\frac{\partial S}{\partial V}\right|_T dV

Considering first term, it can be shown that (see Appendix B).

∂S∂T∣V=∂E∂T∣V1T(8)\left.\frac{\partial S}{\partial T}\right|_V = \left.\frac{\partial E}{\partial T}\right|_V \frac{1}{T} \tag*{(8)}

The VV derivative of the entropy is slightly more involved. It involves the pressure pp, which in statistical mechanics is defined as minus the derivative of the energy with respect to volume, at constant entropy.

p=−∂E∂V∣S(9)p = -\left.\frac{\partial E}{\partial V}\right|_S \tag*{(9)}

This, rather abstract, definition is a kind of generalised pressure that reduces to the familiar quantity in the typical case. It can be used to show (see Appendix C) that:

∂S∂V∣T=pT+∂E∂V∣T1T(10)\left.\frac{\partial S}{\partial V}\right|_T = \frac{p}{T} + \left.\frac{\partial E}{\partial V}\right|_T \frac{1}{T} \tag*{(10)}

Putting these equations together we end up with a familiar expression for the second law of thermodynamics.

References

  1. [1]W. C. Reynolds, The Element Potential Method for Chemical Equilibrium Analysis: Implementation in the Interactive Program STANJAN, Technical Report, Department of Mechanical Engineering, Stanford University, 1986.
  2. [2]S. B. Pope, Gibbs function continuation for the stable computation of chemical equilibrium, Combustion and flame 139 (2004) 222–226.DOI
  3. [3]S. Gordon, B. J. McBride, Computer Program for Calculation of Complex Chemical Equilibrium Compositions and Applications, Technical Report Reference Publication 1311, National Aeronautics and Space Administration, 1994.
  4. [4]D. G. Goodwin, H. K. Moffat, I. Schoegl, R. L. Speth, B. W. Weber, Cantera: An object-oriented software toolkit for chemical kinetics, thermodynamics, and transport processes, https://www.cantera.org, 2023. doi:10.5281/zenodo.8137090, version 3.0.0.
  5. [5]R. M. Dirks, J. S. Bois, J. M. Schaeffer, E. Winfree, N. A. Pierce, Thermodynamic analysis of interacting nucleic acid strands, SIAM Review 49 (2007) 64–88. URL: https://doi.org/10.1137/060651100. doi:10.1137/060651100.
  6. [6]S. R. Turns, D. C. Haworth, An Introduction to Combustion: Concepts and Applications, 4th ed., McGraw-Hill Education, 2020.
  7. [7]J. Anderson, Hypersonic and High Temperature Gas Dynamics, McGraw Hill, 1989.
  8. [8]W. Y. K. Chan, P. A. Jacobs, M. K. Smart, S. Grieve, C. S. Craddock, L. J. Doherty, Aerodynamic design of nozzles with uniform outflow for hypervelocity ground-test facilities, Journal of Propulsion and Power 34 (2018) 1467–1478. doi:10.2514/1.B36938.DOI
  9. [9]Anonymous, Probability that the sum of k dice is n, https://math.stackexchange.com/questions/2290090/probability-that-the-sum-of-k-dice-is-n, 2024. Accessed 22/08/24.
  10. [10]L. Susskind, The theoretical minimum: Statistical mechanics, https://theoreticalminimum.com/courses/statistical-mechanics/2013/spring, 2013. Accessed 27/08/24.

Paper details

vlnc:W_nb6xfd2k
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 10

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

Not recorded for this paper

View statement
Looking for related papers…
Contents