Beispiel #1
0
def test_dummy_loops_c():
    from sympy.tensor import IndexedBase, Idx
    # the following line could also be
    # [Dummy(s, integer=True) for s in 'im']
    # or [Dummy(integer=True) for s in 'im']
    i, m = symbols('i m', integer=True, cls=Dummy)
    x = IndexedBase('x')
    y = IndexedBase('y')
    i = Idx(i, m)
    expected = ('#include "file.h"\n'
                '#include <math.h>\n'
                'void test_dummies(int m_%(mno)i, double *x, double *y) {\n'
                '   for (int i_%(ino)i=0; i_%(ino)i<m_%(mno)i; i_%(ino)i++){\n'
                '      y[i_%(ino)i] = x[i_%(ino)i];\n'
                '   }\n'
                '}\n') % {
                    'ino': i.label.dummy_index,
                    'mno': m.dummy_index
                }
    r = Routine('test_dummies', Eq(y[i], x[i]))
    c = CCodeGen()
    code = get_string(c.dump_c, [r])
    assert code == expected
Beispiel #2
0
def test_ccode_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2 * x))
    assert ccode(g(x)) == "2*x"
    g = implemented_function('g', Lambda(x, 2 * x / Catalan))
    assert ccode(
        g(x)) == "double const Catalan = %s;\n2*x/Catalan" % Catalan.n()
    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x * (1 + x) * (2 + x)))
    assert ccode(g(A[i]),
                 assign_to=A[i]) == ("for (int i=0; i<n; i++){\n"
                                     "   A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
                                     "}")
Beispiel #3
0
def test_ccode_loops_add():
    from sympy.tensor import IndexedBase, Idx
    from sympy import symbols
    n, m = symbols('n m', integer=True)
    A = IndexedBase('A')
    x = IndexedBase('x')
    y = IndexedBase('y')
    z = IndexedBase('z')
    i = Idx('i', m)
    j = Idx('j', n)

    s = (
        'for (int i=0; i<m; i++){\n'
        '   y[i] = x[i] + z[i];\n'
        '}\n'
        'for (int i=0; i<m; i++){\n'
        '   for (int j=0; j<n; j++){\n'
        '      y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\
        '   }\n'
        '}'
    )
    c = ccode(A[i, j] * x[j] + x[i] + z[i], assign_to=y[i])
    assert c == s
Beispiel #4
0
def test_loops_multiple_contractions():
    n, m, o, p = symbols('n m o p', integer=True)
    a = IndexedBase('a')
    b = IndexedBase('b')
    y = IndexedBase('y')
    i = Idx('i', m)
    j = Idx('j', n)
    k = Idx('k', o)
    l = Idx('l', p)

    assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == (
        "for i in 0..m {\n"
        "    y[i] = 0;\n"
        "}\n"
        "for i in 0..m {\n"
        "    for j in 0..n {\n"
        "        for k in 0..o {\n"
        "            for l in 0..p {\n"
        "                y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
        "            }\n"
        "        }\n"
        "    }\n"
        "}")
Beispiel #5
0
def test_rcode_loops_add():
    from sympy.tensor import IndexedBase, Idx
    from sympy import symbols
    n, m = symbols('n m', integer=True)
    A = IndexedBase('A')
    x = IndexedBase('x')
    y = IndexedBase('y')
    z = IndexedBase('z')
    i = Idx('i', m)
    j = Idx('j', n)

    s = (
        'for (i in 1:m){\n'
        '   y[i] = x[i] + z[i];\n'
        '}\n'
        'for (i in 1:m){\n'
        '   for (j in 1:n){\n'
        '      y[i] = A[i, j]*x[j] + y[i];\n'
        '   }\n'
        '}'
    )
    c = rcode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
    assert c == s
Beispiel #6
0
def test_glsl_code_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2*x))
    assert glsl_code(g(x)) == "2*x"
    g = implemented_function('g', Lambda(x, 2*x/Catalan))
    assert glsl_code(g(x)) == "float Catalan = 0.915965594;\n2*x/Catalan"
    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
    assert glsl_code(g(A[i]), assign_to=A[i]) == (
        "for (int i=0; i<n; i++){\n"
        "   A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
        "}"
    )
