Mapping 2D numpy array into dolfinx function

Hi,

I want to get a dolfinx function of my 2D matplotlib contourplot. The functions I want to make are as follows;

There is no polynomial to satisfy these contourplots. Is it possible to map my 2D numpy array into dolfinx function?

Thanks for your answer in advance.

1 Like

You can tabulate the dof coordinates of your function space (assuming they are a Lagrange space/scalar valued), and use the dolfinx.fem.Function.x.array to Get the values at the corresponding degrees of freedom.

Then you can use any of the solutions from: python - Make contour of scatter - Stack Overflow

Thanks for your answer Dokken, but I want to do exact opposite thing you have mentioned. I want to go from 2D numpy array to dolfinx function.

You need to make a function that is able to evaluate the functions at any point (x,y) in the domain.

You should use an interpolator (for instance scipy.interpolate.interp2d — SciPy v1.7.1 Manual)


from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')
def g(x):
    return f(x[0], x[1])
u = dolfinx.fem.Function(V)
u.interpolate(g)

What is g in u.interpolate(g)?
Can I use this code to read a 2D image in dolfinx?
Thank you

g is a function that takes in an array of coordinates (on the form [[x_0, x_1, ...., x_n], [y_0,..., y_n], [z_0,..,z_n]] and returns a value per [x_i,y_i,z_i] coordinate.

As long as you have a function that can take physical coordinate (x,y,z) and return a value from the image, you can create an interpolation operator.

2 Likes

If someone faces a similar problem, I would note that interp2d was deprecated in the newer scipy releases. The alternative is to use a RegularGridInterpolator, but that would require a little tweak to the function proposed by dokken:

f = RegularGridInterpolator((x, y), z, method='linear')
def g(x):
    return f(np.array([x[0], x[1]]).T)
u = fem.Function(V)
u.interpolate(g)