Extracting submechanism in Python

3,651 views
Skip to first unread message

mahdi.ko...@gmail.com

unread,
Nov 15, 2016, 8:39:50 AM11/15/16
to Cantera Users' Group
Dear All,

Is there anyway to extract submechanism from the solution object in python to cti or xml file? Let say I have the solution object which is the GRI mechanism without C2 and higher hydrocarbons species. How to extract it to cti or xml file?
Following is the shortcode from the CANTERA webpage with some modification. I want to extract the submechanism to cti/xml file.

from cantera import *
import numpy as np

reaction_mech = 'gri30.cti'

all_species = Species.listFromFile(reaction_mech)
species = []

# Filter species
for S in all_species:
    comp = S.composition
    #if 'C' in comp and 'H' in comp:
        # Exclude all hydrocarbon species
    #    continue
    if 'C' in comp and comp.get('C') >= 2:
        # Exclude all C compounds with more than 2 C atoms
        #print S
        continue
    if 'N' in comp and comp != {'N':2}:
        # Exclude all nitrogen compounds except for N2
        continue
    if 'Ar' in comp:
        # Exclude Argon
        continue
    species.append(S)

species_names = {S.name for S in species}
print('Species: {0}'.format(', '.join(S.name for S in species)))

# Filter reactions, keeping only those that only involve the selected species
all_reactions = Reaction.listFromFile(reaction_mech)
reactions = []

print('\nReactions:')
for R in all_reactions:
    if not all(reactant in species_names for reactant in R.reactants):
        continue
    if not all(product in species_names for product in R.products):
        continue
    reactions.append(R)
    print(R.equation)

print('\n')

gas1 = Solution('gri30.xml')
gas2 = Solution(thermo='IdealGas', kinetics='GasKinetics',
                   species=species, reactions=reactions)
junk.py

Parker Clayton

unread,
Nov 15, 2016, 9:07:26 PM11/15/16
to Cantera Users' Group

Hi Mahdi,

To my understanding there is no way to do this in Cantera currently. I'm going to attach a couple of scripts I have written that should do the trick. I would advise you to check for consistency between the mechanism files they write and your original one. If you have any trouble, please let me know. 

-Parker
soln2ck.py
soln2cti.py

mahdi.ko...@gmail.com

unread,
Nov 16, 2016, 9:08:33 AM11/16/16
to Cantera Users' Group
Dear Parker,

Thanks again.

I have tried it and seems there is an issue in line 266 of soln2cti.py.
Seems the wrapper from C++ has some issue with coeffs arguments:

Error:
nasa_coeffs = trimmed_solution.species(sp_index).thermo.coeffs
AttributeError: 'cantera._cantera.NasaPoly2' object has no attribute 'coeffs'


I have installed the cantera through conda and here is my versions:
python                    3.5.2
cantera                   2.2.1

Best,
Mahdi

Parker Clayton

unread,
Nov 16, 2016, 4:01:01 PM11/16/16
to Cantera Users' Group
My apologies, I forgot to mention that these two scripts require Cantera version 2.3.0a2 or higher which can be found on the github page here . It turns out the
species.thermo.coeffs
attribute is only available in the most recent development version. If you have any issues with installing the development version, I or someone else on here should be able to help with that too. 

-Parker

mahdi.ko...@gmail.com

unread,
Nov 17, 2016, 1:47:38 AM11/17/16
to Cantera Users' Group
Dear Parker,

Thank a lot. Now it works like a charm.

For those having Anaconda:

conda install -c bryanwweber/channel/devel cantera

will update your cantera to v2.3.0a2 (and higher, as it developed). Then you can use the files Parker sent
I'm going to attach a couple of scripts I have written that should do the trick

In my case it complains about
xrange
I have changed it to
range
and everything works.

Best,
Mahdi

Bryan W. Weber

unread,
Nov 17, 2016, 11:25:36 AM11/17/16
to Cantera Users' Group
Mahdi,

I'd actually recommend you use the official Cantera channel for the conda packages -

conda install -c cantera/label/dev cantera

I'll be deleting those packages from my personal account in the near future.

Your other change is probably related to using Python 2 vs. Python 3.

Best,
Bryan

mahdi.ko...@gmail.com

unread,
Nov 18, 2016, 4:24:43 AM11/18/16
to Cantera Users' Group
Hey Bryan,

Thanks for your comments. I will switch to cantera channel.

Best,
Mahdi

Howard Shaw

