-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathwrapped.pyx
103 lines (76 loc) · 2.69 KB
/
wrapped.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
cimport cython
import numpy as np
cimport numpy as np
DTYPE = np.float
ctypedef np.float_t DTYPE_t
# This file shows 4 examples:
# - Wrapping an external c function into python, "c_hello"
# - Making a wrapped c function on python types w/ cython syntax, "factorial"
# - A c function that takes an ndarray array and returns a scalar, "array_sum"
# - A c function that takes an ndarray and returns an ndarray "tesselation"
cdef extern from "lib/cfunc.h":
# Imports definitions from a c header file
# Corresponding source file (cfunc.c) must be added to
# the extension definition in setup.py for proper compiling & linking
void hello()
def c_hello():
# Exposes a c function to python
hello()
def factorial(int x):
# Basic example of a cython function, which defines
# python-like operations and control flow on defined c types
cdef int m = x
cdef int i
if x <= 1:
return 1
else:
for i in range(1, x):
m = m * i
return m
# decorator turns off bounds-checking for speed
@cython.boundscheck(False)
def array_sum(double[:, ::1] A):
# example of an ndarray function that returns a scalar
cdef int m = A.shape[0]
cdef int n = A.shape[1]
cdef unsigned int i, j # iteration variables should be unsigned for speed
cdef double result = 0
for i in range(m):
for k in range(n):
result += A[i, k]
return result
@cython.boundscheck(False)
def tessellate(double[:, ::1] A):
# example of array function that returns a new ndarray
# turns indices of an m by n array into an 2mn by 12 array of triangle
# faces, as per the STL file format.
cdef int m = A.shape[0]
cdef int n = A.shape[1]
cdef int i, j, idx
cdef double i_ = 0
cdef double k_ = 0
cdef double[:, ::1] results = np.zeros([2 * m * n, 12])
for i in range(m - 1):
for k in range(n - 1):
idx = <unsigned int> i * n + k
results[idx, 3] = i_
results[idx, 4] = k_ + 1
results[idx, 5] = A[i, k + 1]
results[idx, 6] = i_
results[idx, 7] = k_
results[idx, 8] = A[i, k]
results[idx, 9] = i_ + 1
results[idx, 10] = k_ + 1
results[idx, 11] = A[i + 1, k + 1]
results[idx + 1, 3] = i_
results[idx + 1, 4] = k_
results[idx + 1, 5] = A[i, k]
results[idx + 1, 6] = i_ + 1
results[idx + 1, 7] = k_
results[idx + 1, 8] = A[i + 1, k]
results[idx + 1, 9] = i_ + 1
results[idx + 1, 10] = k_ + 1
results[idx + 1, 11] = A[i + 1, k + 1]
i_ += 1
k_ += 1
return results