示例#1
0
        def transform_floating_literal(self, node):
            """Transformation function for floating literal

            Used to get the value and type of the given floating literal.

            Returns
            =======

            val : list
                List with two arguments type and Value
                type contains the type of float
                value contains the value stored in the variable

            Notes
            =====

            Only Base Float type supported for now

            """
            type = FloatBaseType(String('real'))
            try:
                value = next(node.get_tokens()).spelling
            except (StopIteration, ValueError):
                # No tokens
                value = Float(node.literal)
            val = [type, value]
            return val
示例#2
0
        def transform_integer_literal(self, node):
            """Transformation function for integer literal

            Used to get the value and type of the given integer literal.

            Returns
            =======

            val : list
                List with two arguments type and Value
                type contains the type of the integer
                value contains the value stored in the variable

            Notes
            =====

            Only Base Integer type supported for now

            """
            type = IntBaseType(String('integer'))
            try:
                value = next(node.get_tokens()).spelling
            except StopIteration:
                # No tokens
                value = Integer(node.literal)
            val = [type, value]
            return val
示例#3
0
def test_FunctionPrototype_and_FunctionDefinition():
    vx = Variable(x, type=real)
    vn = Variable(n, type=integer)
    fp1 = FunctionPrototype(real, 'power', [vx, vn])
    assert fp1.return_type == real
    assert fp1.name == String('power')
    assert fp1.parameters == Tuple(vx, vn)
    assert fp1 == FunctionPrototype(real, 'power', [vx, vn])
    assert fp1 != FunctionPrototype(real, 'power', [vn, vx])
    assert fp1.func(*fp1.args) == fp1


    body = [Assignment(x, x**n), Return(x)]
    fd1 = FunctionDefinition(real, 'power', [vx, vn], body)
    assert fd1.return_type == real
    assert str(fd1.name) == 'power'
    assert fd1.parameters == Tuple(vx, vn)
    assert fd1.body == CodeBlock(*body)
    assert fd1 == FunctionDefinition(real, 'power', [vx, vn], body)
    assert fd1 != FunctionDefinition(real, 'power', [vx, vn], body[::-1])
    assert fd1.func(*fd1.args) == fd1

    fp2 = FunctionPrototype.from_FunctionDefinition(fd1)
    assert fp2 == fp1

    fd2 = FunctionDefinition.from_FunctionPrototype(fp1, body)
    assert fd2 == fd1
示例#4
0
def bind_C(name=None):
    """ Creates an Attribute ``bind_C`` with a name

    Parameters
    ==========

    name : str

    Examples
    ========

    >>> from sympy import Symbol
    >>> from sympy.printing import fcode
    >>> from sympy.codegen.ast import FunctionDefinition, real, Return, Variable
    >>> from sympy.codegen.fnodes import array, sum_, size, bind_C
    >>> a = Symbol('a', real=True)
    >>> s = Symbol('s', integer=True)
    >>> arr = array(a, dim=[s], intent='in')
    >>> body = [Return((sum_(a**2)/s)**.5)]
    >>> fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
    >>> print(fcode(fd, source_format='free', standard=2003))
    real*8 function rms(a, s) bind(C, name="rms")
    real*8, dimension(s), intent(in) :: a
    integer*4 :: s
    rms = sqrt(sum(a**2)/s)
    end function
    """
    return Attribute('bind_C', [String(name)] if name else [])