unread,
Nov 19, 2016, 12:24:06 PM11/19/16
to Cantera Users' Group
Can I ask that when I read some mechanisms, I found species like SC3H5 Ic4h6 NC3H7 PC3H4? what are they?

Santosh Shanbhogue

unread,
Nov 19, 2016, 7:15:50 PM11/19/16
to Cantera Users' Group
The extra alphabet preceding the chemical formula usually indicates an isomeric form. So n-C3H7 and i-C3H7 would be isomers or propyl radical and refer to the location location of the missing H (whether it is at the end or the center)...

p is tricky. Because I have seen pC3H4 to indicate propyne; but in other mechanisms involving aromatics, it could mean the para form (you know ortho, meta, para)

Santosh

Ryan Johnson

unread,
Mar 10, 2017, 1:18:17 PM3/10/17
to Cantera Users' Group
Parker,
Was looking for something like this, so thanks for you work!!
-Ryan

Fanne

unread,
Jun 7, 2017, 12:10:24 PM6/7/17
to Cantera Users' Group
Parker,

Thank you for providing these scripts, I think they're really useful.
I run into an error on some of my mechanisms, that seem to be related to the nasa_coeffs so I was just wondering if you know if these scripts will work with nasa9 type of coefficients ?

Thanks !
Anne

Bryan W. Weber

unread,
Jun 7, 2017, 12:15:28 PM6/7/17
to Cantera Users' Group
Anne,

If I understand the CK format properly, the standard thermo database does not support NASA 9 coefficients. I'm not sure if newer versions (Chemkin-Pro) might support the NASA 9 style, but if it does, I don't know what that input format looks like. Do you have an example of a CK file with NASA 9 coefficients?

Best,
Bryan

Fanne

unread,
Jun 7, 2017, 12:22:14 PM6/7/17
to Cantera Users' Group
Bryan,

Yes a nasa9 format exists in CK ! Actually, it is the "standard" output from automatic generator like that found online https://www.grc.nasa.gov/WWW/CEAWeb/ceaThermoBuild.htm
Attached, an example for CO speices.
Screen Shot 2017-06-07 at 18.18.03.png

Bryan W. Weber

unread,
Jun 7, 2017, 12:37:23 PM6/7/17
to Cantera Users' Group
Awesome! Well, I suspect that Parker's script only handles the regular (old-style) NASA polynomials, so you'll probably have to modify it to print out NASA 9 polynomials.

Best,
Bryan

Felipe Minuzzi

unread,
Jun 8, 2017, 12:43:14 PM6/8/17
to Cantera Users' Group

Hello guys,

So I'm trying to use Parker's script to generate an inp file for a mechanism that I developed.
The problem is that I'm not sure I'm using correctly the script.
I'm new in using Python so I don't know how to use this functions.

I define my skeletal mechanism as:

skel = ct.Solution(thermo='IdealGas', kinetics='GasKinetics',
        species=speciessk,reactions=reactionssk)

How or what do I have to change in Parker's scripts in order to write my mechanism in an inp file?

Thank you all

Rodolfo Rocha

unread,
Feb 6, 2018, 2:40:30 PM2/6/18
to Cantera Users' Group
Hi everyone,

