Evaluate function on whole mesh

I’m trying to evaluate the solution of a PDE I solved on all the cells of the mesh, to construct an array that contains coordinates and value of the function: [ x, y, z, u(x,y,z) ]

So I have solved the PDE, but I’m quite confused on how should I retrive the cell indexes and coordinate value to call eval on the solution:

...
u, p= Function(V), Function(Q)
x = PETSc.Vec().createNest([_cpp.la.petsc.create_vector_wrap(u.x), _cpp.la.petsc.create_vector_wrap(p.x)])
ksp.solve(b, x)

u_values=u.eval( ?, ?? )

I know ? is an object of shape (num_points,3), namely the coordinates, and ?? are the cell indexes of the points I want to evaluate, but I cannot find a simple way of retrive all the centers of the cells and the corresponding cells indexes from the mesh I used in the solution of the PDE. I’m using dolfinx 0.6.0

Consider

import numpy as np
from mpi4py import MPI
import dolfinx

mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 8, 8)
V = dolfinx.fem.FunctionSpace(mesh, ("CG", 1))
u = dolfinx.fem.Function(V)

u.interpolate(lambda x: np.sin(np.pi*x[0]) * np.sin(np.pi*x[1]))

n = 4j
x = np.c_[np.mgrid[0:1:n, 0:1:n].reshape(2, -1)].T
x = np.c_[x, np.zeros_like(x[:,0])]  # Padding for 2d geometry

bb_tree = dolfinx.geometry.bb_tree(mesh, mesh.topology.dim)
cell_candidates = dolfinx.geometry.compute_collisions_points(bb_tree, x)
colliding_cells = dolfinx.geometry.compute_colliding_cells(mesh, cell_candidates, x)
cells = colliding_cells.array[colliding_cells.offsets[:-1]]
u_values = u.eval(x, cells)

print("x, y, u(x, y)")
print(np.c_[x[:,:2], u_values])
2 Likes

As it seems you want to do this at midpoints, you can use:

local_cells = np.arange(domain.topology.index_map(domain.topology.dim).size_local, dtype=np.int32)
midpoints = mesh.compute_midpoints(domain, domain.topology.dim, local_cells)

to get the two arrays.

If you want to compute this at every cell midpoint, you could also simply interpolate your solution into a DG-0 space, and extract the values directly from the underlying dof-array

2 Likes