当前位置: 首页>>代码示例>>Python>>正文


Python ccode.ccode函数代码示例

本文整理汇总了Python中sympy.printing.ccode.ccode函数的典型用法代码示例。如果您正苦于以下问题:Python ccode函数的具体用法?Python ccode怎么用?Python ccode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ccode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: render_and_write_code

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)
开发者ID:kiaderouiche,项目名称:jitcode,代码行数:26,代码来源:_helpers.py

示例2: _call_printer

    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
开发者ID:Eskatrem,项目名称:sympy,代码行数:25,代码来源:codegen.py

示例3: test_goto_Label

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')
开发者ID:Lenqth,项目名称:sympy,代码行数:13,代码来源:test_cnodes.py

示例4: test_create_expand_pow_optimization

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)'
开发者ID:asmeurer,项目名称:sympy,代码行数:13,代码来源:test_rewriting.py

示例5: dump_c

    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
开发者ID:KevinGoodsell,项目名称:sympy,代码行数:35,代码来源:codegen.py

示例6: get_prototype

    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)
开发者ID:Eskatrem,项目名称:sympy,代码行数:26,代码来源:codegen.py

示例7: test_sizeof

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())
开发者ID:Lenqth,项目名称:sympy,代码行数:7,代码来源:test_cnodes.py

示例8: _render_compile_import

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)
开发者ID:Lenqth,项目名称:sympy,代码行数:11,代码来源:test_applications.py

示例9: test_union

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"
        "}")
开发者ID:Lenqth,项目名称:sympy,代码行数:13,代码来源:test_cnodes.py

示例10: _call_printer

    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
开发者ID:MCGallaspy,项目名称:sympy,代码行数:38,代码来源:codegen.py

示例11: test_struct

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"
        "}")
开发者ID:Lenqth,项目名称:sympy,代码行数:14,代码来源:test_cnodes.py

示例12: test_newtons_method_function__ccode

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
开发者ID:asmeurer,项目名称:sympy,代码行数:20,代码来源:test_algorithms.py

示例13: test_newtons_method_function__ccode_parameters

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 == """\
开发者ID:asmeurer,项目名称:sympy,代码行数:37,代码来源:test_algorithms.py

示例14: get_prototype

    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)
开发者ID:jeffwdoak,项目名称:pycalphad,代码行数:24,代码来源:custom_autowrap.py

示例15: get_c_function

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)
开发者ID:MooVI,项目名称:commutator,代码行数:4,代码来源:commutator.py


注:本文中的sympy.printing.ccode.ccode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。