def dimension(*args):
    """ Creates a 'dimension' Attribute with (up to 7) extents.

    Examples
    ========

    >>> from sympy.printing import fcode
    >>> from sympy.codegen.fnodes import dimension, intent_in
    >>> dim = dimension('2', ':')  # 2 rows, runtime determined number of columns
    >>> from sympy.codegen.ast import Variable, integer
    >>> arr = Variable('a', integer, attrs=[dim, intent_in])
    >>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
    'integer*4, dimension(2, :), intent(in) :: a'

    """
    if len(args) > 7:
        raise ValueError("Fortran only supports up to 7 dimensional arrays")
    parameters = []
    for arg in args:
        if isinstance(arg, Extent):
            parameters.append(arg)
        elif isinstance(arg, string_types):
            if arg == ':':
                parameters.append(Extent())
            else:
                parameters.append(String(arg))
        elif iterable(arg):
            parameters.append(Extent(*arg))
        else:
            parameters.append(sympify(arg))
    if len(args) == 0:
        raise ValueError("Need at least one dimension")
    return Attribute('dimension', parameters)
    def test_function():
        c_src1 = ('void fun1()' + '\n' + '{' + '\n' + 'int a;' + '\n' + '}')
        c_src2 = ('int fun2()' + '\n' + '{' + '\n' + 'int a;' + '\n' +
                  'return a;' + '\n' + '}')
        c_src3 = ('float fun3()' + '\n' + '{' + '\n' + 'float b;' + '\n' +
                  'return b;' + '\n' + '}')
        c_src4 = ('float fun4()' + '\n' + '{}')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()
        res4 = SymPyExpression(c_src4, 'c').return_expr()

        assert res1[0] == FunctionDefinition(
            NoneToken(),
            name=String('fun1'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0)))))

        assert res2[0] == FunctionDefinition(
            IntBaseType(String('integer')),
            name=String('fun2'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0))), Return('a')))

        assert res3[0] == FunctionDefinition(
            FloatBaseType(String('real')),
            name=String('fun3'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('b'),
                             type=FloatBaseType(String('real')),
                             value=Float('0.0', precision=53))), Return('b')))

        assert res4[0] == FunctionPrototype(FloatBaseType(String('real')),
                                            name=String('fun4'),
                                            parameters=())
示例#7
0
文件: test_ast.py 项目: Lenqth/sympy
def test_String():
    st = String('foobar')
    assert st.is_Atom
    assert st == String('foobar')
    assert st.text == 'foobar'
    assert st.func(**st.kwargs()) == st


    class Signifier(String):
        pass

    si = Signifier('foobar')
    assert si != st
    assert si.text == st.text
    s = String('foo')
    assert str(s) == 'foo'
    assert repr(s) == "String('foo')"
        def visit_Function(self, node):
            """Visitor Function for function Definitions

            Visits each function definition present in the ASR and creates a
            function definition node in the Python AST with all the elements of the
            given function

            The functions declare all the variables required as SymPy symbols in
            the function before the function definition

            This function also the call_visior_function to parse the contents of
            the function body

            """
            # TODO: Return statement, variable declaration
            fn_args = []
            fn_body = []
            fn_name = node.name
            for arg_iter in node.args:
                fn_args.append(Variable(arg_iter.name))
            for i in node.body:
                fn_ast = call_visitor(i)
            try:
                fn_body_expr = fn_ast
            except UnboundLocalError:
                fn_body_expr = []
            for sym in node.symtab.symbols:
                decl = call_visitor(node.symtab.symbols[sym])
                for symbols in decl:
                    fn_body.append(symbols)
            for elem in fn_body_expr:
                fn_body.append(elem)
            fn_body.append(Return(Variable(node.return_var.name)))
            if isinstance(node.return_var.type, asr.Integer):
                ret_type = IntBaseType(String('integer'))
            elif isinstance(node.return_var.type, asr.Real):
                ret_type = FloatBaseType(String('real'))
            else:
                raise NotImplementedError("Data type not supported")
            new_node = FunctionDefinition(return_type=ret_type,
                                          name=fn_name,
                                          parameters=fn_args,
                                          body=fn_body)
            self._py_ast.append(new_node)
