예제 #1
0
 def test_speed(self):
     mod_name = 'list_speed'+self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = range(1000000);
     code = """
            int v, sum = 0;
            for(int i = 0; i < a.len(); i++)
            {
                v = a[i];
                if (v % 2)
                 sum += v;
                else
                 sum -= v;
            }
            return_val = sum;
            """
     with_cxx = ext_tools.ext_function('with_cxx',code,['a'])
     mod.add_function(with_cxx)
     code = """
            int vv, sum = 0;
            PyObject *v;
            for(int i = 0; i < a.len(); i++)
            {
                v = PyList_GetItem(py_a,i);
                //didn't set error here -- just speed test
                vv = py_to_int(v,"list item");
                if (vv % 2)
                 sum += vv;
                else
                 sum -= vv;
            }
            return_val = sum;
            """
     no_checking = ext_tools.ext_function('no_checking',code,['a'])
     mod.add_function(no_checking)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import with_cxx, no_checking'
     import time
     t1 = time.time()
     sum1 = with_cxx(a)
     t2 = time.time()
     print 'speed test for list access'
     print 'compiler:',  self.compiler
     print 'scxx:',  t2 - t1
     t1 = time.time()
     sum2 = no_checking(a)
     t2 = time.time()
     print 'C, no checking:',  t2 - t1
     sum3 = 0
     t1 = time.time()
     for i in a:
         if i % 2:
             sum3 += i
         else:
             sum3 -= i
     t2 = time.time()
     print 'python:', t2 - t1
     assert_( sum1 == sum2 and sum1 == sum3)
def gseidel(mod):
    # ****gseidel****
    code="""
    int numpoints=Ny[0];
    double x0;
    for (int i=0; i<n; ++i) {
        for (int j=0; j<numpoints; ++j) {
            x0=0;
            for (int k=0; k<j; ++k) {
                x0+=A(j,k)*x(k);
            };
            for (int k=j+1; k<numpoints; ++k) {
                x0+=A(j,k)*x(k);
            };
            x0=(1-om)*x(j)+om*(y(j)-x0);
            x(j)=x0>0.0 ? x0 : 0;
        }
    }
    """
    n=1 #eigenwert nr
    om=1.0 # relaxation parameter
    A=zeros((2,2),'d') #psf-Matrix
    x=zeros((2),'d') #damas-ergebnis
    y=zeros((2),'d') #beamf-ergebnis
    func = ext_tools.ext_function('gseidel',code,['A','y','x','n','om'],type_converters=converters.blitz)
    mod.add_function(func)

    # ****gseidel1****
    # with relaxation parameter = 1
    code="""
    int numpoints=Ny[0];
    float x0;
    for (int i=0; i<n; ++i) {
        for (int j=0; j<numpoints; ++j) {
            x0=0;
            for (int k=0; k<j; ++k) {
                x0+=A(j,k)*x(k);
            };
            for (int k=j+1; k<numpoints; ++k) {
                x0+=A(j,k)*x(k);
            };
            x0=(y(j)-x0);
            x(j)=x0>0.0 ? x0 : 0;
        } 
    }
    """
    n=1 #eigenwert nr
    om=1.0 # relaxation parameter
    A=zeros((2,2),'f') #psf-Matrix
    x=zeros((2),'f') #damas-ergebnis
    y=zeros((2),'f') #beamf-ergebnis
    func = ext_tools.ext_function('gseidel1',code,['A','y','x','n'],type_converters=converters.blitz)
    mod.add_function(func)
예제 #3
0
def add_state2tensor1(mod):
    # example data for type definitions
    X = np.empty((5,1), dtype='float64', order='F')
    y = np.empty(3)

    code = """
    // unpack
    double m_norm = 1e-10;
    for (int i = 0; i < 3; ++i) {
      double x = m[i] = X[i];
      m_norm += x * x;
    }
    // normalize
    m_norm = sqrt(m_norm);
    for (int i = 0; i < 3; ++i)
      m[i] /= m_norm;

    // flip orientation?
    if (m[0]*y[0] + m[1]*y[1] + m[2]*y[2] < 0) {
        for (int i = 0; i < 3; ++i)
            m[i] = -m[i];
    }

    // lambda (clamped)
    *l1 = max(X[3], 100);
    *l2 = max(X[4], 100);
    """
    m = np.empty((3,1))
    l1 = np.empty(1);
    l2 = np.empty(1);

    fn = et.ext_function('c_state2tensor1', code, ['X', 'y', 'm', 'l1', 'l2'])
    mod.add_function(fn)
def transfer(mod):
    # **** matrix of vectors with transfer Functions **** 
    # mit vorberechneten Abstaenden
    # ohne diag removal
    code="""
    int numpoints = Nrtm[0];
    int nc = Nrtm[1];    
    int numfreq = Nkj[0];
    float expon, kj_freq, r0, factor, ri;
    
    for (int i_freq=0; i_freq<numfreq; ++i_freq) {
        kj_freq = (kj(i_freq)).imag();
        
        for (int t=0; t<numpoints; ++t) {
            r0 = rt0(t);
            
            for (int i=0; i<nc; ++i) {
                ri = rtm(t,i);
                factor = r0/ri;
                expon = kj_freq * ( r0 - ri );                 
                h(i_freq,t,i) = factor*(std::complex<float>(cosf(expon),sinf(expon)));
                
            }
        }
    }
    """
    h=zeros((2,2,2),'D') #ausgabe, spaeter t+i vertauschen t->spalten, i->zeilen
    rtm=zeros((2,2),'d') # Abstaende Mics Gridpts
    rt0=zeros((2),'d') # Abstaende Gridpts Arraycenter
    kj=zeros((2),'D') # wellenzahl * j    
    func = ext_tools.ext_function('transfer',code,['h','rt0','rtm','kj'],
                                  type_converters=converters.blitz)
    mod.add_function(func)
def faverage(mod):    
    # **** faverage *****
    code=""" 
    std::complex<double> temp;
    int nf=Ncsm[0]; 
    int nc=Ncsm[1];
    int f,i,j;
#pragma omp parallel private(f,i,j,temp) shared(csm,nc,nf,ft)
    {
#pragma omp for schedule(auto) nowait 
    for (f=0; f<nf; ++f) {
        for (i=0; i<nc; ++i) {
            temp=conj(ft(f,i));
            for (j=0; j<nc; ++j) {
                 csm(f,i,j)+=temp * ft(f,j);
            }
        }
    }
    }
    """
    #type declarations
    csm=zeros((2,2,2),'D') # cross spectral matrix
    ft=zeros((2,2),'D') # fourier spectra of all channels
    func = ext_tools.ext_function('faverage',code,['csm','ft'],type_converters=converters.blitz)
    mod.add_function(func)
예제 #6
0
def add_model_2tensor_f(mod):
    # typedefs
    X = np.empty((10,1), dtype='float64', order='F')
    m = X.shape[1]

    code = """
    for (int i = 0; i < m; ++i) {
        double *o1 = X, *o2 = X + 5;

        // unpack and normalize orientations
        vec_t m1 = make_vec(o1[0], o1[1], o1[2]); m1 = m1 / norm(m1);
        vec_t m2 = make_vec(o2[0], o2[1], o2[2]); m2 = m2 / norm(m2);
        double l11 = o1[3], l12 = o1[4];
        double l21 = o2[3], l22 = o2[4];
    
        // ensure: lambda >= L
        double L = 100;
        if (l11 < L)   l11 = L;
        if (l12 < L)   l12 = L;
        if (l21 < L)   l21 = L;
        if (l22 < L)   l22 = L;

        // write back
        vec2mem(m1, o1);  vec2mem(m2, o2);
        o1[3] = l11; o2[3] = l21;
        o1[4] = l12; o2[4] = l22;

        // prepare for next
        X += 10;
    }
    """

    fn = et.ext_function('c_model_2tensor_f', code, ['X', 'm'])
    mod.add_function(fn)
