Compute E-field from the potential field (DOLFINx v0.9.0)

Having used FEniCSx to compute a potential field uh -throughout a 3D mesh, I would like to compute the resulting E-field. Unfortunately, I have not managed to find out how to compute that using DOLFINx v0.9.0. I have used the following code.

from dolfinx import fem
from ufl import grad, dot, dx, TrialFunction, TestFunction

# Load the 3D mesh
msh = get_mesh()

# Define & solve the problem
V = fem.functionspace(msh, ("Lagrange", 1))
u = TrialFunction(V)
v = TestFunction(V)
rho = fem.Constant(msh, default_scalar_type(0))
a = dot(grad(u), grad(v)) * dx
L = rho * v * dx
problem = LinearProblem(a, L, bcs=bcs, petsc_options={"ksp_type": "preonly", "pc_type": "lu"})
uh = problem.solve()

# TODO: The E-field E = -grad(uh) should be computed here

# TODO: Visualize the E-field

I have two questions:

  1. How to compute the resulting electric field?
  2. How to visualize it, using e.g. field lines and/or a magnitude visualization, in 3D?

Thanks in advance for your answer.

Use dolfinx.fem.Expression, as shown in for instance:
https://jsdokken.com/fenics22-tutorial/heat_eq.html#post-processing-without-projections

i.e. in your case

gradu = -ufl.grad(uh)
Q = fem.functionspace(msh, ("DG", 0, (msh.geometry.dim, )))
q = dolfinx.fem.Function(Q)
expr = dolfinx.fem.Expression(gradu, Q.element.interpolation_points())
q.interpolate(expr)

You can now store q to file and visualize with Paraview or visualize with pyvista directly.