Beispiel #7
0
def test_jscode_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2*x))
    assert jscode(g(x)) == "2*x"
    g = implemented_function('g', Lambda(x, 2*x/Catalan))
    assert jscode(g(x)) == "var Catalan = %s;\n2*x/Catalan" % Catalan.n()
    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
    assert jscode(g(A[i]), assign_to=A[i]) == (
        "for (var i=0; i<n; i++){\n"
        "   A[i] = A[i]*(1 + A[i])*(2 + A[i]);\n"
        "}"
    )
Beispiel #8
0
def test_loops():
    from sympy import symbols
    n, m = symbols('n m', integer=True)
    A = IndexedBase('A')
    x = IndexedBase('x')
    y = IndexedBase('y')
    i = Idx('i', m)
    j = Idx('j', n)

    expected = ('do i = 1, m\n'
                '   y(i) = 0\n'
                'end do\n'
                'do i = 1, m\n'
                '   do j = 1, n\n'
                '      y(i) = %(rhs)s\n'
                '   end do\n'
                'end do')
    code = fcode(A[i, j] * x[j], assign_to=y[i], source_format='free')
    assert (code == expected % {
        'rhs': 'A(i, j)*x(j) + y(i)'
    } or code == expected % {
        'rhs': 'x(j)*A(i, j) + y(i)'
    })
Beispiel #9
0
def test_jl_tensor_loops_multiple_contractions():
    # see comments in previous test about vectorizing
    from sympy.tensor import IndexedBase, Idx
    from sympy import symbols

    n, m, o, p = symbols("n m o p", integer=True)
    A = IndexedBase("A")
    B = IndexedBase("B")
    y = IndexedBase("y")
    i = Idx("i", m)
    j = Idx("j", n)
    k = Idx("k", o)
    l = Idx("l", p)
    (result, ) = codegen(
        ("tensorthing", Eq(y[i], B[j, k, l] * A[i, j, k, l])),
        "Julia",
        header=False,
        empty=False,
    )
    source = result[1]
    expected = ("function tensorthing(y, A, B, m, n, o, p)\n"
                "    for i = 1:m\n"
                "        y[i] = 0\n"
                "    end\n"
                "    for i = 1:m\n"
                "        for j = 1:n\n"
                "            for k = 1:o\n"
                "                for l = 1:p\n"
                "                    y[i] = A[i,j,k,l].*B[j,k,l] + y[i]\n"
                "                end\n"
                "            end\n"
                "        end\n"
                "    end\n"
                "    return y\n"
                "end\n")
    assert source == expected
Beispiel #10
0
def test_inline_function():
    x = symbols("x")
    g = implemented_function("g", Lambda(x, 2 * x))
    assert fcode(g(x)) == "      2*x"
    g = implemented_function("g", Lambda(x, 2 * pi / x))
    assert fcode(g(x)) == ("      parameter (pi = %sd0)\n"
                           "      2*pi/x") % pi.evalf(17)
    A = IndexedBase("A")
    i = Idx("i", symbols("n", integer=True))
    g = implemented_function("g", Lambda(x, x * (1 + x) * (2 + x)))
    assert fcode(
        g(A[i]),
        assign_to=A[i]) == ("      do i = 1, n\n"
                            "         A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n"
                            "      end do")
Beispiel #11
0
def test_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2 * x))
    assert fcode(g(x)) == "      2*x"
    g = implemented_function('g', Lambda(x, 2 * pi / x))
    assert fcode(g(x)) == ("      parameter (pi = 3.14159265358979d0)\n"
                           "      2*pi/x")
    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x * (1 + x) * (2 + x)))
    assert fcode(
        g(A[i]),
        assign_to=A[i]) == ("      do i = 1, n\n"
                            "         A(i) = (1 + A(i))*(2 + A(i))*A(i)\n"
                            "      end do")
