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

Is it possible to differentiate an expression with respect to user_parameter?

+3 votes

Hi there,

If I have an expression like expr = Expression('x[0]*t', t=0), is it possible to get the derivative of this expression with respect to t? I would expect something like deri = diff(expr, t). Is there some workaround?

Thanks very much.

Charlie

asked Feb 2, 2016 by Chao Zhang FEniCS User (1,180 points)

3 Answers

+4 votes
 
Best answer

Hi, consider using sympy as a workaround

from dolfin import *
from sympy.utilities.codegen import ccode
from sympy import symbols
import sympy as sp

x, y, t, w = symbols('x[0], x[1], t, w')

# Sympy expression
r = sp.sqrt((x-2)**2 + (y-2)**2)
f = sp.cos(w*sp.pi*r*t)/(sp.pi*w*r)
# Derivative
df = f.diff(t, 1)
# Convert to Dolfin expression. Note that args t, w are given values
df = Expression(ccode(df).replace('M_PI', 'pi'), t=1, w=1)

# Demo
mesh = RectangleMesh(Point(-1, -1), Point(1, 1), 20, 20)
V = FunctionSpace(mesh, 'CG', 1)
dfV = interpolate(df, V)
p = plot(dfV, elevate=0., rescale=False)

dt=1E-1
t = 1
while t < 5:
    t += dt
    df.t = t
    dfV = interpolate(df, V)
    p.plot(dfV)
interactive()
answered Feb 2, 2016 by MiroK FEniCS Expert (80,920 points)
selected Feb 3, 2016 by Chao Zhang

Thanks very much. This is exactly what I expected.

Nice one MiroK

+3 votes

You can also use ufl. I think something like this should work:

from dolfin import *

mesh = UnitSquareMesh(12,12)
R = FunctionSpace(mesh, "R", 0)
tt = Function(R)
t = variable(tt)
x = SpatialCoordinate(mesh)

f = sin(t*x[0])

dfdt = diff(f, t)
dfdx = diff(f, x)

print dfdt
print dfdx

answered Feb 2, 2016 by Kent-Andre Mardal FEniCS Expert (14,380 points)

Thanks very much for your answer. In this case, I'd like to obtain an Expression object, so that it could be used in a DirichletBC. I'm sorry I didn't make it clear.

+1 vote

You could use directly UFL, define t as a Constant and use the assign function to update its value. In this way f is also automatically updated.

from dolfin import *
mesh = UnitSquareMesh(20,20)
x = SpatialCoordinate(mesh)
V = VectorFunctionSpace(mesh, "CG", 1)
t = Constant(0.0)
f = x[0]*t
df_dt = diff(f, t)
plot(df_dt, mesh=mesh)
t.assign(0.1)
plot(f, mesh=mesh)
plot(df_dt, mesh=mesh)
answered Oct 4, 2016 by Eleonora FEniCS Novice (280 points)
...