예제 #1
0
    def header(self):
        # Returns a list of strings of C++11 code with expressions for 
        # each real value that constitutes the Hermitian matrix
        # The regular expression replaces Pow(x,2) with x*x

        lines = [sympy.cxxcode(sympy.simplify(e)) for e in self.declarations()]
        return lines
예제 #2
0
def expressionToCode(expression, language):
    '''Converts a SymPy Expression to a line of code in the target language'''
    if (language == "python"):
        return sympy.pycode(expression)
    elif (language == "javascript" or language == "typescript"):
        return sympy.jscode(expression)
    elif (language == "c"):
        return sympy.ccode(expression)
    elif (language == "cpp"):
        return sympy.cxxcode(expression)
    elif (language == "r"):
        return sympy.rcode(expression)
    elif (language == "fortran"):
        return sympy.fcode(expression)
    elif (language == "mathematica"):
        return sympy.mathematica_code(expression)
    elif (language == "matlab" or language == "octave"):
        return sympy.octave_code(expression)
    elif (language == "rust"):
        return sympy.rust_code(expression)
예제 #3
0
 def header_diagonals(self):
     lines = [sympy.cxxcode(sympy.re(self.H[i,i])) for i in range(self.size)]
     return lines
예제 #4
0
    def code(self):
        # Returns a list of strings of C++11 code with expressions for 
        # each real value that constitutes the Hermitian matrix

        lines = [sympy.cxxcode(sympy.simplify(e)) for e in self.expressions()]
        return lines
예제 #5
0
def generateEFGfunc(zstring, printfile, symmap=None):
    """
    Given a string expression for z=f(x,y), the code in this module generates
    a function that will calculate the first fundamental form terms E, F, G.
    It returns a Numba Jitted function.

    Parameters:
    -----------

    zstring: A string that can be evaluated as a function of x and y
             like '0.555*sin(pi*x)*cos(pi*y)'. It creates a file containing a
             function definition.
    printfile: name of the file to which the generated code should be written
    symmap: A mapping of the symbols used in zexpr to sympy's functions.
            e.g. symmap={'sin': sympy.sin} when zstring = sin(x)

    Returns:
    --------
    getEFG: a function
    """
    r, t = sympy.symbols('r t', real=True, positive=True)
    a, b = sympy.symbols('a b', real=True)
    x = a + r*sympy.cos(t)
    y = b + r*sympy.sin(t)

    # Copy the mappings from `symmap` into the local namespace
    if symmap is not None:
        locals().update(symmap)

    z = eval(zstring, None, locals())
    p = sympy.Matrix([x, y, z])

    pr = p.diff(r)
    pt = p.diff(t)

    E = pr.dot(pr)
    F = pr.dot(pt)
    G = pt.dot(pt)

    # Find all free symbols
    funcargs = set()
    for expr in [E, F, G]:
        for s in expr.free_symbols:
            funcargs.add(s)
    
    # Remove the known free symbols from the set
    for sym in [r, t, a, b]:
        funcargs.remove(sym)
    
    # Create a string representing the remaining free symbols
    if len(funcargs) > 0:
        argstr = 'const scalar r, const scalar t, const scalar a, const scalar b, '
        extraargs = ', const scalar '.join([" "] + [str(sym) for sym in funcargs])
        extraargs = extraargs.lstrip(' ,')
        argstr += extraargs
    else:
        argstr = 'const scalar r, const scalar t, const scalar a, const scalar b'

    codestr = [
        '#ifndef __GENERATEDEFG_CODE_H__',
        '#define __GENERATEDEFG_CODE_H__\n',
        '#include <tuple>',
        '#include "settings.h"\n',
        'typedef std::tuple<scalar, scalar, scalar> tuple3;\n',
        'struct EFGFunc{\n',
        '    tuple3 operator()({0}){{'.format(argstr),
        '        /* Function generated by `generatecode.py` */'
        '\n        //############## Sub-expressions ##############']

    # Now the codegeneration part, first eliminate common sub-expressions
    pow_2 = re.compile('std::pow\((\w+), 2\)')
    exprs = [E, F, G]
    assignto = ['E', 'F', 'G']
    replacements, reduced_exprs = sympy.cse(exprs, optimizations='basic')
    for lhs, rhs in replacements:
        rhs_code = sympy.cxxcode(rhs)
        rhs_code = pow_2.sub('\g<1>*\g<1>', rhs_code)
        codestr.append('        scalar {} = {};'.format(lhs, rhs_code))

    codestr.append('\n        //############## Final Expressions ##############')
    for lhs, rhs in zip(assignto, reduced_exprs):
        rhs_code = sympy.cxxcode(rhs)
        rhs_code = pow_2.sub('\g<1>*\g<1>', rhs_code)
        codestr.append('        scalar {} = {};'.format(lhs, rhs_code))

    codestr.append('\n        return {E, F, G};')
    funccode = '\n'.join(codestr) + '\n    }\n};\n#endif //__GENERATEDEFG_CODE_H__\n'
    funccode = funccode.replace('std::', 'math::')
    funccode = funccode.replace('math::tuple', 'std::tuple')
    funccode = funccode.replace('M_PI', 'PI')

    with open(printfile, 'w') as out:
        out.write(funccode)

    return funccode
예제 #6
0
            code.append(fii + " -= error/" + str(args.N) + ";")
        code.append("}")
        code.append("")

        # make sure diagonals are positive
        for fii in fdlist:
            code.append("if(" + fii +
                        "<-100.*parms->maxError) amrex::Abort();")
            code.append("if(" + fii + "<-parms->maxError) " + fii + "=0;")
        code.append("")

        # make sure the flavor vector length is what it would be with a 1 in only one diagonal
        length = sympy.symbols("length", real=True)
        length = f.SU_vector_magnitude()
        target_length = SU_vector_ideal_magnitude(args.N)
        code.append("length = " + sympy.cxxcode(sympy.simplify(length)) + ";")
        code.append("error = length-" + str(target_length) + ";")
        code.append(
            "if( std::abs(error) > 100.*parms->maxError) amrex::Abort();")
        code.append("if( std::abs(error) > parms->maxError) {")
        for fii in flist:
            code.append(fii + " /= length/" + str(target_length) + ";")
        code.append("}")
        code.append("")

    write_code(
        code,
        os.path.join(args.emu_home, "Source/generated_files",
                     "FlavoredNeutrinoContainer.cpp_Renormalize_fill"))
    # Write code to output file, using a template if one is provided
    # write_code(code, "code.cpp", args.output_template)
예제 #7
0
def lambdify(sympy_inputs_str, sympy_expr):
    return sp.lambdify(sp.symbols(sympy_inputs_str),
                       sympy_expr,
                       modules=_lambdify_modules)


_ufns = {'argmax': 'argmax'}

#pylint: disable=unnecessary-lambda
_code_printers = {
    'c':
    lambda expr, **kw: sp.ccode(
        expr, standard='c99', user_functions=_ufns, **kw),
    'cxx':
    lambda expr, **kw: sp.cxxcode(expr, user_functions=_ufns, **kw),
    'rust':
    lambda expr, **kw: sp.rust_code(expr, user_functions=_ufns, **kw),
    'fortran':
    lambda expr, **kw: sp.fcode(expr, standard=95, user_functions=_ufns, **kw),
    'js':
    lambda expr, **kw: sp.jscode(expr, user_functions=_ufns, **kw),
    'r':
    lambda expr, **kw: sp.rcode(expr, user_functions=_ufns, **kw),
    'julia':
    lambda expr, **kw: sp.julia_code(expr, user_functions=_ufns, **kw),
    'mathematica':
    lambda expr, assign_to=None, **kw: sp.mathematica_code(
        expr, user_functions=_ufns, **kw),
    'octave':
    lambda expr, **kw: sp.octave_code(expr, user_functions=_ufns, **kw),