About Userexpression in dolfinx

Hello, I recently upgraded dolfinx to version 0.7.2 and noticed that I could not use ‘UserExpression’ .If ‘UserExpression’ has been replaced, could you please guide me on the alternative method for importing 3D NumPy array data into a FunctionSpace? I appreciate your assistance in resolving this matter.

See for instance: UserExpression in dolfinx

Thanks for replying.I try to use the following code

msh = mesh.create_box(comm=MPI.COMM_WORLD, points=((-30.0, -30.0, -30.0), (30.0, 30.0, 30.0)), n=(Nx, Ny, Nz), cell_type=mesh.CellType.tetrahedron)
V = fem.functionspace(msh, ("Lagrange", 2))

class InterpolateFunction(Expression):
    def __init__(self, data, **kwargs):
        super().__init__(**kwargs)
        self.data = data

    def eval(self, values, x):
        values[0] = self.interpolate_data(x)

    def interpolate_data(self, x):
        i, j, k = int((x[0] + 30) / 60 * Nx), int((x[1] + 30) / 60 * Ny), int((x[2] + 30) / 60 * Nz)
        i = min(max(i, 0), Nx - 1)
        j = min(max(j, 0), Ny - 1)
        k = min(max(k, 0), Nz - 1)

        return self.data[k, j, i]

f = Interpolate(InterpolateFunction(data=density), V)

But I meet some problems:

TypeError: Expression.__init__() missing 2 required positional arguments: 'e' and 'X'

May be using Expression is wrong?(I am a beginner :sob:)

Did you actually look at the link the post I referenced you?
You do not need to use the expression class at all.

class InterpolateFunction():
    def __init__(self, data):
        self.data = data

    def eval(self, x):
        values = np.zeros(x.shape[1], dtype=np.float64)
        for i, point in enumerate(x.T):   
            values[i] = self.interpolate_data(point)

    def interpolate_data(self, x):
        i, j, k = int((x[0] + 30) / 60 * Nx), int((x[1] + 30) / 60 * Ny), int((x[2] + 30) / 60 * Nz)
        i = min(max(i, 0), Nx - 1)
        j = min(max(j, 0), Ny - 1)
        k = min(max(k, 0), Nz - 1)

        return self.data[k, j, i]

func = InterpolateFunction(data=density)
f = fem.Function(V)
f.interpolate(func.eval, V)

As described in for instance: Form compilation — FEniCS Tutorial @ Sorbonne

def u_init(x, sigma=0.1, mu=0.3):
    """
    The input function x is a (3, number_of_points) numpy array, which is then
    evaluated with the vectorized numpy functions for efficiency
    """
    return 1./(2 * np.pi * sigma)*np.exp(-0.5*((x[0]-mu)/sigma)**2)*np.exp(-0.5*((x[1]-mu)/sigma)**2)
u_n = dolfinx.fem.Function(V)
u_n.interpolate(u_init)
1 Like

I am sorry to have discommoded you. It works. :pray: