예제 #1
0
파일: codegen.py 프로젝트: pyccel/lampy
def new_variable(dtype, var, tag=None, prefix=None, kind=None):

    # ...
    if prefix is None:
        prefix = ''

    _prefix = '{}'.format(prefix)
    # ...

    # ...
    if dtype == 'int':
        if kind == 'len':
            _prefix = 'n{}'.format(_prefix)

        elif kind == 'multi':
            _prefix = 'im{}'.format(_prefix)

        else:
            _prefix = 'i{}'.format(_prefix)

    elif dtype == 'real':
        _prefix = 'r{}'.format(_prefix)

    else:
        raise NotImplementedError()
    # ...

    # ...
    if tag is None:
        tag = random_string(4)
    # ...

    pattern = '{prefix}{dim}_{tag}'
    _print = lambda d, t: pattern.format(prefix=_prefix, dim=d, tag=t)

    if isinstance(var, Variable):
        assert (var.rank > 0)

        if var.rank == 1:
            name = _print('', tag)
            return Variable(dtype, name)

        else:
            indices = []
            for d in range(0, var.rank):
                name = _print(d, tag)
                indices.append(Variable(dtype, name))

            return Tuple(*indices)

    elif isinstance(var, (list, tuple, Tuple)):
        ls = [
            new_variable(dtype, x, tag=tag, prefix=str(i), kind=kind)
            for i, x in enumerate(var)
        ]
        return Tuple(*ls)

    else:
        raise NotImplementedError('{} not available'.format(type(var)))
예제 #2
0
    def __new__( cls, t_domain, t_codomain ):
        assert(isinstance(t_domain, BasicTypeVariable))
        assert(isinstance(t_codomain, (TypeVariable, TypeTuple, TypeList)))

        obj = Basic.__new__(cls, t_domain, t_codomain)
        obj._tag = random_string( 4 )

        return obj
예제 #3
0
    def __new__( cls, func, target ):

        if not isinstance(target, (list, tuple, Tuple)):
            target = [target]

        target = Tuple(*target)

        obj = Basic.__new__(cls, func, target)
        obj._tag = random_string( 4 )

        return obj
예제 #4
0
    def __new__( cls, func, target ):

        assert(isinstance( func, FunctionSymbol ))
        assert(isinstance( target, Dict ))

        obj = Basic.__new__( cls, func, target )

        tag = random_string( 4 )
        obj._name = 'partial_{func}_{tag}'.format( func=func.name, tag=tag )
        obj._funcdef = None

        return obj
예제 #5
0
파일: codegen.py 프로젝트: pyccel/lampy
    def __new__(cls, *args):
        # ... create iterator and index variables
        iterable = args
        if len(args) == 1:
            iterable = args[0]

        tag = random_string(4)

        index = new_variable('int', iterable, tag=tag)
        iterator = new_variable('real', iterable, tag=tag)
        length = new_variable('int', iterable, tag=tag, kind='len')
        # ...

        return Basic.__new__(cls, iterable, index, iterator, length)
예제 #6
0
    def __new__( cls, var, rank=0 ):
        assert(isinstance(var, (Variable, TypeVariable)))

        dtype          = var.dtype
        rank           = var.rank + rank
        is_stack_array = var.is_stack_array
        order          = var.order
        precision      = var.precision
        shape          = var.shape

        obj = Basic.__new__( cls, dtype, rank, is_stack_array, order, precision, shape )
        obj._tag = random_string( 4 )

        return obj
예제 #7
0
파일: codegen.py 프로젝트: pyccel/lampy
    def __new__(cls, *args):
        # ... create iterator and index variables
        target = args
        if len(args) == 1:
            print(args)
            raise NotImplementedError('')

        tag = random_string(4)

        length = new_variable('int', target[0], tag=tag, kind='len')
        index = new_variable('int', target[0], tag=tag)
        iterator = new_variable('real', target, tag=tag)
        # ...

        return Basic.__new__(cls, args, index, iterator, length)
