Beispiel #1
0
    def _call_printer(self, routine):
        code_lines = []
        for result in routine.result_variables:
            if isinstance(result, Result):
                assign_to = None
            elif isinstance(result, (OutputArgument, InOutArgument)):
                assign_to = result.result_var

            try:
                constants, not_c, c_expr = ccode(
                    result.expr, assign_to=assign_to, human=False)
            except AssignmentError:
                assign_to = result.result_var
                code_lines.append(
                    "%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
                constants, not_c, c_expr = ccode(
                    result.expr, assign_to=assign_to, human=False)

            for name, value in sorted(constants, key=str):
                code_lines.append("double const %s = %s;\n" % (name, value))
            if assign_to:
                code_lines.append("%s\n" % c_expr)
            else:
                code_lines.append("   return %s;\n" % c_expr)
        return code_lines
Beispiel #2
0
def render_and_write_code(
	expressions,
	helpers,
	folder,
	name,
	user_functions = {},
	chunk_size = 100):
	
	helperlines = (
		check_code( ccode( helper[1], helper[0], user_functions=user_functions ) ) + "\n"
		for helper in helpers
		)
	codelines = (
		check_code( ccode ( expression, user_functions=user_functions ) ) + ";\n"
		for expression in expressions
		)
	
	with \
		open( path.join(folder,name+".c"            ), "w" ) as mainfile, \
		open( path.join(folder,name+"_definitions.c"), "w" ) as deffile:
		if chunk_size < 1:
			for line in chain(helperlines, codelines):
				mainfile.write(line)
		else:
			write_in_chunks(helperlines, mainfile, deffile, name+"helpers", chunk_size)
			write_in_chunks(codelines  , mainfile, deffile, name+"code"   , chunk_size)
Beispiel #3
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'

    l = Label(s)
    assert l.is_Atom
    assert ccode(l) == 'early_exit:'
    assert g.label == l
    assert l == Label(s)
    assert l != Label('foobar')
Beispiel #4
0
def test_create_expand_pow_optimization():
    my_opt = create_expand_pow_optimization(4)
    x = Symbol('x')

    assert ccode(optimize(x**4, [my_opt])) == 'x*x*x*x'

    x5x4 = x**5 + x**4
    assert ccode(optimize(x5x4, [my_opt])) == 'pow(x, 5) + x*x*x*x'

    sin4x = sin(x)**4
    assert ccode(optimize(sin4x, [my_opt])) == 'pow(sin(x), 4)'

    assert ccode(optimize((x**(-4)), [my_opt])) == 'pow(x, -4)'
Beispiel #5
0
    def get_prototype(self, routine):
        """Returns a string for the function prototype for the given routine.

           If the routine has multiple result objects, an CodeGenError is
           raised.

           See: http://en.wikipedia.org/wiki/Function_prototype
        """
        if len(routine.results) > 1:
            raise CodeGenError("C only supports a single or no return value.")
        elif len(routine.results) == 1:
            ctype = routine.results[0].get_datatype('C')
        else:
            ctype = "void"

        type_args = []
        for arg in routine.arguments:
            name = ccode(arg.name)
            if arg.dimensions:
                type_args.append((arg.get_datatype('C'), "*%s" % name))
            elif isinstance(arg, ResultBase):
                type_args.append((arg.get_datatype('C'), "&%s" % name))
            else:
                type_args.append((arg.get_datatype('C'), name))
        arguments = ", ".join(["%s %s" % t for t in type_args])
        return "%s %s(%s)" % (ctype, routine.name, arguments)
Beispiel #6
0
    def dump_c(self, routines, f, prefix, header=True, empty=True):
        """Write the C code file.

           This file contains all the definitions of the routines in c code and
           refers to the header file.

           Arguments:
             routines  --  a list of Routine instances
             f  --  a file-like object to write the file to
             prefix  --  the filename prefix, used to refer to the proper header
                         file. Only the basename of the prefix is used.

           Optional arguments:
             header  --  When True, a header comment is included on top of each
                         source file. [DEFAULT=True]
             empty  --  When True, empty lines are included to structure the
                        source files. [DEFAULT=True]
        """
        if header:
            self._dump_header(f)
        if empty: print >> f
        print >> f, "#include \"%s.h\"" % os.path.basename(prefix)
        print >> f, "#include <math.h>"
        if empty: print >> f
        for routine in routines:
            # function definitions.
            prototype, result = self.get_prototype_result(routine)
            print >> f, "%s {" % prototype
            # return value
            if result is not None:
                print >> f, "  return %s;" % ccode(result.expr)
            # curly closing brackets
            print >> f, "}"
            if empty: print >> f
        if empty: print >> f
Beispiel #7
0
    def get_prototype(self, routine):
        """Returns a string for the function prototype of the routine.

        If the routine has multiple result objects, an CodeGenError is
        raised.

        See: http://en.wikipedia.org/wiki/Function_prototype

        """
        if len(routine.results) == 1:
            ctype = routine.results[0].get_datatype('C')
        else:
            ctype = "void"

        type_args = []
        for arg in routine.arguments:
            name = ccode(arg.name)
            # Hack to make all double-valued arguments into pointers
            if arg.dimensions or isinstance(
                    arg, ResultBase) or arg.get_datatype('C') == 'double':
                type_args.append((arg.get_datatype('C'), "*%s" % name))
            else:
                type_args.append((arg.get_datatype('C'), name))
        arguments = ", ".join(["%s %s" % t for t in type_args])
        return "%s %s(%s)" % (ctype, routine.name, arguments)
Beispiel #8
0
def test_newtons_method_function__ccode():
    x = sp.Symbol("x", real=True)
    expr = sp.cos(x) - x**3
    func = newtons_method_function(expr, x)

    if not cython:
        skip("cython not installed.")
    if not has_c():
        skip("No C compiler found.")

    compile_kw = dict(std="c99")
    with TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings(
            [
                (
                    "newton.c",
                    ("#include <math.h>\n"
                     "#include <stdio.h>\n") + ccode(func),
                ),
                (
                    "_newton.pyx",
                    ("#cython: language_level={}\n".format("3") +
                     "cdef extern double newton(double)\n"
                     "def py_newton(x):\n"
                     "    return newton(x)\n"),
                ),
            ],
            build_dir=folder,
            compile_kwargs=compile_kw,
        )
        assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
Beispiel #9
0
    def get_prototype(self, routine):
        """Returns a string for the function prototype for the given routine.

           If the routine has multiple result objects, an CodeGenError is
           raised.

           See: http://en.wikipedia.org/wiki/Function_prototype
        """
        if len(routine.results) > 1:
            raise CodeGenError("C only supports a single or no return value.")
        elif len(routine.results) == 1:
            ctype = routine.results[0].get_datatype('C')
        else:
            ctype = "void"

        type_args = []
        for arg in routine.arguments:
            name = ccode(arg.name)
            if arg.dimensions:
                type_args.append((arg.get_datatype('C'), "*%s" % name))
            elif isinstance(arg, ResultBase):
                type_args.append((arg.get_datatype('C'), "&%s" % name))
            else:
                type_args.append((arg.get_datatype('C'), name))
        arguments = ", ".join([ "%s %s" % t for t in type_args])
        return "%s %s(%s)" % (ctype, routine.name, arguments)
Beispiel #10
0
def test_sizeof():
    typename = 'unsigned int'
    sz = sizeof(typename)
    assert ccode(sz) == 'sizeof(%s)' % typename
    assert sz.func(*sz.args) == sz
    assert not sz.is_Atom
    assert all(atom == typename for atom in sz.atoms())
Beispiel #11
0
def test_newtons_method_function__ccode_parameters():
    args = x, A, k, p = sp.symbols("x A k p")
    expr = A * sp.cos(k * x) - p * x**3
    raises(ValueError, lambda: newtons_method_function(expr, x))
    use_wurlitzer = wurlitzer

    func = newtons_method_function(expr, x, args, debug=use_wurlitzer)

    if not has_c():
        skip("No C compiler found.")
    if not cython:
        skip("cython not installed.")

    compile_kw = dict(std="c99")
    with TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings(
            [
                (
                    "newton_par.c",
                    ("#include <math.h>\n"
                     "#include <stdio.h>\n") + ccode(func),
                ),
                (
                    "_newton_par.pyx",
                    ("#cython: language_level={}\n".format("3") +
                     "cdef extern double newton(double, double, double, double)\n"
                     "def py_newton(x, A=1, k=1, p=1):\n"
                     "    return newton(x, A, k, p)\n"),
                ),
            ],
            compile_kwargs=compile_kw,
            build_dir=folder,
        )

        if use_wurlitzer:
            with wurlitzer.pipes() as (out, err):
                result = mod.py_newton(0.5)
        else:
            result = mod.py_newton(0.5)

        assert abs(result - 0.865474033102) < 1e-12

        if not use_wurlitzer:
            skip(
                "C-level output only tested when package 'wurlitzer' is available."
            )

        out, err = out.read(), err.read()
        assert err == ""
        assert (out == """\
x=         0.5 d_x=     0.61214
x=      1.1121 d_x=    -0.20247
x=     0.90967 d_x=   -0.042409
x=     0.86726 d_x=  -0.0017867
x=     0.86548 d_x= -3.1022e-06
x=     0.86547 d_x= -9.3421e-12
x=     0.86547 d_x=  3.6902e-17
""")  # try to run tests with LC_ALL=C if this assertion fails
Beispiel #12
0
    def _call_printer(self, routine):
        code_lines = []

        # Compose a list of symbols to be dereferenced in the function
        # body. These are the arguments that were passed by a reference
        # pointer, excluding arrays.
        dereference = []
        for arg in routine.arguments:
            if isinstance(arg, ResultBase) and not arg.dimensions:
                dereference.append(arg.name)

        return_val = None
        for result in routine.result_variables:
            if isinstance(result, Result):
                assign_to = routine.name + "_result"
                t = result.get_datatype('c')
                code_lines.append("{0} {1};\n".format(t, str(assign_to)))
                return_val = assign_to
            else:
                assign_to = result.result_var

            try:
                constants, not_c, c_expr = ccode(result.expr,
                                                 human=False,
                                                 assign_to=assign_to,
                                                 dereference=dereference)
            except AssignmentError:
                assign_to = result.result_var
                code_lines.append("%s %s;\n" %
                                  (result.get_datatype('c'), str(assign_to)))
                constants, not_c, c_expr = ccode(result.expr,
                                                 human=False,
                                                 assign_to=assign_to,
                                                 dereference=dereference)

            for name, value in sorted(constants, key=str):
                code_lines.append("double const %s = %s;\n" % (name, value))
            code_lines.append("%s\n" % c_expr)

        if return_val:
            code_lines.append("   return %s;\n" % return_val)
        return code_lines
Beispiel #13
0
def _render_compile_import(funcdef, build_dir):
    code_str = render_as_source_file(funcdef, settings=dict(contract=False))
    declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
    return compile_link_import_strings([
        ('our_test_func.c', code_str),
        ('_our_test_func.pyx', ("cdef extern {declar}\n"
                                "def _{fname}({typ}[:] inp, {typ}[:] out):\n"
                                "    {fname}(inp.size, &inp[0], &out[0])").format(
                                    declar=declar, fname=funcdef.name, typ='double'
                                ))
    ], build_dir=build_dir)
def _render_compile_import(funcdef, build_dir):
    code_str = render_as_source_file(funcdef, settings=dict(contract=False))
    declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
    return compile_link_import_strings(
        [('our_test_func.c', code_str),
         ('_our_test_func.pyx',
          ("cdef extern {declar}\n"
           "def _{fname}({typ}[:] inp, {typ}[:] out):\n"
           "    {fname}(inp.size, &inp[0], &out[0])").format(
               declar=declar, fname=funcdef.name, typ='double'))],
        build_dir=build_dir)
Beispiel #15
0
def test_union():
    vx, vy = Variable(x, type=float64), Variable(y, type=int64)
    u = union("dualuse", [vx, vy])
    assert u.func(*u.args) == u
    assert u == union("dualuse", (vx, vy))
    assert str(u.name) == "dualuse"
    assert len(u.declarations) == 2
    assert all(isinstance(arg, Declaration) for arg in u.declarations)
    assert ccode(u) == ("union dualuse {\n"
                        "   double x;\n"
                        "   int64_t y;\n"
                        "}")
Beispiel #16
0
    def _call_printer(self, routine):
        code_lines = []
        for result in routine.result_variables:
            if isinstance(result, Result):
                assign_to = None
            elif isinstance(result, (OutputArgument, InOutArgument)):
                assign_to = result.result_var

            try:
                constants, not_c, c_expr = ccode(result.expr, assign_to=assign_to, human=False)
            except AssignmentError:
                assign_to = result.result_var
                code_lines.append("%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
                constants, not_c, c_expr = ccode(result.expr, assign_to=assign_to, human=False)

            for name, value in sorted(constants, key=str):
                code_lines.append("double const %s = %s;\n" % (name, value))
            if assign_to:
                code_lines.append("%s\n" % c_expr)
            else:
                code_lines.append("   return %s;\n" % c_expr)
        return code_lines
Beispiel #17
0
def test_union():
    vx, vy = Variable(x, type=float64), Variable(y, type=int64)
    u = union('dualuse', [vx, vy])
    assert u.func(*u.args) == u
    assert u == union('dualuse', (vx, vy))
    assert str(u.name) == 'dualuse'
    assert len(u.declarations) == 2
    assert all(isinstance(arg, Declaration) for arg in u.declarations)
    assert ccode(u) == (
        "union dualuse {\n"
        "   double x;\n"
        "   int64_t y;\n"
        "}")
Beispiel #18
0
def test_struct():
    vx, vy = Variable(x, type=float64), Variable(y, type=float64)
    s = struct("vec2", [vx, vy])
    assert s.func(*s.args) == s
    assert s == struct("vec2", (vx, vy))
    assert s != struct("vec2", (vy, vx))
    assert str(s.name) == "vec2"
    assert len(s.declarations) == 2
    assert all(isinstance(arg, Declaration) for arg in s.declarations)
    assert ccode(s) == ("struct vec2 {\n"
                        "   double x;\n"
                        "   double y;\n"
                        "}")
Beispiel #19
0
    def _call_printer(self, routine):
        code_lines = []

        # Compose a list of symbols to be dereferenced in the function
        # body. These are the arguments that were passed by a reference
        # pointer, excluding arrays.
        dereference = []
        for arg in routine.arguments:
            if isinstance(arg, ResultBase) and not arg.dimensions:
                dereference.append(arg.name)

        return_val = None
        for result in routine.result_variables:
            if isinstance(result, Result):
                assign_to = routine.name + "_result"
                t = result.get_datatype('c')
                code_lines.append("{0} {1};\n".format(t, str(assign_to)))
                return_val = assign_to
            else:
                assign_to = result.result_var

            try:
                constants, not_c, c_expr = ccode(result.expr, human=False,
                        assign_to=assign_to, dereference=dereference)
            except AssignmentError:
                assign_to = result.result_var
                code_lines.append(
                    "%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
                constants, not_c, c_expr = ccode(result.expr, human=False,
                        assign_to=assign_to, dereference=dereference)

            for name, value in sorted(constants, key=str):
                code_lines.append("double const %s = %s;\n" % (name, value))
            code_lines.append("%s\n" % c_expr)

        if return_val:
            code_lines.append("   return %s;\n" % return_val)
        return code_lines
Beispiel #20
0
def test_struct():
    vx, vy = Variable(x, type=float64), Variable(y, type=float64)
    s = struct('vec2', [vx, vy])
    assert s.func(*s.args) == s
    assert s == struct('vec2', (vx, vy))
    assert s != struct('vec2', (vy, vx))
    assert str(s.name) == 'vec2'
    assert len(s.declarations) == 2
    assert all(isinstance(arg, Declaration) for arg in s.declarations)
    assert ccode(s) == (
        "struct vec2 {\n"
        "   double x;\n"
        "   double y;\n"
        "}")
Beispiel #21
0
def test_create_expand_pow_optimization():
    cc = lambda x: ccode(optimize(x, [create_expand_pow_optimization(4)]))
    x = Symbol('x')
    assert cc(x**4) == 'x*x*x*x'
    assert cc(x**4 + x**2) == 'x*x + x*x*x*x'
    assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x'
    assert cc(sin(x)**4) == 'pow(sin(x), 4)'
    # gh issue 15335
    assert cc(x**(-4)) == '1.0/(x*x*x*x)'
    assert cc(x**(-5)) == 'pow(x, -5)'
    assert cc(-x**4) == '-x*x*x*x'
    assert cc(x**4 - x**2) == '-x*x + x*x*x*x'
    i = Symbol('i', integer=True)
    assert cc(x**i - x**2) == 'pow(x, i) - x*x'
Beispiel #22
0
def test_create_expand_pow_optimization():
    cc = lambda x: ccode(optimize(x, [create_expand_pow_optimization(4)]))
    x = Symbol("x")
    assert cc(x**4) == "x*x*x*x"
    assert cc(x**4 + x**2) == "x*x + x*x*x*x"
    assert cc(x**5 + x**4) == "pow(x, 5) + x*x*x*x"
    assert cc(sin(x)**4) == "pow(sin(x), 4)"
    # gh issue 15335
    assert cc(x**(-4)) == "1.0/(x*x*x*x)"
    assert cc(x**(-5)) == "pow(x, -5)"
    assert cc(-(x**4)) == "-x*x*x*x"
    assert cc(x**4 - x**2) == "-x*x + x*x*x*x"
    i = Symbol("i", integer=True)
    assert cc(x**i - x**2) == "pow(x, i) - x*x"
Beispiel #23
0
def _render_compile_import(funcdef, build_dir):
    code_str = render_as_source_file(funcdef, settings=dict(contract=False))
    declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
    return compile_link_import_strings(
        [
            ("our_test_func.c", code_str),
            (
                "_our_test_func.pyx",
                ("#cython: language_level={}\n".format("3") +
                 "cdef extern {declar}\n"
                 "def _{fname}({typ}[:] inp, {typ}[:] out):\n"
                 "    {fname}(inp.size, &inp[0], &out[0])").format(
                     declar=declar, fname=funcdef.name, typ="double"),
            ),
        ],
        build_dir=build_dir,
    )
Beispiel #24
0
def test_newtons_method_function__ccode_parameters():
    args = x, A, k, p = sp.symbols('x A k p')
    expr = A * sp.cos(k * x) - p * x**3
    raises(ValueError, lambda: newtons_method_function(expr, x))
    use_wurlitzer = wurlitzer

    func = newtons_method_function(expr, x, args, debug=use_wurlitzer)

    if not has_c():
        skip("No C compiler found.")
    if not cython:
        skip("cython not installed.")

    compile_kw = dict(std='c99')
    with tempfile.TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings(
            [('newton_par.c', ('#include <math.h>\n'
                               '#include <stdio.h>\n') + ccode(func)),
             ('_newton_par.pyx',
              ("#cython: language_level={}\n".format("3") +
               "cdef extern double newton(double, double, double, double)\n"
               "def py_newton(x, A=1, k=1, p=1):\n"
               "    return newton(x, A, k, p)\n"))],
            compile_kwargs=compile_kw,
            build_dir=folder)

        if use_wurlitzer:
            with wurlitzer.pipes() as (out, err):
                result = mod.py_newton(0.5)
        else:
            result = mod.py_newton(0.5)

        assert abs(result - 0.865474033102) < 1e-12

        if not use_wurlitzer:
            skip(
                "C-level output only tested when package 'wurlitzer' is available."
            )

        out, err = out.read(), err.read()
        assert err == ''
        assert out == """\
Beispiel #25
0
def test_newtons_method_function__ccode():
    x = sp.Symbol('x', real=True)
    expr = sp.cos(x) - x**3
    func = newtons_method_function(expr, x)

    if not cython:
        skip("cython not installed.")
    if not has_c():
        skip("No C compiler found.")

    compile_kw = dict(std='c99')
    with TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings([
            ('newton.c', ('#include <math.h>\n'
                          '#include <stdio.h>\n') + ccode(func)),
            ('_newton.pyx', ("cdef extern double newton(double)\n"
                             "def py_newton(x):\n"
                             "    return newton(x)\n"))
        ], build_dir=folder, compile_kwargs=compile_kw)
        assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
Beispiel #26
0
def test_newtons_method_function__ccode():
    x = sp.Symbol('x', real=True)
    expr = sp.cos(x) - x**3
    func = newtons_method_function(expr, x)

    if not cython:
        skip("cython not installed.")
    if not has_c():
        skip("No C compiler found.")

    compile_kw = dict(std='c99')
    with TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings(
            [('newton.c', ('#include <math.h>\n'
                           '#include <stdio.h>\n') + ccode(func)),
             ('_newton.pyx', ("cdef extern double newton(double)\n"
                              "def py_newton(x):\n"
                              "    return newton(x)\n"))],
            build_dir=folder,
            compile_kwargs=compile_kw)
        assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
Beispiel #27
0
    def print_cpp(self):
        # Print imports necessary.
        print("#include <cmath> \nusing namespace std;\n")

        # Generate code for input structures.
        moment_state_struct = "struct MomentState {\n"
        for m, _ in self._moment_state_dynamics.items():
            moment_state_struct += "double " + str(m) + ";\n"
        moment_state_struct += "};\n"
        print(moment_state_struct)

        disturbance_moment_struct = "struct DisturbanceMoments{\n"
        for dist_moment in self._disturbance_moments:
            disturbance_moment_struct += "double " + str(dist_moment) + ";\n"
        disturbance_moment_struct += "};\n"
        print(disturbance_moment_struct)

        controls_struct = "struct Controls{\n"
        for control_var in self._control_variables:
            controls_struct += "double " + str(control_var) + ";\n"
        controls_struct += "};\n"
        print(controls_struct)

        # Generate code for the function.
        print("void PropagateMoments(const MomentState *prev_moment_state, const DisturbanceMoments *disturbance_moments, const Controls *control_inputs, MomentState *moment_state){")

        print("// Aliases for the required inputs.")
        for m, dynamics in self._moment_state_dynamics.items():
            print("const double &" + str(m) + " = prev_moment_state->" + str(m) + ";")
        print("\n")
        for dist_moment in self._disturbance_moments:
            print("const double &" + str(dist_moment) + " = disturbance_moments->" + str(dist_moment) + ";")
        if self._control_variables:
            print("\n")
            for control_var in self._control_variables:
                print("const double &" + str(control_var) + " = control_inputs->" + str(control_var) + ";")
        print("\n// Dynamics updates.")
        for m, dynamics in self._moment_state_dynamics.items():
            print("moment_state->" + str(m) + " = " + str(ccode(dynamics)) + ";\n")
        print("return; \n }")
Beispiel #28
0
def test_newtons_method_function__ccode_parameters():
    args = x, A, k, p = sp.symbols('x A k p')
    expr = A*sp.cos(k*x) - p*x**3
    raises(ValueError, lambda: newtons_method_function(expr, x))
    use_wurlitzer = wurlitzer

    func = newtons_method_function(expr, x, args, debug=use_wurlitzer)

    if not has_c():
        skip("No C compiler found.")
    if not cython:
        skip("cython not installed.")

    compile_kw = dict(std='c99')
    with TemporaryDirectory() as folder:
        mod, info = compile_link_import_strings([
            ('newton_par.c', ('#include <math.h>\n'
                          '#include <stdio.h>\n') + ccode(func)),
            ('_newton_par.pyx', ("cdef extern double newton(double, double, double, double)\n"
                             "def py_newton(x, A=1, k=1, p=1):\n"
                             "    return newton(x, A, k, p)\n"))
        ], compile_kwargs=compile_kw, build_dir=folder)

        if use_wurlitzer:
            with wurlitzer.pipes() as (out, err):
                result = mod.py_newton(0.5)
        else:
            result = mod.py_newton(0.5)

        assert abs(result - 0.865474033102) < 1e-12

        if not use_wurlitzer:
            skip("C-level output only tested when package 'wurlitzer' is available.")

        out, err = out.read(), err.read()
        assert err == ''
        assert out == """\
Beispiel #29
0
    def get_prototype(self, routine):
        """Returns a string for the function prototype of the routine.

        If the routine has multiple result objects, an CodeGenError is
        raised.

        See: http://en.wikipedia.org/wiki/Function_prototype

        """
        if len(routine.results) == 1:
            ctype = routine.results[0].get_datatype('C')
        else:
            ctype = "void"

        type_args = []
        for arg in routine.arguments:
            name = ccode(arg.name)
            # Hack to make all double-valued arguments into pointers
            if arg.dimensions or isinstance(arg, ResultBase) or arg.get_datatype('C') == 'double':
                type_args.append((arg.get_datatype('C'), "*%s" % name))
            else:
                type_args.append((arg.get_datatype('C'), name))
        arguments = ", ".join([ "%s %s" % t for t in type_args])
        return "%s %s(%s)" % (ctype, routine.name, arguments)
 def print_in_c(expr, standard='C99'):
     return ccode(expr, standard=standard)
dudy=diff(u_an,y);
dudz=diff(u_an,z);


dvdx=diff(v_an,x);
dvdy=diff(v_an,y);
dvdz=diff(v_an,z);


dwdx=diff(w_an,x);
dwdy=diff(w_an,y);
dwdz=diff(w_an,z);


from sympy.printing.ccode import ccode, CCodePrinter
ccode(u_an)



from sympy.utilities.codegen import codegen,Routine
codegen((
	
	("u_an", u_an),
	("v_an", v_an),
	("w_an", w_an),
	("du_dx",dudx),
	("du_dy",dudy),
	("du_dz",dudz),
	("dv_dx",dvdx),
	("dv_dy",dvdy),
	("dv_dz",dvdz),
Beispiel #32
0
 def codelines():
     for expression in expressions:
         codeline = ccode(expression, user_functions=user_functions)
         yield check_code(codeline) + ";\n"
Bi = Symbol("Bi")
z1r = Symbol("z1r")
z1i = Symbol("z1i")
f1r = Symbol("f1r")
f1i = Symbol("f1i")

solution = solve([Br*( f1r*z1r - f1i*z1i - 1) + Bi*(f1i*z1r + f1r*z1i) + (f1r - z1r),
                  Bi*(-f1r*z1r + f1i*z1i - 1) + Br*(f1i*z1r + f1r*z1i) + (f1i - z1i)], [Br, Bi])

print solution[Br]
# (-fi**2*zr - fr**2*zr + fr*zi**2 + fr*zr**2 - fr + zr)/(fi**2*zi**2 + fi**2*zr**2 + fr**2*zi**2 + fr**2*zr**2 - 1)

print solution[Bi]
# (-fi**2*zi + fi*zi**2 + fi*zr**2 - fi - fr**2*zi + zi)/(fi**2*zi**2 + fi**2*zr**2 + fr**2*zi**2 + fr**2*zr**2 - 1)

print ccode(solution[Br])
# (-fi*fi*zr - fr*fr*zr + fr*zi*zi + fr*zr*zr - fr + zr)/(fi*fi*zi*zi + fi*fi*zr*zr + fr*fr*zi*zi + fr*fr*zr*zr - 1)

print ccode(solution[Bi])
# (-fi*fi*zi + fi*zi*zi + fi*zr*zr - fi - fr*fr*zi + zi)/(fi*fi*zi*zi + fi*fi*zr*zr + fr*fr*zi*zi + fr*fr*zr*zr - 1)

Br = Symbol("Br")
Bi = Symbol("Bi")
Rr = Symbol("Rr")
Ri = Symbol("Ri")
z1r = Symbol("z1r")
z1i = Symbol("z1i")
f1r = Symbol("f1r")
f1i = Symbol("f1i")
z2r = Symbol("z2r")
z2i = Symbol("z2i")
Beispiel #34
0
def test_CommaOperator():
    expr = CommaOperator(PreIncrement(x), 2*x)
    assert ccode(expr) == '(++(x), 2*x)'
    assert expr.func(*expr.args) == expr
Beispiel #35
0
def test_PreDecrement():
    p = PreDecrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == "--(x)"
Beispiel #36
0
def test_alignof():
    ax = alignof(x)
    assert ccode(ax) == "alignof(x)"
    assert ax.func(*ax.args) == ax
Beispiel #37
0
def test_print_Mul():
    x, y = symbols("x y")
    s = ccode(x ** (-3) * y ** (-2))
Beispiel #38
0
def test_PreIncrement():
    p = PreIncrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == '++(x)'
Beispiel #39
0
Br = Symbol("Br", "real")
Bi = Symbol("Bi", "real")
dBr = Symbol("dBr", "real")
dBi = Symbol("dBi", "real")
Pr = Symbol("Pr", "real")
Pi = Symbol("Pi", "real")
Fr = Symbol("Fr", "real")
Fi = Symbol("Fi", "real")
Rr = Symbol("Rr", "real")
Ri = Symbol("Ri", "real")

# print re(((Pr + I*Pi) + (Br + I*Bi)*pone) / ((Br - I*Bi)*(Pr + I*Pi) + pone)).simplify()

# numerator
print ccode(
    (((Pr + I * Pi) + (Br + I * Bi) * sqrt(Pr * Pr + Pi * Pi + 1)) *
     ((Br + I * Bi) * (Pr - I * Pi) + sqrt(Pr * Pr + Pi * Pi + 1))).expand())
# I*Bi*Bi*Pi*pone - Bi*Bi*Pr*pone + 2*Bi*Br*Pi*pone + 2*I*Bi*Br*Pr*pone + I*Bi*Pi*Pi + I*Bi*Pr*Pr + I*Bi*(Pi*Pi + Pr*Pr + 1) - I*Br*Br*Pi*pone + Br*Br*Pr*pone + Br*Pi*Pi + Br*Pr*Pr + Br*(Pi*Pi + Pr*Pr + 1) + I*Pi*pone + Pr*pone

# Real part: -Bi*Bi*Pr*pone + 2*Bi*Br*Pi*pone + Br*Br*Pr*pone + Br*Pi*Pi + Br*Pr*Pr + Br*(Pi*Pi + Pr*Pr + 1) + Pr*pone
# Imag part: I*Bi*Bi*Pi*pone + 2*I*Bi*Br*Pr*pone + I*Bi*Pi*Pi + I*Bi*Pr*Pr + I*Bi*(Pi*Pi + Pr*Pr + 1) - I*Br*Br*Pi*pone + I*Pi*pone

# denominator
print ccode(
    (((Br - I * Bi) * (Pr + I * Pi) + sqrt(Pr * Pr + Pi * Pi + 1)) *
     ((Br + I * Bi) * (Pr - I * Pi) + sqrt(Pr * Pr + Pi * Pi + 1))).expand())
# Bi*Bi*Pi*Pi + Bi*Bi*Pr*Pr + 2*Bi*Pi*pone + Br*Br*Pi*Pi + Br*Br*Pr*Pr + 2*Br*Pr*pone + Pi*Pi + Pr*Pr + 1

### START EXTENDING B TO THE WHOLE PLANE

# numerator
Beispiel #40
0
 def _call_printer(self, routine):
     prototype, result = self.get_prototype_result(routine)
     if result is not None:
         return ["  return %s;\n" % ccode(result.expr)]
     else:
         return []
Beispiel #41
0
def test_PreDecrement():
    p = PreDecrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == '--(x)'
Beispiel #42
0
def test_alignof():
    ax = alignof(x)
    assert ccode(ax) == 'alignof(x)'
    assert ax.func(*ax.args) == ax
Beispiel #43
0
def test_PostDecrement():
    p = PostDecrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == '(x)--'
Beispiel #44
0
def test_PostIncrement():
    p = PostIncrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == "(x)++"
Beispiel #45
0
toHalfPlane = (toDisk + I)/(I*toDisk + 1)

twiceImag = toHalfPlane - toHalfPlane.conjugate()

highPoint = toHalfPlane + twiceImag/2
# highPoint = toHalfPlane + I

backToDisk = (-highPoint + I)/(I*highPoint - 1)

# backToScreen = R.conjugate()*(backToDisk - B)/(-B.conjugate()*backToDisk + 1)
backToScreen = (backToDisk - B)/(-B.conjugate()*backToDisk + 1)

tmp = backToScreen.simplify()

print ccode(tmp)
# (-B + (-2*(B*R + I)/(I*B*R + 1) + (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1) + I)/(I*(2*(B*R + I)/(I*B*R + 1) - (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1)) - 1))*conjugate(R)/(1 - (-2*(B*R + I)/(I*B*R + 1) + (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1) + I)*conjugate(B)/(I*(2*(B*R + I)/(I*B*R + 1) - (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1)) - 1))
# other sign: (B + (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))/(1 + (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))*conjugate(B)/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))
# just I: (B - (B + I)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)))/(-(B + I)*conjugate(B)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)) + 1)

# numer = (-B + (-2*(B*R + I)/(I*B*R + 1) + (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1) + I)/(I*(2*(B*R + I)/(I*B*R + 1) - (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1)) - 1))*conjugate(R)
# denom = (1 - (-2*(B*R + I)/(I*B*R + 1) + (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1) + I)*conjugate(B)/(I*(2*(B*R + I)/(I*B*R + 1) - (conjugate(B)*conjugate(R) - I)/(-I*conjugate(B)*conjugate(R) + 1)) - 1))
# numer = (-B + (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))
# denom = (1 - (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))*conjugate(B)/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))
# numer = (B + (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))
# denom = (1 + (-2*(B + I)/(I*B + 1) + I + (conjugate(B) - I)/(-I*conjugate(B) + 1))*conjugate(B)/(I*(2*(B + I)/(I*B + 1) - (conjugate(B) - I)/(-I*conjugate(B) + 1)) - 1))
# numer = (B - (B + I)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)))
# denom = (-(B + I)*conjugate(B)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)) + 1)
# numer = (-B - (B + I)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)))
# denom = ((B + I)*conjugate(B)/((I*B + 1)*(I*((B + I)/(I*B + 1) + I) - 1)) + 1)
numer = (-B + (-3*(B + I)/(2*(I*B + 1)) + I + (conjugate(B) - I)/(2*(-I*conjugate(B) + 1)))/(I*(3*(B + I)/(2*(I*B + 1)) - (conjugate(B) - I)/(2*(-I*conjugate(B) + 1))) - 1))
Beispiel #46
0
# Writing u_an,v_an, and w_an  and their gradients in a C file ------------------------------------------
dudx = diff(u_an, x)
dudy = diff(u_an, y)
dudz = diff(u_an, z)

dvdx = diff(v_an, x)
dvdy = diff(v_an, y)
dvdz = diff(v_an, z)

dwdx = diff(w_an, x)
dwdy = diff(w_an, y)
dwdz = diff(w_an, z)

from sympy.printing.ccode import ccode, CCodePrinter
ccode(u_an)

from sympy.utilities.codegen import codegen, Routine
codegen((
    ("u_an", u_an),
    ("v_an", v_an),
    ("w_an", w_an),
    ("du_dx", dudx),
    ("du_dy", dudy),
    ("du_dz", dudz),
    ("dv_dx", dvdx),
    ("dv_dy", dvdy),
    ("dv_dz", dvdz),
    ("dw_dx", dwdx),
    ("dw_dy", dwdy),
    ("dw_dz", dwdz),
Beispiel #47
0
def test_CommaOperator():
    expr = CommaOperator(PreIncrement(x), 2 * x)
    assert ccode(expr) == "(++(x), 2*x)"
    assert expr.func(*expr.args) == expr
Beispiel #48
0
					fout.write("<li>%s</li>\n" % _mathml(sol))
					# ccode(sol, assign_to='sol%d' % (i+1))
				fout.write("</ul>")
			
			fout.write("<p>Points in cartesian coordinates (x, y, z)</p>\n")
			fout.write("<ul>")
			for i, sol in enumerate(solutions):
				fout.write("<li><ul>")
				for k, v in ai:
					fout.write("<li>%s: %s</li>\n" % (k, _mathml(v.subs(t, sol))))
				fout.write("</ul></li>")
			fout.write("</ul>")
			fout.write("<h5>C Code</h5>\n")
			for i, sol in enumerate(solutions):
				for k, v in ai:
					fout.write("<pre>%s</pre>\n" % ccode(v.subs(t, sol), assign_to=k))
				
			if len(solutions) == 2:
				sola, solb = solutions
				# compute distance inside
				
				distance = _simplify(Abs(sola - solb))
				fout.write("<h4>Distance inside</h4>\n")
				fout.write("<p>Distance between crossing points.</p>\n")
				fout.write("%s\n" % _mathml(distance))
				fout.write("<h4>C Code</h4>\n")
				for i, sol in enumerate(solutions):
					fout.write("<pre>%s</pre>" % ccode(sol, assign_to='sol%d' % (i+1)))
				fout.write("<pre>%s</pre>" % ccode(distance, assign_to="distance"))

			if len(solutions) == 1:
Beispiel #49
0
def test_PreIncrement():
    p = PreIncrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == "++(x)"
solution = solve(
    [
        Br * (f1r * z1r - f1i * z1i - 1) + Bi * (f1i * z1r + f1r * z1i) + (f1r - z1r),
        Bi * (-f1r * z1r + f1i * z1i - 1) + Br * (f1i * z1r + f1r * z1i) + (f1i - z1i),
    ],
    [Br, Bi],
)

print solution[Br]
# (-fi**2*zr - fr**2*zr + fr*zi**2 + fr*zr**2 - fr + zr)/(fi**2*zi**2 + fi**2*zr**2 + fr**2*zi**2 + fr**2*zr**2 - 1)

print solution[Bi]
# (-fi**2*zi + fi*zi**2 + fi*zr**2 - fi - fr**2*zi + zi)/(fi**2*zi**2 + fi**2*zr**2 + fr**2*zi**2 + fr**2*zr**2 - 1)

print ccode(solution[Br])
# (-fi*fi*zr - fr*fr*zr + fr*zi*zi + fr*zr*zr - fr + zr)/(fi*fi*zi*zi + fi*fi*zr*zr + fr*fr*zi*zi + fr*fr*zr*zr - 1)

print ccode(solution[Bi])
# (-fi*fi*zi + fi*zi*zi + fi*zr*zr - fi - fr*fr*zi + zi)/(fi*fi*zi*zi + fi*fi*zr*zr + fr*fr*zi*zi + fr*fr*zr*zr - 1)

Br = Symbol("Br")
Bi = Symbol("Bi")
Rr = Symbol("Rr")
Ri = Symbol("Ri")
z1r = Symbol("z1r")
z1i = Symbol("z1i")
f1r = Symbol("f1r")
f1i = Symbol("f1i")
z2r = Symbol("z2r")
z2i = Symbol("z2i")
Beispiel #51
0
    def qasm(self, prec=15):
        """Return the corresponding OPENQASM string."""
        if self.value == pi:
            return "pi"

        return ccode(self.value, precision=prec)
Beispiel #52
0
def get_c_function(scalar, couplings):
    args_replace = dict(zip([str(el) for el in couplings],
                            ['args['+str(i)+']' for i in range(len(couplings))]))
    return multiple_replace(ccode(scalar), args_replace)
Beispiel #53
0
def render_declarations(expressions, filename):
	with open(filename, "w") as output:
		for expression in expressions:
			output.write("double " + ccode(expression) + ";\n")
pone = Symbol("pone", "real")   # it doesn't really belive that they're real...
Br = Symbol("Br", "real")
Bi = Symbol("Bi", "real")
dBr = Symbol("dBr", "real")
dBi = Symbol("dBi", "real")
Pr = Symbol("Pr", "real")
Pi = Symbol("Pi", "real")
Fr = Symbol("Fr", "real")
Fi = Symbol("Fi", "real")
Rr = Symbol("Rr", "real")
Ri = Symbol("Ri", "real")

# print re(((Pr + I*Pi) + (Br + I*Bi)*pone) / ((Br - I*Bi)*(Pr + I*Pi) + pone)).simplify()

# numerator
print ccode((((Pr + I*Pi) + (Br + I*Bi)*sqrt(Pr*Pr + Pi*Pi + 1)) * ((Br + I*Bi)*(Pr - I*Pi) + sqrt(Pr*Pr + Pi*Pi + 1))).expand())
# I*Bi*Bi*Pi*pone - Bi*Bi*Pr*pone + 2*Bi*Br*Pi*pone + 2*I*Bi*Br*Pr*pone + I*Bi*Pi*Pi + I*Bi*Pr*Pr + I*Bi*(Pi*Pi + Pr*Pr + 1) - I*Br*Br*Pi*pone + Br*Br*Pr*pone + Br*Pi*Pi + Br*Pr*Pr + Br*(Pi*Pi + Pr*Pr + 1) + I*Pi*pone + Pr*pone

# Real part: -Bi*Bi*Pr*pone + 2*Bi*Br*Pi*pone + Br*Br*Pr*pone + Br*Pi*Pi + Br*Pr*Pr + Br*(Pi*Pi + Pr*Pr + 1) + Pr*pone
# Imag part: I*Bi*Bi*Pi*pone + 2*I*Bi*Br*Pr*pone + I*Bi*Pi*Pi + I*Bi*Pr*Pr + I*Bi*(Pi*Pi + Pr*Pr + 1) - I*Br*Br*Pi*pone + I*Pi*pone

# denominator
print ccode((((Br - I*Bi)*(Pr + I*Pi) + sqrt(Pr*Pr + Pi*Pi + 1)) * ((Br + I*Bi)*(Pr - I*Pi) + sqrt(Pr*Pr + Pi*Pi + 1))).expand())
# Bi*Bi*Pi*Pi + Bi*Bi*Pr*Pr + 2*Bi*Pi*pone + Br*Br*Pi*Pi + Br*Br*Pr*Pr + 2*Br*Pr*pone + Pi*Pi + Pr*Pr + 1

### START EXTENDING B TO THE WHOLE PLANE

# numerator
print ccode(((sqrt(1 + Br*Br + Bi*Bi)*(Pr + I*Pi) + (Br + I*Bi)*sqrt(Pr*Pr + Pi*Pi + 1)) * ((Br + I*Bi)*(Pr - I*Pi) + sqrt(1 + Br*Br + Bi*Bi)*sqrt(Pr*Pr + Pi*Pi + 1))).expand())
# I*Bi*Bi*Pi*pone - Bi*Bi*Pr*pone + 2*Bi*Br*Pi*pone + 2*I*Bi*Br*Pr*pone + I*Bi*Pi*Pi*bone + I*Bi*Pr*Pr*bone + I*Bi*bone*(Pi*Pi + Pr*Pr + 1) - I*Br*Br*Pi*pone + Br*Br*Pr*pone + Br*Pi*Pi*bone + Br*Pr*Pr*bone + Br*bone*(Pi*Pi + Pr*Pr + 1) + I*Pi*(Bi*Bi + Br*Br + 1)*pone + Pr*(Bi*Bi + Br*Br + 1)*pone
Beispiel #55
0
    def qasm(self, prec=15):
        """Return the corresponding OPENQASM string."""
        if self.value == pi:
            return "pi"

        return ccode(self.value, precision=prec)
Beispiel #56
0
def test_PostIncrement():
    p = PostIncrement(x)
    assert p.func(*p.args) == p
    assert ccode(p) == '(x)++'