示例#9
0
    def test_float():
        c_src1 = "float a = 1.0;"
        c_src2 = "float a = 1.25;" + "\n" + "float b = 2.39;" + "\n"
        c_src3 = "float x = 1, y = 2;"
        c_src4 = "float p = 5, e = 7.89;"

        res1 = SymPyExpression(c_src1, "c").return_expr()
        res2 = SymPyExpression(c_src2, "c").return_expr()
        res3 = SymPyExpression(c_src3, "c").return_expr()
        res4 = SymPyExpression(c_src4, "c").return_expr()

        assert res1[0] == Declaration(
            Variable(
                Symbol("a"),
                type=FloatBaseType(String("real")),
                value=Float("1.0", precision=53),
            ))

        assert res2[0] == Declaration(
            Variable(
                Symbol("a"),
                type=FloatBaseType(String("real")),
                value=Float("1.25", precision=53),
            ))

        assert res2[1] == Declaration(
            Variable(
                Symbol("b"),
                type=FloatBaseType(String("real")),
                value=Float("2.3900000000000001", precision=53),
            ))

        assert res3[0] == Declaration(
            Variable(
                Symbol("x"),
                type=FloatBaseType(String("real")),
                value=Float("1.0", precision=53),
            ))

        assert res3[1] == Declaration(
            Variable(
                Symbol("y"),
                type=FloatBaseType(String("real")),
                value=Float("2.0", precision=53),
            ))

        assert res4[0] == Declaration(
            Variable(
                Symbol("p"),
                type=FloatBaseType(String("real")),
                value=Float("5.0", precision=53),
            ))

        assert res4[1] == Declaration(
            Variable(
                Symbol("e"),
                type=FloatBaseType(String("real")),
                value=Float("7.89", precision=53),
            ))
示例#10
0
    def test_int():
        c_src1 = 'int a = 1;'
        c_src2 = ('int a = 1;' + '\n' + 'int b = 2;' + '\n')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))
示例#11
0
    def test_float():
        c_src1 = 'float a = 1.0;'
        c_src2 = ('float a = 1.25;' + '\n' + 'float b = 2.39;' + '\n')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.0', precision=53)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.25', precision=53)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=FloatBaseType(String('real')),
                     value=Float('2.3900000000000001', precision=53)))
示例#12
0
    def test_parse():
        c_src1 = "int a;" + "\n" + "int b;" + "\n"
        c_src2 = "void fun1()" + "\n" + "{" + "\n" + "int a;" + "\n" + "}"

        f1 = open("..a.h", "w")
        f2 = open("..b.h", "w")

        f1.write(c_src1)
        f2.write(c_src2)

        f1.close()
        f2.close()

        res1 = SymPyExpression("..a.h", "c").return_expr()
        res2 = SymPyExpression("..b.h", "c").return_expr()

        os.remove("..a.h")
        os.remove("..b.h")

        assert res1[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert res1[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert res2[0] == FunctionDefinition(
            NoneToken(),
            name=String("fun1"),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol("a"),
                        type=IntBaseType(String("integer")),
                        value=Integer(0),
                    ))),
        )