예제 #8
0
파일: codegen.py 프로젝트: pyccel/lampy
    def __new__(cls, *args):
        # ... create iterator and index variables
        target = args
        assert (len(args) > 1)

        tag = random_string(4)

        length = new_variable('int', target, tag=tag, kind='len')
        index = new_variable('int', target, tag=tag)
        iterator = new_variable('real', target, tag=tag)
        multi_index = new_variable('int', target[0], tag=tag, kind='multi')
        # ...

        obj = Basic.__new__(cls, args, index, iterator, length, multi_index)
        obj._is_list = False

        return obj
예제 #9
0
    def __new__( cls, var, rank=0 ):
        assert(isinstance(var, (tuple, list, Tuple)))

        for i in var:
            assert( isinstance(i, (Variable, TypeVariable)) )

        t_vars = []
        for i in var:
            t_var = TypeVariable( i, rank=rank )
            t_vars.append(t_var)

        t_vars = Tuple(*t_vars)

        obj = Basic.__new__(cls, t_vars)
        obj._tag = random_string( 4 )

        return obj
예제 #10
0
    def __new__( cls, var ):
        assert(isinstance(var, (TypeVariable, TypeTuple, TypeList)))

        obj = Basic.__new__(cls, var)
        obj._tag = random_string( 4 )

        # ...
        def _get_core_type(expr):
            if isinstance(expr, TypeList):
                return _get_core_type(expr.parent)

            else:
                return expr
        # ...

        obj._types = _get_core_type(var)

        return obj
예제 #11
0
    def __new__( cls, target ):

        obj = Basic.__new__(cls, target)
        obj._name = 'reduce_{}'.format( random_string( 4 ) )
        return obj
예제 #12
0
 def __new__( cls, *target ):
     target = Tuple(*target)
     obj = Basic.__new__(cls, target)
     obj._name = 'product_{}'.format( random_string( 4 ) )
     return obj
예제 #13
0
파일: codegen.py 프로젝트: pyccel/lampy
    def _visit_LampyLambda(self, stmt):
        func = stmt.func

        # ...
        args = [self._visit(i) for i in func.variables]
        # ...

        # ...
        body = self._visit(func.expr)
        body = MainBlock(body, accelerator=self.accelerator)
        body = [body]
        # ...

        #        # ... DEBUG
        #        body += [Import('omp_get_max_threads', 'pyccel.stdlib.internal.openmp')]
        #
        #        msg = lambda x: (String('> maximum available threads = '), x)
        #        x = Call('omp_get_max_threads', ())
        #        body += [Print(msg(x))]
        #        # ...

        # ...
        results = self._visit(self.main)
        if not isinstance(results, (list, tuple, Tuple)):
            results = [results]
        # ...

        # ... scalar results
        s_results = [r for r in results if r.rank == 0]
        # ...

        # ... vector/matrix results as inout arguments
        m_results = [r for r in results if not r in s_results]
        # ...

        # ... return a function def where
        #     we append m_results to the arguments as inout
        #     and we return all results.
        #     first, we initialize arguments_inout to False for all args
        inout = [False for i in args]
        inout += [True for i in m_results]

        args = args + m_results
        # ...

        # ...
        if len(s_results) == 1:
            body += [Return(s_results[0])]

        elif len(results) > 1:
            body += [Return(s_results)]
        # ...

        # ...
#        decorators = {'types':         build_types_decorator(args),
#                      'external_call': []}

        decorators = {'types': build_types_decorator(args), 'external': []}

        tag = random_string(6)
        name = 'lambda_{}'.format(tag)
        # ...

        return LambdaFunctionDef(name,
                                 args,
                                 s_results,
                                 body,
                                 arguments_inout=inout,
                                 decorators=decorators,
                                 generators=self.generators,
                                 m_results=m_results)
