Beispiel #1
0
 def test_simple_constructor(self):
     cg = CythonGenerator()
     cg.parse(BasicEq())
     expect = dedent("""
     cdef class BasicEq:
         cdef public list _hidden
         cdef public double c
         cdef public double rho
         def __init__(self, **kwargs):
             for key, value in kwargs.items():
                 setattr(self, key, value)
     """)
     self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #2
0
    def test_python_methods(self):
        cg = CythonGenerator(python_methods=True)
        cg.parse(EqWithMethod())
        expect = dedent("""
        cdef class EqWithMethod:
            cdef public list _hidden
            cdef public double c
            cdef public double rho
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline void func(self, long d_idx, double* d_x):
                cdef double tmp
                tmp = abs(self.rho*self.c)*sin(pi*self.c)
                d_x[d_idx] = d_x[d_idx]*tmp

            cpdef py_func(self, long d_idx, double[:] d_x):
                self.func(d_idx, &d_x[0])
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())

        cg.parse(EqWithReturn())
        expect = dedent("""
        cdef class EqWithReturn:
            cdef public list _hidden
            cdef public double c
            cdef public double rho
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline double func(self, long d_idx, double* d_x):
                return d_x[d_idx]

            cpdef double py_func(self, long d_idx, double[:] d_x):
                return self.func(d_idx, &d_x[0])
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())

        cg.parse(func_with_return)
        expect = dedent("""
        cdef inline double func_with_return(long d_idx, double* d_x, double x):
            x += 1
            return d_x[d_idx] + x

        cpdef double py_func_with_return(long d_idx, double[:] d_x, double x):
            return func_with_return(d_idx, &d_x[0], x)
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #3
0
    def get_stepper_code(self):
        classes = {}
        for dest, stepper in self.object.steppers.items():
            cls = stepper.__class__.__name__
            classes[cls] = stepper

        known_types = dict(self.acceleration_eval_helper.known_types)
        known_types.update(dict(t=0.0, dt=0.0))
        code_gen = CythonGenerator(known_types=known_types)

        wrappers = []
        for cls in sorted(classes.keys()):
            code_gen.parse(classes[cls])
            wrappers.append(code_gen.get_code())
        return '\n'.join(wrappers)
Beispiel #4
0
 def test_detect_type(self):
     cases = [
         (('d_something', None), 'double*'),
         (('s_something', None), 'double*'),
         (('d_idx', 0), 'long'),
         (('x', 1), 'long'),
         (('s', 'asdas'), 'str'),
         (('junk', 1.0), 'double'),
         (('y', [0.0, 1]), 'double*'),
         (('y', [0, 1, 0]), 'double*'),
         (('y', None), 'object'),
     ]
     cg = CythonGenerator()
     for args, expect in cases:
         msg = 'detect_type(*%r) != %r' % (args, expect)
         self.assertEqual(cg.detect_type(*args), expect, msg)
Beispiel #5
0
    def test_wrap_function(self):
        cg = CythonGenerator()
        cg.parse(func_with_return)
        expect = dedent("""
        cdef inline double func_with_return(long d_idx, double* d_x, double x):
            x += 1
            return d_x[d_idx] + x
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())

        cg.parse(simple_func)
        expect = dedent("""
        cdef inline void simple_func(long d_idx, double* d_x, double x):
            d_x[d_idx] += x
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #6
0
    def test_method_with_declare(self):
        cg = CythonGenerator()
        cg.parse(EqWithDeclare())
        expect = dedent("""
        cdef class EqWithDeclare:
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline void func(self, long d_idx, double* d_x):
                cdef float val
                val = d_x[d_idx]
                cdef unsigned int index
                index = d_idx
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #7
0
    def test_method_with_matrix(self):
        cg = CythonGenerator()
        cg.parse(EqWithMatrix())
        expect = dedent("""
        cdef class EqWithMatrix:
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline void func(self, long d_idx, double* d_x):
                cdef double mat[2][2]
                mat[0][0] = d_x[d_idx]
                cdef double vec[3]
                vec[0] = d_x[d_idx]
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #8
0
    def test_method_with_return(self):
        cg = CythonGenerator()
        cg.parse(EqWithReturn())
        expect = dedent("""
        cdef class EqWithReturn:
            cdef public list _hidden
            cdef public double c
            cdef public double rho
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline double func(self, long d_idx, double* d_x):
                return d_x[d_idx]
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
Beispiel #9
0
 def get_equation_wrappers(self, known_types={}):
     classes = defaultdict(lambda: 0)
     eqs = {}
     for equation in self.equations:
         cls = equation.__class__.__name__
         n = classes[cls]
         equation.var_name = '%s%d'%(camel_to_underscore(equation.name), n)
         classes[cls] += 1
         eqs[cls] = equation
     wrappers = []
     predefined = dict(get_predefined_types(self.pre_comp))
     predefined.update(known_types)
     code_gen = CythonGenerator(known_types=predefined)
     for cls in sorted(classes.keys()):
         code_gen.parse(eqs[cls])
         wrappers.append(code_gen.get_code())
     return '\n'.join(wrappers)
def get_code(obj):
    """This function looks at the object and gets any additional code to
    wrap from either the `_cython_code_` method or the `_get_helpers_` method.
    """
    result = []
    if hasattr(obj, '_cython_code_'):
        code = obj._cython_code_()
        doc = '# From %s' % obj.__class__.__name__
        result.extend([doc, code] if len(code) > 0 else [])
    if hasattr(obj, '_get_helpers_'):
        cg = CythonGenerator()
        doc = '# From %s' % obj.__class__.__name__
        result.append(doc)
        for helper in obj._get_helpers_():
            cg.parse(helper)
            result.append(cg.get_code())
    return result
Beispiel #11
0
    def test_simple_method(self):
        cg = CythonGenerator()
        cg.parse(EqWithMethod())
        expect = dedent("""
        cdef class EqWithMethod:
            cdef public list _hidden
            cdef public double c
            cdef public double rho
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline void func(self, long d_idx, double* d_x):
                cdef double tmp
                tmp = abs(self.rho*self.c)*sin(pi*self.c)
                d_x[d_idx] = d_x[d_idx]*tmp
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())
    def get_header(self):
        object = self.object
        headers = []
        headers.extend(get_code(object.kernel))

        # get headers from the Equations
        for equation in object.all_group.equations:
            headers.extend(get_code(equation))

        # Kernel wrappers.
        cg = CythonGenerator(known_types=self.known_types)
        cg.parse(object.kernel)
        headers.append(cg.get_code())

        # Equation wrappers.
        headers.append(object.all_group.get_equation_wrappers(
            self.known_types))

        return '\n'.join(headers)
Beispiel #13
0
    def test_method_with_known_types(self):
        cg = CythonGenerator(
            known_types={
                'WIJ': 0.0,
                'DWIJ': [0.0, 0.0, 0.0],
                'user': KnownType('ndarray'),
                'd_user': KnownType('long*'),
                's_user': KnownType('int*'),
            })
        cg.parse(EqWithKnownTypes())
        expect = dedent("""
        cdef class EqWithKnownTypes:
            def __init__(self, **kwargs):
                for key, value in kwargs.items():
                    setattr(self, key, value)

            cdef inline void some_func(self, long d_idx, double* d_p, double WIJ, double* DWIJ, ndarray user, long* d_user, int* s_user):
                d_p[d_idx] = WIJ*DWIJ[0]
        """)
        self.assert_code_equal(cg.get_code().strip(), expect.strip())