Cython Class,用Zeros创建NumPy

时间:2022-05-26 21:27:24

i am trying to create a cython class which creates a NumPy with zeros. Later i want to write float values in that Numpy... My python class looks like this:

我正在尝试创建一个用零创建NumPy的cython类。后来我想在Numpy中编写浮点值...我的python类看起来像这样:

class test:
    def __init__(self, b):
       self.b = b
       self.eTest = np.zeros((100, 100))

My cython class looks like this so far:

到目前为止,我的cython类看起来像这样:

import numpy as np
cimport numpy as np
FTYPE = np.float
ctypedef np.float_t FTYPE_t
cdef class test:
   def __init__(self, b):
      cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] eTest   <<<works fine without this line
      self.eTest = np.zeros((100,100), dtype=FTYPE)

My cython code doesn't work so far. I am struggling with the question how to create a NumPy of zeros (100, 100) without any Python. Is that even possible? I am not really familiar in cython, i am sorry if i am asking some really trivial questions!

到目前为止,我的cython代码无效。我正在努力解决如何在没有任何Python的情况下创建NumPy零(100,100)的问题。这甚至可能吗?我对cython并不熟悉,如果我问一些非常微不足道的问题,我很抱歉!

Many thanks for all your help and advices!

非常感谢您的帮助和建议!

1 个解决方案

#1


Redefine your class::

重新定义你的课程::

  cdef class test:
  cdef double[:,:] eTest
  def __init__(self, b):
      cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
      tmp = np.zeros((100,100), dtype=FTYPE)
      self.eTest = tmp

Your ndarray (tmp in this case) can only be local to a function (the constructor in this case), so you should declare first eTest as a buffer-supporting type (a memoryview in my example) and then copy the ndarray to it.

你的ndarray(本例中为tmp)只能是函数的本地函数(本例中是构造函数),因此你应该将第一个eTest声明为缓冲支持类型(在我的例子中是一个内存视图),然后将ndarray复制到它。

As a side comment, I would directly assign the zeros ndarray to eTest:

作为旁注,我会直接将零ndarray分配给eTest:

cdef class test:
      cdef double[:,:] eTest
      def __init__(self, b):
          self.eTest =  np.zeros((100,100), dtype=FTYPE)

But I kept your structure in case you needed it.

但是我保留了你的结构,以防你需要它。

#1


Redefine your class::

重新定义你的课程::

  cdef class test:
  cdef double[:,:] eTest
  def __init__(self, b):
      cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
      tmp = np.zeros((100,100), dtype=FTYPE)
      self.eTest = tmp

Your ndarray (tmp in this case) can only be local to a function (the constructor in this case), so you should declare first eTest as a buffer-supporting type (a memoryview in my example) and then copy the ndarray to it.

你的ndarray(本例中为tmp)只能是函数的本地函数(本例中是构造函数),因此你应该将第一个eTest声明为缓冲支持类型(在我的例子中是一个内存视图),然后将ndarray复制到它。

As a side comment, I would directly assign the zeros ndarray to eTest:

作为旁注,我会直接将零ndarray分配给eTest:

cdef class test:
      cdef double[:,:] eTest
      def __init__(self, b):
          self.eTest =  np.zeros((100,100), dtype=FTYPE)

But I kept your structure in case you needed it.

但是我保留了你的结构,以防你需要它。