Guest User

Untitled

a guest
Jan 18th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. # This is a "structarray in cython with numpy recarrays" testfile
  2. import numpy as np
  3. cimport numpy as np
  4.  
  5. # My structarray has nodes with fields x and y
  6. # This also works without packed, but I have seen packed used in other places where people asked similar questions
  7. # I assume that for two doubles that is equivalent but is necessary for in8s in between
  8. cdef packed struct node:
  9. double x
  10. double y
  11. # I suppose that would be the equivalent numpy dtype?
  12. # Note: During compilation it warns me about double to float downcasts, but I do not see where
  13. nodetype = [('x' , np.float64),('y', np.float64)]
  14.  
  15. def fun():
  16. # Make 10 element recarray
  17. # (Just looked it up. A point where 1-based indexing would save a look in the docs)
  18. mynode1 = np.recarray(10,dtype=nodetype)
  19.  
  20. # Recarray with cdef struct
  21. mynode1 = np.recarray(10,dtype=nodetype)
  22.  
  23. # Fill it with non-garbage somewhere
  24. mynode1[2].x=1.0
  25. mynode1[2].y=2.0
  26.  
  27. # Brave: give recarray element to a c function assuming its equivalent to the struct
  28. ny = cfuny(mynode1[2])
  29. assert ny==2.0 # works!
  30.  
  31. # Test memoryview, assuming type node
  32. cdef node [:] nview = mynode1
  33. ny = cfunyv(nview,2)
  34. assert ny==2.0 # works!
  35.  
  36. # This sets the numpy recarray value with a c function the gts a memoryview
  37. cfunyv_set(nview,5,9.0)
  38. assert mynode1[5].y==9.0 # alsow works!
  39.  
  40. return 0
  41.  
  42. # return node element y from c struct node
  43. cdef double cfuny(node n):
  44. return n.y
  45.  
  46. # give element i from memoryview of recarray to c function expecting a c struct
  47. cdef double cfunyv(node [:] n, int i):
  48. return cfuny(n[i])
  49.  
  50. # write into recarray with a function expecting a memoryview with type node
  51. cdef int cfunyv_set(node [:] n,int i,double val):
  52. n[i].y = val
  53. return 0
Add Comment
Please, Sign In to add comment