예제 #7
0
def build_math():
    """ Builds an extension module with fibonacci calculators.
    """
    mod = ext_tools.ext_module('math_ext')
    time = 0.435 # this is effectively a type declaration
    e_code = """
    #include "math.h"
    #include "spike_prop.h"

    #define DECAY 7
    inline double e(double time){
    double asrf=0;
    if (time > 0){
      //spike response function
      asrf = (time * pow(M_E, (1 - time * 0.142857143))) * 0.142857143;
    }
    return asrf;
    }
    """
    
    
    ext_code = """
    return_val = e(time);
    """
    e_ = ext_tools.ext_function('e', ext_code, ['time'])
    e_.customize.add_support_code(e_code)
    mod.add_function(e_)
    mod.compile()
예제 #8
0
def add_model_1tensor_f(mod):
    # example data for type definitions
    X = np.empty((5,1), dtype='float64', order='F')
    m = X.shape[1]

    code = """
    for (int i = 0; i < m; ++i) {
        // normalize
        double m_norm = 1e-16;
        for (int i = 0; i < 3; ++i) {
          double x = X[i];
          m_norm += x * x;
        }
        m_norm = sqrt(m_norm);
        for (int i = 0; i < 3; ++i)
          X[i] /= m_norm;

        // lambda (clamped)
        X[3] = max(X[3], 100);
        X[4] = max(X[4], 100);

        // prepare for next
        X += 5;
    }
    """
    fn = et.ext_function('c_model_1tensor_f', code, ['X', 'm'])
    mod.add_function(fn)
예제 #9
0
    def add_function(self,name, code, *varlist):
        for t in varlist:
            assert(type(t) == tuple)
            assert(len(t) == 2)
            assert(type(t[0]) == str)

        args = [n for n, v in varlist]
        vardict = dict(varlist)
        self.extension.add_function(ext_tools.ext_function(name, code, args, local_dict = vardict))
 def add_function(_module, _func):
     _arg_names = []
     if "arg_names" in _func:
         _arg_names = _func["arg_names"]
         intersection = set(locals()) & set(_func["arg_names"])
         if intersection:
             raise ValueError("The following argument-names collide with Python locals(): %s" % list(intersection))
         locals().update(dict(zip(_arg_names, _func["arg_instances"])))
     
     _module.add_function(ext_tools.ext_function(_func["name"], _func["code"], _arg_names))
def _create_python_code(mod, modname, cppcode):
    # param variable size
    p = {}
    pip = py_init_param
    pip_global = py_init_global_param
    py_notify = Filter().notify_output_observers
    image = np.zeros((1, 1), dtype=np.uint8)
    image_original = np.zeros((1, 1), dtype=np.uint8)
    dct_global_param = {}

    # help
    func = ext_tools.ext_function('help_' + modname, help_code(), [])
    mod.add_function(func)

    # __init__
    func = ext_tools.ext_function('init_' + modname, init_code("void init()" in cppcode), ['p', 'pip', 'py_notify', 'dct_global_param', 'pip_global'])
    func.customize.add_support_code(params_code())
    func.customize.add_support_code(notify_code())
    mod.add_function(func)

    # configure
    if "void configure()" in cppcode:
        has_configure = True
        func = ext_tools.ext_function('config_' + modname, config_code(), [])
        func.customize.add_support_code(params_code())
        func.customize.add_support_code(cppcode)
        func.customize.add_support_code(notify_code())
        mod.add_function(func)
    else:
        has_configure = False

    # destroy
    if "void destroy()" in cppcode:
        has_destroy = True
        func = ext_tools.ext_function('destroy_' + modname, destroy_code(), [])
        mod.add_function(func)
    else:
        has_destroy = False

    # set original image
    func = ext_tools.ext_function('set_original_image_' + modname, set_original_image_code(), ['image_original'])
    mod.add_function(func)

    # set global params
    func = ext_tools.ext_function('set_global_params_' + modname, set_global_params_code(), ['dct_global_param'])
    mod.add_function(func)

    # execute
    # Get the size of parameter
    func = ext_tools.ext_function('exec_' + modname, execute_code(), ['image'])
    func.customize.add_support_code(params_code())
    func.customize.add_support_code(cppcode)
    func.customize.add_support_code(notify_code())
    mod.add_function(func)
예제 #12
0
def add_interp3signal(mod):
    S = np.empty((100, 100, 100, 52), dtype='float32', order='F')
    p = np.empty(3)
    v = np.empty(3)
    sigma = 0.

    code = """
           #line 0 "interp3signal"
           double w_sum = 1e-16;
           double px = p[0], py = p[1], pz = p[2];
           double vx = v[0], vy = v[1], vz = v[2];

           for (int i = 0; i < 2*n; ++i)
               s[i] = 0;

           for (int zz = -1; zz <= 1; ++zz) {
               int z = round(pz) + zz;
               if (z < 0 || nz <= z) continue;
               double dz = (z - pz)*vz, dzz = dz*dz;

               for (int yy = -1; yy <= 1; ++yy) {
                   int y = round(py) + yy;
                   if (y < 0 || ny <= y) continue;
                   double dy = (y - py)*vy, dyy = dy*dy;

                   for (int xx = -1; xx <= 1; ++xx) {
                       int x = round(px) + xx;
                       if (x < 0 || nx <= x) continue;
                       double dx = (x - px)*vx, dxx = dx*dx;
                       double w = exp( -(dxx + dyy + dzz)/sigma );

                       for (int i = 0; i < n; ++i)
                           s[i] += w * S[(nz*ny*x + nz*y + z)*n + i];

                       w_sum += w;
                   }
               }
           }

           w_sum *= 2; // double each occurance
           for (int i = 0; i < n; ++i) {
               s[i  ] /= w_sum;
               s[i+n]  = s[i]; // push into second spot
           }

           """
    nx, ny, nz, n = S.shape
    s = np.empty((2 * n, ), dtype='float32')  # preallocate output (doubled)
    fn = et.ext_function('c_interp3signal', code,
                         ['s', 'S', 'p', 'v', 'sigma', 'nx', 'ny', 'nz', 'n'])
    mod.add_function(fn)
예제 #13
0
def add_interp3signal(mod):
    S = np.empty((100,100,100,52), dtype='float32', order='F')
    p = np.empty(3)
    v = np.empty(3)
    sigma = 0.

    code = """
           #line 0 "interp3signal"
           double w_sum = 1e-16;
           double px = p[0], py = p[1], pz = p[2];
           double vx = v[0], vy = v[1], vz = v[2];

           for (int i = 0; i < 2*n; ++i)
               s[i] = 0;

           for (int zz = -1; zz <= 1; ++zz) {
               int z = round(pz) + zz;
               if (z < 0 || nz <= z) continue;
               double dz = (z - pz)*vz, dzz = dz*dz;

               for (int yy = -1; yy <= 1; ++yy) {
                   int y = round(py) + yy;
                   if (y < 0 || ny <= y) continue;
                   double dy = (y - py)*vy, dyy = dy*dy;

                   for (int xx = -1; xx <= 1; ++xx) {
                       int x = round(px) + xx;
                       if (x < 0 || nx <= x) continue;
                       double dx = (x - px)*vx, dxx = dx*dx;
                       double w = exp( -(dxx + dyy + dzz)/sigma );

                       for (int i = 0; i < n; ++i)
                           s[i] += w * S[(nz*ny*x + nz*y + z)*n + i];

                       w_sum += w;
                   }
               }
           }

           w_sum *= 2; // double each occurance
           for (int i = 0; i < n; ++i) {
               s[i  ] /= w_sum;
               s[i+n]  = s[i]; // push into second spot
           }

           """
    nx,ny,nz,n = S.shape
    s = np.empty((2*n,), dtype='float32')  # preallocate output (doubled)
    fn = et.ext_function('c_interp3signal', code, ['s','S', 'p', 'v', 'sigma', 'nx','ny','nz','n'])
    mod.add_function(fn)
예제 #14
0
파일: test_ext_tools.py 프로젝트: b-t-g/Sim
 def test_string_and_int(self):
     # decalaring variables
     a = 2;b = 'string'
     # declare module
     mod = ext_tools.ext_module('ext_string_and_int')
     code = """
            a=b.length();
            return_val = PyInt_FromLong(a);
            """
     test = ext_tools.ext_function('test',code,['a','b'])
     mod.add_function(test)
     mod.compile(location = build_dir)
     import ext_string_and_int
     c = ext_string_and_int.test(a,b)
     assert_(c == len(b))
