Beispiel #1
0
def test_dotprint():
    text = dotprint(x + 2, repeat=False)
    assert all(e in text for e in dotedges(x + 2, repeat=False))
    assert all(
        n in text for n in
        [dotnode(expr, repeat=False) for expr in (x, Integer(2), x + 2)])
    assert 'digraph' in text

    text = dotprint(x + x**2, repeat=False)
    assert all(e in text for e in dotedges(x + x**2, repeat=False))
    assert all(n in text for n in
               [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)])
    assert 'digraph' in text

    text = dotprint(x + x**2, repeat=True)
    assert all(e in text for e in dotedges(x + x**2, repeat=True))
    assert all(n in text
               for n in [dotnode(expr, pos=()) for expr in [x + x**2]])

    text = dotprint(x**x, repeat=True)
    assert all(e in text for e in dotedges(x**x, repeat=True))
    assert all(n in text
               for n in [dotnode(x, pos=(
                   0, )), dotnode(x, pos=(1, ))])
    assert 'digraph' in text
Beispiel #2
0
def test_dotprint():
    text = dotprint(x+2, repeat=False)
    assert all(e in text for e in dotedges(x+2, repeat=False))
    assert all(
        n in text for n in [dotnode(expr, repeat=False)
        for expr in (x, Integer(2), x+2)])
    assert 'digraph' in text

    text = dotprint(x+x**2, repeat=False)
    assert all(e in text for e in dotedges(x+x**2, repeat=False))
    assert all(
        n in text for n in [dotnode(expr, repeat=False)
        for expr in (x, Integer(2), x**2)])
    assert 'digraph' in text

    text = dotprint(x+x**2, repeat=True)
    assert all(e in text for e in dotedges(x+x**2, repeat=True))
    assert all(
        n in text for n in [dotnode(expr, pos=())
        for expr in [x + x**2]])

    text = dotprint(x**x, repeat=True)
    assert all(e in text for e in dotedges(x**x, repeat=True))
    assert all(
        n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
    assert 'digraph' in text
Beispiel #3
0
def test_Matrix_and_non_basics():
    from sympy import MatrixSymbol

    n = Symbol("n")
    assert (dotprint(MatrixSymbol("X", n, n)) == """digraph{

# Graph style
"ordering"="out"
"rankdir"="TD"

#########
# Nodes #
#########

"MatrixSymbol(Symbol('X'), Symbol('n'), Symbol('n'))_()" ["color"="black", "label"="MatrixSymbol", "shape"="ellipse"];
"Symbol('X')_(0,)" ["color"="black", "label"="X", "shape"="ellipse"];
"Symbol('n')_(1,)" ["color"="black", "label"="n", "shape"="ellipse"];
"Symbol('n')_(2,)" ["color"="black", "label"="n", "shape"="ellipse"];

#########
# Edges #
#########

"MatrixSymbol(Symbol('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('X')_(0,)";
"MatrixSymbol(Symbol('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(1,)";
"MatrixSymbol(Symbol('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(2,)";
}""")
Beispiel #4
0
def write_to_dot(outs, vnaems, suffix="[pp]", folder_ptah="."):
    mi = [0, 1, 2, 4, 5, 8]
    midx = ['00', '01', '02', '11', '12', '22']
    idx = suffix

    # total number of expressions
    # print("--------------------------------------------------------")
    num_e = 0
    for i, e in enumerate(outs):
        if type(e) == list:
            num_e = num_e + len(e)
            for j, ev in enumerate(e):
                print("processing expr : %d var name %s[%s]" %
                      (i, vnaems[i], str(j)))
                ev = replace_userdef_funcs(ev)
                d_str = str(dotprint(ev, labelfunc=sympy.srepr, repeat=False))
                gv_file = open(
                    folder_ptah + "/" + vnaems[i] + "_" + str(j) + ".dot", 'w')
                gv_file.write(d_str)
                gv_file.close()
        elif type(e) == sympy.Matrix:
            num_e = num_e + len(e)
            for j, k in enumerate(mi):
                print("processing expr : %d var name %s[%s]" %
                      (i, vnaems[i], midx[j]))
                e[k] = replace_userdef_funcs(e[k])
                d_str = str(dotprint(e[k], labelfunc=sympy.srepr,
                                     repeat=False))
                gv_file = open(
                    folder_ptah + "/" + vnaems[i] + "_" + str(midx[j]) +
                    ".dot", 'w')
                gv_file.write(d_str)
                gv_file.close()
                #exp_symbols = exp_symbols.union(replace_userdef_funcs(e[k]).free_symbols)
                #exp_symbols = exp_symbols.union(advanced_free_symbols(e[k]))
        else:
            num_e = num_e + 1
            print("processing expr : %d var name %s" % (i, vnaems[i]))
            e = replace_userdef_funcs(e)
            d_str = str(dotprint(e, labelfunc=sympy.srepr, repeat=False))
            gv_file = open(folder_ptah + "/" + vnaems[i] + ".dot", 'w')
            gv_file.write(d_str)
            gv_file.close()
Beispiel #5
0
def dotexport(expr, fname):
    txt = str(dotprint(expr))

    name = os.path.splitext(fname)[0]

    f = open('{}.dot'.format(name), 'w')
    f.write(txt)
    f.close()

    cmd = 'dot {name}.dot -Tpng -o {name}.png'.format(name=name)
    os.system(cmd)
Beispiel #6
0
def expression_graph_as_png(expr, output_file, view=True):
    """ Save a PNG of rendered graph (graphviz) of the symbolic expression.
    :param expr: sympy expression
    :param output_file: string with .png extension
    :param view: set to True if system default PNG viewer should pop up
    :return: None
    """
    assert output_file.endswith('.png')
    graph = Source(dotprint(expr))
    graph.format = 'png'
    graph.render(output_file.rpartition('.png')[0], view=view, cleanup=True)
def expression_graph_as_png(expr, output_file, view=True):
    """ Save a PNG of rendered graph (graphviz) of the symbolic expression.
    :param expr: sympy expression
    :param output_file: string with .png extension
    :param view: set to True if system default PNG viewer should pop up
    :return: None
    """
    assert output_file.endswith('.png')
    graph = Source(dotprint(expr))
    graph.format = 'png'
    graph.render(output_file.rpartition('.png')[0], view=view, cleanup=True)
Beispiel #8
0
def test_equations2():
    equations = [
        "x = a*x(-1) + e",
        "y = b*y(-1) + c*x(-1) + d*p(-1)",
        "p = p(-1) + f",
    ]

    structural = ["a", "b", "c", "d"]
    shocks = ["e", "f"]

    print(sympify("f(1)"))
    print(dotprint(sympify("f(1)")))

    lhs, rhs = [], []
    for equation in equations:
        s_lhs, s_rhs = equation.split("=")

        p_lhs = sympify(s_lhs)
        p_rhs = sympify(s_rhs)

        print(dotprint(p_rhs))

        lhs.append(p_lhs)
        rhs.append(p_rhs)

    print(lhs)
    print(rhs)

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

    left, right = linear_eq_to_matrix(rhs, [x, y, p])

    print(left)
    print(right)

    transition, shock = DsgeModelBuilder.prepare_state_matrices(equations, ['e', 'f'], ['x', 'y', 'p'])

    print("State matrices")

    print(transition)
    print(shock)
Beispiel #9
0
def export(expr, fname):
    """saves the graph as a png/svg file. the extension is eitheir png or svg"""

    name, ext = os.path.splitext(fname)
    ext = ext[1:]

    graph = dotprint(expr)
    f = open('{name}.dot'.format(name=name), 'w')
    f.write(graph)
    f.close()

    cmd = "dot -T{ext} {name}.dot -o{name}.{ext}".format(name=name, ext=ext)
    os.system(cmd)
Beispiel #10
0
def to_dot(expr: sp.Expr,
           graph_style: Optional[Dict[str, Any]] = None,
           short=True):
    """Show a sympy or pystencils AST as dot graph"""
    from pystencils.astnodes import Node
    import graphviz
    graph_style = {} if graph_style is None else graph_style

    if isinstance(expr, Node):
        from pystencils.backends.dot import print_dot
        return graphviz.Source(
            print_dot(expr, short=short, graph_attr=graph_style))
    else:
        from sympy.printing.dot import dotprint
        return graphviz.Source(dotprint(expr, graph_attr=graph_style))
Beispiel #11
0
def test_dotprint_depth():
    text = dotprint(3 * x + 2, depth=1)
    assert dotnode(3 * x + 2) in text
    assert dotnode(x) not in text
    text = dotprint(3 * x + 2)
    assert "depth" not in text
Beispiel #12
0
def test_commutative():
    x, y = symbols('x y', commutative=False)
    assert dotprint(x + y) == dotprint(y + x)
    assert dotprint(x * y) != dotprint(y * x)
def expr_to_dotgraph(name, expr):
    from sympy.printing.dot import dotprint
    with open(name + ".dot", "w") as dot_file:
        dot_file.write(dotprint(expr))
Beispiel #14
0
def test_Matrix_and_non_basics():
    from sympy.matrices.expressions.matexpr import MatrixSymbol
    n = Symbol('n')
    assert dotprint(MatrixSymbol('X', n, n)) == \
"""digraph{
Beispiel #15
0
def test_labelfunc():
    text = dotprint(x + 2, labelfunc=srepr)
    assert "Symbol('x')" in text
    assert "Integer(2)" in text
Beispiel #16
0
def test_Matrix_and_non_basics():
    from sympy import MatrixSymbol
    n = Symbol('n')
    assert dotprint(MatrixSymbol('X', n, n)) == \
"""digraph{
Beispiel #17
0
    def _get_graph_bytes(_expr):
        digraph = dotprint(expr)
        raw_bytes = Source(digraph).pipe(format="png")

        return io.BytesIO(raw_bytes)
Beispiel #18
0
 def show(srepr, pref='dp_'):
     dp = dotprint(sympy_parser.parse_expr(srepr))
     tfn = tempfile.mktemp(suffix='.png', prefix=pref)
     graphviz.Source(dp, filename=os.path.splitext(tfn)[0],
                     format='png').view()
Beispiel #19
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sympy import init_printing, Integral, latex, pretty, pprint, sqrt, symbols, srepr
init_printing(use_unicode=True)
x, y, z = symbols('x y z')
print(Integral(sqrt(1 / x), x))

print(srepr(Integral(sqrt(1 / x), x)))
pprint(Integral(sqrt(1 / x), x), use_unicode=False)

print(pretty(Integral(sqrt(1 / x), x), use_unicode=False))

print(latex(Integral(sqrt(1 / x), x)))
from sympy.printing.mathml import print_mathml
print_mathml(Integral(sqrt(1 / x), x))

from sympy.printing.dot import dotprint
from sympy.abc import x
print(dotprint(x + 2))
Beispiel #20
0
def test_dotprint_depth():
    text = dotprint(3*x+2, depth=1)
    assert dotnode(3*x+2) in text
    assert dotnode(x) not in text
    text = dotprint(3*x+2)
    assert "depth" not in text
Beispiel #21
0
def test_commutative():
    x, y = symbols('x y', commutative=False)
    assert dotprint(x + y) == dotprint(y + x)
    assert dotprint(x*y) != dotprint(y*x)
Beispiel #22
0
def test_Matrix_and_non_basics():
    from sympy import MatrixSymbol
    n = Symbol('n')
    assert dotprint(MatrixSymbol('X', n, n))
Beispiel #23
0
from sympy import Symbol, MatrixSymbol, MatMul, Transpose, Inverse

X = MatrixSymbol('X', n, m)
y = MatrixSymbol('y', n, 1)
beta = MatMul(Inverse(MatMul(Transpose(X), X)), Transpose(X), y)
from sympy.printing.dot import dotprint
dotprint(beta)
with open('images/beta.dot', 'w') as f:
        f.write(dotprint(beta))
Beispiel #24
0
def test_labelfunc():
    text = dotprint(x + 2, labelfunc=srepr)
    assert "Symbol('x')" in text
    assert "Integer(2)" in text
Beispiel #25
0
def generate_separate(ex, vnames, idx):
    """
    Generate the C++ code by simplifying the expressions.
    """
    # print(ex)
    if len(ex)!=1 :
        print ('pass each variable separately ',end='\n')
        return

    mi = [0, 1, 2, 4, 5, 8]
    midx = ['00', '01', '02', '11', '12', '22']

    # total number of expressions
    # print("--------------------------------------------------------")
    num_e = 0
    lexp = []
    lname = []
    for i, e in enumerate(ex):
        if type(e) == list:
            num_e = num_e + len(e)
            for j, ev in enumerate(e):
                lexp.append(ev)
                lname.append(vnames[i]+repr(j)+idx)
        elif type(e) == Matrix:
            num_e = num_e + len(e)
            for j, k in enumerate(mi):
                lexp.append(e[k])
                lname.append(vnames[i]+midx[j]+idx)
        else:
            num_e = num_e + 1
            lexp.append(e)
            lname.append(vnames[i]+idx)

    # print(num_e)
    # print(len(lname))
    c_file=open(vnames[0]+'.cpp','w')
    print('generating code for '+vnames[0])
    print('    bssn::timer::t_rhs.start();',file=c_file)
    print('for (unsigned int k = 3; k < nz-3; k++) { ',file=c_file)
    print('    z = pmin[2] + k*hz;',file=c_file)

    print('for (unsigned int j = 3; j < ny-3; j++) { ',file=c_file)
    print('    y = pmin[1] + j*hy; ',file=c_file)

    print('for (unsigned int i = 3; i < nx-3; i++) {',file=c_file)
    print('    x = pmin[0] + i*hx;',file=c_file)
    print('    pp = i + nx*(j + ny*k);',file=c_file)
    print('    r_coord = sqrt(x*x + y*y + z*z);',file=c_file)
    print('    eta=ETA_CONST;',file=c_file)
    print('    if (r_coord >= ETA_R0) {',file=c_file)
    print('    eta *= pow( (ETA_R0/r_coord), ETA_DAMPING_EXP);',file=c_file)
    print('    }',file=c_file)




    print('// Dendro: {{{ ',file=c_file)
    print('// Dendro: original ops: ', count_ops(lexp),file=c_file)

    # print("--------------------------------------------------------")
    # print("Now trying Common Subexpression Detection and Collection")
    # print("--------------------------------------------------------")

    # Common Subexpression Detection and Collection
    # for i in range(len(ex)):
    #     # print("--------------------------------------------------------")
    #     # print(ex[i])
    #     # print("--------------------------------------------------------")
    #     ee_name = ''.join(random.choice(string.ascii_uppercase) for _ in range(5))
    #     ee_syms = numbered_symbols(prefix=ee_name)
    #     _v = cse(ex[i],symbols=ee_syms)
    #     # print(type(_v))
    #     for (v1,v2) in _v[0]:
    #         print("double %s = %s;" % (v1, v2))
    #     print("%s = %s" % (vnames[i], _v[1][0]))

    #mex = Matrix(ex)
    ee_name = 'DENDRO_' #''.join(random.choice(string.ascii_uppercase) for _ in range(5))
    ee_syms = numbered_symbols(prefix=ee_name)
    _v = cse(lexp, symbols=ee_syms, optimizations='basic')

    custom_functions = {'grad': 'grad', 'grad2': 'grad2', 'agrad': 'agrad', 'kograd': 'kograd'}

    rops=0
    print('// Dendro: printing temp variables',file=c_file)
    for (v1, v2) in _v[0]:
        # print("double %s = %s;" % (v1, v2)) # replace_pow(v2)))
        print('double ', end='', file=c_file)
        print(change_deriv_names(ccode(v2, assign_to=v1, user_functions=custom_functions)),file=c_file)
        rops = rops + count_ops(v2)


    print('// Dendro: printing variables',file=c_file)
    for i, e in enumerate(_v[1]):
        print("//--",file=c_file)
        # print("%s = %s;" % (lname[i], e)) # replace_pow(e)))
        f = open(str(vnames[0])+'.gv','w')
        print(dotprint(e), file=f)
        f.close()
        print(change_deriv_names(ccode(e, assign_to=lname[i], user_functions=custom_functions)),file=c_file)
        #c_file.write('\n')
        rops = rops + count_ops(e)

    print('// Dendro: reduced ops: ', rops,file=c_file)
    print('// Dendro: }}} ',file=c_file)





    print('     /* debugging */',file=c_file)
    print('     /*unsigned int qi = 46 - 1;',file=c_file)
    print('     unsigned int qj = 10 - 1;',file=c_file)
    print('     unsigned int qk = 60 - 1;',file=c_file)
    print('     unsigned int qidx = qi + nx*(qj + ny*qk);',file=c_file)
    print('     if (0 && qidx == pp) {',file=c_file)
    print('     std::cout << ".... end OPTIMIZED debug stuff..." << std::endl;',file=c_file)
    print('     }*/',file=c_file)
    print('  }',file=c_file)
    print(' }',file=c_file)
    print('}',file=c_file)
    print('     bssn::timer::t_rhs.stop();',file=c_file)
    c_file.close()
    print('generating code for '+vnames[0]+' completed')
#%%
h(1 + x)

#%% md
## Expressions ##

#%%
x = sympy.Symbol("x")
expr = 1 + 2 * x**2 + 3 * x**3
expr

#%%
from sympy.printing.dot import dotprint
from graphviz import Digraph, Source
dp = dotprint(expr)
dot = Source(dp)
dot.render('test-output/round-table.gv', view=True)

#%%
expr.args

#%%
expr.args[1]

#%%
expr.args[1].args[1]

#%% md
## Manipulating Expressions ##