示例#13
0
 def test_function():
     src1 = """\
     integer function f(a,b)
     integer :: x, y
     f = x + y
     end function
     """
     expr1.convert_to_expr(src1, "f")
     for iter in expr1.return_expr():
         assert isinstance(iter, FunctionDefinition)
         assert iter == FunctionDefinition(
             IntBaseType(String("integer")),
             name=String("f"),
             parameters=(Variable(Symbol("a")), Variable(Symbol("b"))),
             body=CodeBlock(
                 Declaration(
                     Variable(
                         Symbol("a"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("b"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("f"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("x"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("y"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Assignment(Variable(Symbol("f")), Add(Symbol("x"), Symbol("y"))),
                 Return(Variable(Symbol("f"))),
             ),
         )
示例#14
0
def sizeof(arg):
    """ Generate of FunctionCall instance for calling 'sizeof'

    Examples
    ========

    >>> from sympy.codegen.ast import real
    >>> from sympy.codegen.cnodes import sizeof
    >>> from sympy.printing.ccode import ccode
    >>> ccode(sizeof(real))
    'sizeof(double)'
    """
    return FunctionCall('sizeof', [String(arg) if isinstance(arg, string_types) else arg])
示例#15
0
def test_goto_Label():
    s = 'early_exit'
    g = goto(s)
    assert g.func(*g.args) == g
    assert g != goto('foobar')
    assert ccode(g) == 'goto early_exit'

    l1 = Label(s)
    assert ccode(l1) == 'early_exit:'
    assert l1 == Label('early_exit')
    assert l1 != Label('foobar')

    body = [PreIncrement(x)]
    l2 = Label(s, body)
    assert l2.name == String("early_exit")
    assert l2.body == CodeBlock(PreIncrement(x))
    assert ccode(l2) == ("early_exit:\n" "++(x);")

    body = [PreIncrement(x), PreDecrement(y)]
    l2 = Label(s, body)
    assert l2.name == String("early_exit")
    assert l2.body == CodeBlock(PreIncrement(x), PreDecrement(y))
    assert ccode(l2) == ("early_exit:\n" "{\n   ++(x);\n   --(y);\n}")
示例#16
0
    def test_c_parse():
        src1 = """\
        int a, b = 4;
        float c, d = 2.4;
        """
        expr1.convert_to_expr(src1, 'c')
        ls = expr1.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert ls[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(4)))
        assert ls[2] == Declaration(
            Variable(Symbol('c'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
        assert ls[3] == Declaration(
            Variable(Symbol('d'),
                     type=FloatBaseType(String('real')),
                     value=Float('2.3999999999999999', precision=53)))
示例#17
0
    def test_parse():
        c_src1 = ('int a;' + '\n' + 'int b;' + '\n')
        c_src2 = ('void fun1()' + '\n' + '{' + '\n' + 'int a;' + '\n' + '}')

        f1 = open('..a.h', 'w')
        f2 = open('..b.h', 'w')

        f1.write(c_src1)
        f2.write(c_src2)

        f1.close()
        f2.close()

        res1 = SymPyExpression('..a.h', 'c').return_expr()
        res2 = SymPyExpression('..b.h', 'c').return_expr()

        os.remove('..a.h')
        os.remove('..b.h')

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert res1[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert res2[0] == FunctionDefinition(
            NoneToken(),
            name=String('fun1'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0)))))
示例#18
0
def test_Type():
    t = Type('MyType')
    assert len(t.args) == 1
    assert t.name == String('MyType')
    assert str(t) == 'MyType'
    assert repr(t) == "Type(String('MyType'))"
    assert Type(t) == t
    assert t.func(*t.args) == t
    t1 = Type('t1')
    t2 = Type('t2')
    assert t1 != t2
    assert t1 == t1 and t2 == t2
    t1b = Type('t1')
    assert t1 == t1b
    assert t2 != t1b
示例#19
0
def test_sym_expr():
    src1 = (src + """\
        d = a + b -c
        """)
    expr3 = SymPyExpression(src, 'f')
    expr4 = SymPyExpression(src1, 'f')
    ls1 = expr3.return_expr()
    ls2 = expr4.return_expr()
    for i in range(0, 7):
        assert isinstance(ls1[i], Declaration)
        assert isinstance(ls2[i], Declaration)
    assert isinstance(ls2[8], Assignment)
    assert ls1[0] == Declaration(
        Variable(Symbol('a'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[1] == Declaration(
        Variable(Symbol('b'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[2] == Declaration(
        Variable(Symbol('c'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[3] == Declaration(
        Variable(Symbol('d'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[4] == Declaration(
        Variable(Symbol('p'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[5] == Declaration(
        Variable(Symbol('q'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[6] == Declaration(
        Variable(Symbol('r'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[7] == Declaration(
        Variable(Symbol('s'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls2[8] == Assignment(Variable(Symbol('d')),
                                Symbol('a') + Symbol('b') - Symbol('c'))
示例#20
0
    def test_fortran_parse():
        expr = SymPyExpression(src, "f")
        ls = expr.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[2] == Declaration(
            Variable(Symbol("c"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[3] == Declaration(
            Variable(Symbol("d"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[4] == Declaration(
            Variable(
                Symbol("p"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[5] == Declaration(
            Variable(
                Symbol("q"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[6] == Declaration(
            Variable(
                Symbol("r"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[7] == Declaration(
            Variable(
                Symbol("s"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
示例#21
0
 def test_sym_expr():
     src1 = (
         src
         + """\
         d = a + b -c
         """
     )
     expr3 = SymPyExpression(src, "f")
     expr4 = SymPyExpression(src1, "f")
     ls1 = expr3.return_expr()
     ls2 = expr4.return_expr()
     for i in range(0, 7):
         assert isinstance(ls1[i], Declaration)
         assert isinstance(ls2[i], Declaration)
     assert isinstance(ls2[8], Assignment)
     assert ls1[0] == Declaration(
         Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls1[1] == Declaration(
         Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls1[2] == Declaration(
         Variable(Symbol("c"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls1[3] == Declaration(
         Variable(Symbol("d"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls1[4] == Declaration(
         Variable(Symbol("p"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls1[5] == Declaration(
         Variable(Symbol("q"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls1[6] == Declaration(
         Variable(Symbol("r"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls1[7] == Declaration(
         Variable(Symbol("s"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls2[8] == Assignment(
         Variable(Symbol("d")), Symbol("a") + Symbol("b") - Symbol("c")
     )
示例#22
0
def test_String():
    st = String('foobar')
    assert st.is_Atom
    assert st == String('foobar')
    assert st.text == 'foobar'
    assert st.func(**st.kwargs()) == st
    assert st.func(*st.args) == st

    class Signifier(String):
        pass

    si = Signifier('foobar')
    assert si != st
    assert si.text == st.text
    s = String('foo')
    assert str(s) == 'foo'
    assert repr(s) == "String('foo')"
示例#23
0
    def test_int():
        c_src1 = "int a = 1;"
        c_src2 = "int a = 1;" + "\n" + "int b = 2;" + "\n"
        c_src3 = "int a = 2.345, b = 5.67;"
        c_src4 = "int p = 6, q = 23.45;"

        res1 = SymPyExpression(c_src1, "c").return_expr()
        res2 = SymPyExpression(c_src2, "c").return_expr()
        res3 = SymPyExpression(c_src3, "c").return_expr()
        res4 = SymPyExpression(c_src4, "c").return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(1)))

        assert res2[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(1)))

        assert res2[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(2)))

        assert res3[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(2)))

        assert res3[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(5)))

        assert res4[0] == Declaration(
            Variable(Symbol("p"),
                     type=IntBaseType(String("integer")),
                     value=Integer(6)))

        assert res4[1] == Declaration(
            Variable(Symbol("q"),
                     type=IntBaseType(String("integer")),
                     value=Integer(23)))
示例#24
0
    def test_int():
        c_src1 = 'int a = 1;'
        c_src2 = ('int a = 1;' + '\n' + 'int b = 2;' + '\n')
        c_src3 = 'int a = 2.345, b = 5.67;'
        c_src4 = 'int p = 6, q = 23.45;'

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()
        res4 = SymPyExpression(c_src4, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))

        assert res3[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))

        assert res3[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(5)))

        assert res4[0] == Declaration(
            Variable(Symbol('p'),
                     type=IntBaseType(String('integer')),
                     value=Integer(6)))

        assert res4[1] == Declaration(
            Variable(Symbol('q'),
                     type=IntBaseType(String('integer')),
                     value=Integer(23)))
示例#25
0
    def test_float():
        c_src1 = 'float a = 1.0;'
        c_src2 = ('float a = 1.25;' + '\n' + 'float b = 2.39;' + '\n')
        c_src3 = 'float x = 1, y = 2;'
        c_src4 = 'float p = 5, e = 7.89;'

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()
        res4 = SymPyExpression(c_src4, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.0', precision=53)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.25', precision=53)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=FloatBaseType(String('real')),
                     value=Float('2.3900000000000001', precision=53)))

        assert res3[0] == Declaration(
            Variable(Symbol('x'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.0', precision=53)))

        assert res3[1] == Declaration(
            Variable(Symbol('y'),
                     type=FloatBaseType(String('real')),
                     value=Float('2.0', precision=53)))

        assert res4[0] == Declaration(
            Variable(Symbol('p'),
                     type=FloatBaseType(String('real')),
                     value=Float('5.0', precision=53)))

        assert res4[1] == Declaration(
            Variable(Symbol('e'),
                     type=FloatBaseType(String('real')),
                     value=Float('7.89', precision=53)))
示例#26
0
def test_ast_replace():
    x = Variable('x', real)
    y = Variable('y', real)
    n = Variable('n', integer)

    pwer = FunctionDefinition(real, 'pwer', [x, n], [pow(x.symbol, n.symbol)])
    pname = pwer.name
    pcall = FunctionCall('pwer', [y, 3])

    tree1 = CodeBlock(pwer, pcall)
    assert str(tree1.args[0].name) == 'pwer'
    assert str(tree1.args[1].name) == 'pwer'
    for a, b in zip(tree1, [pwer, pcall]):
        assert a == b

    tree2 = tree1.replace(pname, String('power'))
    assert str(tree1.args[0].name) == 'pwer'
    assert str(tree1.args[1].name) == 'pwer'
    assert str(tree2.args[0].name) == 'power'
    assert str(tree2.args[1].name) == 'power'
示例#27
0
def test_var():
    expr1.convert_to_expr(src, 'f')
    ls = expr1.return_expr()
    for iter in expr1.return_expr():
        assert isinstance(iter, Declaration)
    assert ls[0] == Declaration(
        Variable(Symbol('a'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls[1] == Declaration(
        Variable(Symbol('b'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls[2] == Declaration(
        Variable(Symbol('c'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls[3] == Declaration(
        Variable(Symbol('d'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls[4] == Declaration(
        Variable(Symbol('p'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls[5] == Declaration(
        Variable(Symbol('q'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls[6] == Declaration(
        Variable(Symbol('r'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls[7] == Declaration(
        Variable(Symbol('s'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
示例#28
0
    def test_fortran_parse():
        expr = SymPyExpression(src, 'f')
        ls = expr.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert ls[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert ls[2] == Declaration(
            Variable(Symbol('c'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert ls[3] == Declaration(
            Variable(Symbol('d'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert ls[4] == Declaration(
            Variable(Symbol('p'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
        assert ls[5] == Declaration(
            Variable(Symbol('q'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
        assert ls[6] == Declaration(
            Variable(Symbol('r'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
        assert ls[7] == Declaration(
            Variable(Symbol('s'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
示例#29
0
    def test_variable():
        c_src1 = ('int a;' + '\n' + 'int b;' + '\n')
        c_src2 = ('float a;' + '\n' + 'float b;' + '\n')
        c_src3 = ('int a;' + '\n' + 'float b;' + '\n' + 'int c;')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
        assert res1[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))
        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))

        assert res3[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))

        assert res3[1] == Declaration(
            Variable(Symbol('b'),
                     type=FloatBaseType(String('real')),
                     value=Float('0.0', precision=53)))

        assert res3[2] == Declaration(
            Variable(Symbol('c'),
                     type=IntBaseType(String('integer')),
                     value=Integer(0)))
示例#30
0
 def gen_kernel_model(self, kernel_name, kernel_arg_type_name):
     member_types = {
         "int32": lambda x: (QuotedString("int"), QuotedString(x)),
         "uint32": lambda x:
         (QuotedString("unsigned int"), QuotedString(x)),
         "pint8": lambda x: (QuotedString("signed char *"), QuotedString(x))
     }
     kernel_args = self.kernel_args
     code_block = CodeBlock(
         FunctionCall("LibKernelTemplate",
                      (QuotedString(kernel_arg_type_name),
                       FunctionCall(
                           "CArgs",
                           tuple([Integer(len(kernel_args))] + [
                               FunctionCall(
                                   "TCArg", member_types[kernel_arg[1]]
                                   (kernel_arg[0]))
                               for kernel_arg in kernel_args
                           ])))),
         FunctionCall(
             "LibKernel",
             (QuotedString(kernel_name), String("CALL_PARALLEL"),
              Integer(0), QuotedString(kernel_arg_type_name), Integer(0))))
     return ccode(code_block, contract=False, type_mappings=TYPE_MAPPINGS)
示例#31
0
def _name(arg):
    if hasattr(arg, 'name'):
        return arg.name
    else:
        return String(arg)