Beispiel #12
0
def test_rcode_loops_multiple_contractions():
    n, m, o, p = symbols('n m o p', integer=True)
    a = IndexedBase('a')
    b = IndexedBase('b')
    y = IndexedBase('y')
    i = Idx('i', m)
    j = Idx('j', n)
    k = Idx('k', o)
    l = Idx('l', p)

    s = ('for (i in 1:m){\n'
         '   y[i] = 0;\n'
         '}\n'
         'for (i in 1:m){\n'
         '   for (j in 1:n){\n'
         '      for (k in 1:o){\n'
         '         for (l in 1:p){\n'
         '            y[i] = a[i, j, k, l]*b[j, k, l] + y[i];\n'
         '         }\n'
         '      }\n'
         '   }\n'
         '}')
    c = rcode(b[j, k, l] * a[i, j, k, l], assign_to=y[i])
    assert c == s
Beispiel #13
0
def test_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2*x))
    assert rust_code(g(x)) == "2*x"

    g = implemented_function('g', Lambda(x, 2*x/Catalan))
    assert rust_code(g(x)) == (
        "const Catalan: f64 = %s;\n2*x/Catalan" % Catalan.evalf(17))

    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
    assert rust_code(g(A[i]), assign_to=A[i]) == (
        "for i in 0..n {\n"
        "    A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
        "}")
Beispiel #14
0
def test_rcode_inline_function():
    x = symbols('x')
    g = implemented_function('g', Lambda(x, 2*x))
    assert rcode(g(x)) == "2*x"
    g = implemented_function('g', Lambda(x, 2*x/Catalan))
    assert rcode(
        g(x)) == "Catalan = %s;\n2*x/Catalan" % Catalan.n()
    A = IndexedBase('A')
    i = Idx('i', symbols('n', integer=True))
    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
    res=rcode(g(A[i]), assign_to=A[i])
    ref=(
        "for (i in 1:n){\n"
        "   A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
        "}"
    )
    assert res == ref
Beispiel #15
0
    def build_from_array(self, name="fromArray", separator=", "):
        if not self.uniform_member_type:
            raise TypeError(
                "To generate an array constructor, GlslStruct must have members of\
                uniform type"
            )

        template = Template(
            """\
$type_name $fn_name($base_type X[$size]){
    return $type_name($array_members);
}"""
        )

        x = IndexedBase("X")
        array_members = separator.join([str(x[i]) for i in range(len(self))])
        return template.substitute(
            fn_name=name,
            type_name=self.type_name,
            base_type=self.uniform_member_type,
            array_members=array_members,
            size=len(self),
        )
Beispiel #16
0
# represent the trapezoidal rule for integration

from sympy import Symbol, Sum, Function, Eq
from sympy.tensor import Indexed, Idx, IndexedBase
from sympy.utilities.iterables import preorder_traversal
from derivation_modeling.derivation import derivation, identity
from sum_util import peel_n

i = Symbol('i', integer=True)
n = Symbol('n', integer=True)

I = Symbol('I')
f = Function('f')
h = Symbol('h')
x = IndexedBase('x')

a = Symbol('a')
b = Symbol('b')

definition_of_h = Eq(h, (b - a) / n)

trap = derivation(I, Sum(h / 2 * (f(x[i]) + f(x[i + 1])), (i, 1, n)))
trap.set_name('trapezoidal_int')
trap.set_title('Trapezoidal Rule for Integration')


def split_sum(s):
    v = s.function.expand()
    sums = []
    for t in v.iter_basic_args():
        new_s = Sum(t, s.limits)