I have noticed a little bug in both soln2* files...I have a mechanism that has a falloff reaction H + O2 (+ AR) <=> HO2 (+ AR), and every submechanism I get from it comes with AR efficiencies, which is identified as an error. What is strange is that both have functions to remove efficiencies in those cases, but they did not work. Is there any way to change it (I'm pretty much a noob here)?
Thank you in advance for your response.

Best regards,

Rodolfo Rocha

unread,
Feb 6, 2018, 2:41:55 PM2/6/18
to Cantera Users' Group
Update: another bug:

Traceback (most recent call last):
  File "flamespeed_sensitivity.py", line 27, in <module>
    gas = ct.Solution('pym_.cti')
  File "interfaces/cython/cantera/base.pyx", line 29, in cantera._cantera._SolutionBase.__cinit__ (interfaces/cython/cantera/_cantera.cpp:7782)
  File "interfaces/cython/cantera/base.pyx", line 78, in cantera._cantera._SolutionBase._init_cti_xml (interfaces/cython/cantera/_cantera.cpp:8455)
cantera._cantera.CanteraError:
***********************************************************************
CanteraError thrown by ElementaryReaction::validate:
Undeclared negative pre-exponential factor found in reaction '2 OH <=> H2O + O'
***********************************************************************

The code do not declare negative pre-exponential factor.

Noel

unread,
May 11, 2018, 8:11:46 AM5/11/18
to Cantera Users' Group
Hello Parker,
Sorry for being so ignorant,first, do we agree that these lines are converting a cti file to an inp ?
So, we could later add a couple of line with Chemkin form and then call again ck2cti.

If this is correct I tried adding gas = ct.Solution('gri30_xx.cti')
But no inp file or no errors too...

Thanks for your help
Noel

sandee...@gmail.com

unread,
Jan 4, 2019, 3:22:57 PM1/4/19
to Cantera Users' Group
Indeed, thank you for doing this!

Sandeep.

Sheaker

unread,
Dec 16, 2019, 11:52:59 AM12/16/19
to Cantera Users' Group
Dear All,
I found that provided script is not working anymore. In fact the mechanism can be exported but there is a formatting error in cti file. I was trying to resolve the issue on my own but  since I am not a python expert I failed.
Beside mentioned error in line 392 where 'xrange' should be changed to 'range' there is another one somehow related to functions 'replace_list_1' and 'replace_list_2' in lines 267, 405 and 453.
The issue is that there are spaces in between element name and its number of atoms as well as there is lack of space before atom name and after number of atoms. The issue is presented in attached image.
I was trying to remove all spaces from the following functions but it didn't help. I was trying to add single space before atom name but the program was writing two spaces into the file.
I wonder if someone who was recently using this script (and most likely fixed it already) could share it, please?
Best regards,
Oskar
exportmechanism.png

Eli Baldwin

unread,
Dec 2, 2020, 11:34:52 AM12/2/20
to Cantera Users' Group
Has anyone used this script or one like it recently? I would like to export an extracted mechanism and would prefer not to rework any solved issues!
-Eli

Ingmar Schoegl

unread,
Dec 3, 2020, 9:16:09 AM12/3/20
to Cantera Users' Group
There has been some recent work on this, see discussion on Cantera/enhancements: https://github.com/Cantera/enhancements/issues/52

Unfortunately, this likely won't be supported by Cantera natively until the transition to the new YAML input format has progressed further.
-ingmar-

Daniel Thomas

unread,
Dec 18, 2020, 5:25:58 PM12/18/20
to Cantera Users' Group
@Eli - I did just use Parker's soln2ck, and that seemed to work fine, writing a single .inp file that includes the thermo data and reactions.  (The 2 instances of xrange need to be changed to range, as noted in the discussion above.)  I'm using Cantera 2.5 beta, Python 3.8

@Ingmar - I was also looking at the github issue you linked to.  Can tsikes' yaml2ck be used with Cantera 2.5 beta?  

- Daniel

Ingmar Schoegl

unread,
Dec 18, 2020, 7:14:03 PM12/18/20
to Cantera Users' Group
Dear Daniel, 
I haven’t had a chance to look at tsikes’ code (beyond ck2yaml); unfortunately the discussion didn’t lead to a consensus on how to proceed at the moment but I believe there’s a need for this to continue.
-Ingmar-

Travis Sikes

unread,
Dec 18, 2020, 7:24:43 PM12/18/20
to canter...@googlegroups.com
Daniel,

The code is developed to export any mechanism loaded (into Cantera memory) into a Chemkin readable file, so yes it will work with the newest version of Cantera. The most up to date version can be found here. This should work for your purposes. If it doesn't, please let me know so that I can make changes to the file. I agree with Ingmar that this is something to be pursued further, but we're temporarily stalled into merging it into Cantera until a few more things happen (discussed in the enhancement thread).

Travis

--
You received this message because you are subscribed to the Google Groups "Cantera Users' Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cantera-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cantera-users/a54f66a1-1de8-497c-861b-2bce1e56ddf2n%40googlegroups.com.

Daniel Thomas

unread,
Dec 18, 2020, 9:32:09 PM12/18/20
to Cantera Users' Group
Ingmar -- Thanks for the note.  Yes, I think think this is a very useful project to continue!

Travis -- Thank you for the link to latest version!  Trying it now, it looks like it should do what I need.  I was getting some errors in writing the thermo.  I'll get back to you after I've had a chance to look into it some more.

Daniel Thomas

unread,
Dec 19, 2020, 9:34:07 AM12/19/20
to Cantera Users' Group
Travis,

For my case, soln2ck is able to write the mech and transport files, but fails when writing the thermo.  It looks like it gives the same error using your simple test case:
gas3 = ct.Solution('gri30.cti')
outfile = soln2ck.write(gas3)
Gives the error:
~/openfoam/run/mechanisms/soln2ck.py in thermo_data_text(species_list, note, input_type)
    324 
    325         # attempt to split note and comment
--> 326         if len(note[species.name].split('\n', 1)) == 1:
    327             comment = ''
    328             comment_str = ''
KeyError: 'H2'

Cantera 2.5.0b1, installed with conda, running from a Jupyter nb.

Daniel

Travis Sikes

unread,
Dec 19, 2020, 12:25:11 PM12/19/20
to canter...@googlegroups.com
Daniel,

I fixed this bug in my development fork here. I tested writing gri30.cti and it works.

Travis

Daniel Thomas

unread,
Dec 19, 2020, 4:13:50 PM12/19/20
to Cantera Users' Group
Travis,

Thank you!  That worked for the basic test case, but failed with the same_thermo_file=False option.  It looks like the second call to thermo_data_text() is missing the required note argument.  Giving that a default value as below made it work for my case:
def thermo_data_text(species_list, note=False, input_type='included'):

Very nice to have this!  Thanks for sharing,

Daniel

You received this message because you are subscribed to a topic in the Google Groups "Cantera Users' Group" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/cantera-users/67860KYm6JY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to cantera-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cantera-users/CAB9Bf_stN%2B%3DHWjYuM2vqFWzd4Hvkn4%3Dz%2BYZQR2gLgfCeyJQUqQ%40mail.gmail.com.

Daniel Thomas

unread,
Jun 25, 2021, 9:17:14 PM6/25/21
to Cantera Users' Group
Is there now a better way of saving a Solution to a file now with Cantera 2.5 and yaml?  From the previous discussion it seemed like some things were in the works...

Daniel

Ray Speth

unread,
Jun 27, 2021, 12:06:35 PM6/27/21
to Cantera Users' Group

Hi Daniel,

That feature is complete in the current development version, and will be part of Cantera 2.6.0. You can see how it will work in the updated version of the mechanism_reduction.py example (see the calls to write_yaml).

Regards,
Ray

Daniel Thomas

unread,
Jun 28, 2021, 5:15:42 PM6/28/21
to Cantera Users' Group
Ray,

Thanks for the note, and great to hear that this will be part of 2.6!  I built the development version, and ran the new mechanism_reduction.py without errors.  

I'm working on removing carbon-containing species from mechanisms, to leave the N-H-O chemistry.  To get this working along the lines of extract_submechanism.py, I had to also remove all the carbon-containing third-body species (I was assuming there isn't any built-in option for doing so).  I was able to get an output .yaml file that cantera could load without error, and which looked good to me.  But when using the output yaml to solve a flame I get a floating point exception and no other debug info, even with loglevel=5.  I saw your note in this user group conversation about the floating point error triggered by a 0 falloff coefficient -- but this doesn't seem to be the case here.

