This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

How to generate a sparse stiffness matrix associated with a bilinear form of choice?

+1 vote

My question concerns the two-dimensional numpy array A_array generated by the following block of code:

from dolfin import *

nx = 3
ny = 3

mesh_obj = UnitSquareMesh(nx, ny)

V = FunctionSpace(mesh_obj, "CG", 1)

u = TrialFunction(V)
v = TrialFunction(V)

a = u*v*dx
# compute the stiffness/mass matrix associated with 
# the bilinear form a
A = assemble(a)
A_array = A.array()

I would like to do further computations involving A_array; it has been pointed out to me that the computations will run a lot faster if A_array is sparse (as opposed to if it is dense).

Is there any way to ask FEniCS to produce a sparse matrix A_array?

asked Sep 11, 2015 by kdma-at-dtu FEniCS Novice (590 points)

1 Answer

+6 votes
 
Best answer

A is a stored in sparse format.

If you built dolfin with petsc4py you can access the underlying PETSc object with

A_mat = as_backend_type(A).mat()

You can store the data in scipy.sparse format with

from scipy.sparse import csr_matrix
A_sparray = csr_matrix(A_mat.getValuesCSR()[::-1], shape = A_mat.size)
answered Sep 11, 2015 by Magne Nordaas FEniCS Expert (13,820 points)
selected Sep 17, 2015 by kdma-at-dtu

@Magne Nordaas: Thank you for this information, I'm accepting your answer.

@Magne Nordass, I wonder if there was a way for the output to not skip some of the output data by \vdots and print the entire matrix, howsoever large it is? Alternatively if we can output it to a file?

...