def __lattice_model(generation_context, class_name, lb_method,
                    stream_collide_ast, collide_ast, stream_ast,
                    refinement_scaling):
    stencil_name = get_stencil_name(lb_method.stencil)
    if not stencil_name:
        raise ValueError(
            "lb_method uses a stencil that is not supported in waLBerla")
    is_float = not generation_context.double_accuracy
    dtype = np.float32 if is_float else np.float64

    vel_symbols = lb_method.conserved_quantity_computation.first_order_moment_symbols
    rho_sym = sp.Symbol("rho")
    pdfs_sym = sp.symbols("f_:%d" % (len(lb_method.stencil), ))
    vel_arr_symbols = [
        IndexedBase(sp.Symbol('u'), shape=(1, ))[i]
        for i in range(len(vel_symbols))
    ]
    momentum_density_symbols = [
        sp.Symbol("md_%d" % (i, )) for i in range(len(vel_symbols))
    ]

    equilibrium = lb_method.get_equilibrium()
    equilibrium = equilibrium.new_with_substitutions(
        {a: b
         for a, b in zip(vel_symbols, vel_arr_symbols)})
    _, _, equilibrium = add_types(equilibrium.main_assignments,
                                  "float32" if is_float else "float64", False)
    equilibrium = sp.Matrix([e.rhs for e in equilibrium])

    symmetric_equilibrium = get_symmetric_part(equilibrium, vel_arr_symbols)
    asymmetric_equilibrium = sp.expand(equilibrium - symmetric_equilibrium)

    force_model = lb_method.force_model
    macroscopic_velocity_shift = None
    if force_model:
        if hasattr(force_model, 'macroscopic_velocity_shift'):
            macroscopic_velocity_shift = [
                expression_to_code(e, "lm.", ["rho"], dtype=dtype)
                for e in force_model.macroscopic_velocity_shift(rho_sym)
            ]

    cqc = lb_method.conserved_quantity_computation

    eq_input_from_input_eqs = cqc.equilibrium_input_equations_from_init_values(
        sp.Symbol("rho_in"), vel_arr_symbols)
    density_velocity_setter_macroscopic_values = equations_to_code(
        eq_input_from_input_eqs,
        dtype=dtype,
        variables_without_prefix=['rho_in', 'u'])
    momentum_density_getter = cqc.output_equations_from_pdfs(
        pdfs_sym, {
            'density': rho_sym,
            'momentum_density': momentum_density_symbols
        })
    constant_suffix = "f" if is_float else ""

    required_headers = get_headers(stream_collide_ast)

    if refinement_scaling:
        refinement_scaling_info = [
            (e0, e1, expression_to_code(e2, '', dtype=dtype))
            for e0, e1, e2 in refinement_scaling.scaling_info
        ]
    else:
        refinement_scaling_info = None

    jinja_context = {
        'class_name':
        class_name,
        'stencil_name':
        stencil_name,
        'D':
        lb_method.dim,
        'Q':
        len(lb_method.stencil),
        'compressible':
        lb_method.conserved_quantity_computation.compressible,
        'weights':
        ",".join(str(w.evalf()) + constant_suffix for w in lb_method.weights),
        'inverse_weights':
        ",".join(
            str((1 / w).evalf()) + constant_suffix for w in lb_method.weights),
        'equilibrium_from_direction':
        stencil_switch_statement(lb_method.stencil, equilibrium),
        'symmetric_equilibrium_from_direction':
        stencil_switch_statement(lb_method.stencil, symmetric_equilibrium),
        'asymmetric_equilibrium_from_direction':
        stencil_switch_statement(lb_method.stencil, asymmetric_equilibrium),
        'equilibrium': [cpp_printer.doprint(e) for e in equilibrium],
        'macroscopic_velocity_shift':
        macroscopic_velocity_shift,
        'density_getters':
        equations_to_code(cqc.output_equations_from_pdfs(
            pdfs_sym, {"density": rho_sym}),
                          variables_without_prefix=[e.name for e in pdfs_sym],
                          dtype=dtype),
        'momentum_density_getter':
        equations_to_code(momentum_density_getter,
                          variables_without_prefix=pdfs_sym,
                          dtype=dtype),
        'density_velocity_setter_macroscopic_values':
        density_velocity_setter_macroscopic_values,
        'refinement_scaling_info':
        refinement_scaling_info,
        'stream_collide_kernel':
        KernelInfo(stream_collide_ast, ['pdfs_tmp'], [('pdfs', 'pdfs_tmp')],
                   []),
        'collide_kernel':
        KernelInfo(collide_ast, [], [], []),
        'stream_kernel':
        KernelInfo(stream_ast, ['pdfs_tmp'], [('pdfs', 'pdfs_tmp')], []),
        'target':
        'cpu',
        'namespace':
        'lbm',
        'headers':
        required_headers,
        'need_block_offsets': [
            'block_offset_{}'.format(i) in [
                param.symbol.name
                for param in stream_collide_ast.get_parameters()
            ] for i in range(3)
        ],
    }

    env = Environment(loader=PackageLoader('lbmpy_walberla'),
                      undefined=StrictUndefined)
    add_pystencils_filters_to_jinja_env(env)

    header = env.get_template('LatticeModel.tmpl.h').render(**jinja_context)
    source = env.get_template('LatticeModel.tmpl.cpp').render(**jinja_context)

    generation_context.write_file("{}.h".format(class_name), header)
    generation_context.write_file("{}.cpp".format(class_name), source)