Maybe there is a better place for discussion of write_yaml.  But if you have any suggestions on further debugging, I'd much appreciate it.  I also am attaching test_mechanism.py, a simple script that demonstrates the problem: it gives an error with okafor_NH.yaml from yaml_writer, but works fine with the original okafor.yamlextract_NH_submechanism.py is the code used to generate okafor_NH.yaml.  

I'm using Cantera 2.5 and the development version built on Mac OS 11.4 with all default options.

Daniel

test_mechanism_simple.py
okafor_NH.yaml
extract_NH_submechanism.py
okafor.yaml

Daniel Thomas

unread,
Jun 29, 2021, 5:48:53 PM6/29/21
to Cantera Users' Group
Looking into this more, my problem isn't with write_yaml.  Using the extracted submechanism directly, I get the same error.  This modified version of the extract_submechanism.py Cantera example demonstrates the problem: it works fine for the CounterflowPremixedFlame and for the full mechanism in both flames.  But the CounterflowDiffusionFlame fails for the submechanism simulation.  Again there is no error beyond the  floating point exception so I'm stuck on what else to try.  I get similar results for other mechanisms, and for a H2-CO fuel mix and filtering out hydrocarbon species, as in the original example.  

I'd be very grateful for any suggestions,

Daniel
extract_submechanism_NH.py

Ray Speth

unread,
Jun 30, 2021, 5:30:04 PM6/30/21
to Cantera Users' Group
Hi Daniel,

I can replicate this error with both Cantera 2.5.1 as well as the current development version. Can you please create an issue on the GitHub issue tracker for this, so we can dig into it and find out what's happening?

Regards,
Ray

Daniel Thomas

unread,
Jul 1, 2021, 10:09:26 AM7/1/21
to Cantera Users' Group
Thanks for the note Ray.  I created Issue 1067 for this,

Daniel

Reply all
Reply to author
Forward
0 new messages