How to use the pyccel.ast.core.Assign function in pyccel

To help you get started, we’ve selected a few pyccel examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyccel / pyccel / pyccel / parser / semantic.py View on Github external
target = self._visit(target, **settings)
        d_var = self._infere_type(target, **settings)

        dtype = d_var.pop('datatype')
        d_var['rank'] += 1
        shape = list(d_var['shape'])
        d_var['is_pointer'] = True
        shape.append(dim)
        d_var['shape'] = PythonTuple(*shape)

        lhs_name = _get_name(expr.lhs)

        lhs_empty = Empty(shape, dtype = dtype)
        lhs       = self._create_variable(lhs_name, dtype, lhs_empty, d_var)
        self.insert_variable(lhs)
        lhs_assign = Assign(lhs, lhs_empty)

        lhs = self.get_variable(lhs_name)

        if isinstance(target, PythonTuple) and not target.is_homogeneous:
            errors.report(LIST_OF_TUPLES, symbol=expr,
                bounding_box=(self._current_fst_node.lineno, self._current_fst_node.col_offset),
                severity='error', blocker=self.blocking)

        loops = [self._visit(i, **settings) for i in expr.loops]
        index = self._visit(index, **settings)

        return CodeBlock([lhs_assign, FunctionalFor(loops, lhs=lhs, indices=indices, index=index)])
github pyccel / pyccel / pyccel / parser / semantic.py View on Github external
def _visit_For(self, expr, **settings):


        self.create_new_loop_scope()

        # treatment of the index/indices
        iterable = self._visit(expr.iterable, **settings)
        body     = list(expr.body)
        iterator = expr.target

        if isinstance(iterable, Variable):
            indx   = self._get_new_variable(iterable)
            assign = Assign(iterator, IndexedBase(iterable)[indx])
            assign.set_fst(expr.fst)
            iterator = indx
            body     = [assign] + body

        elif isinstance(iterable, Map):
            indx   = self._get_new_variable(iterable)
            func   = iterable.args[0]
            args   = [IndexedBase(arg)[indx] for arg in iterable.args[1:]]
            assing = assign = Assign(iterator, func(*args))
            assign.set_fst(expr.fst)
            iterator = indx
            body     = [assign] + body

        elif isinstance(iterable, Zip):
            args = iterable.args
            indx = self._get_new_variable(args)
github pyccel / pyccel / pyccel / ast / parallel / mpi.py View on Github external
#        body        = mpify(stmt.body,        **options)
#        local_vars  = mpify(stmt.local_vars,  **options)
#        global_vars = mpify(stmt.global_vars, **options)
#
#        return FunctionDef(name, arguments, results, \
#                           body, local_vars, global_vars)

    if isinstance(stmt, ClassDef):
        name        = mpify(stmt.name,        **options)
        attributs   = mpify(stmt.attributs,   **options)
        methods     = mpify(stmt.methods,     **options)
        options     = mpify(stmt.options,     **options)

        return ClassDef(name, attributs, methods, options)

    if isinstance(stmt, Assign):
        if isinstance(stmt.rhs, Tensor):
            lhs = stmt.lhs
            options['label'] = lhs.name
            rhs = mpify(stmt.rhs, **options)

            return Assign(lhs, rhs, \
                          strict=stmt.strict, \
                          status=stmt.status, \
                          like=stmt.like)

    if isinstance(stmt, Del):
        variables = [mpify(a, **options) for a in stmt.variables]
        return Del(variables)

    if isinstance(stmt, Ones):
        if stmt.grid:
