I have the following .pyx code:
import cython
@cython.boundscheck(False)
@cython.cdivision(True)
@cython.wraparound(False)
def f(m):
cdef int n = len(m)/2
cdef int j, k
z = [[0]*(n+1) for _ in range(n*(2*n-1))]
for j in range(1, 2*n):
for k in range(j):
z[j*(j-1)/2+k][0] = m[j][k]
return solve(z, 2*n, 1, [1] + [0]*n, n)
cdef solve(b, int s, int w, g, int n):
cdef complex h
cdef int u,v,j,k
if s == 0:
return w*g[n]
c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)]
h = solve(c, s-2, -w, g, n)
e = g[:]
for u in range(n):
for v in range(n-u):
e[u+v+1] += g[u]*b[0][v]
for j in range(1, s-2):
for k in range(j):
for u in range(n):
for v in range(n-u):
c[j*(j-1)/2+k][u+v+1] += b[(j+1)*(j+2)/2][u]*b[(k+1)*(k+2)/2+1][v] + b[(k+1)*(k+2)/2][u]*b[(j+1)*(j+2)/2+1][v]
return h + solve(c, s-2, w, e, n)
I don't know how to declare the list of lists in cython to speed the code up.
For example, the variable m
is a matrix represented as a list of lists of floating point numbers. The variable z
is a list of lists of floating point numbers too. What should the line def f(m)
look like for example?
Following the advice in the answer by @DavidW here is my latest version.
import cython
import numpy as np
def f(complex[:,:] m):
cdef int n = len(m)/2
cdef int j, k
cdef complex[:,:] z = np.zeros((n*(2*n-1), n+1), dtype = complex)
for j in range(1, 2*n):
for k in range(j):
z[j*(j-1)/2+k, 0] = m[j, k]
return solve(z, 2*n, 1, [1] + [0]*n, n)
cdef solve(complex[:,:] b, int s, int w, g, int n):
cdef complex h
cdef int u,v,j,k
cdef complex[:,:] c
if s == 0:
return w*g[n]
c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)]
print("c stats:", len(c), [len(c[i]) for i in len(c)])
h = solve(c, s-2, -w, g, n)
e = g[:]
for u in range(n):
for v in range(n-u):
e[u+v+1] = e[u+v+1] + g[u]*b[0][v]
for j in range(1, s-2):
for k in range(j):
for u in range(n):
for v in range(n-u):
c[j*(j-1)/2+k][u+v+1] = c[j*(j-1)/2+k][u+v+1] + b[(j+1)*(j+2)/2][u]*b[(k+1)*(k+2)/2+1][v] + b[(k+1)*(k+2)/2][u]*b[(j+1)*(j+2)/2+1][v]
return h + solve(c, s-2, w, e, n)
The main problem now is how to declare c as it is currently a list of lists.