Converting to SciPy sparse matrix without Eigen backend

Hi,

first off: I’m using FEniCS 2019.1.0 for Python from ppa:fenics-packages/fenics on Ubuntu 18.04.2 LTS.

How can I convert assembled matrices to the SciPy sparse format without using the Eigen backend?

Using parameters[‘linear_algebra_backend’] = ‘Eigen’ at the beginning of my program and then assembling a matrix via, e.g., A = assemble(a), I can later export a sparse matrix with

import scipy.io
row,col,val = as_backend_type(A).data()
A = scipy.sparse.csr_matrix((val,col,row))
scipy.io.savemat('data.mat',mdict={'A':A})

However, I would like to keep the default linear algebra backend. There, the command as_backend_type(A).data() fails.

Hi, if your default backend is PETSc then consider the following

from dolfin import *
from scipy.sparse import csr_matrix

mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, 'CG', 1)
u, v = TrialFunction(V), TestFunction(V)

A = assemble(inner(u, v)*dx)
mat = as_backend_type(A).mat()

csr = csr_matrix(mat.getValuesCSR()[::-1], shape=mat.size)
3 Likes