github pyccel / pyccel / pyccel / codegen / printing / codeprinter.py View on Github external
expr : Expression
            The expression to be printed.

        assign_to : Symbol, MatrixSymbol, or string (optional)
            If provided, the printed code will set the expression to a
            variable with name ``assign_to``.
        """

        if isinstance(assign_to, str):
            assign_to = Symbol(assign_to)
        elif not isinstance(assign_to, (Basic, type(None))):
            raise TypeError("{0} cannot assign to object of type {1}".format(
                    type(self).__name__, type(assign_to)))

        if assign_to:
            expr = Assign(assign_to, expr)
        else:
            expr = _sympify(expr)

        # Do the actual printing
        lines = self._print(expr).splitlines()

        # Format the output
        return "\n".join(self._format_code(lines))
github pyccel / pyccel / pyccel / ast / core.py View on Github external
if str(expr.func) in func_names:
                var = create_variable(expr)
                expr = expr.func(*args, evaluate=False)
                expr = Assign(var, expr)
                stmts.append(expr)

                return var
            else:
                expr = expr.func(*args, evaluate=False)
                return expr
        elif isinstance(expr, GC):
            stmts.append(expr)
            return expr.lhs
        elif isinstance(expr,IfTernaryOperator):
            var = create_variable(expr)
            new = Assign(var, expr)
            new.set_fst(expr.fst)
            stmts.append(new)
            return var
        elif isinstance(expr, List):
            args = []
            for i in expr:
                args.append(substitute(i))

            return List(*args, sympify=False)

        elif isinstance(expr, (Tuple, tuple, list)):
            args = []

            for i in expr:
                args.append(substitute(i))
            return args
github pyccel / pyccel / src_old / syntax_core.py View on Github external
n = len(func.expr)
            x_out   = Variable('double', 'x_out', rank=1, shape=n)
            results = [x_out]

            expressions = []
            for i in func.expr:
                expressions += [sympify(i).evalf()]
            expr = Tuple(*expressions)
        else:
            # TODO to treat other cases
            x_out   = Variable('double', 'x_out')
            results = [x_out]

            expr = sympify(func.expr).evalf()

        body = [Assign(x_out, expr)]

        # TODO local_vars must be updated inside FunctionDef
        #      this is needed for _print_FunctionDef
        F = FunctionDef(str(lhs), arguments, results, body, local_vars=arguments)
        namespace[str(lhs)] = F
        return F
    else:
        raise ValueError("Expecting a builtin function. given : ", name)
    # ...
github pyccel / pyccel / pyccel / functional / ast.py View on Github external
# ... list of all statements
        stmts = []
        # ...

        # ... use a multi index in the case of zip
        length      = generator.length
        multi_index = generator.multi_index
        generator.set_as_list()

        # TODO check formula
        value = index[0]
        for ix, nx in zip(index[1:], length[::-1][:-1]):
            value = nx*value + ix

        stmts += [Assign(multi_index, value)]

        # update index to use multi index
        index = multi_index
        # ...

        # ... we set the generator after we treat map/tmap
        self.set_generator(results, generator)
        # ...

        # ... apply the function to arguments
        if isinstance(iterator, Tuple):
            rhs = func( *iterator )

        else:
            rhs = func( iterator )
        # ...
github pyccel / pyccel / pyccel / symbolic / lambdify.py View on Github external
stmts[i] = pyccel_sum(stmts[i])
        if isinstance(vars_new[i], Indexed):
            ind = vars_new[i].indices
            tp = list(stmts[i + 1].atoms(Tuple))
            size = None
            size = [None] * len(ind)
            for (j, k) in enumerate(ind):
                for t in tp:
                    if k == t[0]:
                        size[j] = t[2] - t[1] + 1
                        break
            if not all(size):
                raise ValueError('Unable to find range of index')
            name = str(vars_new[i].base)
            var = Symbol(name)
            stmt = Assign(var, Function('empty')(size[0]))
            allocate.append(stmt)
            stmts[i] = For(ind[0], Function('range')(size[0]), [stmts[i]], strict=False)
    lhs = create_variable(expr)
    stmts[-1] = Assign(lhs, stmts[-1])
    imports = [Import('empty', 'numpy')]
    return imports + allocate + stmts
github pyccel / pyccel / pyccel / codegen / cwrapper.py View on Github external
results_decs = [Declare(i.dtype, i) for i in expr.results]
    results_decs = '\n    '.join(printer._print(i) for i in results_decs)
    code += '{0}\n    {1}\n    '.format(arg_decs, results_decs)

    code += "if (!PyArg_ParseTuple(args, \""
    code += ''.join(pytype_registry[str_dtype(arg.dtype)] for arg in expr.arguments)
    code += "\", "
    code += ', '.join("&" + printer._print(arg) for arg in expr.arguments)
    code += "))\n        return NULL;\n    "

    if len(expr.results)==0:
        func_call = UndefinedFunction(str(expr.name))(*expr.arguments)
    else:
        results = expr.results if len(expr.results)>1 else expr.results[0]
        func_call = Assign(results,UndefinedFunction(str(expr.name))(*expr.arguments))
    code += printer._print(func_call)
    code += '\n'

    results_dtypes = ''.join(pytype_registry[str_dtype(arg.dtype)] for arg in expr.results)
    result_names = ', '.join(res.name for res in expr.results)
    code += "    return Py_BuildValue(\"{0}\", {1});\n".format(results_dtypes,result_names)
    code += "}\n"
    return code
github pyccel / pyccel / pyccel / codegen / printing / fcode.py View on Github external
status = expr.status
        like   = expr.like

        if isinstance(op, AddOp):
            rhs = lhs + rhs
        elif isinstance(op, MulOp):
            rhs = lhs * rhs
        elif isinstance(op, SubOp):
            rhs = lhs - rhs
        # TODO fix bug with division of integers
        elif isinstance(op, DivOp):
            rhs = lhs / rhs
        else:
            raise ValueError('Unrecongnized operation', op)

        stmt = Assign(lhs, rhs, strict=strict, status=status, like=like)
        return self._print_Assign(stmt)