我目前正在尝试优化我的Python程序并开始使用Cython以减少函数调用开销,并且可能稍后包括优化的C库函数。
所以我遇到了第一个问题:
我在我的代码中使用组合来创建一个更大的类。到目前为止,我已经将我的一个Python类转换为Cython(这很难)。这是代码:
import numpy as np
cimport numpy as np
ctypedef np.float64_t dtype_t
ctypedef np.complex128_t cplxtype_t
ctypedef Py_ssize_t index_t
cdef class bendingForcesClass(object):
cdef dtype_t bendingRigidity
cdef np.ndarray matrixPrefactor
cdef np.ndarray bendingForces
def __init__(self, dtype_t bendingRigidity, np.ndarray[dtype_t, ndim=2] waveNumbersNorm):
self.bendingRigidity = bendingRigidity
self.matrixPrefactor = -self.bendingRigidity * waveNumbersNorm ** 2
cpdef np.ndarray calculate(self, np.ndarray membraneHeight):
cdef np.ndarray bendingForces
bendingForces = self.matrixPrefactor * membraneHeight
return bendingForces
从我编写的Python / Cython类中,我调用了class-method calculate
,所以在我的作文课中我有以下(简化)代码:
from bendingForcesClass import bendingForcesClass
cdef class membraneClass(object):
def __init__(self, systemSideLength, lowerCutoffLength, bendingRigidity):
self.bendingForces = bendingForcesClass(bendingRigidity, self.waveNumbers.norm)
def calculateForces(self, heightR):
return self.bendingForces.calculate(heightR)
我发现了那个 cpdef
使得方法/函数可以从Python和Cython中调用,这很棒且有效,只要我不尝试定义类型 self.bendingForces
预先 - 根据 文档(早期绑定速度) 是必要的,以消除函数调用开销。我尝试了以下,但不起作用:
from bendingForcesClass import bendingForcesClass
from bendingForcesClass cimport bendingForcesClass
cdef class membraneClass(object):
cdef bendingForcesClass bendingForces
def __init__(self, systemSideLength, lowerCutoffLength, bendingRigidity):
self.bendingForces = bendingForcesClass(bendingRigidity, self.waveNumbers.norm)
def calculateForces(self, heightR):
return self.bendingForces.calculate(heightR)
有了这个,我在尝试构建时遇到了这个错误 membraneClass.pyx
与Cython:
membraneClass.pyx:18:6: 'bendingForcesClass' is not a type identifier
building 'membraneClass' extension
请注意,声明位于两个单独的文件中,这使得这更加困难。
所以我怎么做到这一点?如果有人能给我一个指针,我会非常感激,因为除了上面给出的链接之外我找不到任何关于此的信息。
谢谢和最好的问候!