This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

How to convert a sympy expression to Expression in fenics ?

+1 vote

How do I get Expression from ccode like below ?

def myExpression():
    from sympy.physics.vector import ReferenceFrame, curl, divergence, gradient
    from sympy import sin, pi, symbols
    from sympy.printing import print_ccode, ccode

    x, y, z = symbols('x[0] x[1] x[2]')
    R = ReferenceFrame('R')
    u = sin(pi*x) * sin(pi*y) * sin(pi*z)
    laplace_u = divergence(gradient(u, R), R)
    print_ccode(u)
    print_ccode(laplace_u)

Like above, I want to use Laplace u in my fenics code, how should I do?
I know like this:

import sym as sym
x, y, z = sym.symbols('x[0] x[1] x[2]')
u = 1 + x**2 + 2*y**2
var = [sym.printint.ccode(u)]
variable = Expression(var)

Thanks a lot !!!

asked May 17, 2017 by fanronghong FEniCS User (1,680 points)

1 Answer

+1 vote
 
Best answer

Hi, consider the following

import sympy as sp
from dolfin import *

x, y, z = sp.symbols('x[0] x[1] x[2]')

u = x**2 + 2*y**2 + 3*z**2
ddu = sum(u.diff(xi, 2) for xi in (x, y, z)) 

u = Expression(sp.printing.ccode(u), degree=2, cell=tetrahedron)
ddu = Expression(sp.printing.ccode(ddu), degree=2, cell=tetrahedron)

DDU = div(grad(u))
e = DDU - ddu

mesh = UnitCubeMesh(4, 4, 4)
print assemble(inner(e, e)*dx(domain=mesh))  
answered May 17, 2017 by MiroK FEniCS Expert (80,920 points)
selected May 19, 2017 by fanronghong

Thank you very much !!!

It seems simple and great.

So if I want to get a vector-valued Expression, is the below right ?

import sympy as sp
from dolfin import *

x, y, z = sp.symbols('x[0] x[1] x[2]')

u = Expression(sp.printing.ccode(u), degree=2, cell=tetrahedron)

vec_u = Expression((sp.printing.ccode(u), sp.print.ccode(u), sp.print.ccode(u)), degree=2)

Yet, that will work fine.

...