Home
Cantera C++ User`s Guide - Aerospace Research & Engineering
Contents
1. stream output coute c lt lt 4 lt lt oncle coute lt lt an Soc ccevsqzeueengils resizing x resize 500 passing an array to Fortran ftnfunction x begin 28 Chapter 4 Utilities CHAPTER FIVE Writing Functions in C for Use in Fortran and C Cantera provides an interface for Fortran 90 but you can also write your own interface functions in C that can be called from Fortran and C This allows you to use Cantera in Fortran 77 applications for example Let s consider a simple example Suppose you need a function that returns the species molar production rates given the temperature pressure and array of mass fractions If you were writing this in C with no consideration of being able to call it from any other language you might write something like this static IdealGasMix pGas 0 create the gas object void setup string mechfile pGas new IdealGasMix mechfile call to delete the gas object void cleanup delete pGas void getWdot double t double p double y double wdot pGas setState TPY t p y pGas getNetProductionRates wdot A function setup is first called to create an IdealGasMix object A pointer to this object is stored in a global variable for later access by function getWdot A function cleanup is also provided to destroy this object when it is no longer needed Since the memory will be reclaimed anyway when the program
2. ee RG Utilities 41 24 o9 8 ROS en Se are SP RR Oa ON E Writing Functions in C for Use in Fortran and C Reference Class State Temperature Density and Composition Gal PURPOSE ns oko o a ok OE ee Re ae a eres MEDICUM C 6 93 Construction and Inttralizatiom 48 4 225 et 64 Temperature and Density gt c eacee s RU RO UR Ogos X DES 6 3 Setting he Compositions 2 15 3046 xu Had eet ie ota eee whee he 6 0 Getting the 52555025554 o RR dom bape beh nab eee e EG 6 7 cotas 04 bee ee m oo Ur m 27 27 29 7 Class Constituents Elements and Species PURPOSE u 5 epo as m b v b hos os Ron a RR eae 7 23 Adding Elements and Species zo 242556658 SR na RR RO eve d 7 29 JBlementAtibutes os does e x9 OY Y ROROSORUE ee quy Be ae ee TA GSpeCIeSUNIDIDULES A bey BALE Oe e ENSE See Io ibn LO Seung the State ur 6 danas USE dete Me du ds TO Setuns the Composition s sr pa e ner es a eee a eye ER S ee ob T Getting the Composition 2 au ERI RON ETE B eap Es 8 Class Thermo Thermodynamic Properties 8 1 ciun DPI 8 2 JSubelasses 2 uorum meh re a ded S
3. include Cantera h include additional header files here if needed main int argc char argv try your code goes here catch CanteraError showErrors cerr cerr lt lt program terminating lt lt endl 2 2 Creating a Cantera Application 11 Simply fill in the t ry block with your code If you generate a unix Makefile it has the project name and the extension mak If your program is named react for example then you would build the program by typing make f react mak If your program consists of more than one source file you will need to first edit the Makefile to add the other object file names If you generate a Developer Studio project file simply open it and build the project The project file is set up so that the links to the Cantera libraries will be made 2 3 Exception Handling As can be seen from the prototype program above Cantera uses the exception handing mechanism of C to report error conditions Many different possible errors result in CanteraError exception being thrown When this occurs an error message is written to an internal buffer and if thrown within a t ry block transfers execution to the corresponding cat ch block In the prototype program above this simply prints out the error message and terminates execution If necessary additional clean up actions could be taken in this cat ch block 2 4 An Example Cantera C Application An
4. lt lt nsp lt lt endl int k m for 0 lt k 25500 a ol Ae Oe Ne Ve g speciesName k g molecularWeight k g charge k print elemental composition matrix Primer for m 0 m lt nel m printf 10s g elementName m for k 05 lt lt kh printf 10s g speciesName for m 0 m nel m posmtt Ar genAtenms k m prine 7 5 Setting the State Setting the thermodynamic state requires specifying two thermodynamic properties and the chemical composition 7 5 1 Setting the Full State These methods specify all state information The final state is completely determined by the input values and is independent of the initial state 7 5 Setting the State 41 7 5 2 Updating the Current State These methods change some properties of the current state leaving others unchanged The properties of the current state that are held constant if not specified are the temperature density and mass fractions Note in particular that the density not the pressure is held constant If it is desired to hold the pressure fixed one of the methods of the previous section should be used instead void setTemperature double t Set the temperature T K holding density and composition fixed void setDensity double rho Set the density p kg m holding temperature and composition fixed void setPressure double p Set
5. eosType Thermo 49 getChemPotentials Thermo 50 getConcentrations State 39 45 getMassFractions State 39 45 getMoleFractions State 39 45 getPartialMolarCp Thermo 50 getPartialMolarEnthalpies Thermo 49 getPartialMolarEntropies Thermo 50 getPartialMolarVolumes Thermo 49 gibbs_mass Thermo 51 gibbs_mole Thermo 50 initState State 37 intEnergy_mass Thermo 51 intEnergy_mole Thermo 50 massFraction State 39 45 maxTemp Constituents 50 SpeciesThermo 55 meanMolecularWeight State 38 mean X State 39 mean Y State 39 minTemp Constituents 50 SpeciesThermo 56 molarDensity State 38 moleFraction State 39 45 molecularWeight Constituents 42 molecularWeights State 42 nAtoms Constituents 42 nElements Constituents 42 nSpecies Constituents 42 phase Thermo 49 ready State 39 refPressure SpeciesThermo 56 setDensity State 38 44 setMassFractions State 38 44 setMassFractions NoNorm State 38 45 setMoleFractions State 38 45 setMoleFractions NoNorm 66 Index State 38 45 setPressure Thermo 44 setState HP S 52 setState PX Thermo 44 setState PY Thermo 44 setState SP S 52 setState_SV S 52 setState TP Thermo 44 set
6. EIGHT Class Thermo Thermodynamic Properties 8 1 Purpose Class Thermo is the base class for the family of thermodynamic property manager classes Class Thermo only defines the interface if any of its methods are actually called an exception is thrown The virtual public methods should be overloaded in derived classes to implement specific models These classes may be used as mix in classes to provide thermodynamic properties For an example of how to do this see Chapter 8 2 Subclasses IdealGasThermo ConstDensityThermo 8 3 Theory This section is under construction 45 8 3 1 Solution Properties The thermodynamic properties must satisfy the following relationships _ of 2 5 _ _ at 8 ez 8 2 f Ts 8 3 h u Pv 8 4 go 8 5 Os 8 6 1 1 dv 5 8 8 2 y ate 89 T These relationships are written for the specific properties but analogous expressions apply for the molar properties 8 3 2 Partial Molar Properties For any extensive thermodynamic property B T P N Nx the partial molar property for species k is defined by OB b 2 8 10 ON T P Nj It may be shown that 8 11 k The chemical potential ju is identical to the partial molar Gibbs function 8 12 d to i 8 4 Construction and Destruction Thermo phase 1 phase A pointer is stored to object phase
7. The properties are evaluated for the temperature density and composition stored in this object Note that while class Thermo can be instantiated if desired its virtual methods throw exceptions if called This constructor is meant to be called by the constructor of a subclass that overloads the virtual methods with ones that return property values See the subclass documentation for its constructor parameters Use the fact that is extensive to write B T AB T P Nx Now Taylor expand the left hand side in lambda and equate the linear terms 46 Chapter 8 Class Thermo Thermodynamic Properties Table 8 1 Values returned by method eosType Subclass Value Thermo 0 IdealGasThermo 1 IdealSolnThermo 2 Thermo Destructor Does nothing 8 5 Utilities virtual int eosType const An integer flag identifying the equation of state type Class Thermo returns zero Subclasses should return a unique value The values for currently implemented classes are listed in Table phase t amp phase Return a reference to the Phase object const phase_t amp phase const Return a read only reference to the Phase object 8 6 Partial Molar Properties The methods that get the partial molar properties are listed below In all cases the output array must be supplied as an argument and must have length greater than or equal to the number of species virtual void getPartialMolarVolum
8. double b overloaded methods virtual double pressure virtual double enthalpy mole add other virtual methods Then simply fill in the body of methods with the appropriate van der Waals expressions The easiest way to do this would be to copy file IdealGasThermo h and make the necessary modifications We have added a method to set the van der Waals a and b parameters A better model would use a mixture rule to com pute these from data for individual species But those are design decisions that specify the model to be implemented the procedure is the same whatever the model Once this class is finished define class VdwGasMix as class VdwGasMix public Phase public VdwThermo public VdwGasMix string infile virtual VdwGasMix The same code could be used to import the gas specification from a CTML file and then method set VdwConstants called to set a and b Alternatively the function that reads CTML files import CTML could be modified to recognize XML tags that specify van der Waals parameters in the input file By building up classes from more elementary ones in this way it is possible to re use a great deal of code and only code the differences between the new derived class and its base class es The resulting class can be used wherever one of its base classes can be used Instances of class VawGasMix can for example be operated on using the same functions and meth
9. InT T T FT 10 6 ag nT 4 a4T 3 1 a6 10 6 The coefficient array supplied to method init must set up as shown in the Table below coefficient value coef 0 Timid coef 1 coef 7 46 for the low temperature range coef 8 coef 14 ao agfor the high temperature range coefficients for O2 double o2data 15 1000 0 Ju nail 3 78245636e 00 2 99673416 03 9766012 950965097885 WAS S Ted 23 650 657 00 3 28253784e 00 1 48308754e 03 7 ZO SANDS SOSA ake il 5 45323129e 00 NasaThermo nasa eonstzrueter takes 9 84730201e 06 low T a0 a6 06394356e 03 57966669e 07 high T a0 a6 08845772e 03 no parameters install a parameterization for O2 as species 12 12 NASA o2data 20020 350 007 On eAtim s 10 3 Class ShomateThermo the Shomate Parameterization This parameterization is used in the NIST Chemistry WebBook 54 Chapter 10 Species Thermodynamic Properties Seven coefficients ao ac are used to represent c9 T h T and s T as polynomials in T A Bt Ct DP 2 B E A T At F e ta tg g Ur C D sS T Alogt4 Bt 2 3 21 Here t T 1000 0 The coefficient array supplied to method init must set up as shown in the Table below coefficient value coe 0 Tmid coef 1 coef 7 a6 for the low temperature range coef 8 coef 14
10. M sk T Xx log Xy Rlog P Po 9 7 k k 51 T P Xx log RT log P Po 9 8 k k The pure species properties are related by T hy T hy Ty f amp j T dT 9 9 Ta 7 Po f eT am 9 10 To T 52 Chapter 9 Class IdealGasThermo ldeal Gas CHAPTER TEN opecies Thermodynamic Properties The classes discussed in this chapter manage the standard state properties of the pure species These classes are designed for internal use by thermodynamic property managers classes derived from Thermo Many models of the thermodynamic properties of solutions express solution properties in terms of properties for the pure species that depend on temperature but are evaluated at a specified reference or standard state pressure The temperature dependence is typically parameterized as a function of temperature for some temperature range Tmin The parameterization might be a polynomial in for example 10 1 Class SpeciesThermo Class SpeciesThermo is the base class that defines the interface Subclasses of SpeciesThermo implement specific parameterizations virtual void install int index int type const double coeffs double minTemp double maxTemp double refPressure Install a parameterization for the standard state thermodynamic properties of the species with index number index The parameterization type is indicated by the type flag and must correspond to
11. Method set ToEquilState is used by class ChemEquil to compute the chemical equilibrium state For a chemical equilibrium state only the species chemical potentials may be computed from a set of potentials associated with each element the element potentials For any element potential vector A1 the chemical potential vector u defined by Anan 8 17 along with the temperature defines a chemical equilibrium state This method sets the state to the equilibrium state so defined void setToEquilState double lambda Set to the chemical equilibrium state at the current temperature and nondimensional element potentials 50 Chapter 8 Class Thermo Thermodynamic Properties CHAPTER NINE Class IdealGasThermo ldeal Gas 9 1 Purpose Class IdealGasThermo is the thermodynamic property manager class for ideal gas mixtures 9 2 Base Classes Thermo Chapter 8 9 3 Subclasses None 9 4 Theory The pressure is computed using the ideal gas law P nRT 9 1 where n p M and 8314 0 J kmol K For an ideal gas the heat capacities internal energy and enthalpy are functions only of temperature and are linear combinations of the pure species values amp Nonam 9 2 k So he T Xx 9 3 k UT 9 4 amp T c T 9 5 9 6 The entropy and Gibbs function have a logarithmic dependence on partial pressure amp T P
12. S T P M s T RO Xy log Xy Rlog P Ps C 7 k k IT P M Xx log Xy RT log P Po C 8 k k The pure species properties are related by T hy he To 9 To 20 a cu S T Sy To Po f mar C 10 To 62 Appendix C Thermodynamic Property Managers BIBLIOGRAPHY R J Kee F M Rupley and J A Miller Chemkin II A Fortran chemical kinetics package for the analysis of gas phase chemical kinetics Technical Report SAND89 8009 Sandia National Laboratories 1989 63 64 Thermo 49 Constituents addElement 41 addSpecies 41 atomicWeight 41 atomicWeights 42 charge 42 element Index 42 elementName 42 elementNames 42 maxTemp 50 minTemp 50 molecularWeight 42 nAtoms 42 nElements 42 nSpecies 42 speciesIndex 43 speciesName 43 speciesNames 43 Su setState HP 52 setState SP 52 setState SV 52 setState UV 52 SpeciesThermo maxTemp 55 minTemp 56 refPressure 56 State State 37 State State 37 density 38 getConcentrations 39 45 getMassFractions 39 45 getMoleFractions 39 45 initState 37 massFraction 39 45 meanMolecularWeight 38 mean X 39 mean Y 39 molarDensity 38 INDEX moleFraction 39 45 molecularWeights 42 ready 39 setDensity 38 44 setMassFractions 38 44 setMassFraction
13. State stores the the temperature the mass density and the mass fractions for this purpose It also stores a pointer to a vector of species molecular weights and provides methods to convert between mole fractions mass fractions and concentrations Class State contains no other information about the species Class State is meant to be used only as a base class Its methods are not virtual and are not meant to be overloaded in subclasses They are defined in the header file so that they may be inlined by the compiler Classes derived from State include Phase and IdealGasMix 6 2 Theory The thermodynamic state may be specified by any two thermodynamic state variables but some choices are more convenient than others Instances of class State specify the state by storing the temperature mass density and mole fractions for all species This choice of independent variables is made since many quantities depend on and p is always independent of T unlike P 6 3 Construction and Initialization State The constructor takes no arguments initState const vector fp amp mw Initialize the instance The argument is a reference to a vector of species molecular weights A local copy of this vector is made and the number of species is set based on the length of this vector Note This method is declared protected and therefore can only be accessed from within subclasses of State 35 6 4 Temperature and Density double setTemperat
14. Wy Ia Sunel vector double x nsp 1 0 nsp gas setState PY p y set Y hold T gas setMassFractions x set Y hold T and density gas setMassFractions NoNorm x set raw Y hold T and density The methods that set two properties have the same set State form that those that set three do But the methods that set only one property deviate from this form For example the method to set the temperature only holding density and composition fixed is called set Temperature not setState_T 3 5 Thermodynamic Properties The following methods return mixture thermodynamic properties Those with names ending in mole return molar properties and those ending mass return specific properties double v v gas enthalpy mole molar enthalpy J kmol v gas entropy mole v gas gibbs mole v gas cp mole V gas cv mole v gas enthalpy mass specific enthalpy J kg V gas entropy mass v gas gibbs mass v gas cp mass V gas cv mass Property values associated with individual species may also be determined The partial molar properties represent the contribution of each species to the mixture properties The pure molar properties are those of the pure species at the mixture temperature and pressure These may not work in the current release 22 Chapter 3 Phases of Matter int nsp gas nSpecies vector double output nsp
15. a parameterization suppported by the subclass The coefficients of the parameterization must be provided in array coeffs The parameterization is valid in the temperature range minTemp maxTemp and is for pressure refPressure virtual void update double t vector fp amp R vector fp amp h RT vector fp amp s_R const 0 Compute the species non dimensional standard state properties at temperature 1 On return Cor T cp R k ZZ 10 1 p 10 1 h RT k AKT 10 2 RT s R k T 10 3 R double maxTemp Lint k const The highest temperature for which the parameterization s are valid 53 double minTemp int k const The lowest temperature for which the parameterization s are valid double refPressure The lowest temperature for which the parameterization s are valid const 10 2 Class NasaThermo the NASA Polynomial Parameterization A widely used parameterization is the one first used in the NASA chemical equilibrium program which consists of two fourth order polynomials for cp The first one is used for Tmin lt T lt Tmia and the second one for Timid lt T lt Traz The midpoint temperature Tmia must be specified along with the two sets of coefficients The standard state properties are given by ax ap aiT aT asT 10 4 R h T ai 2 3 a4 T T T 10 5 ao 2 3 5 45 8 T 0272 03 53 44 4
16. and must be overloaded in subclasses virtual double enthalpy mole const Molar enthalpy J kmol virtual double intEnergy mole const Molar internal energy J kmol virtual double entropy_mole const Molar entropy J kmol K virtual double gibbs_mole const Molar Gibbs function g J kmol 48 Chapter 8 Class Thermo Thermodynamic Properties virtual double cp mole const Molar heat capacity at constant pressure J kmol K virtual double cv mole const Molar heat capacity at constant volume J kmol K 8 8 Specific Thermodynamic Properties These methods return property values per unit mass They are evaluated by dividing the corresponding molar property by the mean molecular weight The are not declared virtual and do not need to be overloaded in subclasses double enthalpy mass const Specific enthalpy J kg double intEnergy mass const Specific internal energy u J kg double entropy mass const Specific entropy s J kg K double gibbs mass const Specific Gibbs function g J kg double cp mass const Specific heat at constant pressure J kg K double cv mass const Specific heat at constant volume c J kg K 8 9 Setting the State For classes that derive from both Phase and Thermo these methods add to the set of setState XYZ methods defined in Phase These methods are defined here since they involve setting the pressure which requires the pressur
17. ao ag for the high temperature range 10 7 10 8 10 9 coefficients for CH4 double ch4data 15 1300 0 0237030297 MOS CAIUS ar 5 MATEOS 6684967 dE LLE Sy IA zo 002 Ss E9107 co Hm oe qo 224 4140 install a parameterization for CH4 as species 5 ShomateThermo sh constructor takes no parameters sh install 5 NASA ch4data 298 0 6000 0 OneAtm 10 3 Class ShomateThermo the Shomate Parameterization 55 56 APPENDIX A Glossary closed A system that does not exchange mass with the environment Since mass is conserved the total mass of a closed system is constant in time If nuclear reactions can be neglected the total mass of each element is also constant for a closed system See also isolated isolated A system is isolated if it is closed and in addition does not exchange energy in any form with the environment The total mass and the total energy are both constant for an isolated system See also closed open A system that exchanges mass with the environment substance A macroscopic sample of matter with a precise characteristic composition Pure water is a substance since it is always made up of H20 molecules any pure element is also a substance compound A substance containing more than one element Sodium chloride water and silicon carbide are all compounds mixture A macroscopic sample of matter made by combining two or more substances
18. const Return the species mole fractions in x double massFraction intk const Mass fraction of species k double moleFraction intk const Mole fraction of species k 6 7 Utilities bool ready const Return t rue if the instance has been initialized and is ready for use double mean X double Q const Return the mole fraction weighted mean of the entries in array Q The return value R is computed from R XQ 6 1 k double mean Y double const Return the mass fraction weighted mean of the entries in array Q The return value R is computed from R Y YQ 62 k double sum xlogx const Return R log Xx double sum_xlogQ double const Return R log Qk 6 6 Getting the Composition 37 38 CHAPTER SEVEN Class Constituents Elements and Purpose 7 2 Adding Elements and Species void addElement string name double atomicWt const Add an element Both the name and the atomic weight must be specified void addSpecies string name double atoms double charge const Species Class Constituents handles basic properties of the elements and species It is meant to be used as a mix in class and is not usually instantiated directly Class Phase derives from Constituents and so the methods described here can be invoked on objects of class Phase and its subclasses Add a species with name name The atoms array must contain atom numbers for each element in the orde
19. directory where you want them to be written This unix build procedure also works on linux systems and on Windows PCs running the Cygwin unix like environ ment If the configure script is left unmodified it s settings are appropriate to build Cantera on a linux or cygwin system using the GNU compilers available from http www cygwin com 10 Chapter 2 Cantera in C 2 1 4 Compilers Cantera can be built with recent versions of most C compilers The compiler must support namespaces the bool datatype and have good support for templates including the Standard Template Library STL If your C compiler is several years old you may need to upgrade it first Different compilers come with different implementations of the STL some of which are better than others A good implementation that should work with most compilers is available from http www sgi com tech st1l download html If you are using a recent compiler but still get errors when you try to compile please post a message at the Cantera User s Group stating the problem someone else may have experienced the same problem and knows the solution or perhaps there is an incompatibility in the Cantera source code or Makefiles that can be modified to eliminate the problem If you found a problem and were able to modify something to fix it please post a message with your fix We would like Cantera to compile out of the box on as many systems as possible a
20. exits calling cleanup is only needed if it is desired to reclaim memory before the program finishes These functions as written cannot be called from Fortran or even from C There are several problems the first of which is name mangling C compilers change the names of functions they compile to incorporate information about the argument types Since Fortran and C don t know anything about C name mangling they will be unable to find the functions in the object file and the link will fail This problem can be remedied by surrounding every function that is to be exported from the object file by extern C Another problem is that the setup function takes a st ring argument which is a C class and therefore unknown to Fortran and C For C a solution is to rewrite the function to take a pointer to a NULL terminated array of char a C string The IdealGasMix constructor takes a st ring argument but this can be constructed from the C string 29 within the function For use in C programs the following rewrite of the above functions will work static IdealGasMix pGas 0 extern C create the gas object void setup char mechfile pGas new IdealGasMix string mechfile call to delete the gas object void cleanup delete pGas void getWdot double t double p double y double wdot pGas setState TPY t p y pGas gt getNetProductionRates wdot If we want to use
21. g silane xml Gu sce states SiH AS OO equilibrate g TP g Cout return 0 catch CanteraError showErrors cerr cerr lt lt program terminating lt lt endl return 1 This program creates an ideal gas mixture from a specification in an input file sets its initial state finds the chemical equilibrium state at the same temperature and pressure and then prints out a summary of the results This program requires adding only four statements to the boilerplate code generated by ct setup The output looks like this temperature 2000 K pressure 100 Pa density 1 33182e 05 kg m 3 mean mol weight 2 21455 amu 15 1 kg 1 kmol enthalpy 3 03206e 07 6 715e 07 J internal energy 2 28121e 07 5 052e 07 J entropy 111327 2 465e 05 J K Gibbs function 1 92333e 08 4 259e 08 J heat capacity c_p 15109 6 3 346e 04 J K heat capacity c_v 11355 4 2 515e 04 J K X Y H2 9 402287e 01 8 559033e 01 H 5 023175e 02 2 286333e 02 5 4 1 904176 10 2 761643 09 SI 9 493714e 03 1 204037e 01 SIH 2 610042e 05 3 428973e 04 SIH2 2 437203e 06 3 312835e 05 SIH3 5 801418e 09 8 149792e 08 H3SISIH 3 881514e 15 1 055211e 13 SI2H6 9 861394e 20 2 770644e 18 H2SISIH2 4 058658e 14 1 103369e 12 SI2 1 619905e 05 4 108876e 04 SI3 1 121605e 06 4 267413e 05 This output is all produced by the call to printSummary This is a very useful way to get a quick overview of
22. gas getChemPotentials output chemical potentials gas getPartialEnthalpies mole output gas getPartialEntropies mole output gas getPartialGibbs mole output gas getPartialCp mole output partial molar properties species properties PureEnthalpies mole output PureEntropies mole output PureGibbs mole output PureCp mole output pur gas ge gas ge gas ge gas ge qu mr er mp wq 3 6 Kinetics Objects of type IdealGasMix represent reacting ideal gas mixtures The most useful methods for kinetics are introduced here int nsp gas nSpecies int nrx gas nReactions vector fp rxndata nrx vector fp spdata nsp gas getFwdRatesOfProgress rxndata begin gas getRevRatesOfProgress rxndata begin gas getNetRatesOfProgress rxndata begin gas getCreationRates spdata begin gas getDestructionRates spdata begin gas getNetProductionRates spdata begin These examples show only a fraction of the methods available in class IdealGasMix These and others will be described in more detail in subsequent chapters 3 7 Transport Properties Currently transport properties are not integrated into class IdealGasMix although they may be in subsequent re lease See Chapter for information on calculation of transport properties 3 8 Structure We saw in the last few sections that class IdealGasMix provides a rich set of meth
23. lt aes Comment Elemental Composition SI 1 H o N Thermo NASA Tmin Tmid Tmax 300 1000 2000 low 1 451640400E 000 1 398736300E 002 4 234563900E 006 2 360614200E 009 1 371208900E 012 3 113410500E 003 1 232185500E 001 high 7 935938000E 001 1 767189900E 002 1 139800900E 005 3 599260400 009 4 524157100E 013 3 198212700E 003 1 524225700E 001 silane xml Done fiai rn 3 599260400 009 4 524157100E 013 3 198212700E 003 1 524225700E 001 lt floatArray gt lt NASA gt lt thermo gt lt species gt The input file is written in an XML based format we call CTML for Cantera Markup Language It is a plain text file and may be edited with any text editor But CTML files are meant to be viewed and edited with graphical tools If the file containing this silane entry is viewed in Internet Explorer or any other XML viewer the silane record appears as shown in Fig 3 2 And if this file is opened in an XML editor like XML Spy species records can be added deleted or modified graphically This is a big advantage of using XML data files graphical XML viewers and editors already exist so there is no need to write special graphical tools for this purpose as would be necessary if some non standard file format we
24. required since a few external routines that Cantera uses are written in Fortran 77 Cantera has been built successfully on PCs running several flavors of the Windows operating system and on most common unix or unix like platforms 2 1 4 Environment Variables Before running applications that use Cantera the environment variable CANTERA should be set to the top level Cantera directory For example if Cantera is located at usr local cantera 1 3 then CANTERA ROOT should besetto usr local cantera 1 3 Also the CANTERA_ROOT bin subdirectory should be put on the PATH since this contains some useful utility programs On a Windows PC environment variables can be set from the Control Panel by double clicking on the System icon and selecting the tab labeled Advanced On a unix system they may be set using shell commands These may be put in a startup file for example cshrc or profile A typical csh unix script might look like this bin csh setenv CANTERA_ROOT usr local cantera 1 3 setenv PATH 5 5 ROOT bin The equivalent commands for the GNU bash shell would be bin bash export CANTERA_ROOT usr local cantera 1 3 export PATH PATH SCANTERA_ROOT bin 2 1 2 Windows Build Procedure Under Windows Cantera can be built using Microsoft Visual C and Compaq Visual Fortran Both share the same Developer Studio development environment The Cantera dis
25. the pressure P Pa holding temperature and composition fixed void setState PX double p const double x Set the pressure Pa and mole fractions holding the temperature fixed void setState PY double p const double y Set the pressure Pa and mass fractions holding the temperature fixed void setState TP double t double p Set the temperature K and pressure Pa holding the composition fixed 7 6 Setting the Composition The composition may be set by specifying species mole fractions mass fractions or concentrations The methods of class State described here allow setting the co This may be done with an array of values for each species or with a string The string format is a comma separated list of name value pairs as shown below gasl setMoleFractions N2 2 0 FINES 5 OE OOO TONS gas2 setMassFractions AR H ima 0 Species not listed in the string are set to zero The string format is patrticularly convenient for setting the initial or inlet composition where only a few species are non zero If a large number of species values must be specified then the array format may be used This is also the most convenient form when the composition information is taken from external flowfield data void setMassFractions double yin const Set the species mass fractions to the values in array yin after normalizing them so that gt gt 1 void setMassFractions string yin const Set
26. the species mass fractions to the values specified in string yin after normalizing them so that 5 Y 1 42 Chapter 7 Class Constituents Elements and Species void setMassFractions NoNorm double yin const Set the species mass fractions to the values in array yin without normalizing them so that Y 1 void setMoleFractions double xin const Set the species mole fractions to the values in array xin after normalizing them so that gt 1 void setMoleFractions string xin const Set the species mole fractions to the values specified in string xin after normalizing them so that gt 1 void setMoleFractions NoNorm double xin const Set the species mole fractions to the values in array xin without normalizing them so that Xy 1 See also Section 7 5 7 Getting the Composition These methods retrieve composition data either for one species or for all of them For those that take an array argument the array must have length of at least void getConcentrations double c const Return the species concentrations kmol m in array c void getMassFractions vector fp amp y const Return the species mass fractions in x void getMoleFractions vector fp amp x const Return the species mole fractions in x double massFraction intk const Mass fraction of species k double moleFraction intk const Mole fraction of species k 7 7 Getting the Composition 43 44 CHAPTER
27. 27 0 407 2220 N20 44 0128 81 5950 1 0 0 2 0 HNO 31 0141 106 2523 1 1 0 0 CN 26 0179 438 6564 0 0 0 HCN 2740258 130 8079 0 1 0 H2CN 28 0338 247 3193 0 2 1 0 HCNN 41 0325 462 0938 0 1 2 0 HCNO 43 0252 171 0257 1 1 0 HOCN 43 0252 11 8014 1 1 0 HNCO 43 0252 118 0712 1 1 0 NCO 42 0173 131 7890 1 0 1 1 O0 N2 28 0134 0 0014 0 0 0 2 0 AR 39 9480 0 0000 0 0 0 0 1 C3H7 43 0892 100 4942 0 7 3 0 0 C3H8 44 0972 103 9476 00 8 3 0 0 CH2CHO 43 0456 25 1008 1 3 2 0 0 CH3CHO 44 0536 166 1798 1 4 2 0 0 We ll look at many more examples in subsequent chapters 2 5 Summary This chapter has described the basics of how to download and install Cantera and how to build a C application With this as background we are now ready to begin looking at how to use Cantera to solve problems 14 Chapter 2 Cantera in C CHAPTER THREE Phases of Matter Some of the most useful classes Cantera provides are those that model phases of matter in various forms gases liquids and solids In this chapter we ll introduce these classes and work through several examples showing how to use them 3 1 Ideal Gas Mixtures Let s begin by looking at how ideal gas mixtures are represented The Cantera class representing ideal gas mixtures is class IdealGasMix A simple program that uses this class is shown below Listing 3 1 A simple program using class IdealGasMix include Cantera h int main int argc char argv try IdealGasMix
28. 5 Writing Functions in C for Use in Fortran and C pGas 0 void getwdot double t double p double y double wdot pGas setState TPY t p y pGas gt getNetProductionRates wdot Once compiled the functions are equivalent to Fortran 77 subroutines with the following interface SUBROUTINE SETUP MECHFILE CHARACTER MECHFILE END SUBROUTINE GETWDOT T P Y WDOT DOUBLE PRECISION T P Y 1 WDOT 1 END SUBROUTINE CLEANUP END They may be called from Fortran as follows PROGRAM REACT DOUBLE PRECISION T 1000 P Y 100 WDOT 100 CALL SETUP mech xml DO I 1 1000 CAT GERWDOM Gl CH 12 0 WD OI END DO G finished with GETWDOT so release memory CALL CLEANUP These Fortran callable functions can of course also be used from C To do so a header file should be written that declares these functions as shown below ifndef MY FUNC LIB H definE MY FUNC LIB H void setup char mechfile int n void getwdot double t double p double y double wdot void cleanup endif 31 32 Part II Reference 33 CHAPTER SIX Class State Temperature Density and Composition 6 1 Purpose The thermodynamic state is uniquely specified by the values of any two thermodynamic properties and the composi tion Class
29. Cantera C User s Guide David G Goodwin October 3 2002 California Institute of Technology Email dgoodwin caltech edu II CONTENTS User s Guide Introduction lli 2 s eame o br ox oe RR AUS HE my m x eR 1 2 The Langase Interfaces serp 2 v9 ea eb dnb bb Re es Ra dT SEES LS The Kernel ovocitos RUE Go 44050445 4 60 4456 4004 14 Versions of this Document xe cogo eR m xm ox Roc RUE Rum RR Uu Y Cantera in C 2 Installing C ntera 222222222222 wee A eee ee eee OD Rom e 2 2 Creating a Cantera Application i e LEGE GR nh RU ORC RR BOS 2 3 Exception Handing 222 546 Behe ee ETE HL 24 Example Cantera Application 264 gebe Ara xe ed LS BSS Pe REUS 2 5 SUMMARY Ben e e USURIS GONE nde e dun Phases of Matter S Ideal Gas Mixtures x xo oom ek x UR y em om deg kon ea Poe RO Roy m dee Rd 3 2 23422 o Rod d Se RD RR croi en BE diet Red Boe ug 3 3 Methods i ioo Eee 4 4 4 404144064 bee web eee ha eat A 34 Updating the State x ok RO SA GR Be ey dete 8 33 Thermodynamic Properties nos Ye A ee eg 20 WKANGUCS A seen etek YEG EG ICT 227 Transport Properties 2 lt so Set So REOR dem ea ee NB gc
30. State TPX Thermo 51 setState TPY Thermo 52 setState UV S3 32 setTemperature State 38 44 setToEquilState Thermo 52 speciesIndex Constituents 43 speciesNane Constituents 43 speciesNames Constituents 43 sum xlogQ State 39 sum xlogx State 39 temperature State 38 addElement 41 addSpecies 41 atomicWeight 41 atomicWeights 42 CANTERA ROOT 9 10 18 charge 42 chemical potential 50 cp mass 51 cp mole 51 cv mass 51 0 51 cv mole density 38 element potentials 52 elementIndex 42 elementName 42 elementNames 42 enthalpy partial molar 49 enthalpy mass 51 enthalpy mole 50 entropy partial molar 50 entropy mass 51 entropy mole 50 environment variables CANTERA ROOT 9 10 18 PATH 10 eosType 49 getChemPotentials 50 getConcentrations 39 45 getMassFractions 39 45 getMoleFractions 39 45 getPartialMolarCp 50 getPartialMolarEnthalpies 49 getPartialMolarEntropies 50 getPartialMolarVolumes 49 gibbs mass 51 gibbs mole 50 heat capacity partial molar 50 index number 19 initState 37 install 55 intEnergy mass 51 intEnergy_mole 50 massFraction 39 45 maxTemp 50 55 mean X 39 mean Y 39 meanMolecularWeight 38 minTemp 50 56 molarDensity 38 molecularWeight 42 molecu
31. ame j gas elementIndex s name gt index number a gas atomicWeight m tS OTT NE e Ue OF S gas speciesName index number name j gas speciesIndex s name index number a gas molecularWeight m mol wt While elements and species may be referenced by name or by index number reactions can only be referenced by number As with elements and species numbers are assigned in order as reactions are added to the mixture bool rev for 1 0 5 ES S gas reactionString i rxn equation rev gas isReversible i reversible rxn je xm e reaction type flag 3 3 2 Setting the State The methods discussed in the last section are examples of methods that return the values of constant read only mixture attributes like the number of species their names the coefficients that are used to compute their properties etc Once set during the construction phase that is while building the object from the input file specification these 3 3 Methods 19 attributes are frozen and cannot be changed Other methods return the values of physical properties that may change during the course of a simulation Examples include methods that return thermodynamic properties transport properties and kinetic rates These all depend on the thermodynamic state of the gas mixture which is fully specified by the values of any two indepe
32. butes double charge const The electrical charge of species k in multiples of the electron charge e 1 602 x 10 1 Coulombs double molecularWeight intk const Molecular weight of species k kg kmol const vector molecularWeights const Return a read only reference to the vector of molecular weights kg kmol double nAtoms int k intm const The number of atoms of element m in species k int nSpecies const Number of species 40 Chapter 7 Class Constituents Elements and Species double speciesIndex string name const Index of species named name The index is an integer assigned to each species in the order it is added beginning with 0 for the first species If name is not the name of a species in the set then the value 1 is returned string speciesName intk const Name of species with index k If k lt 0 or k gt nSpecies an exception is thrown const vector lt string gt amp speciesNames const Return a read only reference to the vector of species names This program takes an input file name from the command line and prints a list of species with their molecular weights and charges and the elemental composition matrix include Cantera h main int argc char argv sie lt 2 Y cout lt lt missing filename lt lt endl salis IdealGasMix g string argv 1 int nsp g nSpecies int nel g nElements cout lt lt Number of species
33. duce a literal in the string 18 Chapter 3 Phases of Matter 3 3 Methods Class IdealGasMix has a large number of methods most of which are inherited from base classes We ll look at some of the most useful methods here others are described in the Reference section 3 31 Element Species and Reaction Information A few useful methods to retrieve information about the elements species and reactions for the mixture are shown below int nel gas nElements number of elements int nsp gas nSpecies number of species int nrx gas nReactions number of reactions The elements and species have an index number which is assigned in sequence as they are added to the mixture object Therefore the index number corresponds to the order in which they are declared in the input file Since indexing of arrays in C C begins with zero the first element listed in the input file has index number 0 and the last one has index number nElements 1 Similarly the first species has index number 0 and the last one has index number nSpecies 1 Note that this convention differs in the other Cantera language interfaces since Cantera uses the default indexing scheme for the local environment Thus in Python indexing also begins with 0 but in MATLAB and Fortran it begins with 1 be q les MEI String Ss for 0 m lt nel m S gas elementName m index number n
34. e equation of state These methods are not virtual and should not be overridden in subclasses void setState TPX double t double p const double x Set the temperature K pressure Pa and mole fractions void setState TPX double t double p string x Set the temperature K pressure Pa and mole fractions 8 8 Specific Thermodynamic Properties 49 void setState TPY double t double p double y Set the temperature K pressure Pa and mass fractions void setState TPY double t double p string y Set the temperature K pressure Pa and mass fractions 8 10 Setting the Enthalpy Internal Energy or Entropy These methods set the specific enthalpy specific internal energy or specific entropy at specified pressure or specific volume These are implemented using Newton iteration in temperature to find the state with the desired property The optional tol argument specifies the error tolerance to use in the Newton iteration default value 1078 void setState HP double h double p double tol et the specific enthalpy J kg and pressure Pa void setState_UV double u double v tol et the specific internal energy J kg and specific volume m kg void setState_SP double s double p tol et the specific entropy J kg K and pressure Pa void setState SV double s double v tol et the specific entropy J kg K and specific volume m kg 8 11 Setting to Equilibrium
35. ecific Entropy 5 These methods take three arguments which must be the chosen property values in the same order The first two arguments are given as floating point numbers and the third argument specifying the chemical composition must be either an array or a string 3 3 3 Specifying the Composition Using an Array If the composition is specified with an array it must contain values mole fractions or mass fractions for each species ordered by species index number Although 1 values are actually required due to the summation condition these methods require that all values be input This is done for convenience so that relative values may be specified that do not satisfy the summation conditions The input values will be scaled by dividing by their sum so that the scaled values are guaranteed to sum to one Therefore if you want to set the species mole fractions all to the same value it is sufficient to set them all to 1 0 or any other non zero value vector fp x gas nSpecies 1 0 gas setState TPX 300 0 OneAtm x begin 20 Chapter 3 Phases of Matter Sometimes it is desired to set the mole or mass fractions to values that do not sum to 1 0 Often this occurs when computing small perturbations to a system of equationa about a point where the summation condition is sat isfied Two methods are provided that set the state without scaling the input values setState TPX NoNorm and setState TPY N
36. eek Boge te Ten V EO 22 MEU e e 84 Construction and Destruction 2 4 was uses 55 ONES sx Re els SUE hs eae 66 Paral Molar Properties 42245 dub um dd Serb dv bs ees 8 7 Molar Thermodynamic Properties lt ss so oe omo x A E Roe Pus 8 8 Specific Thermodynamic Properties esis R99 eh 2 008 x mas dE TP e rA 89 Setting the State ks ea ar sr EASE SERRE Ae ste EUR 8 10 Setting the Enthalpy Internal Energy or Entropy 8 11 Setting to Equilibrium s s p a 2 40225 Se Rom eRe eR ROE Ro m 9 Class IdealGasThermo Ideal Gas o ate uris Be ee e oput cede oe de ey ee Her 92 22 554 Ace ei ee ete eae Sh eee ee Se Ls Se d ors 9 3 Subclasses GS eee X Be Soke Fe e an 9A THEON 4 sese we Rie RM E e Ba ee Bead BG dia ed VR d Bee 10 Species Thermodynamic Properties 19 1 Class SpeciesThermo 8 erw sehen ee eae eee 10 2 Class NasaThermo the NASA Polynomial Parameterization 10 3 Class ShomateThermo the Shomate Parameterization A Glossary Web Resources Reaction Mechamsm Files 3 ouo ee Ae RRS Re ES AY SRA o C Thermodynamic Property Managers Cla
37. ere is only a single phase Note that a phase does not need to be thermodynamically globally stable Diamond is a valid phase of carbon at atmospheric pressure even though graphite is the thermodynamically stable phase 57 58 APPENDIX B Web Resources under construction B 1 Reaction Mechanism Files Prof J E Shepherd s Mechanism Library Professor J E Shepherd at Caltech has posted a number of combustion related reaction mechanism files at http www galcit caltech edu EDL mechanisms library library html GRI Mech 3 0 description 59 60 APPENDIX C Thermodynamic Property Managers These classes are derived from class Thermo and implement thermodynamic properties for particular equations of state C 1 Class IdealGasThermo Ideal Gas C 2 Purpose Class IdealGasThermo is the thermodynamic property manager class for ideal gas mixtures C 3 Base Classes Thermo Chapter 8 C 4 Subclasses None C 5 Theory The pressure is computed using the ideal gas law P nRT where n p M and R 8314 0 J kmol K C 1 For an ideal gas the heat capacities internal energy and enthalpy are functions only of temperature and are linear combinations of the pure species values 61 amp NOR 2 Mix C 3 k UT h T RT C 4 amp T e T C 5 C 6 The entropy and Gibbs function have a logarithmic dependence on partial pressure
38. es double const Get the array of species partial molar volumes m kmol OV 4 8 13 N 4k virtual void getPartialMolarEnthalpies double hbar const Get the array of species partial molar enthalpies J kmol 27 8 14 8 5 Utilities 47 virtual void getPartialMolarEntropies double sbar const Get the array of species partial molar entropies J kmol K 5 Sk 27 8 15 ON virtual void getPartialMolarCp double cpbar const Get the array of species partial molar heat capacities at constant pressure J kmol K OC a 8 16 pk 5 8 16 virtual void getChemPotentials double mu const Get the array of chemical potentials partial molar Gibbs functions J kmol K 8 6 1 Limits The parameterizations used to evaluate the properties may only be valid for a limited range of temperature density or pressure These methods return those limits These methods accept an optional species index parameter If supplied then the returned values represent the limits for the data for that species Otherwise the limits are for all species double maxTemp Lint k const The highest temperature for which the parameterization s are valid double minTemp Lint kb const The lowest temperature for which the parameterization s are valid 8 7 Molar Thermodynamic Properties These methods return molar properties They are all virtual methods
39. example of a C Cantera application is shown below This program creates an object representing an ideal gas mixture reads an input file specifying its attributes and prints a table listing the species names their molecular weights standard state enthalpy of formation at 25 C and elemental composition Listing 2 1 A program to list species data include Cantera h include lt stdio h gt void printSpeciesInfo IdealGasMix amp gas int nsp gas nSpecies int nel gas nElements int k m print header printf 10s 10s 10s Species MolWt Mai gt for m 0 m nel m printf 3s gas elementName m c str printf n 10s 10s 10s g mol Peine print data for each species SNG gt 12 Chapter 2 Cantera in C for 0 lt kd x gas speciesName k 1 gas setState_TPX 298 15 OneAtm x prine UP des plo ose gas speciesName k c str gas molecularWeight k 1 e 6 gas enthalpy mole for m 0 m nel m printf 3d int gas nAtoms k m fone minicar UNOS int main int argc char argv try if lt 2 cout usage speciesinfo filename endl else string fname string argv 1 IdealGasMix g fname printSpeciesInfo g return 0 catch CanteraError showErrors cerr cerr lt lt program terminating l
40. hods that take double arguments Until recently Cantera used the Standard Template Library vector lt double gt class for this purpose It was con venient to use and method begin returned a double pointer to the underlying contiguous data array How ever some recent implementations of vector double define method begin to return an iterator of type vector double iterator which is not convertible into a double pointer Method begin returns an iterator in all implementations but in older ones vector double iterator is only a typedef for double The solution to this problem is to move away from using vector lt double gt to represent arrays Cantera now defines its own lightweight class that defines only those methods that are really needed far fewer than are defined in the std vector template and guarantees that begin returns a double pointer to the first element This class is accessed as vector fp within Cantera which is simply a typedef for class ct ct vector_fp declared in file ctvector h This class is used exclusively within Cantera when double arrays are needed and can also be used in user programs Some examples of its use are shown below include Cantera h create an array of length 10 and fill it with 0 0 VETO REE A Oron lplain old data 27 create a zero length array vector fp y append array elements int i For L 07 a Eis
41. ix chem xml call setState TPX gas 300 0 OneAtm 4 1 02 2 write molar enthalpy enthalpy mole gas Python from Cantera import gas IdealGasMix chem xml gas setState TPX 300 0 OneAtm CH4 1 02 2 print molar enthalpy gas enthalpy mole MATLAB gas IdealGasMix chem xml setState_TPX gas 300 0 OneAtm CH4 1 02 2 disp molar enthalpy enthalpy mole gas C include Cantera h IdealGasMix gas chem xml gas setState_TPX 300 0 OneAtm CH4 1 02 2 cout lt lt molar enthalpy gas enthalpy_mole The structure of Cantera is shown schematically in Fig 1 1 If Cantera is used from any language other than C access to the kernel goes through a C callable library that provides functions to create link manipulate and destroy kernel objects These functions are wrapped by language specific interface code that uses the capabilities of each language to represent Cantera objects 1 3 The Kernel Cantera is built on a kernel written in C The kernel consists of classes and functions that provide the core capabilities that can be accessed from all language environments It is implemented as a static library The kernel has a modular structure and can be configured with only those features desired For example if Cantera is only going to be used to evaluate thermodynamic and transport properties then the module
42. larWeights 42 moleFraction 39 45 name mangling 31 nAtoms 42 nElements 42 nSpecies 42 partial molar 22 enthalpy 49 entropy 50 Index 67 heat capacity 50 volume 49 PATH 10 phase 49 potential chemical 50 ready 39 refPressure 56 setDensity 38 44 setMassFractions 38 44 setMassFractions_NoNorm 38 45 setMoleFractions 38 45 setMoleFractions_NoNorm 38 45 setPressure 44 setState 52 setState 44 setState 44 setState SP 52 setState SV 52 setState TP 44 setState TPX 51 setState TPY 52 setState UV 52 setTemperature 38 44 setToEquilState 52 speciesIndex 43 speciesName 43 speciesNames 43 State 37 sum xlogQ 39 sum xlogx 39 temperature 38 Thermo 48 thermodynamic property manager 47 thermodynamic state 20 update 55 volume partial molar 49 68 Index
43. nd species It itself derives from two more elementary classes State and Constituents IdealGasThermo This class provides the thermodynamic property methods It is a member of a family of classes that derive from class Thermo Each family member has the same set of public methods but implements them using expressions appropriate for a particular thermodynamic model Class IdealGasThermo is the family member that computes properties using expressions valid for ideal gas mixtures GasKinetics Class GasKinetics provides the methods that compute reaction rates of progress and species production rates It uses rate expressions valid for elementary reactions in ideal gas mixtures Like IdealGasThermo GasKinetics is part of a family of clases that derive from a common base class Kinetics Each of these classes is described in more detail in later chapters The advantage of this structure is that it is easy to create new classes representing different types of gases liquids or solids For example suppose we want to create a class representing gas mixtures that obey the van der Waals equation of state For simplicity we will not do kinetics simulations with this class so only need to derive a new class for the thermodynamic properties All we need to do is first derive a class from Thermo class VdwThermo public Thermo public VdwThermo phase t amp phase virtual VdwThermo new methods void setVdwConstants double a
44. nd will incorporate your fix into Cantera if practical to do so If you don t have C and Fortran 77 compilers specifically for your system you can use the free GNU g and 477 compilers http www gnu org software gcc gcc html If you have these on your system the configure script will select them automatically unless you edit the configure script to specify different compilers If you do use the GNU compilers it is strongly recommended that you use version 3 0 or later preferably 3 2 or later Earlier versions of g will compile Cantera but may be slow and do not provide adequate support for exception handling Throwing an exception is likely to cause your program to terminate even if you supply code to catch the exception 2 2 Creating a Cantera Application Cantera comes with a utility program ct setup that generates properly configured Makefiles or Visual Studio project files for your application It can also create a prototype main program file To begin a new application type at the command line ctsetup If CANTERA_ROOTI bin is not on your path then you will need to type the full path instead When you run ct setup it will ask you for a project i e program name the directory where files should be written and the type of output file to generate a unix Makefile or a Developer Studio project file If there is no file named lt project gt cpp present one will be created with the following contents
45. ndent thermodynamic properties of the mixture plus the chemical composition If we consider only the intensive state the state of a unit amount then the composition is specified by kK 1 mole or mass fraction values since the last one can be obtained from the summation conditions 5 X 1 3 1 k and Y Y 1 3 2 k We will use the notation as shorthand for 03 26 where K is the total number of species in the mixture If there are species in the mixture then the intensive thermodynamic state is a function of K 1 parameters two thermodynamic properties and K 1 mole fractions mass fractions or concentrations Cantera allows the state to be set by specifying the value of one quantity from each of the three columns in the table below The methods to set the state have names that begin with setState which is followed by three uppercase letters The letters denote the properties that are being specified and corrrepond to the letters in parentheses in the table The three letters must be in the same order as the columns of this table the first letter must be T H or 5 the second one P or R and the third one X or Y For example to set the temperature density and mole fractions you would call method set State_TRX to set the specific entropy pressure and mass fractions you would call method setState SPY Temperature T Density R Mole Fractions X Specific Enthalpy H Pressure Mass Fractions Y Sp
46. oNorm 3 3 4 Using a String In cases where only a few species have non zero mole or mass fractions it is sometimes more convenient to specify the composition with a string Versions of the setState abc methods are also provided that take a string rather than an array for the third argument The format of the string is a list of comma separated name value pairs for example SI2H6 2 SIH4 1 2 O2 0 1 The colon separating the name and the value is required as is the comma separating the species The format of the number can be anything that the C function atof can parse correctly The species name is case sensitive and must match a species in the mixture exactly All unspecified species are set to zero and if a species is specified that is not present in the mixture an exception is thrown nsp gas nSpecies MS Oya OU imsy9 n double t 300 0 p OneAtm rho 0 001 setState TPX t je see Je OX gas set T density and X ss gas setState1pxX t p zsering UA BE D vector fp y nsp 1 0 nsp gas setState TPY t p y gt de Ye gas setState TRY t rho y 3 CIC TIS CSV and ny sisi MORO NE Waa gas ys Prima Re 82 3 4 Updating the State The methods of the previous section set the complete the
47. ods to simulate the behavior of reacting ideal gas mixtures Many of them of course would be useful for simulating dense gases liquids or even solids It would be very inefficient to have to implement the entire set from scratch for each class representing some material phase 3 6 Kinetics 23 IdealGasThermo IdealGasMix Figure 3 2 Inheritance diagram for class IdealGasMix In fact most of the methods discussed in previous sections are not defined in class IdealGasMix at all They are defined in more elementary base classes from which IdealGasMix derives Class IdealGasMix is derived from three lower level classes Phase GasKinetics IdealGasThermo It defines relatively few methods of its own A simplified version of its definition is shown below and the inheritance diagram is shown in Fig class IdealGasMix public Phase public IdealGasThermo public GasKinetics public IdealGasMix IdealGasMix string infile string dbase bool validate true virtual IdealGasMix a few utility methods 77 Each of the base classes of IdealGasMix handles a specific portion of the required tasks as described below Phase Class Phase provides a basic no frills representation of any phase It provides methods to set or get the 24 Chapter 3 Phases of Matter temperature density and composition in several forms and handles constant data for the elements a
48. ods used for IdealGasMix except for kinetics which we didn t implement 3 8 Structure 25 26 CHAPTER FOUR Utilities This chapter describes some classes templates and functions that have nothing to do with kinetics thermodynamics or transport processes but are useful just the same They are used internally within Cantera and may be useful in user programs too 4 1 Arrays Many methods and functions in Cantera take array arguments of type double Although there are many different implementations in C of classes for arrays the POD type double is used for this purpose in Cantera since these methods must be accessible from other languages too Fortran arrays MATLAB arrays and NumPy arrays in Python all can be accessed through pointers of type double If the method arguments were instead a C array class such as std vector lt double gt then the language interfacing code would have to copy the native array data into C objects before invoking the function or method Still when writing C code it is convenient to use an array class that handles memory allocation and deallocation automatically defines oerator so that arrays can be easily printed for debugging and can dynamically grow by adding elements to the end As long as the underlying data structure is a double array and a method is provided to return a pointer to the first element in this array the use of such a class is entirely compatible with met
49. r the elements were added The molecular weight is constructed from the atom numbers and the element atomic weights If the species is charged the charge may be entered as an optional third parameter Phase s lement 1200 mada AO double 2 0 atoms 2 0 1 0 s addSpecies H20 2 atoms double oh atoms 11 0 1 0 s addSpecies hydroxyl oh atoms s addSpecies oh plus oh atoms 1 0 7 3 Element Attributes double atomicWeight intm const Atomic weight of element m 39 const vector fp amp atomicWeights const Return a read only reference to the vector of atomic weights int elementIndex string name const Index of element named name The index is an integer assigned to each element in the order it was added beginning with 0 for the first element If name is not the name of an element in the set then the value 1 is returned string elementName intm const Name of element with index m If m lt 0 or m gt nElements an exception is thrown const vector lt string gt amp elementNames const Return a read only reference to the internal vector of element names int nElements const Number of elements int nel s nElements cout lt lt Number of elements lt lt nel lt lt endl for int m 0 m nel m Pralinen ie s elementName m s atomicWeight m 7 4 Species Attri
50. re used The graphical view may not work in the current release In addition to CTML input files in the format used in the Chemkin software package Kee et al 1989 may be used We will call this format CK format Files in this format often have extensions inp or dat In any case Cantera looks at the file contents not the extension to determine the file type so any extension may be used The CK format specification allows species thermodynamic data to be taken from a separate database file This file may be specified as a second parameter if it is required If a database file is specified then it must exist whether or not it is actually needed 3 2 Input Files 17 All of the following are valid ways to call the deal GasMix constructor CTML file with one phase specification IdealGasMix gl silane xml CTML file with multiple phases IdealGasMix gl silane xml vapor self contained CK file IdealGasMix gl silane inp CK file with an external database IdealGasMix gl silane inp therm dat A utility program ck2ctm1 is included in the distribution that converts files in this format into CTML For example ck2ctml i chem inp t therm dat o mech xml converts Chemkin input file chem inp into CTML file mech xml using file therm dat to resolve undefined species in the input file Specifying a CK format input file in the call to IdealGasMi
51. rmodynamic state After one of them has been invoked the state of the object is entirely independent of its previous state In contrast the methods discussed here only update the current state by changing the values of some but not all properties In implementing methods that set only part of the state there is some ambiguity about which unspecified property is held fixed For example if method set St at e_TX is called to set the temperature and mass fractions is the pressure held constant or the density A convention must be adopted and this is the one Cantera uses 1 If neither T H or S is specified then T is held to its current value 2 If neither P nor R is specified then the density is held to its current value 3 If neither X nor Y is specified then the composition is held fixed 3 4 Updating the State 21 nsp gas nSpecies vector tp x nsp 1 0 double t 300 0 p OneAtm rho 0 001 gas setState TP t p set T and P hold comp gas setState PX p x 12 ane pus holder gas setState TR t rho set T and density hold comp gas setTemperature t secte densi ey comp gas setDensity rho set density hold T and comp gas setPressure p set BE hold and gas setMoleFractions x set X hold T and density gas setMoleFractions_NoNorm x set raw X hold T and density Si Dam gis stan gu CHACO N2 STOP Game Stats cm edm cR MZ Eee
52. rtran and C But Cantera is also designed to be easy to learn and use and can even be used interactively from Python or MATLAB It is also open source software which means that you can always find out exactly what Cantera is doing internally should you need to know It also means that you can customize it as necessary for your application Cantera s efficient kinetics algorithms can result in substantial performance gains for codes that spend much of their time evaluating chemical production rates For typical real world applications for example rich flame simulations increases in speed of a factor of two or more have been achieved simply by using Cantera to evaluate the production rates leaving the rest of the code in Fortran untouched Cantera is also designed to be used in teaching The Python and MATLAB interfaces in particular allow students to quickly solve problems involving chemical equilibrium thermochemistry kinetics in well stirred reactors one dimensional flames and much more Problems that previously involved too much computation for effective use in class now can be easily solved freeing students to focus on the concepts being taught instead of carrying out long calculations by hand In addition more interesting problems involving design or optimization are feasible and unlike point and click what you see is all you get programs the work is documented and saved in a script 1 2 The Langage Interfaces Cantera curren
53. s implementing kinetics 6 Chapter 1 Introduction C Python MATLAB Fortran application script m file application Cantera Cantera Cantera Python MATLAB Fortran 90 package Toolbox modules C callable interface library Cantera C kernel Figure 1 1 Cantera internal structure 1 3 The Kernel one dimensional flows ODE solvers and other capabilities can be excluded This cuts down both on the size of the kernel library and on its compile time 1 4 Versions of this Document For each language there is a version of this manual The one you are reading is the C version For information about using Cantera from any of the other supported languages consult the appropriate version of the manual 8 Chapter 1 Introduction CHAPTER TWO Cantera in C Cantera is itself written in C and this makes using it in C programs different than using it to write programs in any of the other supported languages It also makes this version of the user s manual different than the other versions too since it includes a discussion of procedures to modify and extend Cantera and a description of some of Cantera s internal features 2 1 Installing Cantera To use Cantera in C programs download the Cantera source distribution and compile it on your system The latest version of Cantera is always available from http www cantera org To compile Cantera both a C compiler and a Fortran 77 compiler are
54. s_NoNorm 38 45 setMoleFractions 38 45 setMoleFractions_NoNorm 38 45 setTemperature 38 44 sum 1090 39 sum xlogx 39 temperature 38 Thermo Thermo 48 Thermo Thermo 48 Thermo 49 cp_mass 5 cp_mole mass cv mole enthalpy mass 51 enthalpy mole 50 entropy mass 51 entropy mole 50 eosType 49 getChemPotentials 50 getPartialMolarCp 50 getPartialMolarEnthalpies 49 getPartialMolarEntropies 50 getPartialMolarVolumes 49 gibbs mass 51 gibbs mole 50 intEnergy mass 51 Energy mole 50 phase 49 setPressure 44 setState PX 44 setState PY 44 44 5 Zn eRe 51 51 51 51 Apot setState TP setState 51 setState_TPY 2 Un gt 65 setToEquilState 52 Thermo Thermo 49 addElement Constituents 4l addSpecies Constituents 4l atomicWeight Constituents 4l atomicWeights Constituents 42 charge Constituents 42 cp mass Thermo 51 cp_mole Thermo 51 cv_mass Thermo 51 cv mole Thermo 51 density State 38 element Index Constituents 42 elementName Constituents 42 elementNanes Constituents 42 enthalpy_mass Thermo 51 enthalpy_mole Thermo 50 entropy mass Thermo 51 entropy mole Thermo 50
55. ss IdealGasThermo Ideal GaS y ce on Roy eR e C2 2 554 ere Eee A hoe p SS ES Base Classes on pe a bw dave ea e dune be bees Baum dee oe eA C4 Subclasses 2 6 9 bo LR Rogo m o 9 n ee a XC RR ee mum EO AUR bee he EI Emo ete Dee IDEEN iode ned ed ie irm UR Index 39 39 39 40 41 42 43 45 45 45 45 46 47 47 48 49 49 50 50 51 51 51 51 51 53 53 54 54 57 59 59 61 61 61 61 61 65 Part I User s Guide CHAPTER ONE Introduction 1 1 Whatis Cantera Cantera is a collection of object oriented software tools for problems involving chemical kinetics thermodynamics and transport processes It consists of a kernel that provides the core numerical capabilities and language interfaces that allow accessing the kernel from various environments including MATLAB Python Fortran 90 and C Cantera works with objects that represent components of a simulation gas mixtures reactors kinetics models surfaces equations of state flames ODE integrators reaction path diagrams and so on Numerical models are constructed in a physical intuitive way by creating and assembling components Cantera provides the advanced capabilities needed for use in research including fast efficient algorithms the capa bility to work with large reaction mechanisms and interfaces for Fo
56. t lt endl return 1 This program is invoked from the command line with a filename as follows speciesinfo gri30 xml The resulting output looks like this Species MolWt 298 O H C NAR g mol kJ mol H2 2 0159 0 0000 0 2 0 0 0 H 1 0080 217 9851 0 1 0 0 0 15 9994 249 1598 1 0 0 0 0 02 31 9988 0 0000 2 0 0 0 0 OH 17 0074 39 3447 1 1 0 0 0 H20 18 0153 241 8112 1 2 0 0 0 HO2 33 0068 12 5512 2 1 0 0 0 H202 34 0147 135 8717 2 2 0 0 O0 e 12 0112 716 6360 0 0 1 0 0 CH 13 0191 597 3014 0 1 1 0 0 CH2 14 0271 392 3113 0 2 1 0 Q CH2 S 14 0271 429 8661 0 2 1 0 O0 2 4 An Example Cantera C Application 13 CH3 15 0351 146 8910 0 3 0 0 CH4 16 0430 74 5954 0 4 0 0 co 28 0106 110 5232 1 0 0 0 CO2 44 0100 893 4859 2 0 0 0 HCO 29 0185 41 9974 1 0 0 CH20 30 0265 108 5733 2 0 0 2 31 0345 14 6270 3 0 0 CH30 31 0345 16 3028 3 0 0 CH30H 32 0424 200 9277 1 4 1 0 0 C2H 25 0303 566 1707 0 1 2 0 0 C2H2 26 0382 228 1860 0 2 2 0 0 C2H3 27 0462 299 7218 0 3 2 0 0 C2H4 28 0542 52 4968 0 4 2 0 0 C2H5 29 0622 118 6510 0 5 2 0 0 C2H6 30 0701 83 8464 0 6 2 0 0 HCCO 41 0297 177 4009 1 1 2 0 0 CH2CO 42 0376 47 6971 31 2 2 0 0 HCCOH 42 0376 78 2540 1 2 2 0 0 N 14 0067 472 6510 0 0 0 0 NH 15 0147 356 8964 0 1 0 0 NH2 16 0226 192 0384 0 2 0 0 NH3 17 0306 45 8957 0 3 0 1 0 NNH 29 0214 249 5017 0 1 0 2 0 NO 30 0061 91 2594 1 0 0 0 NO2 46 0055 2
57. the state of the gas mixture 3 2 Input Files It is clear from the output above that the ideal gas mixture this object represents contains multiple species We did not explicitly specify these species and their properties in program statements although we could have Instead they were read in from file silane xml This file contains an entry for each species similar to the one shown below It also contains entries for every reaction 1 SIH4 species id this s SIHA name SIH4 phaseType G gt string title comment gt 90784 lt string gt lt atomArray gt lt integer title SI gt 1 lt integer gt lt integer title H gt 4 lt integer gt gt lt atomArray gt lt thermo gt NASA Tmax 2000 Tmid 1000 Tmin 300 gt lt floatArray size 7 title low gt 1 451640400E 000 1 398736300 002 4 234563900 006 2 360614200 009 1 371208900 012 3 113410500E 003 1 232185500E 001 lt floatArray gt lt floatArray size 7 title high gt 7 935938000E 001 1 767189900 002 1 139800900E 005 16 Chapter 3 Phases of Matter Figure 3 1 Silane XML data as viewed in a graphical XML viewer like Internet Explorer xML Spy silane xml EM Eile Edit Project XML DTD Schema Schema design XSL Document Editor Convert View Browser Soap Tools Window Help Bx T 2 ass wd
58. these functions in Fortran 77 we still have some work to do however Unlike Fortran 90 Fortran 77 does not support the INTERFACE statement so it is not possible to tell the compiler that the first two parameters to get Wdot should be passed by value not by reference Nor can we specify that set up expects a C string not a Fortran string So we need to modify these functions to put them in the form Fortran 77 expects to see Fortran passes strings to functions by passing two arguments a character array and a hidden integer length param eter Most Fortran compilers pass all string length parameters at the end of the argument list but some including Compaq Visual Fortran CVF pass them immediately after each string argument CVF can optionally pass them at the end however Finally most Fortran compilers modify the function names before writing them to the object file by adding a trailing underscore and changing the name to lowercase Functions written in C C for use in Fortran must also have lowercase names with a trailing underscore The following modified version is now Fortran callable static IdealGasMix pGas 0 extern C create the gas object void setup char mechfile int n String fname 1 00 copy mechfile mechfile n fname begin delete pGas pGas new IdealGasMix string mechfile call to delete the gas object void cleanup delete pGas 30 Chapter
59. tly supports four programming languages Python MATLAB Fortran 90 and C Python is a popular object oriented scripting language and MATLAB is a widely used problem solving environment that has its own scripting language Both have good support for graphics and array operations are relatively easy to learn and use and can be used interactively Python is available free for most major platforms from http www python org MATLAB is a product of the Mathworks Inc Many universities have MATLAB site licenses and an inexpensive student version is also available Fortran 90 and C are of course widely used compiled programming languages Fortran has traditionally been the dominant language used for scientific computing especially the older Fortran 77 version of the language Fortran 90 adds many modern features found in other programming languages to Fortran including partial support for object oriented programming The use of C in scientific computing is growing rapidly due to the development of efficient C compilers that have largely eliminated the performance penalty of C compared to Fortran The language interfaces are designed so that Cantera has a similar look and feel in all environments As an example the statements required to create an object representing an ideal gas mixture set its state and print out its molar enthalpy are shown below for each language Fortran 90 use Cantera gasmix t gas gas IdealGasM
60. tribution comes with Developer Studio workspace and project files configured to build Cantera Simply open the workspace cantera dsw in folder win32 set the Active Configuration on the Build menu to examples Win32 Release and build the project This will build the Cantera kernel static libraries and a test program examples exe Execute examples exe to verify that Cantera has been correctly installed 2 1 3 Unix Build Procedure On a unix system go to CANTERA ROOT and edit file configure Set the options appropriate for your system save the file and then run it by typing at the shell prompt configure This will cause a set of Makefiles to be written that are configured appropriately for your system After configure has completed type make to build Cantera and then make install to install it You may need to have the superuser for your system help you with the last step depending on how your system s file priviliges are set Be sure to use a make program compatible with GNU make This may be called something other than make on your system When make finishes you should build the example programs to verify that Cantera is working properly Type cd examples cxx make to build them If CANTERA ROOTv bin is on your PATH then the examples may be run from any directory by typing cxx_examples Note that doing so will generate several output files be sure to run this command from a
61. ure Set the temperature K double temperature const The temperature K double setDensity Set the density kg m double density const The mass density kg m double molarDensity const The molar density kmol m double meanMolecularWeight const The mean molecular weight kg m 6 5 Setting the Composition void setMassFractions double yin const Set the species mass fractions to the values in array yin after normalizing them so that Yp 1 void setMassFractions NoNorm double yin const Set the species mass fractions to the values in array yin without normalizing them so that gt Y 1 void setMoleFractions double xin const Set the species mole fractions to the values in array xin after normalizing them so that Xy 1 void setMoleFractions_NoNorm double xin const Set the species mole fractions to the values in array xin without normalizing them so that gt 1 See also Sectionphasesetcomp 36 Chapter 6 Class State Temperature Density and Composition 6 6 Getting the Composition These methods retrieve composition data either for one species or for all of them For those that take an array argument the array must have length of at least void getConcentrations double c const Return the species concentrations kmol m in array c void getMassFractions double y const Return the species mass fractions in x void getMoleFractions double x
62. usually but not necessarily finely divided and intermixed Liquid water with dissolved oxygen and nitrogen is a mixture as are sand air wood beer and most other everyday materials In fact since even highly purified substances contain measurable trace impurities it is exceptionally rare to encounter anything that is not a mixture i e anything that is truly a substance solution A mixture in which the constituents are fully mixed on a molecular scale In a solution all molecules of a given constituent or all sites of a given type are statistically equivalent and the configurational entropy of the mixture is maximal Mixtures of gases are solutions as are mixtures of mutually soluble liquids or solids For example silicon and germanium form a crystalline solid solution Si Ge where 2 is continuously variable over a range of values phase A macroscopic sample of matter with a homogeneous composition and structure that is stable to small perturba tions Example water at a temperature below its critical temperature and above its triple point can exist in two stable states a low density state vapor or a high density one liquid There is no stable homogeneous state at intermediate densities and any attempt to prepare such a state will result in its spontaneous segregation into liquid and vapor regions Liquid water and water vapor are two phases of water below its critical temperature Above it these two phases merge and th
63. x automatically calls ck2ctml also to generate an equivalent CTML file For example if the input file is specified as chem inp then the call to IdealGasMix will create a file chem xml This file can optionally be used later instead of chem inp One advantages of doing so is that it allows viewing editing the file graphically Also CTML files are self contained with all thermodynamic data for each species ck2ctml exe for Windows PCs may be downloaded from http blue caltech edu cantera dist tools ck2ctml exe 3 2 1 The Search Path Whenever a file name is specified Cantera first searches the local directory for a file with the specified name If one is not found then Cantera data directories are searched including directory CANTERA ROOT data inputs where the input files used in the examples are located If you want to use your own input files in application programs in different directories you can put the files into CANTERA_ROOT data inputs instead of copying the input file to every directory where you want to use it Alternatively additional directories can be added to the Cantera search path This is done by calling function addDirectory addDirectory usr local inputs The format of the directory string depends on the operating system On a PC running Windows the call to addDirectory might look like this addDirectory c inputs Note that two backslashes are required to pro
Download Pdf Manuals
Related Search
Related Contents
1) Je me 6705-8230 - Lega Italy Radiation Safety User Manual R BG - NordCap Konfiguration HP EliteBook WK312EA USB-EXE取扱説明書 Canada Manual de Instruções Bedienungsanleitung Mode d'emploi Istruzioni per l Copyright © All rights reserved.
Failed to retrieve file