1

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:

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

My cython class looks like this so far:

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!

Many thanks for all your help and advices!

4
  • When you say it "doesn't work", what exactly happens? Commented May 4, 2015 at 12:38
  • i get a CompileError, so i guess something is wrong with the way i write the class?! Commented May 4, 2015 at 12:43
  • It is generally quite useful if you tell us what compiler error you get. Commented May 4, 2015 at 12:44
  • CompileError: command 'cc' failed with exit status 1 Commented May 4, 2015 at 13:05

1 Answer 1

2

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.

As a side comment, I would directly assign the zeros ndarray to 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.