-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler_19.pyx
87 lines (65 loc) · 2.07 KB
/
euler_19.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
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.float64_t real
ctypedef unsigned int number
cdef class Array:
cdef real* data
def __setitem__(self, number index, real value):
self.data[index] = value
def __getitem__(self, number index):
return self.data[index]
cdef class ODES:
cdef int nvars
def __cinit__(self):
self.nvars = 2
def func(self, np.ndarray[real, ndim=1] x, real t,
np.ndarray[real, ndim=1] dxdt):
self._func(<real*>x.data, t, <real*>dxdt.data)
cdef void _func(self, real* x, real t, real* dxdt):
raise NotImplementedError
cpdef euler(self, np.ndarray[real, ndim=1] x0, np.ndarray[real, ndim=1] t):
cdef int n, m, N, M
cdef np.ndarray[real, ndim=2] X
cdef np.ndarray[real, ndim=1] x
cdef np.ndarray[real, ndim=1] dxdt
cdef real dt, tcur, tlast, *px, *pt, *pdxdt, *pX
N = len(x0)
M = len(t)
X = np.zeros((M, N), float)
x = np.zeros(N, float)
dxdt = np.zeros(N, float)
px = <real*>x.data
pt = <real*>t.data
pdxdt = <real*>dxdt.data
pX = <real*>X.data
# Pre-loop setup
for n in range(N):
pX[0 + n] = px[n] = <real>x0[n]
tlast = t[0]
# Main loop
for m in range(1, M):
tcur = pt[m]
dt = tcur - tlast
self._func(px, tlast, pdxdt)
for n in range(N):
px[n] += pdxdt[n] * dt
pX[m*N + n] = px[n]
tlast = tcur
return X
cdef class pyODES(ODES):
cdef void _func(self, real* x, real t, real* dxdt):
cdef Array ax, adxdt
ax = Array()
adxdt = Array()
ax.data = x
adxdt.data = dxdt
self.func(ax, t, adxdt)
cpdef func(self, Array x, real t, Array dxdt):
raise NotImplementedError
cdef class ODES_sub(ODES):
cdef void _func(self, real* x, real t, real* dxdt):
dxdt[0] = x[1]
dxdt[1] = - x[0]
def euler(x0, t):
return ODES_sub().euler(x0, t)