예제 #14
0
def to_sympy(stmt):

    if isinstance(stmt, NamedAbstraction):
        name = stmt.name
        expr = to_sympy(stmt.abstraction)
        return expr

    elif isinstance(stmt, Abstraction):
        args = [to_sympy(i) for i in stmt.args]
        expr = to_sympy(stmt.expr)

        func = Lambda(args, expr)
        # add a name for the lambda expression
        # TODO improve this by implementing a new class
        #      for Lambda in lampy
        setattr(func, 'name', 'lambda_{}'.format(random_string(4)))

        return func

    elif isinstance(stmt, Application):
        name = stmt.name
        first = to_sympy(stmt.args[0])

        if name in _internal_map_functors:
            if not isinstance(first, (Lambda, BasicMap)):
                func_name = str(stmt.args[0])
                func = FunctionSymbol(func_name)

            else:
                func = first

            arguments = stmt.args[1:]
            arguments = [to_sympy(i) for i in arguments]

            return _map_registery[name](func, arguments)

        elif name == 'reduce':
            if not (len(stmt.args) == 2):
                raise ValueError('Wrong number of arguments for reduce')

            op = stmt.args[0]
            if not op in _internal_reduction_operators:
                msg = "Only 'add' and 'mul' reduction operators are available"
                raise ValueError(msg)

            target = to_sympy(stmt.args[1])

            if op == 'add':
                return AddReduce(target)

            elif op == 'mul':
                return MulReduce(target)

        elif name == 'partial':
            if not isinstance(first, Lambda):
                func_name = str(stmt.args[0])
                func = FunctionSymbol(func_name)

            else:
                func = first

            arguments = stmt.args[1:]
            arguments = [to_sympy(i) for i in arguments]

            assert (all([isinstance(i, Tuple) for i in arguments]))

            # ...
            d = {}
            for i in arguments:
                key = i[0]
                value = i[1]

                d[key] = value

            arguments = Dict(d)
            # ...

            return PartialFunction(func, arguments)

        else:
            args = [to_sympy(i) for i in stmt.args]

            return Function(name)(*args)

    elif isinstance(stmt, (int, float)):
        return stmt

    elif isinstance(stmt, str):
        if stmt == '_':
            return _

        else:
            return sympify(stmt)

    elif isinstance(stmt, ValuedItem):
        key = to_sympy(stmt.name)
        value = to_sympy(stmt.value)
        return Tuple(key, value)

    else:
        raise TypeError('Not implemented for {}'.format(type(stmt)))
예제 #15
0
    def __init__(self, expr, **kwargs):
        assert (isinstance(expr, Lambda))

        self._expr = LampyLambda(expr)

        # ...
        self._d_types = {}
        self._d_domain_types = {
        }  # for each codomain we store its associated domain type
        self._d_expr = {}
        self._tag = random_string(8)

        # TODO to be removed later?
        self._d_functions = {}

        # to store current typed expr
        # this must not be a private variable,
        # in order to modify it on the fly
        self.main = self.expr
        self.main_type = None
        # ...

        # ... add types for arguments and results
        #     TODO use domain and codomain optional args for functions
        self._typed_functions = kwargs.pop('typed_functions', {})
        for f in self.typed_functions.values():
            type_domain = assign_type(f.arguments)
            type_codomain = assign_type(f.results)

            self._set_type(f, value=type_domain, domain=True)
            self._set_type(f, value=type_codomain, codomain=True)
            self._set_domain_type(type_domain, type_codomain)
            self._insert_function(f, type_domain, type_codomain)
        # ...

        # ... default Type
        prefix = kwargs.pop('prefix', 'd')  # doubles as default
        dtype = None
        precision = None
        if prefix == 'i':
            dtype = Int
            precision = 4

        elif prefix == 's':
            dtype = Real
            precision = 4

        elif prefix == 'd':
            dtype = Real
            precision = 8

        elif prefix == 'c':
            dtype = Complex
            precision = 8

        elif prefix == 'z':
            dtype = Complex
            precision = 16

        else:
            raise ValueError('Wrong prefix. Available: i, s, d, c, z')

        var = Variable(dtype, 'dummy_' + self.tag, precision=precision)
        self._default_type = TypeVariable(var)
        # ...

        # ... get all functions
        functions = list(expr.atoms(FunctionSymbol))

        for f in functions:
            if f.name in _elemental_math_functions:
                type_domain = self.default_type
                type_codomain = self.default_type

                self._set_type(f, value=type_domain, domain=True)
                self._set_type(f, value=type_codomain, codomain=True)
                self._set_domain_type(type_domain, type_codomain)
                self._insert_function(str(f), type_domain, type_codomain)

            elif not str(f) in list(_internal_applications) + list(
                    self.typed_functions.keys()):
                raise NotImplementedError('{} not available'.format(str(f)))