Equivalent for Expression in dolfinx

The Expression class has been removed, as it caused a headache for developers and it is not clear what it does.
The new way of doing this is to interpolate an expression into a function:

from dolfinx import UnitSquareMesh, Function, FunctionSpace, MPI, Constant
from dolfinx.fem import assemble_vector
from ufl import TestFunction, dx, inner
import numpy as np

class MyExpression:
    def __init__(self):
        self.t = 0.0

    def eval(self, x):
        # Added some spatial variation here. Expression is sin(t)*x
        return np.full(x.shape[1], np.sin(self.t)*x[0])

# If your Expression is not spatially dependent, use Constant
# f = Constant(mesh, 0)
# L = inner(f, v)*dx
# f.value = np.sin(2)
mesh = UnitSquareMesh(MPI.comm_world, 10, 10)
V = FunctionSpace(mesh, ("CG", 1))
f = MyExpression()
f.t = 0
w = Function(V)
v = TestFunction(V)
L = inner(w, v)*dx
w.interpolate(f.eval)

print(assemble_vector(L).array)
f.t = 2
w.interpolate(f.eval)
print(assemble_vector(L).array)
5 Likes