0

I am converting a vanilla python to cython to speed up the performance. I need to define a class PFR with an attribute gas. The type of gas is Solution which is a type from an external library called cantera (written in C++ with a python interface created using Cython).

# distutils: language=c++
cimport cantera as ct

cdef class PFR:
    cdef public ct.Solution gas;
    def __init__(self):
        self.gas = None;

    def set_gas(self, gas):
        self.gas = gas

When I complie the code I get this error:

    Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++
cimport cantera as ct

cdef class PFR:
    cdef public ct.Solution gas;
               ^
------------------------------------------------------------

C:\Users\[****]\.ipython\cython\_cython_magic_d7002e8c4a676e8ba0827e69fe89ba2a.pyx:5:16: 'Solution' is not a type identifier

Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++
cimport cantera as ct

cdef class PFR:
    cdef public ct.Solution gas;
                           ^
------------------------------------------------------------

C:\Users\[****]\.ipython\cython\_cython_magic_d7002e8c4a676e8ba0827e69fe89ba2a.pyx:5:28: C attribute of type '<error>' cannot be accessed from Python

I found a trick to make the code work. I declare gas initially as a object instead of ct.Solution

# distutils: language=c++
import cantera as ct

cdef class PFR:
    cdef public object gas;
    def __init__(self):
        self.gas = None;

    def set_gas(self, gas):
        self.gas = gas;

    def set_TP(self, T, P):
        self.gas.TP = T, P

This works fine without any errors. I can create a gas object, connect it to an instance of PFR using the gas attribute and modify it using set.TP(T,P) method.

But, I am not sure if this approach is correct because I do not understand what is happening under the hood. Could this cause performance errors when I expand the class or create multiple instances of PFR?

mo adib
  • 65
  • 6
  • You need to use cimport instead of import. – DavidW Sep 19 '22 at 20:27
  • https://stackoverflow.com/questions/29311207/cython-compilation-import-vs-cimport – DavidW Sep 19 '22 at 20:31
  • I already did that, but it did not work. I used cimport with numpy and I know that it allows you to use numpy types – mo adib Sep 19 '22 at 20:33
  • Dunno then. I suspect you're giving the final error message and the first error message is probably more informative – DavidW Sep 19 '22 at 20:46
  • I edited the question. I added the complete error with "cimport cantera as ct" – mo adib Sep 19 '22 at 21:01
  • It looks like `Solution` is probably a regular Python type, so I think the best you can do is declare it as `object`: https://github.com/Cantera/cantera/blob/ade1a381c74d207fa1cc2f167a5d4db1d015cbb3/interfaces/cython/cantera/composite.py#L29 – DavidW Sep 19 '22 at 21:28

0 Answers0