예제 #15
0
 def __call__(self,func):        
     name = func.__name__
     code = func.__doc__
     if code == None:
         code = func()
     import inspect                
     (args,_,_,defaults) = inspect.getargspec(func)
     (file,line) = inspect.getframeinfo(inspect.currentframe().f_back)[0:2]
     code = ('#line %d "%s"\n'%(line,file))+code
     defaults = [] if defaults==None else defaults
     if len(args) != len(defaults):
         raise Exception("The %s function must have default values for all arguments"%name)
     vardict = dict(zip(args,defaults))
     self.extension.add_function(ext_tools.ext_function(name, code, args, local_dict = vardict))
     return func
예제 #16
0
 def __call__(self,func):        
     name = func.__name__
     code = func.__doc__
     if code == None:
         code = func()
     import inspect                
     (args,_,_,defaults) = inspect.getargspec(func)
     (file,line) = inspect.getframeinfo(inspect.currentframe().f_back)[0:2]
     code = ('#line %d "%s"\n'%(line,file))+code
     defaults = [] if defaults==None else defaults
     if len(args) != len(defaults):
         raise Exception("The %s function must have default values for all arguments"%name)
     vardict = dict(list(zip(args,defaults)))
     self.extension.add_function(ext_tools.ext_function(name, code, args, local_dict = vardict))
     return func
예제 #17
0
 def test_string_and_int(self):
     # decalaring variables
     a = 2;b = 'string'
     # declare module
     mod = ext_tools.ext_module('ext_string_and_int')
     code = """
            a=b.length();
            return_val = PyInt_FromLong(a);
            """
     test = ext_tools.ext_function('test',code,['a','b'])
     mod.add_function(test)
     mod.compile(location = build_dir)
     import ext_string_and_int
     c = ext_string_and_int.test(a,b)
     assert(c == len(b))
