Create initial condition with Expression and interpolate

Hello,

I am trying to use the following code to create an initial condition with expression such that it specifies a circle of radius R centered at (0, 0), all values outside of the circle is m and all inside the circle is n. Does anyone know how to do this with Expression?

from dolfin import *
nx = ny = 40
mesh = RectangleMesh(Point(-2, -2), Point(2,2), nx, ny)
V = FunctionSpace(mesh, 'P', 1)
u0 = Expression('some expression',degree=2)
un = interpolate(u0, V)

You can do it using the conditional operator ? in C++:

from dolfin import *
nx = ny = 40
mesh = RectangleMesh(Point(-2, -2), Point(2,2), nx, ny)
V = FunctionSpace(mesh, 'P', 1)
R = 1
m = 3
n = -3
u0 = Expression('(pow(x[0],2) + pow(x[1],2) > pow(R,2)) ? m : n',degree=2,R=R,m=m,n=n)
un = interpolate(u0, V)

plot(un)
1 Like

Thank you! I am not very familiar with C++ conditional operators, I just tried what you suggested with R=2.0, m=0.5, n=0.9 and got the following field, it seems like inside the circle it’s all zero?

It is not 0, I had a similar issue in the past. I don’t know why it sets the maximum value of your colormap to white.

If you scale your data to a range slightly wider than the one you actually have, you will see that it is correctly set.
Add at the beginning: from matplotlib import pyplot as plt and just replace the line where you plot with:

p = plot(un,title='Initialization', mode='color',vmin=0.4,vmax=1.0)
cbar = plt.colorbar(p)
1 Like

Thank you so much!!!