Beispiel #18
0
import matplotlib.pyplot as plt
import numpy as np
import numpy.polynomial.chebyshev as cheb
import sympy
from sympy import Product, Sum, DeferredVector, lambdify
from sympy.abc import a, j
from sympy.tensor import IndexedBase, Idx

N = 4
A = -3
B = 3
x = IndexedBase('x')
y = IndexedBase('y')

i = sympy.symbols('i', cls=Idx)

L = Sum(
    y[i] * Product((a - x[j]) / (x[i] - x[j]), (j, 0, i - 1)).doit() * Product(
        (a - x[j]) / (x[i] - x[j]), (j, i + 1, N)).doit(), (i, 0, N)).doit()
L_lambda = lambdify([a, DeferredVector('x'), DeferredVector('y')], L, 'numpy')

display_grid = np.linspace(A, B, 1000)
interpol_grid = np.linspace(A, B, N + 1)
che_interpol_grid = (cheb.chebroots((0, 0, 0, 0, 0, 1)) * (B - A) + A + B) / 2
plt.plot(display_grid,
         L_lambda(a=display_grid, x=interpol_grid, y=np.sin(interpol_grid)),
         color='red',
         label='Lagrange polynomial (equidistant nodes)')
plt.plot(display_grid,
         L_lambda(a=display_grid,
                  x=che_interpol_grid,
Beispiel #19
0
from sympy.codegen.ast import none
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.functions import acos, Piecewise, sign, sqrt
from sympy.logic import And, Or
from sympy.matrices import SparseMatrix, MatrixSymbol, Identity
from sympy.printing.pycode import (MpmathPrinter, NumPyPrinter,
                                   PythonCodePrinter, pycode, SciPyPrinter,
                                   SymPyPrinter)
from sympy.testing.pytest import raises
from sympy.tensor import IndexedBase

x, y, z = symbols('x y z')
p = IndexedBase("p")


def test_PythonCodePrinter():
    prntr = PythonCodePrinter()

    assert not prntr.module_imports

    assert prntr.doprint(x**y) == 'x**y'
    assert prntr.doprint(Mod(x, 2)) == 'x % 2'
    assert prntr.doprint(And(x, y)) == 'x and y'
    assert prntr.doprint(Or(x, y)) == 'x or y'
    assert not prntr.module_imports

    assert prntr.doprint(pi) == 'math.pi'
    assert prntr.module_imports == {'math': {'pi'}}
Beispiel #20
0
    vector = ensure_list_of_pairs(vector)

    # This is the lhs of the original tensor expression, which is used to determine
    # where the original indices were
    tensor = expr.lhs
    if not isinstance(tensor, Indexed):
        raise TypeError("Require an indexed expression on lhs.")

    # Expand sums, generate expressions
    exprs = expand_sums(expr, indices)
    exprs = enumerate_indices(exprs, indices)
    exprs = apply_rules(tensor, exprs, voigt, kinematic, vector)
    return exprs


A = IndexedBase("A")
B = IndexedBase("B")
C = IndexedBase("\mathbb{C}")
N = IndexedBase("N")
dNdX = IndexedBase("\\frac{dN}{dX}")
IoI = IndexedBase("I \otimes I")
II = IndexedBase("\mathbb{I}")
P = IndexedBase("\mathbb{P}")
dRdu = IndexedBase("dRdu")

strain = IndexedBase("varepsilon")

i = Idx("i", 2)
j = Idx("j", 2)
k = Idx("k", 2)
l = Idx("l", 2)