예제 #18
0
 def test_complex_return(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1.+1j
     code = """
            a= a + std::complex<double>(2.,2.);
            return_val = PyComplex_FromDoubles(a.real(),a.imag());
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 1.+1j
     c = test(b)
     assert_(c == 3.+3j)
예제 #19
0
 def test_return(self):
     mod_name = 'string_return' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 'string'
     code = """
            a= std::string("hello");
            return_val = PyString_FromString(a.c_str());
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 'bub'
     c = test(b)
     assert_(c == 'hello')
예제 #20
0
 def test_return(self):
     mod_name = 'string_return'+self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 'string'
     code = """
            a= std::string("hello");
            return_val = PyString_FromString(a.c_str());
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import test'
     b='bub'
     c = test(b)
     assert_( c == 'hello')
예제 #21
0
 def test_complex_return(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1. + 1j
     code = """
            a= a + std::complex<double>(2.,2.);
            return_val = PyComplex_FromDoubles(a.real(),a.imag());
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 1. + 1j
     c = test(b)
     assert_(c == 3. + 3j)
예제 #22
0
 def test_float_return(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1.
     code = """
            a=a+2.;
            return_val = PyFloat_FromDouble(a);
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 1.
     c = test(b)
     assert_(c == 3.)
예제 #23
0
 def test_float_return(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1.
     code = """
            a=a+2.;
            return_val = PyFloat_FromDouble(a);
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import test'
     b=1.
     c = test(b)
     assert_( c == 3.)
예제 #24
0
def add_model_2tensor_h(mod):
    # typedefs
    X = np.empty((10, 1), dtype='float64', order='F')
    u = np.empty((102, 3), dtype='float64', order='F')
    b = 900.0

    n = u.shape[0]
    m = X.shape[1]
    s = np.empty((n, m), order='F')

    code = """
    for (int i = 0; i < m; ++i) {
        double *o1 = X, *o2 = X + 5;
        // unpack and normalize orientations
        vec_t m1 = make_vec(o1[0], o1[1], o1[2]); m1 /= norm(m1);
        double l11 = o1[3], l12 = o1[4];
        vec_t m2 = make_vec(o2[0], o2[1], o2[2]); m2 /= norm(m2);
        double l21 = o2[3], l22 = o2[4];

        // ensure: lambda >= L
        double L = 100;
        if (l11 < L)   l11 = L;
        if (l12 < L)   l12 = L;
        if (l21 < L)   l21 = L;
        if (l22 < L)   l22 = L;

        // flip if necessary
        if (m1._[0] < 0)   m1 = -m1;
        if (m2._[0] < 0)   m2 = -m2;

        // calculate diffusion matrix
        mat_t D1 = diffusion(m1, l11, l12);
        mat_t D2 = diffusion(m2, l21, l22);

        // reconstruct signal
        for (int i = 0; i < n; ++i, ++s) {
            vec_t u_ = make_vec(u[3*i], u[3*i+1], u[3*i+2]);
            *s = (exp(-b*dot(u_,D1*u_)) + exp(-b*dot(u_,D2*u_)))/2;
        }

        // prepare for next
        X += 10;
    }
    """
    fn = et.ext_function('c_model_2tensor_h', code,
                         ['s', 'X', 'u', 'b', 'n', 'm'])
    mod.add_function(fn)
예제 #25
0
    def __compile_weave_func(self):
        """ 
    Fast version of the integrand function f() in moment().
    We write all functions called in f() in C-code and 
    compile it once during runtime. See scipy.weave for info.

    NOTE: remove TEM_wqslit_weave.so if C-code is changed
    """
        from scipy.weave import ext_tools

        mod = ext_tools.ext_module('TEM_wqslit_weave')
        # create module TEM_wqslit_weave
        r = a = b = x1 = x2 = y1 = y2 = q = qE = q0 = dqx = dqy = n = 1.
        # declaration of variable type

        # translated C-code for arc_segment() and arc_in_box()
        code = """
        double arc_segment(double r, double a, double b) {
          if      (r<a)          return 0; 
          else if (r*r>a*a+b*b)  return r*asin(b/r); 
               else              return r*acos(a/r); 
        };
  
        double arc_in_box(double r, double x1, double y1, double x2, double y2) {
          double x, y;
          if (x1<0 && x2<0) { x1=-x1; x2=-x2;};
          if (y1<0 && y2<0) { y1=-y1; y2=-y2;};
          if (x1>x2)        {x=x1; x1=x2; x2=x;};
          if (y1>y2)        {y=y1; y1=y2; y2=y;};
        
          if (x1*x2<0) return arc_in_box(r, 0, y1, -x1, y2) + arc_in_box( r, 0, y1, x2, y2); 
          if (y1<0)    return arc_in_box(r, x1, 0, x2, y2)  - arc_in_box( r, x1, 0, x2,-y1);
          if (y1>0)    return arc_in_box(r, x1, 0, x2, y2)  + arc_in_box( r, x1, 0, x2, y1);
    
          return arc_segment(r,x1,y2) - arc_segment(r,x2,y2);
        };
        """
        # translated C-code for integrand in moment(), skips p(), weight_q()
        main = "return_val = pow(q,n) / (q*q + qE*qE) * 2 \
                        * arc_in_box(q, q0-dqx/2., 0, q0+dqx/2., dqy/2.);"

        # compile module
        func = ext_tools.ext_function('f', main,
                                      ['q', 'qE', 'n', 'q0', 'dqx', 'dqy'])
        func.customize.add_support_code(code)
        mod.add_function(func)
        mod.compile()
예제 #26
0
 def test_return(self):
     mod_name = 'list_return'+self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = [1]
     code = """
            a=py::list();
            a.append("hello");
            return_val = a;
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import test'
     b=[1,2]
     c = test(b)
     assert_( c == ['hello'])
예제 #27
0
    def test_string_and_int(self):
        # decalaring variables
        a = 2
        b = "string"
        # declare module
        mod = ext_tools.ext_module("ext_string_and_int")
        code = """
               a=b.length();
               return_val = PyInt_FromLong(a);
               """
        test = ext_tools.ext_function("test", code, ["a", "b"])
        mod.add_function(test)
        mod.compile(location=build_dir)
        import ext_string_and_int

        c = ext_string_and_int.test(a, b)
        assert_(c == len(b))
예제 #28
0
 def test_return(self):
     mod_name = 'dict_return'+self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = {'z':1}
     code = """
            a=py::dict();
            a["hello"] = 5;
            return_val = a;
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import test'
     b = {'z':2}
     c = test(b)
     assert_( c['hello'] == 5)
예제 #29
0
 def test_return(self):
     mod_name = 'list_return' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = [1]
     code = """
            a=py::list();
            a.append("hello");
            return_val = a;
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = [1, 2]
     c = test(b)
     assert_(c == ['hello'])
예제 #30
0
def add_model_2tensor_h(mod):
    # typedefs
    X = np.empty((10,1), dtype='float64', order='F')
    u = np.empty((102,3), dtype='float64', order='F')
    b = 900.0

    n = u.shape[0]
    m = X.shape[1]
    s = np.empty((n,m), order='F')

    code = """
    for (int i = 0; i < m; ++i) {
        double *o1 = X, *o2 = X + 5;
        // unpack and normalize orientations
        vec_t m1 = make_vec(o1[0], o1[1], o1[2]); m1 /= norm(m1);
        double l11 = o1[3], l12 = o1[4];
        vec_t m2 = make_vec(o2[0], o2[1], o2[2]); m2 /= norm(m2);
        double l21 = o2[3], l22 = o2[4];

        // ensure: lambda >= L
        double L = 100;
        if (l11 < L)   l11 = L;
        if (l12 < L)   l12 = L;
        if (l21 < L)   l21 = L;
        if (l22 < L)   l22 = L;

        // flip if necessary
        if (m1._[0] < 0)   m1 = -m1;
        if (m2._[0] < 0)   m2 = -m2;

        // calculate diffusion matrix
        mat_t D1 = diffusion(m1, l11, l12);
        mat_t D2 = diffusion(m2, l21, l22);

        // reconstruct signal
        for (int i = 0; i < n; ++i, ++s) {
            vec_t u_ = make_vec(u[3*i], u[3*i+1], u[3*i+2]);
            *s = (exp(-b*dot(u_,D1*u_)) + exp(-b*dot(u_,D2*u_)))/2;
        }

        // prepare for next
        X += 10;
    }
    """
    fn = et.ext_function('c_model_2tensor_h', code, ['s', 'X', 'u', 'b', 'n', 'm'])
    mod.add_function(fn)
예제 #31
0
def r_beam_psf4(mod):
    # ****r_beam_psf4**** (siehe Sarradj2012, Variante IV 'true location')
    # mit vorberechneten Abstaenden
    # ohne diag removal
    code = """
    std::complex<float> term2;
    int numpoints_grid = Nrtm[0];
    int numpoints = Nrsm[0];
    int nc = Nrtm[1];    
    float term1, expon, kj_freq;
    float r0, rsi, rti;
    
    kj_freq = kj.imag();

    for (int t=0; t<numpoints_grid; ++t) {
        for (int s=0; s<numpoints; ++s) {
            term1 = 0;
            term2 = 0;
    
            for (int i=0; i<nc; ++i) {
                rsi = rsm(s,i);
                rti = rtm(t,i);
                
                term1 += 1/(rti*rti);
               
                expon = kj_freq * (rti-rsi);
                term2 += (std::complex<float>(cosf(expon),sinf(expon))) / (rsi*rti);
            }
            r0 = rs0(s);
            h(t,s) = r0*r0 / (nc*term1*term1) * (term2*conj(term2)).real();
        }
    }
    """
    h = zeros((2, 2), 'd')  #ausgabe
    rtm = zeros((2, 2), 'd')  # Abstaende Mics Gridpts
    rsm = zeros((2, 2), 'd')  # Abstaende Mics Deconv.pts
    rs0 = zeros((2), 'd')  # Abstaende Gridpts Arraycenter
    rt0 = zeros((2),
                'd')  # Abstaende Deconv.pts Arraycenter -- not needed here
    dummy = zeros((2), 'D')  # to declare complex128, alt.: kj=1.2+0.3j
    kj = dummy[0]  # wellenzahl * j
    func = ext_tools.ext_function('r_beam_psf4',
                                  code,
                                  ['h', 'rt0', 'rs0', 'rtm', 'rsm', 'kj'],
                                  type_converters=converters.blitz)
    mod.add_function(func)
예제 #32
0
    def test_int_return(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir, mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1
        code = """
               a=a+2;
               return_val = PyInt_FromLong(a);
               """
        test = ext_tools.ext_function('test', code, ['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec 'from ' + mod_name + ' import test'
        b = 1
        c = test(b)

        assert (c == 3)
예제 #33
0
 def test_return(self):
     mod_name = 'dict_return' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = {'z': 1}
     code = """
            a=py::dict();
            a["hello"] = 5;
            return_val = a;
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = {'z': 2}
     c = test(b)
     assert_(c['hello'] == 5)
예제 #34
0
def r_beam_psf(mod):
    # ****r_beam_psf****
    # mit vorberechneten Abstaenden
    # ohne diag removal
    code = """
    std::complex<float> temp1,kjj;
    int numpoints=Nrm[0];
    int nc=Nrm[1];   
    int numfreq=Nkj[0];
    float temp2;
    float r00,rmm,r0m,rs;
    for (int i=0; i<numfreq; ++i) {
        kjj=kj(i);//.imag();
        for (int j=0; j<numpoints; ++j) {
            for (int p=0; p<numpoints; ++p) {
                rs=0;
                r00=r0(p);
                temp1=0.0;
                for (int ii=0; ii<nc; ++ii) {
                    rmm=rm(p,ii);
                    rs+=1.0/(rmm*rmm);
                    r0m=rm(j,ii);
                    temp2=(kjj*(r00+r0m-rmm)).imag();
                    e(ii)=(std::complex<double>(cosf(temp2),sinf(temp2)))*(1.0/(rmm*r0m));
                }
                rs*=r00/nc;
                temp1=0.0;
                for (int ii=0; ii<nc; ++ii) {
                    temp1+=e(ii);
                }
                h(i,j,p)=(temp1*conj(temp1)).real()/(rs*rs);
            }
        }
    }
    """
    e = zeros((2), 'D')  #hilfsvektor
    f = zeros((2), 'D')  #hilfsvektor
    h = zeros((2, 2, 2), 'd')  #ausgabe
    rm = zeros((2, 2), 'd')
    r0 = zeros((2), 'd')
    kj = zeros((2), 'D')  # wellenzahl * j
    func = ext_tools.ext_function('r_beam_psf',
                                  code, ['e', 'f', 'h', 'r0', 'rm', 'kj'],
                                  type_converters=converters.blitz)
    mod.add_function(func)
예제 #35
0
 def test_return(self):
     mod_name = 'tuple_return'+self.compiler
     mod_name = unique_mod(test_dir,mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = (1,)
     code = """
            a=py::tuple(2);
            a[0] = "hello";
            a.set_item(1,py::None);
            return_val = a;
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = test_dir, compiler = self.compiler)
     exec 'from ' + mod_name + ' import test'
     b=(1,2)
     c = test(b)
     assert_( c == ('hello',None))
예제 #36
0
 def test_return(self):
     mod_name = 'tuple_return' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = (1, )
     code = """
            a=py::tuple(2);
            a[0] = "hello";
            a.set_item(1,py::None);
            return_val = a;
            """
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = (1, 2)
     c = test(b)
     assert_(c == ('hello', None))
예제 #37
0
def build_ex1():
    ext = ext_tools.ext_module('_ex1')
    # Type declarations - define a sequence and a function
    seq = []
    func = string.upper
    code = """
           py::tuple args(1);
           py::list result(seq.length());
           for(int i = 0; i < seq.length();i++)
           {
              args[0] = seq[i];
              result[i] = func.call(args);
           }           
           return_val = result;
           """
    func = ext_tools.ext_function('my_map', code, ['func', 'seq'])
    ext.add_function(func)
    ext.compile()
예제 #38
0
def add_s2ga(mod):
    s = np.empty((102,1), dtype='float64')
    n = s.shape[0]

    code = """
           #line 0 "s2ga"
           double mu = 0, mu_sq = 0;
           for (int i = 0; i < n; ++i, ++s) {
               mu    += *s;
               mu_sq += *s * *s;
           }
           mu    /= n;
           mu_sq /= n;
           double ga = sqrt(mu_sq - mu*mu) / sqrt(mu_sq);
           return_val = ga;
           """
    fn = et.ext_function('c_s2ga', code, ['s', 'n'])
    mod.add_function(fn)
예제 #39
0
def add_s2ga(mod):
    s = np.empty((102, 1), dtype='float64')
    n = s.shape[0]

    code = """
           #line 0 "s2ga"
           double mu = 0, mu_sq = 0;
           for (int i = 0; i < n; ++i, ++s) {
               mu    += *s;
               mu_sq += *s * *s;
           }
           mu    /= n;
           mu_sq /= n;
           double ga = sqrt(mu_sq - mu*mu) / sqrt(mu_sq);
           return_val = ga;
           """
    fn = et.ext_function('c_s2ga', code, ['s', 'n'])
    mod.add_function(fn)
예제 #40
0
  def __compile_weave_func(self):
    """ 
    Fast version of the integrand function f() in moment().
    We write all functions called in f() in C-code and 
    compile it once during runtime. See scipy.weave for info.

    NOTE: remove TEM_wqslit_weave.so if C-code is changed
    """
    from scipy.weave import ext_tools;
    
    mod = ext_tools.ext_module('TEM_wqslit_weave'); # create module TEM_wqslit_weave
    r=a=b=x1=x2=y1=y2=q=qE=q0=dqx=dqy=n=1.;         # declaration of variable type

    # translated C-code for arc_segment() and arc_in_box()
    code="""
        double arc_segment(double r, double a, double b) {
          if      (r<a)          return 0; 
          else if (r*r>a*a+b*b)  return r*asin(b/r); 
               else              return r*acos(a/r); 
        };
  
        double arc_in_box(double r, double x1, double y1, double x2, double y2) {
          double x, y;
          if (x1<0 && x2<0) { x1=-x1; x2=-x2;};
          if (y1<0 && y2<0) { y1=-y1; y2=-y2;};
          if (x1>x2)        {x=x1; x1=x2; x2=x;};
          if (y1>y2)        {y=y1; y1=y2; y2=y;};
        
          if (x1*x2<0) return arc_in_box(r, 0, y1, -x1, y2) + arc_in_box( r, 0, y1, x2, y2); 
          if (y1<0)    return arc_in_box(r, x1, 0, x2, y2)  - arc_in_box( r, x1, 0, x2,-y1);
          if (y1>0)    return arc_in_box(r, x1, 0, x2, y2)  + arc_in_box( r, x1, 0, x2, y1);
    
          return arc_segment(r,x1,y2) - arc_segment(r,x2,y2);
        };
        """
    # translated C-code for integrand in moment(), skips p(), weight_q()
    main = "return_val = pow(q,n) / (q*q + qE*qE) * 2 \
                        * arc_in_box(q, q0-dqx/2., 0, q0+dqx/2., dqy/2.);"

    # compile module
    func = ext_tools.ext_function('f',main,['q','qE','n','q0','dqx','dqy']);
    func.customize.add_support_code(code);
    mod.add_function(func);
    mod.compile();
예제 #41
0
def r_beam_psf3(mod):
    # ****r_beam_psf3**** (siehe Sarradj2012, Variante III 'true level')
    # mit vorberechneten Abstaenden
    # ohne diag removal
    code="""
    std::complex<float> term2;
    int numpoints_grid = Nrtm[0];
    int numpoints = Nrsm[0];
    int nc = Nrtm[1];    
    float term1, expon, kj_freq;
    float r0, rsi, rti;

    kj_freq = kj.imag();

    for (int t=0; t<numpoints_grid; ++t) {
        for (int s=0; s<numpoints; ++s) {
            term1 = 0;
            term2 = 0;
    
            for (int i=0; i<nc; ++i) {
                rsi = rsm(s,i);
                rti = rtm(t,i);
                
                term1 += 1/(rti*rti);
               
                expon = kj_freq * (rti-rsi);
                term2 += (std::complex<float>(cosf(expon),sinf(expon))) / (rsi*rti);
            }
            r0 = rs0(s)/rt0(t);
            h(t,s) = r0*r0 / (term1*term1) * (term2*conj(term2)).real();
        }
    }

    """
    h=zeros((2,2),'d') #ausgabe
    rtm=zeros((2,2),'d') # Abstaende Mics Gridpts
    rsm=zeros((2,2),'d') # Abstaende Mics Deconv.pts
    rt0=zeros((2),'d') # Abstaende Deconv.pts Arraycenter
    rs0=zeros((2),'d') # Abstaende Gridpts Arraycenter
    dummy=zeros((2),'D') # to declare complex128, alt.: kj=1.2+0.3j 
    kj=dummy[0] # wellenzahl * j   
    func = ext_tools.ext_function('r_beam_psf3',code,['h','rt0','rs0','rtm','rsm','kj'],type_converters=converters.blitz)
    mod.add_function(func)
예제 #42
0
def r_beam_psf(mod):
    # ****r_beam_psf****
    # mit vorberechneten Abstaenden
    # ohne diag removal
    code="""
    std::complex<float> temp1,kjj;
    int numpoints=Nrm[0];
    int nc=Nrm[1];   
    int numfreq=Nkj[0];
    float temp2;
    float r00,rmm,r0m,rs;
    for (int i=0; i<numfreq; ++i) {
        kjj=kj(i);//.imag();
        for (int j=0; j<numpoints; ++j) {
            for (int p=0; p<numpoints; ++p) {
                rs=0;
                r00=r0(p);
                temp1=0.0;
                for (int ii=0; ii<nc; ++ii) {
                    rmm=rm(p,ii);
                    rs+=1.0/(rmm*rmm);
                    r0m=rm(j,ii);
                    temp2=(kjj*(r00+r0m-rmm)).imag();
                    e(ii)=(std::complex<double>(cosf(temp2),sinf(temp2)))*(1.0/(rmm*r0m));
                }
                rs*=r00/nc;
                temp1=0.0;
                for (int ii=0; ii<nc; ++ii) {
                    temp1+=e(ii);
                }
                h(i,j,p)=(temp1*conj(temp1)).real()/(rs*rs);
            }
        }
    }
    """
    e=zeros((2),'D') #hilfsvektor    
    f=zeros((2),'D') #hilfsvektor
    h=zeros((2,2,2),'d') #ausgabe
    rm=zeros((2,2),'d')
    r0=zeros((2),'d')
    kj=zeros((2),'D') # wellenzahl * j    
    func = ext_tools.ext_function('r_beam_psf',code,['e','f','h','r0','rm','kj'],type_converters=converters.blitz)
    mod.add_function(func)
예제 #43
0
def build_ramp_ext():
    mod = ext_tools.ext_module('ramp_ext')

    # type declarations
    result = array([0],float64)
    start,end = 0.,0.
    code = """
           const int size = Nresult[0];
           const double step = (end-start)/(size-1);
           double val = start;
           for (int i = 0; i < size; i++)
           {
              result[i] = val;
              val += step;
           }
           """
    func = ext_tools.ext_function('Ramp',code,['result','start','end'])
    mod.add_function(func)
    mod.compile(compiler='gcc')
예제 #44
0
파일: test_ext_tools.py 프로젝트: b-t-g/Sim
 def test_return_tuple(self):
     # decalaring variables
     a = 2
     # declare module
     mod = ext_tools.ext_module('ext_return_tuple')
     var_specs = ext_tools.assign_variable_types(['a'],locals())
     code = """
            int b;
            b = a + 1;
            py::tuple returned(2);
            returned[0] = a;
            returned[1] = b;
            return_val = returned;
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location = build_dir)
     import ext_return_tuple
     c,d = ext_return_tuple.test(a)
     assert_(c==a and d == a+1)
 def test_return_tuple(self):
     # decalaring variables
     a = 2
     # declare module
     mod = ext_tools.ext_module('ext_return_tuple')
     var_specs = ext_tools.assign_variable_types(['a'],locals())
     code = """
            int b;
            b = a + 1;
            py::tuple returned(2);
            returned[0] = a;
            returned[1] = b;
            return_val = returned;
            """
     test = ext_tools.ext_function('test',code,['a'])
     mod.add_function(test)
     mod.compile(location=build_dir)
     import ext_return_tuple
     c,d = ext_return_tuple.test(a)
     assert_(c == a and d == a+1)
예제 #46
0
def add_model_1tensor_h(mod):
    # typedefs
    X = np.empty((5, 1), dtype='float64', order='F')
    u = np.empty((102, 3), dtype='float64', order='F')
    b = 900.0

    n = u.shape[0]
    m = X.shape[1]
    s = np.empty((n, m), order='F')

    code = """
    for (int i = 0; i < m; ++i) {
        // unpack and normalize orientations
        vec_t m1 = make_vec(X[0], X[1], X[2]); m1 /= norm(m1);
        double l11 = X[3], l12 = X[4];

        // ensure: lambda >= L
        double L = 100;
        if (l11 < L)   l11 = L;
        if (l12 < L)   l12 = L;

        // flip if necessary
        if (m1._[0] < 0)   m1 = -m1;

        // calculate diffusion matrix
        mat_t D = diffusion(m1, l11, l12);

        // reconstruct signal
        for (int i = 0; i < n; ++i, ++s) {
            vec_t u_ = make_vec(u[3*i], u[3*i+1], u[3*i+2]);
            *s = exp(-b*dot(u_,D*u_));
        }

        // prepare for next
        X += 5;
    }
    """

    fn = et.ext_function('c_model_1tensor_h', code,
                         ['s', 'X', 'u', 'b', 'n', 'm'])
    mod.add_function(fn)
예제 #47
0
def add_interp3scalar(mod):
    M = np.empty((100, 100, 100), dtype='uint16', order='F')
    p = np.empty(3)
    v = np.empty(3)
    sigma = 0.

    code = """
           #line 0 "interp3scalar"
           double s = 0, w_sum = 1e-16;
           double px = p[0], py = p[1], pz = p[2];
           double vx = v[0], vy = v[1], vz = v[2];

           for (int zz = -1; zz <= 1; zz++) {
               int z = round(pz) + zz;
               if (z < 0 || nz <= z) continue;
               double dz = (z - pz)*vz, dzz = dz*dz;

               for (int yy = -1; yy <= 1; yy++) {
                   int y = round(py) + yy;
                   if (y < 0 || ny <= y) continue;
                   double dy = (y - py)*vy, dyy = dy*dy;

                   for (int xx = -1; xx <= 1; xx++) {
                       int x = round(px) + xx;
                       if (x < 0 || nx <= x) continue;
                       double dx = (x - px)*vx, dxx = dx*dx;

                       float w = exp( -(dxx + dyy + dzz)/sigma );
                       float d = M[nz*ny*x + nz*y + z];
                       s     += w * d;
                       w_sum += w;
                   }
               }
           }
           return_val = s / w_sum;
           """
    nx, ny, nz = M.shape

    fn = et.ext_function('c_interp3scalar', code,
                         ['M', 'p', 'v', 'sigma', 'nx', 'ny', 'nz'])
    mod.add_function(fn)
예제 #48
0
def add_interp3scalar(mod):
    M = np.empty((100,100,100), dtype='uint16', order='F')
    p = np.empty(3)
    v = np.empty(3)
    sigma = 0.

    code = """
           #line 0 "interp3scalar"
           double s = 0, w_sum = 1e-16;
           double px = p[0], py = p[1], pz = p[2];
           double vx = v[0], vy = v[1], vz = v[2];

           for (int zz = -1; zz <= 1; zz++) {
               int z = round(pz) + zz;
               if (z < 0 || nz <= z) continue;
               double dz = (z - pz)*vz, dzz = dz*dz;

               for (int yy = -1; yy <= 1; yy++) {
                   int y = round(py) + yy;
                   if (y < 0 || ny <= y) continue;
                   double dy = (y - py)*vy, dyy = dy*dy;

                   for (int xx = -1; xx <= 1; xx++) {
                       int x = round(px) + xx;
                       if (x < 0 || nx <= x) continue;
                       double dx = (x - px)*vx, dxx = dx*dx;

                       float w = exp( -(dxx + dyy + dzz)/sigma );
                       float d = M[nz*ny*x + nz*y + z];
                       s     += w * d;
                       w_sum += w;
                   }
               }
           }
           return_val = s / w_sum;
           """
    nx,ny,nz = M.shape

    fn = et.ext_function('c_interp3scalar', code, ['M', 'p', 'v', 'sigma', 'nx','ny','nz'])
    mod.add_function(fn)
예제 #49
0
 def test_float_var_in(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1.
     code = "a=2.;"
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec 'from ' + mod_name + ' import test'
     b = 1.
     test(b)
     try:
         b = 1.
         test(b)
     except TypeError:
         pass
     try:
         b = 'abc'
         test(b)
     except TypeError:
         pass
예제 #50
0
 def test_var_in(self):
     mod_name = 'dict_var_in' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = {'z': 1}
     code = 'a=py::dict();'  # This just checks to make sure the type is correct
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = {'y': 2}
     test(b)
     try:
         b = 1.
         test(b)
     except TypeError:
         pass
     try:
         b = 'string'
         test(b)
     except TypeError:
         pass
예제 #51
0
 def test_var_in(self):
     mod_name = 'tuple_var_in' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = (1, )
     code = 'a=py::tuple();'
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = (1, 2)
     test(b)
     try:
         b = 1.
         test(b)
     except TypeError:
         pass
     try:
         b = 'string'
         test(b)
     except TypeError:
         pass
예제 #52
0
 def test_var_in(self):
     mod_name = 'int_var_in' + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1
     code = "a=2;"
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 1
     test(b)
     try:
         b = 1.
         test(b)
     except TypeError:
         pass
     try:
         b = 'abc'
         test(b)
     except TypeError:
         pass
예제 #53
0
 def test_complex_var_in(self):
     mod_name = sys._getframe().f_code.co_name + self.compiler
     mod_name = unique_mod(test_dir, mod_name)
     mod = ext_tools.ext_module(mod_name)
     a = 1. + 1j
     code = "a=std::complex<double>(2.,2.);"
     test = ext_tools.ext_function('test', code, ['a'])
     mod.add_function(test)
     mod.compile(location=test_dir, compiler=self.compiler)
     exec('from ' + mod_name + ' import test')
     b = 1. + 1j
     test(b)
     try:
         b = 1.
         test(b)
     except TypeError:
         pass
     try:
         b = 'abc'
         test(b)
     except TypeError:
         pass
예제 #54
0
    def test_var_in(self):
        mod_name = 'string_var_in' + self.compiler
        mod_name = unique_mod(test_dir, mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 'string'
        code = 'a=std::string("hello");'
        test = ext_tools.ext_function('test', code, ['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)

        exec('from ' + mod_name + ' import test')
        b = 'bub'
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 1
            test(b)
        except TypeError:
            pass
def buildBoundedThinPlateLibrary():
    from scipy.weave import ext_tools

    thinPlate2D_code = r"""
  #line 8 "_bounded_thinPlate.py"
  //void thinPlate2D_mat(double* C,double R, int cmin=0, int cmax=-1, int symm=0)

  if (cmax==-1)
    cmax=Nc[1];

  if (symm)
  {
    for(int j=cmin;j<cmax;j++)
    {
      C2(j,j)=1.;
      for(int i=0;i<j-1;i++)
      {
        C2(i,j)=thinPlate2D(C2(i,j),R);
      }
    }
  } else {
    for(int j=cmin;j<cmax;j++)
    {
      C2(j,j)=1.;
      for(int i=0;i<Nc[0];i++)
      {
        C2(i,j)=thinPlate2D(C2(i,j),R);
      }
    }
  }
  """

    thinPlate3D_code = thinPlate2D_code.replace('2D', '3D')

    thinPlate_support_code = r"""
  #line 39 "_bounded_thinPlate.py"
  double thinPlate2D(double d, double R)
  {
    double t;

    if (d == 0.0)
      t = 1.0;
    else {
      if (d < R){
        const double d2 = d*d;
        const double R2 = R*R;
        t = (2*d2*log(d)-(1+2*log(R))*d2+R2)/R2;
      }else{
        t = 0.0e0 ;
      }
    }

    return t;
  }

  double thinPlate3D(double d,double R)
  {
    double t;
      if (d == 0.) 
          t = 1.0e0;
      else {
          if (d < R) {
            const double d2 = d*d;
            const double d3 = fabs(d)*d2;
            const double R2 = R*R;
            const double R3 = fabs(R)*R2;
            t = (2*d3-3*R*d2+R3)/R3;
          }else{
            t = 0.0e0; 
          }
        }

        return t;

  }
  """

    innerProduct_thinPlate3D_normalized_code = r"""
  #line  83 "_bounded_thinPlate.py"
  //innerProduct_thinPlate3D_normalized(C,Q,R,symm)
        if (R < Q) {
          const double a = Q;
          Q = R;
          R = a;
        }

       double Rs[10];
       double Qs[10];
       Rs[0] = R;
       Qs[0] = Q;
       int i;
       for( i=0;i<9;i++ ){
         Rs[i+1] = Rs[i] * R;
         Qs[i+1] = Qs[i] * Q;
       }

        if (symm) {
          for (int j=0;j<Nc[1];i++)
          {
            int i;
            for (i=0; i<j; i++){
               C2(i,j) = covIntegralThinPlateR3Normalized( C2(i,j), Q, R, Qs, Rs);
               C2(j,i) = C2(i,j);
            }
          }
        }else{ 
          for(int j=0; j<Nc[1]; j++)
          {
            int i;
            for(i=0;i<Nc[0]; i++)
            {
               C2(i,j) = covIntegralThinPlateR3Normalized( C2(i,j), Q, R, Qs, Rs);
            }
          }
        }

  """

    innerProduct_thinPlate3D_normalized_support_code = r"""
  #line 115 "_bounded_thinPlate.py"
  double covIntTPR3NwLTRminusQ (double w, double Q, double R, const double* Qs, const double* Rs);
  double covIntTP3NRminusQLTw ( double w, double Q, double R, const double* Qs, const double* Rs);
  double covIntTP3NwGTR ( double w, double Q, double R, const double* Qs, const double* Rs);



  double covIntegralThinPlateR3Normalized( double w, double Q, double R, const double* Qs, const double* Rs)
  {
    double aux;

        if ( Q > R ) {
          aux = R;
          R = Q;
          Q = aux;
        }

        if ( w == 0 ) {
         return acos( -1.0e0 ) * double(Qs[3]) * double(84 * Rs[3] - 81 *R * Qs[2] + 35 * Qs[3]) / double(Rs[3]) / 0.315e3;
        }else if ( w <= (R-Q) ) {
          return covIntTPR3NwLTRminusQ(w,Q,R,Qs,Rs);
        }else if ( ( (R-Q) < w ) && ( w <= R) ) {
          return covIntTP3NRminusQLTw(w,Q,R,Qs,Rs);
        }else if ( w > R ) {
          return covIntTP3NwGTR(w,Q,R,Qs,Rs);
        }

        return 0;

  }

  double covIntTPR3NwLTRminusQ (double w, double Q, double R, const double* Qs, const double* Rs)
  {

          if ( w <= Q ) {
            return acos( -1.0e0 ) * double(-405 * Qs[8] * R - 1260 * Qs[6] * R * pow(w,2) + 420 * Qs[6] * Rs[3] + 15 * Q * pow(w,8) + 175 * Qs[9] + 900 * Qs[7] * pow(w,2) + 378* Qs[5] * pow(w,4) - 60 * Qs[3] * pow(w,6) - 4 * pow(w,9)) / double(Qs[3]) / double(Rs[3]) / 0.1575e4;
          }else{ 
            return acos( -1.0e0 ) * double(Qs[3]) * double(-135 * Qs[2] * w * R - 420 * pow(w,3) * R + 140 * w * Rs[3] + 180 * Qs[2] * pow(w,2) + 280 * pow(w,4) + 8 * Qs[4]) / double(w) / double(Rs[3]) / 0.525e3;
          }
  }

  double covIntTP3NRminusQLTw ( double w, double Q, double R, const double* Qs, const double* Rs)
  {
          if ( w <= Q ) { 
           return  -0.40e1 / 0.525e3 * M_PI *(pow(w,10) / 0.2e1 + (-0.5e1 / 0.8e1 * R - 0.5e1 / 0.8e1 * Q) * pow(w,9) - 0.135e3 / 0.64e2 * pow(w,8) * R * Q + (0.5e1 / 0.2e1 * Rs[3] + 0.5e1 / 0.2e1 * Qs[3]) * pow(w,7) + 0.105e3 / 0.16e2 * Q * R * (Rs[2] + Qs[2]) * pow(w,6) + (-0.63e2 / 0.4e1 * Qs[5] - 0.63e2 / 0.4e1 * Rs[5]) * pow(w,5) + (-0.945e3 / 0.32e2 * Q * Rs[5] - 0.175e3/ 0.16e2 * Qs[3] * Rs[3] - 0.945e3 / 0.32e2 * Qs[5] * R + 0.35e2 * Rs[6] + 0.35e2 * Qs[6]) * pow(w,4) + (0.105e3 / 0.2e1 * Rs[6] * Q - 0.75e2 / 0.2e1 * Rs[7] + 0.105e3 / 0.2e1 * Qs[6] * R - 0.75e2 / 0.2e1 * Qs[7]) * pow(w,3) + 0.45e2 / 0.2e1 * pow(( Q - R ),4)* (Qs[4] + 0.17e2 / 0.8e1 * Qs[3] * R + 0.5e1 / 0.2e1 * Qs[2] *Rs[2] + 0.17e2 / 0.8e1 * Q * Rs[3] + Rs[4]) * pow(w,2) + (0.135e3 / 0.8e1 * Rs[8] * Q - 0.175e3 / 0.24e2 * Qs[9] - 0.35e2 /0.2e1* Qs[6] * Rs[3] - 0.175e3 / 0.24e2 * Rs[9] - 0.35e2 / 0.2e1 *Rs[6] * Qs[3] + 0.135e3 / 0.8e1 * Qs[8] * R)*w + pow(( Q - R ),6) * (Qs[4] + 0.209e3 / 0.64e2 * Qs[3] * R + 0.147e3 / 0.32e2 * Qs[2] * Rs[2] + 0.209e3 / 0.64e2 * Q * Rs[3] + Rs[4])) / Qs[3] / w / Rs[3] ;

        }else{

        return  M_PI * (0.192e3 * pow(Q,10) - 0.192e3 * pow(R,10) - 0.32e2 * pow(w,10) + 0.8100e4 * pow(w,2) * Qs[7] * R - 0.10080e5 * pow(w,3) * Qs[6] * R + 0.8100e4 * Q * pow(w,2) * Rs[7] - 0.3780e4 * pow(w,2) * Qs[5] * Rs[3] + 0.3360e4 * Rs[6] * Qs[3] * w - 0.3240e4 * w * Qs[8] * R - 0.900e3 * Qs[7] * Rs[3] + 0.480e3 * pow(w,7) * Qs[3] + 0.405e3 * pow(w,8) * R * Q - 0.3780e4 * Qs[3] * pow(w,2) * Rs[5] - 0.1260e4 * pow(w,6) * Qs[3] * R + 0.5670e4 * Q * pow(w,4) * Rs[5] + 0.5670e4 * pow(w,4) * Qs[5] * R - 0.3240e4 * Rs[8] * Q * w + 0.3360e4 * w * Qs[6] * Rs[3] + 0.2100e4 * pow(w,4) * Qs[3] * Rs[3] - 0.1260e4 * pow(w,6) * Q * Rs[3] - 0.10080e5 * pow(w,3) * Rs[6] * Q + 0.525e3 * Qs[9] * R - 0.480e3 * pow(w,7) * Rs[3] + 0.120e3 * pow(w,9) * R - 0.120e3 * pow(w,9) * Q - 0.1400e4 * w * Qs[9] + 0.4320e4 * pow(w,2) * Qs[8] - 0.7200e4 * pow(w,3) * Qs[7] + 0.6720e4 * pow(w,4) * Qs[6] + 0.525e3 * Q * Rs[9] + 0.1134e4 * Qs[5] * Rs[5] - 0.900e3 * Qs[3] * Rs[7] + 0.7200e4 * pow(w,3) * Rs[7] + 0.1400e4 * w * Rs[9] - 0.6720e4 * pow(w,4) * Rs[6] + 0.3024e4 * pow(w,5) * Rs[5] - 0.4320e4 * pow(w,2) * Rs[8] - 0.3024e4 * pow(w,5) * Qs[5]) / Qs[3] / w / Rs[3] / 0.25200e5;
        }

  }

  double covIntTP3NwGTR ( double w, double Q, double R, const double* Qs, const double* Rs)
  {
          if ( w <= R+Q ) {
            return 0.4e1 / 0.525e3 * acos( -1.0e0 ) * pow((R + Q - w),6) * (pow(w,4) / 0.6e1 + (0.3e1 / 0.8e1 * Q + 0.3e1 / 0.8e1 * R) * pow(w,3) + (0.103e3 / 0.64e2 * Q * R - Qs[2] / 0.4e1 - Rs[2] / 0.4e1) * pow(w,2) - 0.31e2 / 0.24e2 * (Rs[2] - 0.247e3 / 0.124e3 * Q * R + Qs[2]) * (R + Q) * w + Rs[4] - 0.209e3 / 0.64e2 * Qs[3] * R + 0.147e3 / 0.32e2 * Qs[2] * Rs[2] + Qs[4] -0.209e3 / 0.64e2 * Q * Rs[3]) / Qs[3] / w / Rs[3];
          }else{
            return 0;
          }

  }
  """

    import numpy

    c = numpy.eye(5, dtype=float)
    R = 1.
    Q = 1.
    cmin = 1
    cmax = 1
    symm = 1

    thinPlateArguments = ['c', 'R', 'cmin', 'cmax', 'symm']

    innerProductArguments = ['c', 'R', 'Q', 'symm']

    mod = ext_tools.ext_module('_bounded_thinPlate_lib')
    mod.add_function(
        ext_tools.ext_function('thinPlate2D_mat', thinPlate2D_code,
                               thinPlateArguments))
    mod.add_function(
        ext_tools.ext_function('thinPlate3D_mat', thinPlate3D_code,
                               thinPlateArguments))
    mod.add_function(
        ext_tools.ext_function('innerProduct_thinPlate3D_normalized',
                               innerProduct_thinPlate3D_normalized_code,
                               innerProductArguments))

    mod.customize.add_support_code(thinPlate_support_code)
    mod.customize.add_support_code(
        innerProduct_thinPlate3D_normalized_support_code)
    #  mod.customize.add_extra_compile_arg('-O3')
    #  mod.customize.add_extra_link_arg('-O3')

    mod.compile()
예제 #56
0
파일: __init__.py 프로젝트: zhafree/Ibex
def compile_cpp_filters():
    """
    This method finds and compile every c++ filters
    If a c++ file changed, the file must be recompiled in a new .so file
    """

    BUILD_DIR = 'build'
    RELOAD_DIR = os.path.join('build', 'reload')
    if not os.path.exists(BUILD_DIR):
        os.mkdir(BUILD_DIR)
    if not os.path.exists(RELOAD_DIR):
        os.mkdir(RELOAD_DIR)
    if len(g.cppfiles) == 0:
        for f in os.listdir(RELOAD_DIR):
            os.remove(os.path.join(RELOAD_DIR, f))

    image = np.zeros((1,1), dtype=np.uint8)
    params = {}

    def ext_code():
        """
        Return the code that calls a c++ filter
        """
        return """
            cv::Mat mat(Nimage[0], Nimage[1], CV_8UC(3), image);
            cv::Mat ret = execute(mat);
            if (mat.data != ret.data) {
                ret.copyTo(mat);
            }

            """

    def init_code():
        """
        This method returns the code to initialize the parameters
        """
        return """
        params = p;
        py_init_param = pip;
        init();
        """

    def params_code():
        """
        Support code to declare parameters in the C++ filters
        It assumes a method py_init_param received as a parameter from
        the python side to create the parameters in the python object.
        """
        return """
            py::dict params;
            py::object py_init_param;
            void init_param(const char* name, int min, int max, int def_val) {
                    py::tuple args(4);
                    args[0] = name;
                    args[1] = min;
                    args[2] = max;
                    args[3] = def_val;
                    py_init_param.call(args);
            }
            long ParameterAsInt(const char* name, int min, int max, int def_val) {
                if(!params.has_key(name)) {
                    init_param(name, min, max, def_val);
                }
                py::object o = params.get(name);
                return PyInt_AsLong(o.mcall("get_current_value"));
            }

            bool ParameterAsBool(const char* name, int min, int max, int def_val) {
                if(!params.has_key(name)) {
                    init_param(name, min, max, def_val);
                }
                return PyInt_AsLong(params.get(name).mcall("get_current_value"));
            }
        """

    def help_code():
        """
        Return the code that returns the help string from a c++ file
        """
        return """
            #ifdef DOCSTRING
            return_val = DOCSTRING;
            #else
            return_val = "";
            #endif
            """

    def config_code():
        """
        Code to reconfigure the filter
        """
        return """
            configure();
        """

    def create_execute(cppfunc):
        """
        Create and return an "execute" method for the dynamically
        created class that wraps the c++ filters
        """
        def execute(self, image):
            cppfunc(image)
            return image
        return execute

    def create_configure(cppfunc):
        """
        """
        def configure(self):
            cppfunc()
        return configure

    def create_init(cppfunc, params):
        """
        """
        def __init__(self):
            self.params = {}
            cppfunc(self.params, self.py_init_param)
        return __init__

    def py_init_param(self, name, min, max, def_val):
        param = Parameter(name, min, max, def_val)
        self.params[name] = param
        setattr(self, name, param)

    dirname = os.path.dirname(__file__)
    for f in os.listdir(dirname):
        if not f.endswith(".cpp"):
            continue
        filename, _ = os.path.splitext(f)
        cppcode = open(os.path.join(dirname, f)).read()

        #Verify if there are changes in the c++ code file.  If there are
        #changes, add a timestamp to the filter .so file name to force a
        #reimportation of the new filter.
        if g.cppfiles.has_key(filename):
            if cppcode != g.cppfiles[filename]:
                g.cpptimestamps[filename] = str(int(time.time()))

        g.cppfiles[filename] = cppcode

        if g.cpptimestamps.has_key(filename):
            modname = filename + g.cpptimestamps[filename]
        else:
            modname = filename

        #Compile filters
        #The included files are found in the .cpp file
        mod = ext_tools.ext_module(modname)
        [mod.customize.add_header(line.replace('#include ', ''))
                                 for line in cppcode.split('\n')
                                 if line.startswith('#include')]
        mod.customize.add_header("<Python.h>")
        mod.customize.add_extra_link_arg("`pkg-config --cflags --libs opencv python`")
        mod.customize.add_extra_link_arg("-L/usr/local/cuda/lib64")

        func = ext_tools.ext_function('exec_' + filename, ext_code(),['image'])
        func.customize.add_support_code(params_code())
        func.customize.add_support_code(cppcode)
        mod.add_function(func)

        helpfunc = ext_tools.ext_function('help_' + filename, help_code(), [])
        mod.add_function(helpfunc)

        p = params
        pip = py_init_param
        initfunc = ext_tools.ext_function('init_' + filename, init_code(), ['p', 'pip'])
        initfunc.customize.add_support_code(params_code())
        #initfunc.customize.add_support_code(cppcode)
        mod.add_function(initfunc)

        configfunc = ext_tools.ext_function('config_' + filename, config_code(), [])
        configfunc.customize.add_support_code(params_code())
        configfunc.customize.add_support_code(cppcode)
        mod.add_function(configfunc)

        try:
            if g.cpptimestamps.has_key(filename):
            #Reloaded modules are saved in the reload folder for easy cleanup
                mod.compile(RELOAD_DIR)
            else:
                mod.compile(BUILD_DIR)

            cppmodule = __import__(modname)

            params = {}
            clazz = type(filename, (object,),
                 {'__init__' : create_init(
                                    getattr(cppmodule, 'init_' + filename), params),
                  'configure' : create_configure(
                                    getattr(cppmodule, 'config_' + filename)),
                  'execute' : create_execute(
                                    getattr(cppmodule, 'exec_' + filename)),
                  'py_init_param' : py_init_param,
                  '__doc__' : getattr(cppmodule, 'help_' + filename)()})

            setattr(sys.modules[__name__], filename, clazz)
            del clazz
        except Exception as e:
            sys.stderr.write(str(e) + '\n')
            sys.stderr.write(traceback.format_exc() + "\n")