Generating electric field from electric potential

I am trying to generate the electric field for the electric potential generated. I have electric potentials stored in self.phi.vector().get_local() which is the following dimension (2999801,1)
. I am trying to get the electric field by finding the gradient for electric potential. I tried using mesh = self.geometry.mesh
V = FunctionSpace(mesh, ‘CG’, self.order)

f = self.phi

Q = VectorFunctionSpace(mesh, ‘DG’, self.order)

p, q = TrialFunction(Q), TestFunction(Q)

L = inner(grad(f), q)*dx

M = assemble(inner(p, q)*dx)

b = assemble(L)

grad_f0 = Function(Q)
x0 = grad_f0.vector()
solve(M, x0, b)
which I found from https://fenicsproject.org/qa/12634/gradient-of-a-cg-order-one-element/ but it gets killed after L = inner(grad(f), q)*dx. How can I solve it ? or is there a different way to do this ?

Please make a minimal reproducible example.
It seems like you are trying to do a projection of a solution with 3 million dofs into something with more than 10 million dofs (vector space and DG).

Then you need to specify an iterative solver when solving, or use the LocalSolver in legacy FEniCS.
See for instance: Error: Unable to orthonormalize vector basis. Reason: Vector space has linear dependency. Where: This error was encountered inside Vector Space Basis.cpp - #10 by dokken

This is far from a minimal reproducible example, so i cannot help you any further.