How to set the initial conditions in FEniCSx

Hello, every one

I am new to FEniCSx.
It is quite simple to set the initial conditions in FEniCS. The following example is written by FEnics.

set the intial conditions in FEniCS

from fenics import *
import time
import matplotlib
import matplotlib.pyplot as plt

T = 2.0 # final time
num_steps = 10 # number of time steps
dt = T / num_steps # time step size

Create mesh and define function space

nx = ny = 20
mesh = RectangleMesh(Point(0,0), Point(1,1), nx, ny)
V = FunctionSpace(mesh, ‘P’, 1)

Define initial value

u_0 = Expression(‘10.0’,degree=2)
u_n = interpolate(u_0, V)
u_n.rename(‘u’, ‘initial value’)

plt.figure(0)
plot(u_n)

But I have some difficulty in setting the same conditions using FEniCSx. There are some problems in the following codes. Could you give some help?

from mpi4py import MPI
import time
from dolfinx import fem, mesh, io, plot
from ufl import SpatialCoordinate

T=2.0
num_steps=10
dt=T/num_steps

creat mesh and define function space

nx, ny = 20, 20
domain = mesh.create_rectangle(MPI.COMM_WORLD, [np.array([0, 0]), np.array([1, 1])],
[nx, ny], mesh.CellType.triangle)
tdim=domain.topology.dim
num_cells=domain.topology.index_map(tdim).size_local
V = fem.FunctionSpace(domain, (“CG”, 1))

Define initial value

u_0=10.0
u_n.interpolate(u_0,num_cells)
u_n.rename (“u_n”)

Thank you very much in advance.

Best regards,

Lei

Please use markdown formatting, i.e.

```python
from dolfin import *
mesh = .....
def f(x):
   return x
```

to make the code render nicely.
If you want to set the initial condition as a constant value you can either do

u_n.x.array[:] = 10.

or

u_n.interpolate(lambda x: numpy.full(x.shape[1], 10, dtype=numpy.float64))
1 Like

Hi, Jorgen

Thank you very much for your quick reply.
I had been looking for the answers for several days. Thanks for helping me out. I really appreciate that!
Next time I will use the markdown formatting.

Best regards,

Lei