Unable to link Fenics with Petsc(4py)?

Hello,

I’m trying to build a lumped mass matrix in Fenics and then perform some matrix operations on it (such as: invert it, perform matrix-matrix-multiplications, etc.). To this end, I need to be able to explicitly construct the matrix through the linear algebra backend in Fenics. A google search pointed me to

as_backend_type(…).mat()

So I wrote a test program which looks like this:

from dolfin import *

mesh = UnitSquareMesh(2,2)

V = VectorFunctionSpace(mesh, “CG”, 2)
v = TestFunction(V)
u = TrialFunction(V)

mass_form = dot(v,u)*dx
mass_action_form = action(mass_form,Constant((1,1)))
M_lumped = assemble(mass_form)
M_lumped.zero()
M_lumped.set_diagonal(assemble(mass_action_form))
M_lumped_mat = as_backend_type(M_lumped).mat()

This gives me the following error message:
ERROR: could not import petsc4py!
Traceback (most recent call last):
File “test.py”, line 14, in
M_lumped_mat = as_backend_type(M_lumped).mat()
RuntimeError: Error when importing petsc4py

I’m using python3 and installed petsc & petsc4py (seemingly) without issues. Could someone point me in the direction of where I went wrong? Thank you!

How did you install fenics?

Thank you for the fast reply! Through the package manager (I’m on Linux Mint 19.2 by the way):

sudo add-apt-repository ppa:fenics-packages/fenics
sudo apt-get update
sudo apt-get install fenics
sudo apt-get dist-upgrade

Did you install petsc and petsc4py separately? There might be a conflict in versions then.

I first pulled the latest Petsc version from the git repository, then installed petsc4py like this:
pip3 numpy mpi4py
pip3 petsc4py

Should I try some older versions of Petsc?

If you uninstall that version of petsc and petsc4py, and then rerun:

sudo apt-get update
sudo apt-get install fenics
sudo apt-get dist-upgrade

Does it then work?

Sure enough, I’m not getting any error messages anymore!

But why does it suddenly work after uninstalling petsc4py … ?

Because dolfin when installed through the package manager comes with its own petsc and petsc4py installation.
If you want to use another build of petsc or petsc4py, you have to build dolfin from source, see: https://fenics.readthedocs.io/en/latest/installation.html#from-source

Oooh, I see! Thank you very much!