vendredi 10 juin 2016

Using c++ complex functions in Cython


I am trying to do a complex exponential in Cython.

I have been able to cobble together the following code for my pyx:

from libc.math cimport sin, cos, acos, exp, sqrt, fabs, M_PI, floor, ceil

cdef extern from "complex.h":
    double complex cexp(double complex z)

import numpy as np
cimport numpy as np
import cython
from cython.parallel cimport prange, parallel

def try_cexp():
    cdef:
        double complex rr1
        double complex rr2
    rr1 = 1j
    rr2 = 2j

    print(rr1*rr2)

    #print(cexp(rr1))

Note that the print(cexp(rr1)) is commented. When the line is active, I get the following error when running setup.py:

error: command 'C:\WinPYthon\Winpython-64bit-3.4.3.6\python-3.4.3.amd64\scripts\gcc.exe' failed with exit status 1

Note that when cexp is commented out, everything runs expected... I can run setup.py, and when I test the function it prints out the product of the two complex numbers.

Here is my setup.py file. Note that it includes code to run openmp in Cython using g++:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
import os
os.environ["CC"] = "g++-4.7"
os.environ["CXX"] = "g++-4.7"

# These were added based on some examples I had seen of cexp in Cython. No effect.
#import pyximport
#pyximport.install(reload_support=True)

ext_modules = [
    Extension('complex_test',
              ['complex_test.pyx',
              language="c++",
              extra_compile_args=['-fopenmp'],
              extra_link_args=['-fopenmp', '-lm'])  # Note that '-lm' was
              # added due to an example where someone mentioned g++ required
              # this. Same results with and without it.
    ]

setup(
    name='complex_test',
    cmdclass={'build_ext': build_ext},
    ext_modules=ext_modules,
    include_dirs=[np.get_include()]
    )

Ultimately my goal is to speed up a calcualtion that looks like k*exp(z), where k and z are complex. Currently I am using Numerical expressions, however that has a large memory overhead, and I believe that it's possible to optimize further than it can.

Thank you for your help.


Aucun commentaire:

Enregistrer un commentaire